Skip to main content

Overview

Color spaces are different ways of representing colors numerically. OpenCV supports numerous color space conversions through the cvtColor() function.

BGR Color Space

Default in OpenCV

OpenCV uses BGR (Blue-Green-Red) as its default color format:
Most other libraries (including matplotlib, PIL) use RGB order. Always convert when needed.

Common Color Spaces

RGB/BGR

Use case: Display, most common representation

Grayscale

Use case: Simplify processing, reduce computation

HSV (Hue-Saturation-Value)

Use case: Color-based segmentation, lighting-independent processing
  • Hue: Color type (0-179 in OpenCV)
  • Saturation: Color intensity (0-255)
  • Value: Brightness (0-255)

LAB (Lab*)

Use case: Perceptually uniform, skin detection
  • L: Lightness (0-100)
  • a: Green-Red axis
  • b: Blue-Yellow axis

YCrCb

Use case: Video compression, skin detection
  • Y: Luminance
  • Cr: Red-difference
  • Cb: Blue-difference

Color Conversion

Basic Conversion

Common Conversion Codes

FromToCode
BGRGrayCOLOR_BGR2GRAY
BGRRGBCOLOR_BGR2RGB
BGRHSVCOLOR_BGR2HSV
BGRLABCOLOR_BGR2Lab
BGRYCrCbCOLOR_BGR2YCrCb
HSVBGRCOLOR_HSV2BGR
GrayBGRCOLOR_GRAY2BGR

Practical Examples

Color Detection

Lighting Normalization

Skin Detection

Color Space Selection

HSV

  • Color-based segmentation
  • Lighting-independent tracking
  • Hue provides rotation invariance

LAB

  • Perceptually uniform
  • Separate luminance from color
  • Better for color difference calculations

YCrCb

  • Video compression
  • Skin detection
  • Chroma subsampling

Grayscale

  • Simplest representation
  • Fastest processing
  • Use when color not needed

Best Practices

Conversion Tips

  1. Minimize conversions: Convert once, cache result
  2. Choose appropriate space: Match algorithm requirements
  3. Remember value ranges: HSV hue is 0-179, not 0-255
  4. Consider precision: Use CV_32F for sensitive operations

Performance

See Also