在CV2轮廓中获取像素值

时间:2016-04-16 16:54:57

标签: python opencv image-processing

我正在尝试在轮廓内获取像素值。我跟着类似问题的答案,但我的结果已经结束了。

这段代码找到图像的轮廓,然后遍历它们以找到包含最大区域的轮廓。我添加了结束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)]

car_color:

(136, 89, 96)

1 个答案:

答案 0 :(得分:2)

看起来你要求代码返回的只是像素值列表中第二个点的RGB值(这里称为'像素')传递给grab_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])。