使用颜色跟踪技术在OpenCV 2.x中跟踪多个物体

4

目前我正在尝试通过颜色跟踪多个对象。我已经基于文档编写了代码。

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])

    # Threshold the HSV image to get only blue colors
    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

使用上述代码,我正在追踪过滤HSV蓝色通道的蓝色物体。我想同时追踪绿色物体,并在“res”图像中显示蓝色和绿色。

我已添加了以下代码,但没有成功

lower_green = np.array([50, 100, 100])
upper_green = np.array([70, 255, 255]) 
green_mask = cv2.inRange(hsv, lower_green, upper_green) # I have the Green threshold image.

我不知道如何在只有一个“res”图像中使用bitwise-and添加绿色蒙版和蓝色蒙版。你能给我提供一些指导吗?
非常感谢。

创建蓝色和绿色的单独掩码,然后将两者相加得到最终结果。 - Haris
1个回答

9

将它们相加即可。

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

    # Take each frame
    _, frame = cap.read()

    # Convert BGR to HSV
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    # define range of blue color in HSV
    lower_blue = np.array([110,50,50])
    upper_blue = np.array([130,255,255])

    lower_green = np.array([50, 50, 120])
    upper_green = np.array([70, 255, 255]) 
    green_mask = cv2.inRange(hsv, lower_green, upper_green) # I have the Green threshold image.

    # Threshold the HSV image to get only blue colors
    blue_mask = cv2.inRange(hsv, lower_blue, upper_blue)
    mask = blue_mask + green_mask

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(frame,frame, mask= mask)

    cv2.imshow('frame',frame)
    cv2.imshow('mask',mask)
    cv2.imshow('res',res)
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

1
非常感谢。你提供的解决方案真的帮了我很多。 - alejandro zuleta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接