पाठ 3 / 26

Colour Spaces

RGB, BGR, grayscale and HSV.

Different coordinates for colour

RGB stores red, green and blue intensities. OpenCV loads images in BGR order by historical convention, so a mistaken order swaps red and blue. Grayscale keeps only brightness, often enough for shapes and text. HSV separates hue (colour), saturation (purity) and value (brightness), which makes colour-based selection more robust to lighting than raw RGB thresholds. LAB and YCrCb are other spaces used for perceptual differences and skin or compression tasks.

Converting colour spaces and masking by hue, run

I ran this on CPU with Python 3, OpenCV 5.0.0, scikit-image 0.26.0, PyTorch 2.14.1 and torchvision 0.29.1, using scikit-image's bundled sample photos and torchvision's published pretrained weights. The coffee photo converts from RGB to grayscale and HSV; a hue and saturation mask marks 70.1% of pixels as strongly red or orange (the photo is dominated by warm tones). The first pixel reads [21, 13, 8] in RGB and [8, 13, 21] in BGR order.

import cv2, numpy as np
from skimage import data
rgb = data.coffee()
gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV)
print("RGB", rgb.shape, "-> gray", gray.shape, "-> HSV", hsv.shape)
# select strongly red/orange pixels by hue and saturation (OpenCV hue range 0-179)
mask = ((hsv[..., 0] < 15) | (hsv[..., 0] > 165)) & (hsv[..., 1] > 120) & (hsv[..., 2] > 60)
print(f"share of strongly red/orange pixels: {mask.mean():.1%}")
bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
print("first pixel RGB", rgb[0, 0].tolist(), "vs same pixel in BGR order", bgr[0, 0].tolist())

Output:

RGB (400, 600, 3) -> gray (400, 600) -> HSV (400, 600, 3)
share of strongly red/orange pixels: 70.1%
first pixel RGB [21, 13, 8] vs same pixel in BGR order [8, 13, 21]

Convert BGR right after cv2.imread

If the rest of your pipeline expects RGB, convert immediately after loading with OpenCV and keep one convention everywhere.

त्वरित जाँच: Why is HSV useful for colour selection?

  • It removes all noise
  • It uses fewer pixels
  • It is the format neural networks require
  • It separates colour (hue) from brightness, so masks are more robust to lighting
Answer

It separates colour (hue) from brightness, so masks are more robust to lighting — Hue stays similar when brightness changes.