You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

YOLOv5检测僵尸自动点击报错:TypeError列表索引需为整数或切片

问题分析与解决

错误原因很明确:results.pandas().xyxy返回的是列表类型(哪怕只传入单张图像,YOLOv5也会把检测结果包裹在列表中),你直接用字符串索引df['class']访问列表元素,自然触发TypeError: list indices must be integers or slices, not str。

解决步骤

  1. 提取列表中的DataFrame:将df = results.pandas().xyxy改为df = results.pandas().xyxy[0],拿到当前截图对应的检测结果DataFrame。
  2. 修正点击坐标(关键细节):你截图的区域是region=(0,535, 1900, 475),意味着截图内的坐标是相对于屏幕左上角(0,535)的偏移量,直接用检测到的center_x/center_y点击会偏离目标,需要加上截图区域的起始坐标。

修改后的完整代码

import time
import pyautogui
import numpy as np
import cv2
# 假设你已完成模型加载,示例:model = torch.hub.load('ultralytics/yolov5', 'custom', path='你的模型路径.pt')

time.sleep(2)

while True: 
    screen = pyautogui.screenshot(region=(0,535, 1900, 475))
    screen_array = np.array(screen)
    corrected_colors = cv2.cvtColor(screen_array, cv2.COLOR_RGB2BGR)
    
    results = model(corrected_colors)
    
    # 提取列表中对应单张图的检测结果DataFrame
    df = results.pandas().xyxy[0]
    # 筛选class为0的目标(需确保0对应zombie,可核对data.yaml的类别顺序)
    df = df[df['class'] == 0]
    
    if not df.empty:
        # 筛选置信度≥0.6的结果
        valid_results = df[df['confidence'] > 0.60]
        if not valid_results.empty:
            top_result = valid_results.iloc[0]
            xmin, ymin, xmax, ymax = top_result['xmin'], top_result['ymin'], top_result['xmax'], top_result['ymax']
            center_x = int((xmin + xmax) / 2)
            center_y = int((ymin + ymax) / 2)
            # 转换为屏幕绝对坐标
            pyautogui.click(center_x + 0, center_y + 535)
    
    cv2.imshow('YOLO', np.squeeze(results.render()))

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cv2.destroyAllWindows()

额外优化提示

  • 可以在模型推理时直接设置置信度阈值,减少后续过滤操作:results = model(corrected_colors, conf=0.6),返回结果会自动过滤掉置信度低于0.6的目标。
  • 核对data.yaml中的类别顺序,确保class == 0确实对应"zombie",避免筛选错误目标。

内容的提问来源于stack exchange,提问作者Dolarn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:50:23