Convert BGR and RGB with Python, OpenCV (cvtColor)
When the image file is read with the OpenCV function
imread(), the order of colors is BGR (blue, green, red). On the other hand, in Pillow, the order of colors is assumed to be RGB (red, green, blue).
Therefore, if you want to use both the Pillow function and the OpenCV function, you need to convert BGR and RGB.
You can use the OpenCV function
cvtColor() or simply change the order of
This article describes the following contents.
- OpenCV is BGR, Pillow is RGB
- Convert BGR and RGB with OpenCV function
- Convert BGR and RGB without using
OpenCV is BGR, Pillow is RGB
When reading a color image file, OpenCV
imread() reads as a NumPy array
row (height) x column (width) x color (3). The order of color is BGR (blue, green, red).
The OpenCV function
imwrite() that saves an image assumes that the order of colors is BGR, so it is saved as a correct image.
import cv2 import numpy as np from PIL import Image im_cv = cv2.imread('data/src/lena.jpg') cv2.imwrite('data/dst/lena_bgr_cv.jpg', im_cv)
When performing image processing with Pillow, you can convert
ndarray to a
PIL.Image object with
Image.fromarray(), but in Pillow the color order assumes RGB (red, green, blue).
Therefore, if the
ndarray of the image read by OpenCV
imread() is converted to a
PIL.Image object and saved, the image with the wrong color is saved.
pil_img = Image.fromarray(im_cv) pil_img.save('data/dst/lena_bgr_pillow.jpg')
If you want to convert
PIL.Image objects to use both Pillow and OpenCV functions, you need to convert BGR and RGB.
Convert BGR and RGB with OpenCV function cvtColor()
Various color spaces such as RGB, BGR, HSV can be mutually converted using OpenCV function
dst = cv2.cvtColor(src, code)
Refer to the following document for the value to be specified for the parameter
cv2.COLOR_BGR2RGB, BGR is converted to RGB.
When converted to RGB, it will be saved as a correct image even if it is saved after being converted to a
im_rgb = cv2.cvtColor(im_cv, cv2.COLOR_BGR2RGB) Image.fromarray(im_rgb).save('data/dst/lena_rgb_pillow.jpg')
When converted to RGB and saved with OpenCV
imwrite(), it will be an incorrect color image.
code when converting from RGB to BGR is
cv2.COLOR_RGB2BGR. Use this when reading an image file as a
PIL.Image, convert it to
ndarray, and save it using OpenCV
im_pillow = np.array(Image.open('data/src/lena.jpg')) im_bgr = cv2.cvtColor(im_pillow, cv2.COLOR_RGB2BGR) cv2.imwrite('data/dst/lena_bgr_cv_2.jpg', im_bgr)
Convert BGR and RGB without using cvtColor()
Converting BGR and RGB can be realized without using
There are several ways, for example, as follows.
im_bgr = cv2.imread('data/src/lena.jpg') im_rgb = im_bgr[:, :, [2, 1, 0]] Image.fromarray(im_rgb).save('data/dst/lena_swap.jpg') im_rgb = im_bgr[:, :, ::-1] Image.fromarray(im_rgb).save('data/dst/lena_swap_2.jpg')