问题描述
我已经写了一个基本的Python代码来创建图像,然后在边界上放置一个矩形.这似乎不起作用.我已经检查了多个站点,这是它们使用的确切代码.不知道是什么问题.
I have written a basic Python code to create an image and then putting a rectangle on the boundaries. This doesn't seem to work. I have checked multiple sites and this is the exact code they use. Don't know what is the issue.
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
实例.
The cv2
module works with numpy arrays as images, not with PIL
Image
instances.
由于cv2.rectangle
实现和Image
类型都是完全在编译代码中实现的,所以回溯并不能帮助理解问题所在.在幕后,本机cv2.rectangle()
代码尝试访问图像对象上需要整数的内容,而cv2.rectangle()
则希望在元组中传递它,因为它希望与numpy数组进行交互.
Because both the cv2.rectangle
implementation and the Image
type are implemented entirely in compiled code, the traceback is not all that helpful in understanding what is going wrong. Under the hood, the native cv2.rectangle()
code tries to access something on the image object that required an integer but cv2.rectangle()
passed in a tuple instead, as it was expecting to be interacting with a numpy array.
如果您想要的只是一张具有统一RGB颜色的空白图像,请创建一个形状(宽度,高度,3)并将3个波段设置为首选RGB值的numpy数组:
If all you wanted was a blank image with uniform RGB colour, create a numpy array with shape (width, height, 3) and your 3 bands set to your preferred RGB value:
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()
调用应用于该数组.
then apply your cv2.rectangle()
call to that array.
您始终可以使用以下方法从PIL图像转换为:
You can always convert from and to a PIL image with:
# create numpy array from PIL image
nparray = np.array(img)
# create PIL image from numpy array
img = Image.fromarray(nparray)
这篇关于获取“整数是必需的(元类型元组)".错误,使用cv2绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!