Search code examples
pythonopencvcolorscolor-detection

Color detection using Python & OpenCV


Is it possible to customize this code in such a way so that it can print something if a specific color is present in a frame or print something else if the color is not detected in the frame? If not, then how can I develop this feature? Any suggestions? I am just a begginer at Computer Vision and Image Processing. Thank You.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while True:
    ret, frame = cap.read()
    width = int(cap.get(3))
    height = int(cap.get(4))

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_blue = np.array([90, 50, 50])
    upper_blue = np.array([130, 255, 255])

    mask = cv2.inRange(hsv, lower_blue, upper_blue)

    result = cv2.bitwise_and(frame, frame, mask=mask)

    cv2.imshow('frame', result)
    cv2.imshow('mask', mask)

    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Solution

  • I think you could use region props on your mask:

    for region in regionprops(mask):
        # take regions with large enough areas
        if region.area >= 20:
            print("color")
        else:
            print("no color")
    
    

    Something like this should work. I used 20 for the region area but you would have to try what is the best value according to your usage. This code could even detect how many area of colors are present