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
| Color | Hue Range (H) | Saturation (S) | Value (V) |
|---|
| Red | 0-10, 170-180 | 50-255 | 50-255 |
| Orange | 10-25 | 50-255 | 50-255 |
| Yellow | 25-35 | 50-255 | 50-255 |
| Green | 35-85 | 50-255 | 50-255 |
| Blue | 100-130 | 50-255 | 50-255 |
| Purple | 130-160 | 50-255 | 50-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
| Function | Description |
|---|
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
| Conversion | Code |
|---|
| BGR to RGB | COLOR_BGR2RGB |
| BGR to Gray | COLOR_BGR2GRAY |
| BGR to HSV | COLOR_BGR2HSV |
| BGR to LAB | COLOR_BGR2LAB |
| HSV to BGR | COLOR_HSV2BGR |
| Gray to BGR | COLOR_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).