gpt4 book ai didi

python - 出现 "integer is required (got type tuple)"错误,使用 cv2 绘制矩形

转载 作者:太空宇宙 更新时间:2023-11-04 09:34:09 24 4
gpt4 key购买 nike

我已经编写了一个基本的 Python 代码来创建一个图像,然后在边界上放置一个矩形。这似乎不起作用。我检查了多个站点,这是他们使用的确切代码。不知道是什么问题。

import cv2
import numpy as np
img = Image.new('RGB', (800, 900), color= (171, 183, 255))
cv2.rectangle(img,(1,1),(800,900),(255,0,0),15)
img

我收到这个错误

TypeError
<ipython-input-251-4b78f75077e8> in <module>()
4 img = Image.new('RGB', (800, 900), color= (171, 183, 255))
5 # cv2.rectangle(img, 0, 0, 800, 900, (255,0,0))
----> 6 cv2.rectangle(img,(1,1),(800,900),(255,0,0),15)
7 img

TypeError: an integer is required (got type tuple)

有人可以帮忙吗?

最佳答案

cv2 模块使用 numpy 数组 作为图像,而不是使用 PIL Image 实例。

因为 cv2.rectangle 实现和 Image 类型都是完全在编译代码中实现的,所以回溯对于理解问题所在并没有多大帮助。在幕后, native cv2.rectangle() 代码尝试访问图像对象上需要整数的内容,但 cv2.rectangle() 却传入了一个元组,因为它期望与 numpy 数组交互。

如果您只想要一个具有统一 RGB 颜色的空白图像,请创建一个形状为 (width, height, 3) 的 numpy 数组,并将您的 3 个波段设置为您喜欢的 RGB 值:

import numpy as np

# numpy equivalent of Image.new('RGB', (800, 900), color=(171, 183, 255))
img = np.zeros((800, 900, 3), np.uint8)
img[..., :] = (171, 183, 255)

然后将您的 cv2.rectangle() 调用应用到该数组。

您始终可以通过以下方式与 PIL 图像相互转换:

# create numpy array from PIL image
nparray = np.array(img)
# create PIL image from numpy array
img = Image.fromarray(nparray)

关于python - 出现 "integer is required (got type tuple)"错误,使用 cv2 绘制矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54460134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com