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

QuantumRich picture QuantumRich · Nov 27, 2012 · Viewed 49.3k times · Source

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

Answer

s_kanawat picture s_kanawat · Aug 10, 2013

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()