Fix Python – Convert image from PIL to openCV format

Question

Asked By – md1hunox

I’m trying to convert image from PIL to OpenCV format. I’m using OpenCV 2.4.3.
here is what I’ve attempted till now.

>>> from PIL import Image
>>> import cv2 as cv
>>> pimg = Image.open('D:\\traffic.jpg')                           #PIL Image
>>> cimg = cv.cv.CreateImageHeader(pimg.size,cv.IPL_DEPTH_8U,3)    #CV Image
>>> cv.cv.SetData(cimg,pimg.tostring())
>>> cv.cv.NamedWindow('cimg')
>>> cv.cv.ShowImage('cimg',cimg)
>>> cv.cv.WaitKey()

But I think the image is not getting converted to CV format. The Window shows me a large brown image.
Where am I going wrong in Converting image from PIL to CV format?

Also , why do i need to type cv.cv to access functions?

Now we will see solution for issue: Convert image from PIL to openCV format


Answer

use this:

pil_image = PIL.Image.open('Image.jpg').convert('RGB') 
open_cv_image = numpy.array(pil_image) 
# Convert RGB to BGR 
open_cv_image = open_cv_image[:, :, ::-1].copy() 

This question is answered By – Abhishek Thakur

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0