Search code examples
pythonopencvcolorsdetection

how to know if a color is detected on opencv


I'm currently working on a project including color detection. I'm using opencv on python to do so, I can detect the color I want, i.e. blue, but I cannot manage to make the software know that this color has been detected. Here is the code I have.

` hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) boundaries = [([94, 90, 45], [145, 255, 255])]

# loop over the boundaries
for (lower, upper) in boundaries:
    # create NumPy arrays from the boundaries
    lower = np.array(lower, dtype="uint8")
    upper = np.array(upper, dtype="uint8")

    # find the colors within the specified boundaries and apply
    # the mask
    mask = cv2.inRange(hsv_frame, lower, upper)
    output = cv2.bitwise_and(frame, frame, mask=mask)
    imageOut = np.hstack([frame, output])`

It isolates the color blue properly like this output of my code.

My problem is that from there I don't know how I can have my software to know that the color blue has been detected and isolated.


Solution

  • Here is a basic approach:

    Define the color you want to detect. Threshold the image for that color - this will result in a mask where the wanted color is white and the rest is black. Sum the mask, if there is any white (meaning if any color is detected) the sum will be larger then 0.

    I created an example, where I also show the images to help understand the process, but that is not necessary. I use the HSV colorspace to do the color separation. You can use this script to find good lower / upper color ranges. It can also help you understand how HSV works.

    enter image description here

    import cv2
    import numpy as np
    # load image
    img = cv2.imread("img.jpg")
    # Convert to HSV
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    
    # define range wanted color in HSV
    lower_val = np.array([37,42,0]) 
    upper_val = np.array([84,255,255]) 
    
    # Threshold the HSV image - any green color will show up as white
    mask = cv2.inRange(hsv, lower_val, upper_val)
    
    # if there are any white pixels on mask, sum will be > 0
    hasGreen = np.sum(mask)
    if hasGreen > 0:
        print('Green detected!')
    
    # show image 
    # apply mask to image
    res = cv2.bitwise_and(img,img,mask=mask)
    fin = np.hstack((img,res))
    # display image
    cv2.imshow("Res", fin)
    cv2.imshow("Mask", mask)
    cv2.waitKey(0)
    cv2.destroyAllWindows()