Skip to content

Instantly share code, notes, and snippets.

@flyte
Last active July 19, 2017 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flyte/03cad1e7253e21b067ce3bd23f7a4b64 to your computer and use it in GitHub Desktop.
Save flyte/03cad1e7253e21b067ce3bd23f7a4b64 to your computer and use it in GitHub Desktop.
Scan barcodes in an image using zbar, cv2 and PIL/Pillow.
import zbar
import cv2
from PIL import Image
def scan_barcodes(img):
"""
Scan barcodes in image and return their data.
:param img: Source image
:type img: PIL.Image
:return: A list of barcode type/data tuples.
:rtype: list
"""
scanner = zbar.ImageScanner()
frame = img.convert("RGB")
gray = cv2.cvtColor(numpy.array(frame), cv2.COLOR_BGR2GRAY, dstCn=0)
pil = Image.fromarray(gray)
width, height = pil.size
zimg = zbar.Image(width, height, "Y800", pil.tobytes())
scanner.scan(zimg)
return [(s.type, s.data) for s in zimg]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment