【YOLOv4运行demo.py报错】:cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function ‘rectangle‘

一、问题描述

最近在linux服务器上部署YOLOv4项目(https://github.com/Tianxiaomo/pytorch-YOLOv4),配置好环境以后,运行demo.py进行测试,报错如下:

Traceback (most recent call last):
  File "demo.py", line 161, in <module>
    detect_cv2(args.cfgfile, args.weightfile, args.imgfile)
  File "demo.py", line 57, in detect_cv2
    plot_boxes_cv2(img, boxes[0], savename='predictions.jpg', class_names=class_names)
  File "/opt/data/private/YOLOv5/pytorch-YOLOv4-master/tool/utils.py", line 145, in plot_boxes_cv2
    cv2.rectangle(img, (x1,y1), (np.float32(c3[0]), np.float32(c3[1])), rgb, -1)
cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function 'rectangle'
> Overload resolution failed:
>  - Can't parse 'pt2'. Sequence item with index 0 has a wrong type
>  - Can't parse 'pt2'. Sequence item with index 0 has a wrong type
>  - Can't parse 'rec'. Expected sequence length 4, got 2
>  - Can't parse 'rec'. Expected sequence length 4, got 2

二、解决方法

报错显示,在调用函数cv2.rectangle时,无法分析“pt2”参数。索引为0的序列项的类型错误,去opencv官网查看用法如下:
【YOLOv4运行demo.py报错】:cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function ‘rectangle‘_第1张图片
这下对应上了,是第二个参数pt2类型错误,强转int后运行,这个函数没报错了,又有其他opencv的函数报错。。。

最终方案
一个一个改也不是办法,最终发现是python版本和opencv_python不对应,我的python版本是3.6,opencv_python为4.5.5.64,改为4.4.0.46之后问题解决,具体操作如下:

  1. 查看opencv_python版本:
    pip show opencv_python
    
  2. 卸载原来的opencv_python:
    pip uninstall opencv_python
    
  3. 安装4.4.0.46版本的的opencv_python:
    pip install opencv_python==4.4.0.46
    

如果是其他版本的python,请参考下图找到对应版本的opencv_python
【YOLOv4运行demo.py报错】:cv2.error: OpenCV(4.5.5) :-1: error: (-5:Bad argument) in function ‘rectangle‘_第2张图片

你可能感兴趣的:(Python,计算机视觉,python,opencv,目标检测)