Code: opencvImage = numpy.array(PILImage)
Suppose you have an image that has been manipulated with the Python Imaging Library, and you want to convert that image into a format that can be understood by the OpenCV Version 2 Library.
To do that, as of OpenCV v2, you can use the NumPy array as an intermediary format between the two libraries, where NumPy can convert PIL data into the NumPy array format, and OpenCV v2 can recognize the NumPy array natively.
To demonstrate this conversion, here's some code.
# First you need to import the libraries in question.
import numpy
import cv2
from PIL import Image
# And then you need a PIL image to work with, for now, an image from a local file is going to be used.
PILImage = Image.open("demo1.jpg")
demo1.jpg
# The conversion from PIL to OpenCV is done with the handy NumPy method "numpy.array" which converts the PIL image into a NumPy array.
opencvImage = numpy.array(PILImage)
# Display the OpenCV image using inbuilt methods.
cv2.imshow('Demo Image',opencvImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Which results in:
However, as you can see in the demonstration, the output OpenCV image turned a little weird, with the colour not matching the original PIL image (in the sense that the OpenCV image having the wrong colours). You can try this out for yourself...This is because we're dealing with a multi-channel/"RGB" format and not a single channel image file, and a conversion from PIL to OpenCV involves a little bit of additional translation, this can be solved with OpenCV's "cvtColor" method.
Code: opencvImage = cv2.cvtColor(numpy.array(PILImage), cv2.COLOR_RGB2BGR)
To demonstrate this additional translation, here's some code.
# First you need to import the libraries in question.
import numpy
import cv2
from PIL import Image
# And then you need a PIL image to work with, for now, an image from a local file is going to be used.
PILImage = Image.open("demo2.jpg")
demo2.jpg
# The conversion from PIL to OpenCV is done with the handy NumPy method "numpy.array" which converts the PIL image into a NumPy array.
# cv2.cvtColor does the trick for correcting the colour when converting between PIL and OpenCV Image formats via NumPy.
opencvImage = cv2.cvtColor(numpy.array(PILImage), cv2.COLOR_RGB2BGR)
# Display the OpenCV image using inbuilt methods.
cv2.imshow('Demo 2 Image',opencvImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Which results in:
And that's it!
Note that this post was made specifically for OpenCV v2, as documentation online were frustratingly for OpenCV v1, which has different methods and such.
As a disclaimer, things might change in a newer version of OpenCV, so this information is correct as of July 2015.
Covered Topics:
PIL to NumPy conversion
PIL to cv2 conversion
PIL to OpenCV conversion
Adaptors.PIL2Ipl alternative/replacement/not working
Creating an OpenCV image from a PIL image
Converting an OpenCV image into a PIL Image