Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Color Detection/Filter using OpenCV and Webcam
# Color Detection/Filter using OpenCV and Webcam
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
while True:
_, frame = cap.read()
hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
# Red Color
low_red = np.array([161, 155, 84])
high_red = np.array([179, 255, 255])
red_mask = cv2.inRange(hsv_frame, low_red, high_red)
red = cv2.bitwise_and(frame, frame, mask=red_mask)
# Blue Color
low_blue = np.array([94, 80, 2])
high_blue = np.array([126, 255, 255])
blue_mask = cv2.inRange(hsv_frame, low_blue, high_blue)
blue = cv2.bitwise_and(frame, frame, mask=blue_mask)
# Green Color
low_green = np.array([52, 52, 72])
high_green = np.array([102, 255, 255])
green_mask = cv2.inRange(hsv_frame, low_green, high_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)
# Original Frame
cv2.imshow("Original Frame", frame)
# Red Frame
cv2.imshow("Red Filter #1", red_mask)
cv2.imshow("Red Filter #2", red)
# Blue Frame
cv2.imshow("Blue Filter #1", blue_mask)
cv2.imshow("Blue Filter #2", blue)
# Green Frame
cv2.imshow("Green Filter #1", green_mask)
cv2.imshow("Green Filter #2", green)
# Result
cv2.imshow("All Except White", result)
key = cv2.waitKey(1)
if key == 27:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment