COLOR DETECTION USING OPENCV AND PYTHON

  • In this post, we are going to see how the colors are detected by the OpenCV module. 
  • The first step to get into this is just install the modules as I mentioned below and import the modules, then read the input image and convert the BGR (Blue, Green, Red) image to HSV (Hue, Saturation, Variance) image then find the lower and higher HSV value of the color which you want to detect from the HSV color map (Shown below), 
hsv color map
  • Then, we have to generate the mask of the color which we chose. So, we will use the cv2.inRange() function to generate the mask. Just pass the input image, lower HSV value higher HSV Value. This will generate a masked image of the input image and assign the masked image to the variable (mask).
  • To detect the color we have to use the cv2.bitwise_and() function and pass the input image as the first and second argument and the third argument will be the mask and store this in the variable (detected_image).
  • detected_image will be the final output of our program and just display using cv2.imshow() function.
  • In our case, we are going to detect the red and green color of the input image and the following code will be in detecting the red and green colors only.

Packages to install : 

  • pip install opencv-python
  • pip install numpy

Image used as input : 


Program : 

import cv2
import numpy as np

# reading the image
bgr_img = cv2.imread("images/rgb-intersection.png")
bgr_img = cv2.resize(bgr_img, (320, 240))

# converting BGR to HSV
hsv_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2HSV)

# function to add the
# mask of lower_1 & higher_1 hsv and mask of lower_2 & higher_2 hsv
# because the red has red color is divided into two parts in the HSV color map
def red_hsv():
# h -> 0->10
# s -> 175-255
# v -> 20-255 (variance is default for all colors)
lower_hsv_1 = np.array([0, 175, 20])
higher_hsv_1 = np.array([10, 255, 255])

# h -> 170-180
# s -> 175-255
# v -> 20-255 (variance is default for all colors)
lower_hsv_2 = np.array([170, 175, 20])
higher_hsv_2 = np.array([180, 255, 255])

mask_1 = cv2.inRange(hsv_img, lower_hsv_1, higher_hsv_1)
mask_2 = cv2.inRange(hsv_img, lower_hsv_2, higher_hsv_2)
return mask_1 + mask_2

# function to get the mask of the green color
def green_hsv():
# h -> 40-70
# s -> 150-255
# v -> 20-255
lower_hsv = np.array([40, 150, 20])
higher_hsv = np.array([70, 255, 255])

mask = cv2.inRange(hsv_img, lower_hsv, higher_hsv)
return mask

# adding red and green mask together to get the single mask
mask = red_hsv() + green_hsv()

detected_img = cv2.bitwise_and(bgr_img, bgr_img, mask=mask) # final output

cv2.imshow("Detected Image", detected_img)
cv2.waitKey(0)

Output Image :

Comments

Popular posts from this blog

MOTION DETECTION AND TRACKING USING OPENCV AND PYTHON

BASIC HAND TRACKING USING PYTHON

FACE DETECTION USING MEDIAPIPE AND PYTHON