OpenCV and Pillow color code order difference, BGR vs RGB


We can use opencv to read in a video, and extract each frame as an image. Then we can use Python Image Library to further analyze or edit
the image. But when you open the image, you might find it the color seems totally wrong.

This is just because opencv and Python Image Library (PIL) use different order of color code. The order in opencv is BGR, while in PIL it’s RGB. Fortunately, it’s easy to correct it as you will find in the following example

Read a short video of Robin bird using opencv

import cv2
vidcap = cv2.VideoCapture('robin.mp4')

success = True
count = 0
while success and count<100:
success,image = vidcap.read()
count += 1


# we got the 100th frame in the video as an image array


Now we use PIL to view the image, and find the Robin in blue color. If you checked the original video, or you have seen a Robin before,
you know there is something wrong.

from PIL import Image

display(Image.fromarray(image))

Switch from BGR to RGB using opencv

image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

Now we get the correct image of Robin, much better!

display(Image.fromarray(image_rgb))

https://github.com/robotlearner001/blog/blob/main/opencv-and-pillow-color-order-difference/2022-09-20-opencv-and-pillow-channel-difference.ipynb


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC