Detecting specific colors is a common task in computer vision. OpenCV allows you to detect colors by converting images into the HSV color space and applying masks. This technique is widely used in object tracking, lane detection, and AR applications.
Since RGB is not ideal for color segmentation, we convert the image to HSV (Hue, Saturation, Value).
import cv2
import numpy as np
img = cv2.imread("objects.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Define lower and upper HSV ranges for the color you want to detect. Example: detecting the color blue.
# Blue color range lower_blue = np.array([100, 150, 0]) upper_blue = np.array([140, 255, 255])
Use cv2.inRange() to create a binary mask where the detected color appears white.
mask = cv2.inRange(hsv, lower_blue, upper_blue)
cv2.imshow("Mask", mask)
Finally, apply the mask on the original image using cv2.bitwise_and().
result = cv2.bitwise_and(img, img, mask=mask)
cv2.imshow("Color Detection Result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
✅ In this lesson, you learned how to perform color detection and masking in OpenCV.
By converting an image to HSV, creating a mask, and applying it, you can isolate specific colors.
👉 Next, we will study image histograms and histogram equalization.
