使用python的cv2.polylines在图片上画出物体的运动轨迹时,遇到一些bug:
- ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (32,) + inhomogeneous part.
- cv2.error: OpenCV(4.9.:- 1: error:(-5:Bad argument) in function ‘polylines’
- cv2.polylines没有报错但是无法画线
- 列表转换为numpy数组无逗号
解决方法依次如下:
1. ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (32,) + inhomogeneous part.
将numpy版本降为1.23.0,使用命令:
pip install numpy==1.23.0
参考这个答案:网址
2. cv2.error: OpenCV(4.9.: -1: error:(-5:Bad argument) in function ‘polylines’
这个报错提示了函数polylines输入参数问题,我这里的问题是输入的坐标pts(array)格式有问题,原来的报错语句是:
my[bbox[4]].append([int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)])
修改为正确的语句为:
my[bbox[4]].append([[int((bbox[0] + bbox[2]) / 2), int((bbox[1] + bbox[3]) / 2)]])
3. cv2.polylines没有报错但是无法画线
这个问题如果初次遇到还不太好找原因,因为它没有给出如何报错信息。但我这里无法画线的原因是因为输入的参数pts有点小问题。
正常的输入参数格式应该为:
pts = np.array([[40,300],[54,378],[60,420],[30,333]],np.int32)
但是我用print打印出来的坐标结果却是这样的:
[[[1556 637]]
[[1556 638]]
[[1556 643]]]
显然问题出现在numpy数组的格式不太对,没有逗号。
# 原先导致没有逗号、不能划线的代码语句:
pts = np.array(my[bbox[4]], dtype=object).astype(np.int64)
# 正确修改后:
pts = []
pts.append(np.array(my[bbox[4]], dtype=object).astype(np.int64))
正确修改后的输出打印结果为:
[array([[[1556, 637]],
[[1556, 638]],
[[1556, 643]]], dtype=int64)]
4. 列表转换为numpy数组无逗号
除了bug3的解决方式可以使得numpy转换后的输出有逗号外,如果你只是想在print打印结果中显示出逗号,那么可以参考这个方法:
网址1
网址2