Objects can often be detected based on their color. By converting an image from BGR to HSV color space, OpenCV makes it easier to segment and detect colored objects. This technique is widely used in object tracking, ball detection, and robotics.
HSV (Hue, Saturation, Value) is preferred for color detection since it separates color information (hue) from intensity.
import cv2
import numpy as np
# Load image
img = cv2.imread("objects.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Define lower and upper ranges for the target color. Example: detecting red objects.
# Red color range lower_red = np.array([0, 120, 70]) upper_red = np.array([10, 255, 255])
Use cv2.inRange() to generate a binary mask where detected pixels are white (255).
mask = cv2.inRange(hsv, lower_red, upper_red)
cv2.imshow("Mask", mask)
Use cv2.bitwise_and() to highlight only the detected objects in the original image.
result = cv2.bitwise_and(img, img, mask=mask)
cv2.imshow("Detected Object", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
You can apply the same logic with cv2.VideoCapture() for live object detection using webcam.
✅ In this lesson, you learned how to detect objects using color spaces (HSV) in OpenCV.
This method is widely used in real-time tracking, robotics, and AR applications.
👉 Next, we will explore object tracking techniques (Meanshift & Camshift).
