English 中文(简体)
OpenCV Python - Color Spaces
  • 时间:2024-11-03

OpenCV Python - Color Spaces


Previous Page Next Page  

A color space is a mathematical model describing how colours can be represented. It is described in a specific, measurable, and fixed range of possible colors and luminance values.

OpenCV supports following well known color spaces −

    RGB Color space − It is an additive color space. A color value is obtained by combination of red, green and blue colour values. Each is represented by a number ranging between 0 to 255.

    HSV color space − H, S and V stand for Hue, Saturation and Value. This is an alternative color model to RGB. This model is supposed to be closer to the way a human eye perceives any colour. Hue value is between 0 to 179, whereas S and V numbers are between 0 to 255.

    CMYK color space − In contrast to RGB, CMYK is a subtractive color model. The alphabets stand for Cyan, Magenta, Yellow and Black. White pght minus red leaves cyan, green subtracted from white leaves magenta, and white minus blue returns yellow. All the values are represented on the scale of 0 to 100 %.

    CIELAB color space − The LAB color space has three components which are L for pghtness, A color components ranging from Green to Magenta and B for components from Blue to Yellow.

    YCrCb color space − Here, Cr stands for R-Y and Cb stands for B-Y. This helps in separation of luminance from chrominance into different channels.

OpenCV supports conversion of image between color spaces with the help of cv2.cvtColor() function.

The command for the cv2.cvtColor() function is as follows −


cv.cvtColor(src, code, dst)

Conversion Codes

The conversion is governed by following predefined conversion codes.

Sr.No. Conversion Code & Function
1

cv.COLOR_BGR2BGRA

Add alpha channel to RGB or BGR image.

2

cv.COLOR_BGRA2BGR

Remove alpha channel from RGB or BGR image.

3

cv.COLOR_BGR2GRAY

Convert between RGB/BGR and grayscale.

4

cv.COLOR_BGR2YCrCb

Convert RGB/BGR to luma-chroma

5

cv.COLOR_BGR2HSV

Convert RGB/BGR to HSV

6

cv.COLOR_BGR2Lab

Convert RGB/BGR to CIE Lab

7

cv.COLOR_HSV2BGR

Backward conversions HSV to RGB/BGR

Example

Following program shows the conversion of original image with RGB color space to HSV and Gray schemes −


import cv2
img = cv2.imread( messi.jpg )
img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY )
img2 = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
# Displaying the image
cv2.imshow( original , img)
cv2.imshow( Gray , img1)
cv2.imshow( HSV , img2)

Output

RGB Color Space

RGB Color Space

RGB Color Space Advertisements