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.
JavaScript
x
9
1
>>> from PIL import Image
2
>>> import cv2 as cv
3
>>> pimg = Image.open('D:\traffic.jpg') #PIL Image
4
>>> cimg = cv.cv.CreateImageHeader(pimg.size,cv.IPL_DEPTH_8U,3) #CV Image
5
>>> cv.cv.SetData(cimg,pimg.tostring())
6
>>> cv.cv.NamedWindow('cimg')
7
>>> cv.cv.ShowImage('cimg',cimg)
8
>>> cv.cv.WaitKey()
9
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?
Advertisement
Answer
use this:
JavaScript
1
5
1
pil_image = PIL.Image.open('Image.jpg').convert('RGB')
2
open_cv_image = numpy.array(pil_image)
3
# Convert RGB to BGR
4
open_cv_image = open_cv_image[:, :, ::-1].copy()
5