gpt4 book ai didi

python - 获取 CV2 轮廓内的像素值

转载 作者:太空宇宙 更新时间:2023-11-03 22:26:45 25 4
gpt4 key购买 nike

我正在尝试获取轮廓内的像素值。我遵循了类似问题的答案,但我的结果是错误的。

此代码块查找图像的轮廓,然后遍历它们以找到包含最大区域的轮廓。我添加了结束 if 语句,如果是在白天,它会尝试获取代码的 RGB 值。原始图像(视频帧)连同轮廓一起传递到我编写的函数 (grab_rgb)

    thresh = cv2.dilate(thresh, None, iterations=2)
(_, cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# look for motion
motion_found = False
biggest_area = 0

# examine the contours, looking for the largest one
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
# get an approximate area of the contour
found_area = w * h
# find the largest bounding rectangle
if (found_area > MIN_AREA) and (found_area > biggest_area):
biggest_area = found_area
motion_found = True

if not is_nighttime():
rgb = grab_rgb(image, c)
else:
rgb = 'nighttime'

这是我写的函数:

def grab_rgb(image, c):
pixels = []

# TODO: Convert to real code
# Detect pixel values (RGB)
mask = np.zeros_like(image)
cv2.drawContours(mask, c, -1, color=255, thickness=-1)

points = np.where(mask == 255)

for point in points:
pixel = (image[point[1], point[0]])
pixel = pixel.tolist()
pixels.append(pixel)

pixels = [tuple(l) for l in pixels]
car_color = (pixels[1])

r = car_color[0]
g = car_color[1]
b = car_color[2]

pixel_string = '{0},{1},{2}'.format(r, g, b)

return pixel_string

代码运行,但只返回三个 RGB 值,只有第二个值包含任何有意义的东西(值 0 和 2 是 [0,0,0],[0,0,0]。肯定应该超过轮廓内的三个像素,所以我不确定哪里出错了。

编辑:我意识到将实际存储在变量中的内容包括在内可能会有所帮助。

面具:

[[[  0   0   0]
[ 0 0 0]
[ 0 0 0]
...,
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]

[[ 0 0 0]
[255 0 0]
[ 0 0 0]
...,
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]

[[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
...,
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]

...,
[[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
...,
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]

[[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
...,
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]

[[ 0 0 0]
[ 0 0 0]
[ 0 0 0]
...,
[ 0 0 0]
[ 0 0 0]
[ 0 0 0]]]

积分:

(array([ 1,  1,  3,  5, 10, 11, 11, 12, 12, 13, 13, 14, 14], dtype=int32), array([ 1, 22, 22, 24, 24, 21, 23, 16, 20,  9, 15,  1,  8], dtype=int32), array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int32))

像素:

[0, 0, 0] [136, 89, 96] [0, 0, 0]

像素:

[(0, 0, 0), (136, 89, 96), (0, 0, 0)]

汽车颜色:

(136, 89, 96)

最佳答案

看起来您要求代码返回的只是传递给 grab_rgb 的每个轮廓中的点的像素值列表(此处称为“像素”)中第二个点的 RGB 值,

car_color = (pixels[1])

r = car_color[0]

g = car_color[1]

b = car_color[2]

所以输出应该意味着你的图像至少有三个检测到的轮廓满足你的区域限制,并且轮廓点列表中第二个点的 RGB 值就是你提到的([0,0,0],[ x,y,z] 和 [0,0,0])。

关于python - 获取 CV2 轮廓内的像素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36666991/

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