Skip to content

Instantly share code, notes, and snippets.

@pixelistik
Created May 20, 2012 12:13
Show Gist options
  • Save pixelistik/2757857 to your computer and use it in GitHub Desktop.
Save pixelistik/2757857 to your computer and use it in GitHub Desktop.
QRCODE recognition with zbar and PIL
def _decodeImage(self, imagePath):
"""
Get the QR code out of a given image file. This includes multiple
attempts at scanning and a helpless attempt to increase image quality.
"""
# obtain image data
pil = Image.open(imagePath).convert('L')
width, height = pil.size
# Resize to something reasonable, 512 px height
aspectRatio = float(width) / height
pil = pil.resize([int(aspectRatio * 512), 512])
width, height = pil.size
logging.debug("QR image opened, " + imagePath + ": " + repr(width) + "x" + repr(height))
resultTimecode = False
enhanceAttempt = 0
while enhanceAttempt < 10 and not resultTimecode:
try:
resultTimecode = self._scanForQrCode(pil)
except errors.NoQrTimecodeDetectedError:
# Fail? Make the image better!
# Enhance contrast
contrastEnhancer = ImageEnhance.Contrast(pil)
pil = contrastEnhancer.enhance(2.5)
# Blur some
pil = pil.filter(ImageFilter.BLUR)
enhanceAttempt += 1
#pil.show()
if not resultTimecode:
raise errors.NoQrTimecodeDetectedError("Gave up finding QR, enhancing didn't help")
return resultTimecode
def _scanForQrCode(self, pil):
"""
Scan for a QR code in a given PIL image
"""
width, height = pil.size
raw = pil.tostring()
# create a reader
scanner = zbar.ImageScanner()
# configure the reader
scanner.parse_config('enable')
# wrap image data
image = zbar.Image(width, height, 'Y800', raw)
# scan the image for barcodes
scanner.scan(image)
# extract results
resultTimecode = False
for symbol in image:
# look for a QRCODE result
logging.debug("zbar found a symbol, " + repr(symbol.type) + ": " + symbol.data)
if symbol.type == 64: # 64 -> QRCODE
resultTimecode = symbol.data
# Nothing found?
if not resultTimecode:
raise errors.NoQrTimecodeDetectedError("No QR code found")
# clean up
del(image)
return float(resultTimecode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment