Opencv Python 简明教程
OpenCV Python - Color Spaces
色彩空间是一个数学模型,描述了如何表示颜色。它在特定的、可测量的、固定的可能颜色和亮度值范围内描述了颜色。
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 支持以下知名的色彩空间 −
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 light 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 lightness, 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 支持使用 cv2.cvtColor() 函数在色域之间转换图像。
OpenCV supports conversion of image between color spaces with the help of cv2.cvtColor() function.
cv2.cvtColor() 函数的命令如下 −
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
以下程序显示了将原始图像从 RGB 色彩空间转换为 HSV 和 Gray 方案的过程 −
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)