#Python – Convert an #OpenCV frame to PIL image and viceversa

Buy Me A Coffee

Hi !

It’s amazing how I can code and have fun for hours, and them suddenly spent 2 hours trying to manually do something, that it’s already resolved in all internet. Today’s challenge:

Convert an OpenCV frame to PIL image

And, why ? very simple, OpenCV follows the BGR convention and PIL follows RBG convention. So even, if the array have the same values, they are in different formats. So, here it goes both scenarios:

OpenCV image to PIL Image

# importing Image from PIL
img_tmp = cv2.cvtColor(img_openCV, cv2.COLOR_BGR2RGB)
im_PIL = Image.fromarray(img_tmp)

PIL Image to OpenCV Image

# using numpy
img_openCV = np.asarray(im_pil)

And, that’s it ! I’ll leave it here and I know I’ll save a couple of hours to myself in the near future.

Happy coding!

Greetings

El Bruno

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.