Search code examples
pythonimageopencvcolorsdetection

how to return boolean if certain color exist in captured area using python


I am new to python and just started learning it on my own and I cannot find exact solution to my problem.

here's what I'm trying to do.

  1. Capture image using

  2. find whether certain color (eg. red, blue green) exist in the captured image

  3. return boolean

i have spent couple of days searching for the answer but i cannot find any.

the only thing i know is to use openCV...

I guess the solution is too simple to ask. I am fairly new to computer language, so i would really appreciate as detailed as possible. thanks!


Solution

  • Here are two ways to do that in Python/OpenCV.

    Use color thresholding with cv2.inRange(). Then either count the number of white pixels using np.nonzero() or test the average over the thresholded image with cv2.mean().

    Input:

    enter image description here

    import cv2
    import numpy as np
    
    # read image
    img = cv2.imread('red_brushed.png')
    
    # set red range
    lowcolor = (0,0,255)
    highcolor =(128,128,255)
    
    # threshold
    thresh = cv2.inRange(img, lowcolor, highcolor)
    
    # Method 1: count number of white pixels and test if zero
    count = np.sum(np.nonzero(thresh))
    print("count =",count)
    if count == 0:
        print("Not Red")
    else:
        print("Red")
    
    print("")
    
    # Method 2: get the average of the image and test if zero
    average = cv2.mean(thresh)[0]
    print("average =",average)
    if average == 0:
        print("Not Red")
    else:
        print("Red")
    
    # write thresholded image to disk
    cv2.imwrite("red_brushed_thresh.png", thresh)
    
    # display it
    cv2.imshow("IMAGE", img)
    cv2.imshow("THRESH", thresh)
    cv2.waitKey(0)
    


    Thresholded image:

    enter image description here

    Textual Results:

    count = 3534485
    Red
    
    average = 6.933746337890625
    Red