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]))
本博文本意在于记录个人的思考与经验,部分博文采用英语写作,可能影响可读性,请见谅
本文来自博客园,作者:ZXYFrank,转载请注明原文链接:https://www.cnblogs.com/zxyfrank/p/17363630.html