【问题标题】:What happened to the python binding for the color parameter in OpenCV's draw rectangle (cv2.rectangle)?OpenCV的绘制矩形(cv2.rectangle)中颜色参数的python绑定发生了什么?
【发布时间】:2021-07-24 01:57:09
【问题描述】:

这曾经有效:

cv2.rectangle(image, (top,left), (bottom,right), color=color_tuple, thickness=2)

其中 image 是 np.uint8 值的 nxmx3 数组,而 color_tuple 由 np.uint8 值的 3 个元组组成,例如(2,56,135)。现在它会在我自己的代码(不是 Numpy 或 OpenCV 代码)中产生这个错误:

Exception has occurred: TypeError
Argument given by name ('color') and position (3)

从参数中删除名称:

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 本机整数来运行它。

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

【问题讨论】:

  • 试试np.int8。 OpenCV 使用 float 或 uint8 类型的图像
  • 您认为它曾经在哪个版本中工作?从 docs.opencv.org/3.0.0/d6/d6e/… 的文档可以追溯到 3.0.0,它从来都不是 color=。它始终只是一个元组。

标签: python-3.x numpy opencv


【解决方案1】:

根据this 的帖子,使用tolist() 可能是正确的解决方案。

问题在于 color_tuple 的元素类型是 <class 'numpy.int32'>
cv2.rectangle 需要 native python 类型 - 元素类型为 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)

以上代码打印&lt;class 'numpy.int32'&gt;并引发异常:

由名称('color')和位置(3)给出的参数

.tolist()相同的代码:

color_tuple = tuple(np.array(np.random.random(size=3)*255, dtype=np.int).tolist())

print(type(color_tuple[0]))

上面的代码打印&lt;class 'int'&gt;没有异常。


显然.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 元素的列表。

listtolist() 的区别在here 中描述。

【讨论】:

  • cv2.rectangle(image, (top,left), (bottom,right), color=color_tuple.tolist(), thickness=2)
猜你喜欢
  • 2019-09-30
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-25
相关资源
最近更新 更多