Created
November 10, 2016 17:35
-
-
Save PM2Ring/ef4cd23f8bd7aa436c1009aa5744b59b to your computer and use it in GitHub Desktop.
Simple demo of using the Python 2 zbar module to decode QR codes / barcodes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
''' zbar demo | |
Handles local files and URLs | |
Not that PIL requires ImageMagick or GraphicsMagick to display images | |
Written by PM 2Ring 2016.11.11 | |
''' | |
import sys, urllib, io, zbar | |
from PIL import Image | |
def GetImage(fhandle, show=False): | |
# obtain image data | |
img = Image.open(fhandle).convert('L') | |
if show: | |
img.show() | |
# wrap raw image data into a zbar object | |
# image.data is a raw byte stream, i.e NO headers | |
width, height = img.size | |
raw = img.tobytes() | |
image = zbar.Image(width, height, 'Y800', raw) | |
return image | |
def Extract(scanner, image): | |
# scan the image for barcodes | |
scanner.scan(image) | |
# extract results | |
for symbol in image: | |
# do something useful with results | |
print 'Decoded', symbol.type, 'symbol', '"%s"' % symbol.data | |
def main(): | |
if len(sys.argv) < 2: | |
print 'QR / barcode decoder using zbar\nUsage %s URL ...' % sys.argv[0] | |
sys.exit() | |
# create a reader & configure it | |
scanner = zbar.ImageScanner() | |
scanner.parse_config('enable') | |
for url in sys.argv[1:]: | |
print url | |
fd = urllib.urlopen(url) | |
#Wrap it so that seek works | |
fhandle = io.BytesIO(fd.read()) | |
image = GetImage(fhandle, show=True) | |
Extract(scanner, image) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment