Loading

Python元组传参, cv2.rectangle的奇怪错误

colors = (np.array(colors) * 255).astype(np.int)
color = colors[i]
cv2.rectangle(img, (x0, y0), (x1, y1), color, 2)
"""
tuple(colors[i])
(0, 255, 0)
tuple(colors[i]) == (0,255,0)
True
cv2.rectangle(img, (x0, y0), (x1, y1), colors[i], 2)
Traceback (most recent call last):
  File "<string>", line 1, in <module>
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'rectangle'
> Overload resolution failed:
>  - Scalar value for argument 'color' is not numeric
>  - Scalar value for argument 'color' is not numeric
>  - Can't parse 'rec'. Expected sequence length 4, got 2
>  - Can't parse 'rec'. Expected sequence length 4, got 2

cv2.rectangle(img, (x0, y0), (x1, y1), (0,255,0), 2)
"""

就是这个问题,tuple(a),a 是一个numpy int的数组,然后a也和某个元组相等,但是传参就不行

通过这个博客得到了启发

进行如下尝试

import numpy as np
a = np.array([1,2,3]).astype(np.int32)
b = tuple(a)
print(b) # (1,2,3)
print(b == a) # [ True  True  True]
print(type(b[0])) # <class 'numpy.int32'>
c = (1,2,3)
print(c == a) # [ True  True  True]
print(c == b) # True
print(type(c[0])) # <class 'int'>

发现,虽然通过 Numpy 转换过来的b虽然和a数值上相等,但是其数据类型不是int,因此在 cv2 当中出现了报错

正确的转换方式应该是

tuple_int = tuple(map(lambda x:int(x), a))
print(type(tuple_int[0]))
posted @ 2023-04-29 09:56  ZXYFrank  阅读(457)  评论(0编辑  收藏  举报