Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert openCV image into PIL Image in Python (for use with Zbar library)

I'm trying to use the Zbar library's QR code detection methods on images I extract with OpenCV's camera methods. Normally the QR code detection methods work with images (jpg, png, etc.) on my computer, but I guess the captured frames of OpenCV are different.
Is there a way of making the captured frame into a PIL Image?

Thank you.

from PIL import Image import zbar import cv2.cv as cv  capture = cv.CaptureFromCAM(1) imgSize = cv.GetSize(cv.QueryFrame(capture)) img = cv.QueryFrame(capture)  #SOMETHING GOES HERE TO TURN FRAME INTO IMAGE img = img.convert('L') width, height = img.size  scanner = zbar.ImageScanner() scanner.parse_config('enable') zbar_img = zbar.Image(width, height, 'Y800', img.tostring())  # scan the image for barcodes scanner.scan(zbar_img)  for symbol in zbar_img:     print symbol.data 
like image 749
QuantumRich Avatar asked Nov 27 '12 01:11

QuantumRich


People also ask

Does PIL use OpenCV?

OpenCV is written in C and C++ whereas PIL is written using Python and C, hence just from this information, OpenCV seems faster. While dealing with 1000s of images for data extraction, the processing speed 🚀 matters. Here is a quick comparison of these two libraries.

Which is better PIL or OpenCV?

OpenCV+albumentations is faster than PIL+torchvisiondata. DataLoader by using cv2. imread + albumentations, instead of PIL.

Is PIL image RGB or BGR?

The basic difference between OpenCV image and PIL image is OpenCV follows BGR color convention and PIL follows RGB color convention and the method of converting will be based on this difference.

Can OpenCV read PIL image?

Images reading from the PIL library gives error while operating in OpenCV. As OpenCV follows BGR color format and PIL follows RGB color format. Besides these, PIL uses integer division and on the other side, OpenCV uses float point percentages.


2 Answers

With the python CV2, you can also do this:

import Image, cv2  cap = cv2.VideoCapture(0) # says we capture an image from a webcam _,cv2_im = cap.read() cv2_im = cv2.cvtColor(cv2_im,cv2.COLOR_BGR2RGB) pil_im = Image.fromarray(cv2_im) pil_im.show() 
like image 119
s_kanawat Avatar answered Oct 05 '22 18:10

s_kanawat


I think I may have found the answer. I'll edit later with results.

OpenCV to PIL Image

import Image, cv cv_im = cv.CreateImage((320,200), cv.IPL_DEPTH_8U, 1) pi = Image.fromstring("L", cv.GetSize(cv_im), cv_im.tostring()) 

Source: http://opencv.willowgarage.com/documentation/python/cookbook.html

like image 35
QuantumRich Avatar answered Oct 05 '22 20:10

QuantumRich