Python scanning QR code and barcodes script with demo.

Python scan QR code or barcodes script with a demo.

Python | scan QR code and barcodes using webcam or scanner machine. a complete script with demo.

Detect and decode barcodes and QR codes in an image using Python.

Step 1 : Install ZBar
pip install zbar
Step 2 : Install pyzbar
pip install pyzbar
Step 3 : Understand the complete Python script as below:
from import VideoStream
from pyzbar import pyzbar
import argparse
import datetime
import imutils
import time
import cv2

ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", type=str, default="barcodes.csv", help="path to output CSV file containing barcodes")
args = vars(ap.parse_args())

print("[INFO] starting video stream...")

vs = VideoStream(src=0).start()


csv = open(args["output"], "a") #a
found = set()

# loop over the frames from the video stream
while True:
  # grab the frame from the threaded video stream and resize it to
  # have a maximum width of 400 pixels
  frame =
  frame = imutils.resize(frame, width=400)

  cv2.line(frame, (85, 50), (100, 50), (255, 255, 255), 2)
  #cv2.line(frame, (100, 30), (100, 50), (255, 255, 255), 2)
  # find the barcodes in the frame and decode each of the barcodes
  barcodes = pyzbar.decode(frame)
  for barcode in barcodes:
    # extract the bounding box location of the barcode and draw
    # the bounding box surrounding the barcode on the image
    (x, y, w, h) = barcode.rect
    cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)

    # the barcode data is a bytes object so if we want to draw it
    # on our output image we need to convert it to a string first
    barcodeData ="utf-8")
    barcodeType = barcode.type

    # draw the barcode data and barcode type on the image
    text = "{} ({})".format(barcodeData, barcodeType)
    cv2.putText(frame, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

    # if the barcode text is currently not in our CSV file, write
    # the timestamp + barcode to disk and update the set
    if barcodeData not in found:
      csv.write("{},{}\n".format(, barcodeData))
  # show the output frame
  cv2.imshow("QR-Code Scanner", frame)
  key = cv2.waitKey(1) & 0xFF
  # if the `q` key was pressed, break from the loop
  if key == ord("q"):

# close the output CSV file do a bit of cleanup
print("[INFO] cleaning up...")

Any query? Please share your thoughts in the comments below. Glad to help you!

Was this page helpful? Do not forget to share this post!

Leave a Reply

Your email address will not be published. Required fields are marked *