https://github.com/ghostman-ai/Detection-of-colour—OpenCV-with-Pyton.git
“””
@author: Sahil
“””
import cv2
import numpy as np
import datetime as dt
# to open a camera
img = cv2.VideoCapture(0)
# start a loop where we get frames and we do the detection
while True:
ret, frame = img.read()
#for putting date time in output
font = cv2.FONT_HERSHEY_SIMPLEX
date_time = str(dt.datetime.now())
frame = cv2.putText(frame, date_time, (10, 50), font, 1, (255, 255, 0), 3, cv2.LINE_AA)
hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
# Inside a loop we define a HSV ranges, we create the mask. first define the hsv range of blue(high blue and low blue)
high_blue = np.array([126, 255, 255])
low_blue = np.array([94, 80, 2])
blue_mask = cv2.inRange(hsv_frame, low_blue, high_blue)
blue = cv2.bitwise_and(frame, frame, mask=blue_mask)
# Similar for red
high_red = np.array([179, 255, 255])
low_red = np.array([161, 155, 84])
red_mask = cv2.inRange(hsv_frame, high_red, low_red)
red = cv2.bitwise_and(frame, frame, mask=red_mask)
# Similar for green
high_green = np.array([102, 255, 255])
low_green = np.array([94, 80, 2])
green_mask = cv2.inRange(hsv_frame, high_green, low_green)
green = cv2.bitwise_and(frame, frame, mask=green_mask)
# Every color except white
low = np.array([0, 42, 0])
high = np.array([179, 255, 255])
mask = cv2.inRange(hsv_frame, low, high)
result = cv2.bitwise_and(frame, frame, mask=mask)
# showing the result
cv2.imshow(“Frame”, frame)
cv2.imshow(“Red”, red)
cv2.imshow(“Blue”, blue)
cv2.imshow(“Green”, green)
cv2.imshow(“Result”, result)
key = cv2.waitKey(1)
if key == 27:
break
img.release()
cv2.destroyAllWindows()