Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Practical Color Detection
A practical colour detection system that finds and highlights objects of a specific colour in a real image.
10 min•By Priygop Team•Updated 2026
Complete Colour Detection System
Complete Colour Detection System
import cv2
import numpy as np
def colour_detector(image_path, target_colour="red"):
"""
Detects objects of a specific colour and draws bounding boxes.
Returns the processed image and detection count.
"""
image = cv2.imread(image_path)
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
colour_ranges = {
"red": [(np.array([0,100,100]), np.array([10,255,255])),
(np.array([160,100,100]), np.array([179,255,255]))],
"green": [(np.array([35,100,100]), np.array([85,255,255]))],
"blue": [(np.array([100,100,100]), np.array([130,255,255]))],
"yellow": [(np.array([20,100,100]), np.array([35,255,255]))],
}
colour_bgr = {"red": (0,0,255), "green": (0,255,0),
"blue": (255,0,0), "yellow": (0,255,255)}
# Build mask
mask = np.zeros(hsv.shape[:2], dtype=np.uint8)
for lower, upper in colour_ranges.get(target_colour, []):
mask |= cv2.inRange(hsv, lower, upper)
# Clean with morphology
k = np.ones((5, 5), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, k)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, k)
# Find contours of detected regions
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
result = image.copy()
detection_count = 0
for contour in contours:
area = cv2.contourArea(contour)
if area > 500: # Ignore tiny detections
x, y, w, h = cv2.boundingRect(contour)
color_bgr = colour_bgr.get(target_colour, (0,255,0))
cv2.rectangle(result, (x,y), (x+w, y+h), color_bgr, 2)
cv2.putText(result, f"{target_colour} ({area:.0f}px)",
(x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color_bgr, 1)
detection_count += 1
cv2.imwrite(f"detected_{target_colour}.jpg", result)
print(f"Found {detection_count} {target_colour} object(s)")
return result, detection_count
colour_detector("photo.jpg", "blue")Diagram
Loading diagram…
Machine Learning follows a structured pipeline from data to deployment