Change Image from PIL to OpenCV format and vice-versa (Python)

Hello Dear Programmers,

OpenCV and PIL are the two most common libraries in Python to deal with images. 

Therefore, while working on an image processing project, you might have felt the need of converting your image from PIL to OpenCV format and vice-versa

So, here I am providing the code snippet to do that for all who are looking for it.




To convert from PIL to OpenCV, use:

import cv2
import numpy as np
from PIL import Image

pil_image=Image.open("demo2.jpg") # open image using PIL

# use numpy to convert the pil_image into a numpy array
numpy_image=numpy.array(pil_img)  

# convert to a openCV2 image, notice the COLOR_RGB2BGR which means that 
# the color is converted from RGB to BGR format
opencv_image=cv2.cvtColor(numpy_image, cv2.COLOR_RGB2BGR) 

To convert from OpenCV to PIL, use:

import cv2
import numpy as np
from PIL import Image

opencv_image=cv2.imread("demo2.jpg") # open image using openCV2

# convert from openCV2 to PIL. Notice the COLOR_BGR2RGB which means that 
# the color is converted from BGR to RGB
color_coverted = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB)
pil_image=Image.fromarray(color_coverted)

 I hope it helped you with your project. Please let me know if it did. Thanks.

Buy Me a Coffee - https://www.buymeacoffee.com/agautam

Comments