[Python OpenCV format conversion: RGB and BGR conversion]

[Python OpenCV format conversion: RGB and BGR conversion]

Color space conversion is an important issue in image processing. Among them, RGB and BGR are the two most common formats, and OpenCV is one of the most popular image processing libraries. In OpenCV, we can easily convert between RGB and BGR formats.

Here is a code example of how to convert RGB format to BGR format using Python OpenCV:

import cv2

img_rgb = cv2.imread('image.jpg', cv2.IMREAD_UNCHANGED)  # 读取RGB图像
img_bgr = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2BGR)  # 将RGB转换为BGR格式

cv2.imwrite('image_bgr.jpg', img_bgr)  # 保存BGR图像

In this code, we first use cv2.imread()the method to read an image in RGB format and store it in img_rgba variable. Next, we use cv2.cvtColor()the method img_rgbto convert from RGB format to BGR format and store it in img_bgra variable. Finally, we can use cv2.imwrite()the method to img_bgrsave the image file in BGR format.

Similarly, we can also convert images in BGR format to RGB format. Here is a code example of how to convert BGR format to RGB format using Python OpenCV:

import cv2

img_bgr = cv2.imread('image.jpg', cv2.IMREAD_UNCHANGED)  # 读取BGR图像
img_rgb = cv2.cvtColor(img_bgr, c

Guess you like

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