You are currently viewing How to convert image from PIL format to OpenCV format

How to convert image from PIL format to OpenCV format

If you want to use any OpenCV operations on an image that has been read in the Pillow library, then you got an error. Because OpenCV and PIL read images in different formats. OpenCV read images in BGR format and PIL read them in RGB format.

Here is a solution, follow these steps

  1. Open image in PIL
  2. Convert the image into numpy array
  3. Convert the numpy array into openCV image
  4. Use OpenCV color conversion code cv2.COLOR_RGB2BGR which will convert RGB color arrangement to BGR.

Note: RGB and BGR both stand for Red (R), Green (G), and Blue (B) color but with different arrangments.

import cv2
import numpy as np
from PIL import Image
PillowImage ="DemoImage.png")
NumpyImage = np.array(PillowImage)  
OpenCVImage = cv2.cvtColor(NumpyImage, cv2.COLOR_RGB2BGR)

Convert image from OpenCV to PIL format

If you want to perform an image processing operation using Pillow library and the image has been read using OpenCV library. Then you first need to convert the image from BGR to RGB format using OpenCV function cv2.COLOR_BGR2RGB.

import cv2
from PIL import Image
OpenCVImage = cv2.imread("DemoImage.png")
ColorConvertImage = cv2.cvtColor(OpenCVImage, cv2.COLOR_BGR2RGB)
PillowImage = Image.fromarray(ColorConvertImage)

Check out more blog posts:

Top 7 Free Image Annotation Tools for Computer Vision

How to Install Python/Anaconda/Jupyter Notebook/Spyder on Ubuntu (Linux)

Leave a Reply