Home > OS >  Color detection using Python & OpenCV
Color detection using Python & OpenCV

Time:10-05

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()

CodePudding user response:

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

CodePudding user response:

The following might work:

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)
    # only one colour in range:
    lower_blue = np.array([90, 50, 50])
    upper_blue = np.array([90, 50, 50])
    included = False
    mask = cv2.inRange(hsv, lower_blue, upper_blue)
    for i in range(mask.shape[0]):
         for j in range(mask.shape[1]):
              if mask[i,j] == 1:
                   included = True

    if included == True:
        print("colour is included")
    else:
        print("colour is not included")
    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()

CodePudding user response:

You can print colorful like this

import os

os.system('')
#Red: \33[31m
#Green: \033[1;32;40m
#Reset color: \033[0;37;40m

print('\033[1;32;40mHello everyone.\033[0;37;40m')
print("\33[31mBrooo this is red and so susy i think.\033[0;37;40m\n")
  • Related