Skip to main content

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!

Lesson 9 of 12

Module 4 Practice Project

Build a colour analysis tool that reports the dominant colours in an image and how much of the image each colour covers.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Colour Coverage Analyser

Colour Coverage Analyser
import cv2
import numpy as np

def analyse_colour_coverage(image_path):
    """Analyse what percentage of an image each colour covers."""
    image = cv2.imread(image_path)
    if image is None:
        print("Could not load image")
        return

    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    total = image.shape[0] * image.shape[1]

    colour_ranges = {
        "Red":    [(np.array([0,80,80]),   np.array([10,255,255])),
                   (np.array([160,80,80]), np.array([179,255,255]))],
        "Orange": [(np.array([10,80,80]),  np.array([20,255,255]))],
        "Yellow": [(np.array([20,80,80]),  np.array([35,255,255]))],
        "Green":  [(np.array([35,80,80]),  np.array([85,255,255]))],
        "Cyan":   [(np.array([85,80,80]),  np.array([100,255,255]))],
        "Blue":   [(np.array([100,80,80]), np.array([130,255,255]))],
        "Purple": [(np.array([130,80,80]), np.array([160,255,255]))],
    }

    print(f"=== Colour Coverage: {image_path} ===")
    print(f"Image size: {image.shape[1]}x{image.shape[0]} ({total:,} pixels)")
    print()

    results = []
    for colour, ranges in colour_ranges.items():
        mask = np.zeros(hsv.shape[:2], dtype=np.uint8)
        for lower, upper in ranges:
            mask |= cv2.inRange(hsv, lower, upper)
        pixels = cv2.countNonZero(mask)
        pct = pixels / total * 100
        results.append((colour, pixels, pct))

    results.sort(key=lambda x: x[2], reverse=True)
    for colour, pixels, pct in results:
        bar = "█" * int(pct / 2)
        print(f"  {colour:8s}: {pct:5.1f}% {bar}")

analyse_colour_coverage("your_photo.jpg")
Diagram
Loading diagram…

Machine Learning follows a structured pipeline from data to deployment

Key Takeaways from Module 4

  • HSV separates colour type (hue) from brightness (value), making it robust to lighting changes
  • OpenCV HSV ranges: Hue=0–179, Saturation=0–255, Value=0–255
  • cv2.inRange() creates a binary mask that selects pixels within an HSV range
  • Combine multiple HSV ranges with bitwise OR (|) to handle colours like red that wrap around the hue wheel
  • Use morphological operations (MORPH_OPEN, MORPH_CLOSE) to clean up noisy masks
  • Bilateral filter preserves edges while smoothing — use it when contours matter
  • Median blur is the best choice for removing salt-and-pepper noise

Key Takeaways

  • Build a colour analysis tool that reports the dominant colours in an image and how much of the image each colour covers.
  • HSV separates colour type (hue) from brightness (value), making it robust to lighting changes
  • OpenCV HSV ranges: Hue=0–179, Saturation=0–255, Value=0–255
  • cv2.inRange() creates a binary mask that selects pixels within an HSV range

Topics in This Module

0/12 done