Skip to main content
This guide covers color space conversions between BGR, RGB, HSV, grayscale, and other formats, along with thresholding techniques for image segmentation.

Overview

Color spaces represent colors in different ways for various purposes:
  • BGR/RGB: Standard color representation for displays
  • HSV: Hue, Saturation, Value - intuitive for color filtering
  • Grayscale: Single channel intensity values
  • LAB: Perceptually uniform color space
  • YCrCb: Luminance and chrominance separation

BGR to RGB Conversion

OpenCV reads images in BGR format by default, but many libraries expect RGB.
OpenCV uses BGR format by default for historical reasons related to early camera standards. Always convert to RGB when interfacing with other libraries like Matplotlib, PIL, or TensorFlow.

BGR to Grayscale Conversion

Convert color images to grayscale for simplified processing.
You can also load images directly in grayscale using imread("image.jpg", IMREAD_GRAYSCALE) to skip the conversion step.

BGR to HSV Conversion

HSV (Hue, Saturation, Value) is ideal for color-based object detection and filtering.

Color Range Detection with HSV

Detect specific colors by defining HSV ranges.

Common HSV Color Ranges

In OpenCV, Hue values range from 0-179 (not 0-359) to fit in a single byte. Adjust your ranges accordingly.

Thresholding

Thresholding converts grayscale images to binary images by applying a threshold value.

Basic Thresholding

Adaptive Thresholding

Adaptive thresholding calculates different thresholds for different regions, useful for varying lighting conditions.

Other Color Space Conversions

Key Functions

Common Color Space Codes

For color-based object detection, HSV color space is generally more robust than BGR/RGB because it separates color information (Hue) from lighting conditions (Value).