【问题标题】:Python TypeError: an integer is required (got type tuple) - (OpenCV / Numpy)Python TypeError:需要一个整数(获取类型元组)-(OpenCV / Numpy)
【发布时间】:2020-03-31 10:30:26
【问题描述】:

我知道周围有很多类似的问题,但这些问题似乎都不适用于我的问题。这就是我决定创建另一个帖子的原因。

首先,以下代码的基本思想是它将检测特定坐标的像素值,以创建具有相同颜色的矩形。

这是我的代码:

# 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)

即使使用“astype(int)”将值“R”、“G”和“B”转换为整数,我也会收到以下错误:

image = cv2.rectangle(img, start_point, end_point, color, -1)
TypeError: an integer is required (got type tuple)

通过使用 30、53、100 等数字作为颜色值,一切正常。通过设置此图像中坐标的像素值,我收到的值似乎存在问题。我真的不知道问题可能出在哪里,所以我感谢每一个帮助!

提前致谢。

【问题讨论】:

    标签: python numpy opencv integer tuples


    【解决方案1】:

    我认为最简单的解决方案是使用color = (int(R), int(G), int(B))

    问题是即使使用pixel = img[start_point].astype(int)pixel 的元素也是&lt;class 'numpy.int32'&gt; 类型而不是int 类型。

    【讨论】:

      【解决方案2】:

      你自己回答了——你输入了numpy.int32,他们期待int。对于人类来说是一样的,但是 python 很难处理所有可以相互转换的类型。 你必须通过传递来帮助他们:

      image = cv2.rectangle(img, start_point, end_point, [int(x) for x in color], -1)
      

      【讨论】:

      • 哦,哇,我的错。由于缺乏知识,我什至不知道 Int32 和“正常”整数之间存在差异。非常感谢你! @NadavS
      猜你喜欢
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多