There may be scenarios where you need to convert an OpenCV image to a Pillow (PIL) image, for example, when you need to pass an image to a function that only accepts PIL images. Luckily, this conversion process is pretty simple. This tutorial shows how to do that using Python.
Prepare environment
- Install the following packages using
pip
:
pip install Pillow
pip install opencv-python
Code
In the following code, we load the image using the OpenCV. OpenCV uses BGR as its default color space, while PIL uses RGB. So, we convert the color space of the loaded image from BGR to RGB. OpenCV image is represented in the NumPy array. So finally, we create the PIL image from the NumPy array. That's it, now PIL image object can be used with functions that accept PIL images.
import cv2
from PIL import Image
cvImg = cv2.imread('test.jpg')
cvImg = cv2.cvtColor(cvImg, cv2.COLOR_BGR2RGB)
pilImg = Image.fromarray(cvImg)
Leave a Comment
Cancel reply