Skip to content

Instantly share code, notes, and snippets.

@foemre
Last active October 5, 2018 14:24
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 foemre/4019efdd63cf3142579155fa4e33e3f2 to your computer and use it in GitHub Desktop.
Save foemre/4019efdd63cf3142579155fa4e33e3f2 to your computer and use it in GitHub Desktop.
A mashup of various code snippets for case-specific (Barcode and QR code scanning) use.
# Barcode and QR Code scanner
# Created by F.O.Emre Erdem
# A mashup of various code snippets for case-specific use.
# Sources:
# https://www.learnopencv.com/barcode-and-qr-code-scanner-using-zbar-and-opencv/
# https://www.pyimagesearch.com/2018/05/21/an-opencv-barcode-and-qr-code-scanner-with-zbar/
from __future__ import print_function
import pyzbar.pyzbar as pyzbar
import numpy as np
import cv2
import argparse
def decode(im) :
# Find barcodes and QR codes
decodedObjects = pyzbar.decode(im)
# Print results
for obj in decodedObjects:
print('Type : ', obj.type)
print('Data : ', obj.data,'\n')
return decodedObjects
# Display barcode and QR code location
def display(im, decodedObjects):
# Loop over all decoded objects
for decodedObject in decodedObjects:
points = decodedObject.polygon
# If the points do not form a quad, find convex hull
if len(points) > 4 :
hull = cv2.convexHull(np.array([point for point in points], dtype=np.float32))
hull = list(map(tuple, np.squeeze(hull)))
else :
hull = points;
# Number of points in the convex hull
n = len(hull)
qrData = decodedObject.data.decode("utf-8")
qrType = decodedObject.type
# Extremely sketchy way to take the top-leftmost point. ¯\_(ツ)_/¯
x=hull[0][0]
y=hull[0][1]
# draw the QR data and QR type on the image
text = "{} ({})".format(qrData, qrType)
cv2.putText(im, text, (x-20, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)
# Draw the convext hull
for j in range(0,n):
cv2.line(im, hull[j], hull[ (j+1) % n], (255,0,0), 3)
print(hull[j][1])
# Display results
cv2.imshow("Results", im);
cv2.waitKey(0);
# Main
if __name__ == '__main__':
# Read image
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to input image")
args = vars(ap.parse_args())
# load the input image
im = cv2.imread(args["image"])
decodedObjects = decode(im)
display(im, decodedObjects)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment