[英]Python TypeError: an integer is required (got type tuple) - (OpenCV / Numpy)
I know that there have been many similar questions around, but none of those seem to work for my problem.我知道周围有很多类似的问题,但这些问题似乎都不能解决我的问题。 That's why I decided to create another post.
这就是为什么我决定创建另一个帖子。
To start off, the basic idea of the following code is that it will detect the pixel value of a specific coordinate in order to create a rectangle with the same color.首先,以下代码的基本思想是检测特定坐标的像素值,以创建具有相同颜色的矩形。
This is my code:这是我的代码:
# open image
img = cv2.imread("image.png")
# set coordinates for rectangle
start_point = (35, 39)
end_point = (50, 60)
# get pixel value of start point; outputs something like "[132 42 52]"
pixel = img[start_point].astype(int)
R = pixel[0]
G = pixel[1]
B = pixel[2]
# outputs type: "<class 'numpy.ndarray'> <class 'numpy.int32'> <class 'numpy.int32'> <class 'numpy.int32'>"
print(type(pixel), type(R), type(G), type(B))
# draws rectangle
color = (R, G, B)
image = cv2.rectangle(img, start_point, end_point, color, -1)
Even though the values "R", "G" and "B" are converted into integers by using "astype(int)" I get the following error:即使使用“astype(int)”将值“R”、“G”和“B”转换为整数,我也会收到以下错误:
image = cv2.rectangle(img, start_point, end_point, color, -1)
TypeError: an integer is required (got type tuple)
By using numbers like 30, 53, 100 as the color values everything works out perfectly fine.通过使用像 30、53、100 这样的数字作为颜色值,一切都很好。 There just seems to be a problem with the values I receive by setting the pixel value of a coordinate in this image.
通过设置此图像中坐标的像素值,我收到的值似乎有问题。 I don't really know where the problem could be, so I appreciate every help!
我真的不知道问题出在哪里,所以我感谢每一个帮助!
Thanks in advance.提前致谢。
You answered yourself - you passed type numpy.int32
and they expect int
.你自己回答 - 你传递了类型
numpy.int32
并且他们期望int
。 For humans it's the same, but python has a hard time handling all types convertible to one another.对于人类来说是一样的,但是 python 很难处理所有可以相互转换的类型。 You have to help them by passing:
你必须通过传递帮助他们:
image = cv2.rectangle(img, start_point, end_point, [int(x) for x in color], -1)
I think the simplest solution is using color = (int(R), int(G), int(B))
.我认为最简单的解决方案是使用
color = (int(R), int(G), int(B))
。
The issue is that even when using pixel = img[start_point].astype(int)
, the elements of pixel
are of type <class 'numpy.int32'>
and not of type int
.问题是,即使使用
pixel = img[start_point].astype(int)
, pixel
的元素也是<class 'numpy.int32'>
类型而不是int
类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.