In this tutorial, we will use an example to show you how to detect a color from an image in python opencv.
We will detect the green color in this example.
1.Read an image
import cv2 import numpy as np img = cv2.imread("pydetect.png")
2.Convert rgb image to hsv
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Here is an detailed tutorial:
Convert an Image to HSV Using Python OpenCV
3.Create a NumPy array for the lower green values and the upper green values
lower_green = np.array([34, 177, 76]) upper_green = np.array([255, 255, 255])
4.Use cv2.inRange() to get color mask
masking = cv2.inRange(hsv_img, lower_green, upper_green)
5.Get the masked image
cv2.imshow("Green Color detection", masking) cv2.waitKey(0)
If you want to save the resultant image, you can refer this tutorial: