How to detect object of particular color in OpenCV?

We can extract any color of image using color space and inRange function

Steps for extracting red color Image

1: Read input image

2: Convert image BGR to HSV

3: Then threshold the HSV image for a range of red color.

4: Now get the red image

import cv2
import numpy as np

img = cv2.imread("redimg.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

#lower red
lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])

#upper red
lower_red2 = np.array([170,50,50])
upper_red2 = np.array([180,255,255])

mask = cv2.inRange(hsv, lower_red, upper_red)
res = cv2.bitwise_and(img,img, mask= mask)


mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
res2 = cv2.bitwise_and(img,img, mask= mask2)

rose = res+res2



cv2.imshow('res3',rose)

cv2.waitKey(0)
cv2.destroyAllWindows()

Block Title

Orignal image

Rose extracted

Leave a Comment

Your email address will not be published. Required fields are marked *