Python 3.x OpenCV';中颜色参数的python绑定发生了什么变化;绘制矩形(cv2.rectangle)?
这曾经奏效:Python 3.x OpenCV';中颜色参数的python绑定发生了什么变化;绘制矩形(cv2.rectangle)?,python-3.x,numpy,opencv,Python 3.x,Numpy,Opencv,这曾经奏效: cv2.rectangle(image, (top,left), (bottom,right), color=color_tuple, thickness=2) 其中,image是np.uint8值的nxmx3数组,color_元组由np.uint8值的3元组组成,例如(2,56135)。现在,它会在我自己的代码(不是Numpy或OpenCV代码)中产生此错误: 从参数中删除名称: cv2.rectangle(image, (top,left), (bottom,right),
cv2.rectangle(image, (top,left), (bottom,right), color=color_tuple, thickness=2)
其中,image是np.uint8值的nxmx3数组,color_元组由np.uint8值的3元组组成,例如(2,56135)。现在,它会在我自己的代码(不是Numpy或OpenCV代码)中产生此错误:
从参数中删除名称:
cv2.rectangle(image, (top,left), (bottom,right), color_tuple, 2)
产生以下错误:
TypeError: function takes exactly 4 arguments (2 given)
我相信这两个错误都与openCV源代码中的重写矩形函数有关,在该函数中,它会查找后跟一对元组的图像。如果找不到它,它会尝试使用接受图像和矩形元组的重写函数。所以回溯并不能代表错误,但我不明白为什么numpy类型不再被接受。我尝试了np.int16,int(将其转换为np.int64)。我只能通过使用tolist()函数将数组转换为python原生int来运行它
color_tuple = tuple(np.array(np.random.random(size=3)*255, dtype=np.int).tolist())
这是什么原因?OpenCV中还有其他numpy数据类型不起作用的地方吗
Python: 3.6.9
OpenCV: 4.5.1
Numpy: 1.19.5
IDE: VSCode
根据post,使用tolist()
可能是正确的解决方案
问题是color\u tuple
的元素类型是
cv2.rectangle
需要nativepython类型-元素类型为int
的元组
以下是重现错误的代码示例:
import numpy as np
import cv2
image = np.zeros((300, 300, 3), np.uint8) # Create mat with type uint8
top, left, bottom, right = 10, 10, 100, 100
color_tuple = tuple(np.array(np.random.random(size=3)*255, dtype=np.int))
print(type(color_tuple[0])) # <class 'numpy.int32'>
cv2.rectangle(image, (top, left), (bottom, right), color=color_tuple, thickness=2)
上述代码无例外地打印
显然
.tolist()
将类型转换为本机int
(NumPy数组类实现方法.tolist()
)
返回l=list(np.array((1,2,3),np.int))
元素的列表numpy.int32
返回l=np.array((1,2,3),np.int).tolist()
元素的列表int
描述了
list
和tolist()
的区别。尝试np.int8
。OpenCV对图像使用float或uint8
类型。您认为它在哪个版本中工作?从3.0.0的文档来看,它从来都不是color=
。它始终只是一个tuple.cv2.rectangle(图像,(顶部,左侧),(底部,右侧),color=color\u tuple.tolist(),厚度=2)
import numpy as np
import cv2
image = np.zeros((300, 300, 3), np.uint8) # Create mat with type uint8
top, left, bottom, right = 10, 10, 100, 100
color_tuple = tuple(np.array(np.random.random(size=3)*255, dtype=np.int))
print(type(color_tuple[0])) # <class 'numpy.int32'>
cv2.rectangle(image, (top, left), (bottom, right), color=color_tuple, thickness=2)
color_tuple = tuple(np.array(np.random.random(size=3)*255, dtype=np.int).tolist())
print(type(color_tuple[0]))