【问题标题】:How to detect two different colors using `cv2.inRange` in Python-OpenCV?如何在 Python-OpenCV 中使用 `cv2.inRange` 检测两种不同的颜色?
【发布时间】:2018-06-15 00:47:03
【问题描述】:

如何定义两种不同颜色的“下”和“上”范围,例如红色和蓝色(因为红色和蓝色在 HSV 颜色中不相邻)

这个属于红色的:

lower_red = np.array([160,20,70])
upper_red = np.array([190,255,255])

而这个属于蓝色:

lower_blue = np.array([101,50,38])
upper_blue = np.array([110,255,255])

我尝试使用 if 条件将它们组合起来或制作自己的功能但不起作用,你们能告诉我解决方案吗?

P/s:Python 中的 OpenCV

【问题讨论】:

标签: python opencv


【解决方案1】:

下图显示了 HSV 颜色空间,它使用色相、饱和度和值(或亮度)。

在 HSV 颜色空间中工作时,请务必记住这一点,并且红色和绿色等概念是一种转换回不同数据类型的过程。

因此,您的上限和下限只能是该空间中的一个点,但可以包括红色和蓝色光谱的一部分,即紫色。您需要选择满足您需要的任何处理输出标准的阈值。

要么运行两个单独的循环,要么运行两个单独的循环,第一个是对红色进行阈值处理,第二个是对蓝色进行阈值处理,然后使用 OpenCV Blend 函数将这两个图像混合在一起。请参阅here 了解混合两种颜色空间。

【讨论】:

  • 我正在使用交通标志,其中一个是红色的,另一个是蓝色的,我无法将它们混合在一起。有没有办法设置 2 个不同的范围或只运行两个单独的循环?
【解决方案2】:
# Make a copy of the image

image_copy = np.copy(image)
## TODO: Define the color selection boundaries in RGB values
# play around with these values until you isolate the blue background

lower_blue = np.array([200,0,0]) 
upper_blue = np.array([250,250,255])

# Define the masked area

mask = cv2.inRange(image_copy, lower_blue, upper_blue)
# Vizualize the mask

plt.imshow(mask,cmap='gray')

【讨论】:

    【解决方案3】:

    当你得到两个colors 掩码时,然后使用cv2.bitwise_or 得到最后一个掩码。

    import cv2
    
    ## Read
    img = cv2.imread("sunflower.jpg")
    
    ## convert to hsv
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    
    ## mask of green (36,0,0) ~ (70, 255,255)
    mask1 = cv2.inRange(hsv, (36, 0, 0), (70, 255,255))
    
    ## mask o yellow (15,0,0) ~ (36, 255, 255)
    mask2 = cv2.inRange(hsv, (15,0,0), (36, 255, 255))
    
    ## final mask and masked
    mask = cv2.bitwise_or(mask1, mask2)
    target = cv2.bitwise_and(img,img, mask=mask)
    
    cv2.imwrite("target.png", target)
    

    来源:

    找到绿色和黄色(范围不是那么准确):


    顺便说一句,为了获得更准确的范围,这是我相关答案中的参考地图:

    How to define a threshold value to detect only green colour objects in an image :Opencv

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-14
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多