In some cases, you may need to convert a Pillow (PIL) image to an OpenCV image to take advantage of the advanced image processing and computer vision features provided by OpenCV. Fortunately, this conversion process is pretty straightforward. 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 PIL image module. Next, we convert the PIL image to a NumPy array because OpenCV operates on arrays in the NumPy format. OpenCV uses BGR as its default color space, while PIL uses RGB. So, we convert the color space of the loaded image from RGB to BGR. That's it, now OpenCV image object can be used for further image processing tasks.
import cv2
from PIL import Image
import numpy as np
pilImg = Image.open('test.jpg')
arrImg = np.array(pilImg)
cvImg = cv2.cvtColor(arrImg, cv2.COLOR_RGB2BGR)
Leave a Comment
Cancel reply