How to find the RED color regions using OpenCV?

后端 未结 4 1264
野性不改
野性不改 2020-11-29 09:45

I am trying to make a program where I detect red. However sometimes it is darker than usual so I can\'t just use one value. What is a good range for detecting different shad

4条回答
  •  無奈伤痛
    2020-11-29 10:21

    RGBis not a good color space for specific color detection. HSV will be a good choice.

    For RED, you can choose the HSV range (0,50,20) ~ (5,255,255) and (175,50,20)~(180,255,255)using the following colormap. Of course, the RED range is not that precise, but it is just ok.

    The code taken from my another answer: Detect whether a pixel is red or not

    #!/usr/bin/python3
    # 2018.07.08 10:39:15 CST
    # 2018.07.08 11:09:44 CST
    import cv2
    import numpy as np
    ## Read and merge
    img = cv2.imread("ColorChecker.png")
    img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    
    ## Gen lower mask (0-5) and upper mask (175-180) of RED
    mask1 = cv2.inRange(img_hsv, (0,50,20), (5,255,255))
    mask2 = cv2.inRange(img_hsv, (175,50,20), (180,255,255))
    
    ## Merge the mask and crop the red regions
    mask = cv2.bitwise_or(mask1, mask2 )
    croped = cv2.bitwise_and(img, img, mask=mask)
    
    ## Display
    cv2.imshow("mask", mask)
    cv2.imshow("croped", croped)
    cv2.waitKey()
    

    Related answers:

    1. Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)
    2. How to define a threshold value to detect only green colour objects in an image :Opencv
    3. How to detect two different colors using `cv2.inRange` in Python-OpenCV?
    4. Detect whether a pixel is red or not

    Of course, for the specific question, maybe other color space is also OK.

    How to read utility meter needle with opencv?

提交回复
热议问题