python-3.x - 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
解决方案
根据这篇文章,使用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()
描述。
推荐阅读
- javascript - javascript中的RSA加密和Java中的解密
- matlab - 如何在matlab中对所有维度的向量进行条件处理?
- jqgrid - Jqgrid reload with reload with reload with current set to true 不能正确地重新加载网格
- mysql - SQL中如何查找员工工资总和大于等于10000的部门?
- node.js - sudo:节点:在 EC2 Ubuntu 上找不到命令
- visual-studio - PowerShell Pro Tools 多个表单未按预期运行
- neural-network - PyTorch中准确率反复增加和减少是否正常?
- javascript - 如何像滚动一样创建 waaark.com?
- git - 如何在 git 中重新登录
- mysql - 从重复行中选择最大的 deleted_data