Skip to content

Instantly share code, notes, and snippets.

@yifeikong yifeikong/qrcode.py
Created Feb 23, 2018

Embed
What would you like to do?
import time
import logging
import zbar
from PIL import Image, ImageEnhance, ImageFilter
def timing(f):
def wrap(*args):
time1 = time.time()
ret = f(*args)
time2 = time.time()
print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
return ret
return wrap
@timing
def decode_image(image_path):
"""
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
img = Image.open(image_path).convert('L')
width, height = img.size
enhanceAttempt = 0
while enhanceAttempt < 10:
if scan(img):
return True
else:
img = enhance(img)
enhanceAttempt += 1
return False
@timing
def enhance(img):
# Fail? Make the image better!
# Enhance contrast
contrastEnhancer = ImageEnhance.Contrast(img)
img = contrastEnhancer.enhance(2.5)
# Blur some
#img = img.filter(ImageFilter.BLUR)
return img
@timing
def scan(img):
"""
Scan for a QR code in a given img image
"""
width, height = img.size
raw = img.tobytes()
# 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)
for symbol in image:
# look for a QRCODE result
if 'http' in symbol.data:
return True
return False
if __name__ == '__main__':
if decode_image('/Users/yifei/Downloads/qrcode.jpeg'):
print 'ok'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.