"Python OpenCV image format conversion: RGB and BGR conversion" - in the process of using the OpenCV library for image processing, conversion between different formats is often required. The most common of these is R...

"Python OpenCV image format conversion: RGB and BGR conversion" - in the process of using the OpenCV library for image processing, it is often necessary to convert between different formats. The most common of these is the conversion between RGB and BGR formats. This article will detail how to use the opencv-python library to convert images from RGB format to BGR format and from BGR format to RGB format.

To realize the function of image format conversion, you first need to install the OpenCV library. After the installation is complete, we can use the cv2.cvtColor() method to complete the conversion between RGB and BGR formats.

An image in RGB format usually consists of three channels of red, green, and blue, and each pixel corresponds to the value of these three channels. The image in BGR format is composed of three channels of blue, green, and red, and each pixel corresponds to the value of these three channels. Therefore, when performing format conversion, we need to pay attention to the order of channels.

Next, we will introduce how to convert an image in RGB format to an image in BGR format, and how to convert an image in BGR format to an image in RGB format.

Convert an image in RGB format to an image in BGR format

code show as below:

import cv2

# 读取RGB格式的图片
img = cv2.imread("test.jpg")

# 将RGB格式的图像转换为BGR格式的图像
bgr_img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)

# 显示转换后的图像
cv2.imshow("BGR Image", bgr_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

In the above code, we first use the cv2.imread() method to read an image in RGB format and store it in the img variable. Next, we use the cv2.cvtColor() method to convert the image in RGB format stored in the img variable to an image in BGR format, and store the result in the bgr_img variable. Finally, we use cv2.im

Guess you like

Origin blog.csdn.net/update7/article/details/129801946