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

ColorHue Range (H)Saturation (S)Value (V)
Red0-10, 170-18050-25550-255
Orange10-2550-25550-255
Yellow25-3550-25550-255
Green35-8550-25550-255
Blue100-13050-25550-255
Purple130-16050-25550-255
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

FunctionDescription
cvtColor()Convert image between color spaces
split()Split multi-channel image into separate channels
merge()Merge separate channels into multi-channel image
inRange()Create binary mask for pixels within specified range
threshold()Apply global threshold to grayscale image
adaptiveThreshold()Apply adaptive threshold for varying lighting

Common Color Space Codes

ConversionCode
BGR to RGBCOLOR_BGR2RGB
BGR to GrayCOLOR_BGR2GRAY
BGR to HSVCOLOR_BGR2HSV
BGR to LABCOLOR_BGR2LAB
HSV to BGRCOLOR_HSV2BGR
Gray to BGRCOLOR_GRAY2BGR
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).