首页 > 解决方案 > OpenCV的绘制矩形(cv2.rectangle)中颜色参数的python绑定发生了什么?

问题描述

这曾经有效:

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

标签: python-3.xnumpyopencv

解决方案


根据这篇文章,使用tolist()可能是正确的解决方案。

问题在于 的元素的类型color_tuple<class 'numpy.int32'>
cv2.rectangle期望带有 type 元素的原生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)

上面的代码打印<class 'numpy.int32'>并引发异常:

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

相同的代码.tolist()

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

print(type(color_tuple[0]))

上面的代码打印<class 'int'>无异常。


显然.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()描述。


推荐阅读