Detect By Color

Each color have some color code, so here we will be targeting only. We will be considering for yellow color.

Let’s look at an code :


# Import neccessary libraries
import cv2
import numpy as np

# Initialize
cap = cv2.VideoCapture(0)
# define range of Yellow color in HSV
lower_yellow = np.array([51,51,0])
upper_yellow = np.array([255,255,224])

# loop until break statement is exectured
while True:
    # Read webcam image
    ret, frame = cap.read()
    # Convert image from RBG/BGR to HSV so we easily filter
    hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    # Use inRange to capture only the values between lower & upper_yellow
    mask = cv2.inRange(hsv_img, lower_yellow, upper_yellow)
    # Perform Bitwise AND on mask and our original frame
    res = cv2.bitwise_and(frame, frame, mask=mask)
    # Show mask and frame
    cv2.imshow('Original', frame)
    cv2.imshow('mask', mask)
    cv2.imshow('Filtered Color Only', res)
    # Exit when the Enter Key is pressed
    if cv2.waitKey(1) == 13:
        break

# destroy windows and release camera
cap.release()
cv2.destroyAllWindows()


Our Output frame will look like this: