lucians home

Barcode reader with Python, OpenCV and Pyzbar

Today we are gonna read a barcode (and QR code) with Python, OpenCV and the dedicated library Pyzbar.

First thing we do is install pyzbar using pip. So, open you CMD/Terminal and paste this:

pip install pyzbar

Once finished, oper your IDE (I am using PyCharm) and paste the next code into it:

from pyzbar.pyzbar import decode
import cv2
import numpy as np


def barcodeReader(image, bgr):
    gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    barcodes = decode(gray_img)

    for decodedObject in barcodes:
        points = decodedObject.polygon

        pts = np.array(points, np.int32)
        pts = pts.reshape((-1, 1, 2))
        cv2.polylines(image, [pts], True, (0, 255, 0), 3)

    for bc in barcodes:
        cv2.putText(frame, bc.data.decode("utf-8") + " - " + bc.type, (30, 30), cv2.FONT_HERSHEY_SIMPLEX, 1,
                    bgr, 2)

        return "Barcode: {} - Type: {}".format(bc.data.decode("utf-8"), bc.type)


bgr = (8, 70, 208)

cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    barcode = barcodeReader(frame, bgr)
    print(barcode)
    cv2.imshow('Barcode reader', frame)
    code = cv2.waitKey(10)
    if code == ord('q'):
        break

And now let’s go with the explanations.

First we import our modules: pyzbar, cv2 and numpy. Pyzbar is a module used to detect and read barcodes and QR codes.

Then we create a function barcodeReader() which have 2 parameters: the image we want to work with and a tuple of values which represents text color on display window.

Inside the function we are convert to gray the image and pass the result to the pyzbar decode() function. This decode datamatrix barcodes in image and return “human readable” values (the value of the barcode).

An example of decoded function output is this:

[Decoded(data=b'20769581', type='EAN8', rect=Rect(left=134, 
top=50, width=208, height=111), polygon=[Point(x=134, y=131), 
Point(x=134, y=161), Point(x=342, y=160), Point(x=342, y=124), 
Point(x=341, y=50), Point(x=243, y=50), Point(x=137, y=51), Point(x=136,
 y=75)])]

As you can see we have the result, barcode type and some coordinates points. With these last ones we can draw a ROI/bounding box around the barcode (first for loop).

barcode_roi

In the second for loop we compose the text which is going to be displayed on output window.

Outside barcodeReader we initialize cap variable with cv2.VideoCapture(0) function. This is going to use our webcam as input image.

Finally we are going to pass each frame the webcam will acquire to barcodeReader() and print the result in console.

To exit press “q”.

The same script works with QR code.

qrbarcode_roi

The possibilities of this are wide:

  • detect food barcodes and search for infos on Internet
  • create a personal DB and search for items by their barcode (maybe with a mobile version of barcode scanner)
  • tracking system – for example, you can scan hundreds of tracking number and then send them to an online tracking system