How to detect two different colors using `cv2.inRange` in Python-OpenCV?

后端 未结 3 1159
旧时难觅i
旧时难觅i 2020-11-27 06:06

How can I define \"lower\" and \"upper\" range of two different color, such as red and blue (because red and blue are not next to each other in the HSV color)

This o

3条回答
  •  被撕碎了的回忆
    2020-11-27 06:43

    As you get two masks of colors, then use cv2.bitwise_or to get the final mask.

    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)
    

    Source:

    Find green and yellow(the range is not that accurate):


    BTW, to get more accurate range, here is a refer map in my related answer:

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

提交回复
热议问题