Some color space conversions in OpenCV

In OpenCV, cv2.COLOR_ is a constant used to represent color space conversion. These constants define different color space conversion codes that can be used in image processing.

The following are some commonly used cv2.COLOR_ constants:

cv2.COLOR_BGR2GRAY: Convert BGR color image to grayscale image.
cv2.COLOR_BGR2RGB: Convert BGR color image to RGB color image.
cv2.COLOR_BGR2HSV: Convert BGR color images to HSV color space.
cv2.COLOR_BGR2Lab: Convert BGR color image to Lab color space.
cv2.COLOR_RGB2GRAY: Convert RGB color image to grayscale image.
cv2.COLOR_RGB2BGR: Convert RGB color image to BGR color image.
cv2.COLOR_RGB2HSV: Convert RGB color images to HSV color space.
cv2.COLOR_RGB2Lab: Convert RGB color image to Lab color space.
cv2.COLOR_GRAY2BGR: Convert grayscale image to BGR color image.
cv2.COLOR_GRAY2RGB: Convert grayscale image to RGB color image.
cv2.COLOR_HSV2BGR: Convert HSV color space image to BGR color image.
cv2.COLOR_HSV2RGB: Convert HSV color space image to RGB color image.

The specific implementation code and principle are as follows:

cv2.COLOR_BGR2GRAY
When converting a color image to grayscale using cv2.COLOR_BGR2GRAY in OpenCV, you can use the following code:

import cv2
# 读取彩色图像
image = cv2.imread('color_image.jpg')
# 将彩色图像转换为灰度图像
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 显示灰度图像
cv2.imshow('Gray Image', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Principle:
When using cv2.COLOR_BGR2GRAY to convert a color image to a grayscale image, it performs the conversion based on the principle of brightness perception. A grayscale image is a single-channel image in which the value of each pixel represents the brightness value of the pixel and does not contain color information. During the conversion process, the following mathematical formula is used to calculate the gray value of each pixel:
G ray = 0.299 × R + 0.587 × G + 0.114 × B Gray= 0.299\times R+0.587\times G+0.114\times BGray=0.299×R+0.587×G+0.114×BThis
formula is based on the human eye's perception weight of different colors, because the human eye is more sensitive to green and less sensitive to red and blue.
The specific steps are as follows:
Read the color image.
Iterate over each pixel of the image.
For each pixel, the grayscale value is calculated according to the above formula.
Assign the calculated grayscale value to the pixel at the corresponding position of the grayscale image.
The final grayscale image contains the brightness information of the image, but removes the color information.
In this way, with cv2.COLOR_BGR2GRAY, you can convert a color image into a grayscale image and focus more on the brightness features of the image.

cv2.COLOR_BGR2RGB
Here is a sample code to convert an image from BGR format to RGB format using OpenCV:

import cv2
# 读取图像
image_bgr = cv2.imread('input_image.jpg')
# 将图像从 BGR 格式转换为 RGB 格式
image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
# 显示原始图像和转换后的图像
cv2.imshow('Original Image', image_bgr)
cv2.imshow('RGB Image', image_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()

Principle:
In OpenCV, BGR (blue, green, and red) and RGB (red, green, and blue) are two commonly used image representation methods. BGR is the default image format of OpenCV, while RGB is the image format that people are generally more familiar with and commonly used.
In the conversion from BGR to RGB, the order of the color channels of each pixel will change, that is, the blue channel in the original image Blue BlueBlue and red channelRed RedRed performs an exchange and maintains the green channel Green GreenG ree n remains unchanged. This converts images from BGR format to RGB format.
The mathematical formula for conversion is as follows:
R _ new = B , G _ new = G , B _ new = RR\_new = B,G\_new = G,B\_new = RR_new=B,G_new=G,B_new=R
其中, R _ n e w = B 、 G _ n e w = G 、 B _ n e w = R R\_new = B、G\_new = G、B\_new = R R_new=BG_new=GB_new=R represents the pixel values ​​of the red, green and blue channels in the converted RGB image respectively. Through this conversion, we can process images in RGB format more conveniently, because the RGB format is more consistent with human perception and commonly used color representations.

cv2.COLOR_BGR2HSV
When converting a BGR image to an HSV image, you need to use OpenCV's cv2.cvtColor() function and set the conversion code to cv2.COLOR_BGR2HSV. Here's a more detailed code example:

import cv2
# 读取图像
bgr_image = cv2.imread('image.jpg')
# 将 BGR 图像转换为 HSV 图像
hsv_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2HSV)
# 显示原始图像和转换后的图像
cv2.imshow('BGR Image', bgr_image)
cv2.imshow('HSV Image', hsv_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

HSV is a color space where H stands for hue hueh u e , S represents saturationsaturations a t u r a t i o n , V represents brightnessvalue valuev a l u e . This is different from the BGR color space, which means that the colors in the image are composed of blueBlueB l u e、GreenGreenGreenGreen and redRed RedThe combination of R e d . In HSV space, the value of a color is represented by three parameters: hue (H), saturation (S), and brightness (V). HSV space is more consistent with human perception of color, so in some image processing tasks, it makes more sense to convert images to HSV space. Note that the range of pixel values ​​in the converted HSV image is different. The value range of H (hue) is [0, 179], and the value range of S (saturation) and V (lightness) is [0, 255]. Therefore, if you want to obtain or modify pixel values ​​in the converted image, you need to consider the limitations of these ranges.
Principle:
HSV (hue, saturation, brightness) is a color space. The BGR (blue, green, red) color space is converted into HSV color space through the following mathematical formula: 1. Normalized RGB values: Convert the BGR
image The pixel value of each channel is divided by 255, so that the value range of each channel is between [0, 1].
R ′ = R 255 , G ′ = G / 255 , B ′ = B / 255 R' = R255,G' = G /255,B' = B/255R=R 255 ,G=G/255,B=B /255 2. Calculate the maximum and minimum values: find the maximum value M ax Max
among the normalized RGB valuesM a x and the minimum valueM in MinMin
M a x = m a x ( R ′ , G ′ , B ′ ) , M i n = m i n ( R ′ , G ′ , B ′ ) Max = max(R', G', B'),Min = min(R', G', B') Max=max(R,G,B),Min=my ( R,G,B )
3. Calculate hue (H):
IfMax = M in Max=MinMax=M in , then the hueH = 0 H=0H=0 .
IfMax = R ′ Max=R'Max=R,且 G ′ > = B ′ G' >= B' G>=B , then the hueH = ( 60 ∗ ( G ′ − B ′ ) ) / ( M ax − M in ) + 0 H= (60 * (G' - B')) / (Max - Min)+0H=(60(GB))/(MaxMin)+0 .
IfMax = R ′ Max=R'Max=R,且 G ′ < B ′ G' < B' G<B , then the hueH = ( 60 ∗ ( G ′ − B ′ ) ) / ( M ax − M in ) + 360 H=(60 * (G' - B')) / (Max - Min) + 360H=(60(GB))/(MaxMin)+360 .
IfMax = G ′ Max=G'Max=G , then the hueH = ( 60 ∗ ( B ′ − R ′ ) ) / ( M ax − M in ) + 120 H=(60 * (B' - R')) / (Max - Min) + 120H=(60(BR))/(MaxMin)+120 .
IfMax = B ′ Max=B'Max=B , then the hueH = ( 60 ∗ ( R ′ − G ′ ) ) / ( M ax − M in ) + 240 H=(60 * (R' - G')) / (Max - Min) + 240H=(60(RG))/(MaxMin)+240 .
The value range of the hue H here is [0, 360].
4. Calculate saturation (S):
ifMax = 0 Max=0Max=0 , then the saturationS = 0 S=0S=0 .
IfMax! = 0 Max!=0Max!=0 , then the saturationS = ( M ax − M in ) / M ax S= (Max - Min) / MaxS=(MaxM in ) / M a x .
The value range of the saturation S here is [0, 1].
5. Calculate brightness (V): brightness V is Max.
The value range of the brightness V here is [0, 1].
With these formulas, pixel values ​​in the BGR color space can be converted into hue, saturation, and brightness values ​​in the HSV color space. This completes the color space conversion from BGR to HSV.

cv2.COLOR_BGR2Lab
Here is the code to convert an image from BGR color space to Lab color space using OpenCV:

import cv2
# 读取图像
image_bgr = cv2.imread('image.jpg')
# 将BGR图像转换为Lab图像
image_lab = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2Lab)
# 显示原始图像和转换后的图像
cv2.imshow('BGR Image', image_bgr)
cv2.imshow('lab Image', image_lab)
cv2.waitKey(0)
cv2.destroyAllWindows()

Lab color space is a color model that contains three components: brightness (L), red and green channels (a), and blue and yellow channels (b). By converting the image from BGR to Lab, the color information can be separated into two independent channels of brightness and color, which facilitates some image processing tasks.
The principle of converting an image from BGR color space to Lab color space involves multiple mathematical formulas and transformation matrices. The following is a mathematical formula explanation of this process:
First, we represent the three channels (blue, green, and red) in the BGR color space as vectors, denoted [B, G, R].
Then, we calculate the corresponding linear transformation through the following formula:
X = R / 255.0 , Y = G / 255.0 , Z = B / 255.0X=R/255.0,Y=G/255.0,Z=B /255.0
where X, Y and Z are values ​​normalized in RGB color space.
Next, we convert the RGB color space to the XYZ color space using the following matrix multiplication:

[ X ]     [ 0.412453  0.357580  0.180423 ]   [ R ]
[ Y ]  =  [ 0.212671  0.715160  0.072169 ] * [ G ]
[ Z ]     [ 0.019334  0.119193  0.950227 ]   [ B ]

Among them, the matrix on the left is the transformation matrix, and the vector on the right is the RGB normalized value.
Next, we calculate the L, a, and b components in the Lab color space through the following formula:

L = f(Y / Yn)
a = f((X / Xn) - (Y / Yn))
b = f((Y / Yn) - (Z / Zn))

These formulas describe the process of converting normalized XYZ values ​​into L, a, and b components in Lab color space.
The L component represents brightness. According to the formula L = f(Y / Yn), it is calculated by dividing the normalized Y value by Yn and applying a conversion function f. The conversion function f is a nonlinear function used to adjust the perception of brightness. It usually takes the form of a logarithmic function or other suitable mapping.
The a component represents the range from green to red. According to the formula a = f((X / Xn) - (Y / Yn)), it is calculated by dividing the normalized X value by Xn, dividing the normalized Y value by Yn, and then calculating the difference between the two. And apply the conversion function f to get it. This difference represents the offset of the red component relative to the reference white point.
The b component represents the range from blue to yellow. According to the formula b = f((Y / Yn) - (Z / Zn)), it is calculated by dividing the normalized Y value by Yn, dividing the normalized Z value by Zn, and then calculating the difference between the two. And apply the conversion function f to get it. This difference represents the offset of the yellow component relative to the reference white point.
Yn, Xn, and Zn in these formulas are white point reference values ​​in Lab color space, which are used to normalize XYZ values ​​to ensure consistency in color space conversion. The conversion function f can be chosen according to specific color space standards to meet the perceptual requirements for brightness and chromaticity. The specific implementation of these formulas can be achieved through functions in related programming libraries (such as OpenCV).

cv2.COLOR_GRAY2BGR
cv2.COLOR_GRAY2BGR is a color conversion code that converts grayscale images to BGR color images.

import cv2
# 读取灰度图像
gray_image = cv2.imread('gray_image.jpg', cv2.IMREAD_GRAYSCALE)
# 将灰度图像转换为 BGR 彩色图像
bgr_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2BGR)
# 显示 BGR 彩色图像
cv2.imshow('BGR Image', bgr_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

cv2.COLOR_GRAY2BGR is a color conversion that converts grayscale images to BGR color images. The following is the mathematical formula explanation of this color conversion:
Assume that the pixel value of the input grayscale image is G, and the pixel value of the BGR color image is (B, G, R).
Since grayscale images have only one channel, when converting to a BGR color image, each pixel value needs to be assigned the same value as the B, G, and R components. Therefore, the value of the G channel is copied to the B, G, and R channels during the conversion process, maintaining the consistency of the pixel values.
The mathematical formula is as follows:
B = G
G = G
R = G
This means that during the conversion process, the B, G and R values ​​of each pixel of the BGR color image are equal to the pixel values ​​of the input grayscale image.
Through this conversion process, a grayscale image can appear as a color image, but since the B, G, and R values ​​of each pixel are the same, the image looks grayscale without color effects.
This conversion is often used when color marking is done on a grayscale image or when the image needs to be converted to a color format during image processing.

cv2.COLOR_HSV2BGR

import cv2
import numpy as np
# 读取HSV彩色图像
hsv_image = cv2.imread('input_image.jpg', cv2.IMREAD_COLOR)
# 将HSV图像转换为BGR彩色图像
bgr_image = cv2.cvtColor(hsv_image, cv2.COLOR_HSV2BGR)
# 显示BGR彩色图像
cv2.imshow('BGR Image', bgr_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

HSV (Hue-Saturation-Value) is a commonly used color representation method, in which hue (Hue), saturation (Saturation) and brightness (Value) respectively represent different attributes of color. BGR (Blue-Green-Red) is a commonly used color image representation method in computers.
The cv2.COLOR_HSV2BGR function is used to convert HSV images to BGR images. The specific conversion process can be expressed by the following mathematical formula:
For an HSV image, assume that H is the hue, S is the saturation, and V is the brightness. For the corresponding BGR image, assume that B is the blue channel, G is the green channel, and R is the red channel.
During the conversion process, the normalization range and mapping relationship between HSV and BGR need to be considered.
Normalization range:
The range of H is [0, 360], converted to [0, 179], as the hue value of the BGR image.
The range of S is [0, 1], no conversion is required, and it is directly used as the saturation value of the BGR image.
The range of V is [0, 1], no conversion is required, and it is directly used as the brightness value of the BGR image.
Mapping relationship:
When converting H to the hue value of a BGR image, normalized mapping is required. The mapping relationship is: B = H * 2, G = H * 2 - 1, R = H * 2 - 2. Among them, the ranges of B, G, and R are [0, 255].
Saturation and brightness are directly used as the corresponding channel values ​​of the BGR image, ranging from [0, 255].
To sum up, the principle of cv2.COLOR_HSV2BGR is to convert each pixel of the HSV image according to the above mathematical formula to obtain the corresponding BGR image. This achieves color space conversion from HSV to BGR

Guess you like

Origin blog.csdn.net/qq_50993557/article/details/130714267