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

使用YOLOv5运行脚本时遇TypeError:forward()不支持size参数

解决YOLOv5推理时TypeError: forward() got an unexpected keyword argument 'size'问题

问题根源

YOLOv5的模型推理接口中,指定输入图像尺寸的参数并非size,而是imgsz。你传入的size参数不在模型forward方法的接受范围内,因此触发参数错误。

修复步骤

  1. 修正参数名称
    将代码中调用模型的行里的size=640替换为imgsz=640:

    results = model(screenshot, imgsz=640)
    
  2. 可选:处理截图通道格式
    mss截取的截图默认是BGRA四通道格式,而YOLOv5期望输入RGB三通道图像,建议添加格式转换步骤避免检测异常:

    import cv2
    
    with mss() as sct:
        monitor = {"top": 220, "left": 640, "width": 640, "height":640}
    
        while(True):
            screenshot = np.array(sct.grab(monitor))
            # 将BGRA格式转换为RGB
            img_rgb = cv2.cvtColor(screenshot, cv2.COLOR_BGRA2RGB)
            # 使用正确的imgsz参数调用模型
            results = model(img_rgb, imgsz=640)
            df= results.pandas().xyxy[0]
    

补充优化

如果需要固定模型的输入尺寸,也可以在加载模型时直接指定imgsz,后续推理无需重复传入:

model = torch.hub.load('ultralytics/yolov5', 'yolov5s', imgsz=640)

内容的提问来源于stack exchange,提问作者Makicimiliano de jesus santos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:35:28