Building a Barcode/QR code Reader using Python

Original article was published by Behic Guven on Artificial Intelligence on Medium

Decoding Function

In this step, we write the decoding function, where most of the cool things will be happening. The decoding function will be doing mainly three things, and can be listed as follows:

  • Recognizing and decoding the barcode/QR code that we will be showing to the camera.
  • Adding the stored information as a text on the recognized barcode/QR code.
  • And lastly, exporting the stored information as a text document.

Let’s import the libraries we installed before we write to the function:

#import librariesimport cv2
from pyzbar import pyzbar

Now, let’s write the function. Instead of adding part by part, I will share the whole function with you. Since, indentation matters when writing in python, I don’t want to disorganize things by ruining the structure of the code. I will add my comments below the code.

def read_barcodes(frame):
barcodes = pyzbar.decode(frame)
for barcode in barcodes:
x, y , w, h = barcode.rect
barcode_info ='utf-8')
cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)

cv2.putText(frame, barcode_info, (x + 6, y - 6), font, 2.0, (255, 255, 255), 1)
with open("barcode_result.txt", mode ='w') as file:
file.write("Recognized Barcode:" + barcode_info)
return frame

Understanding the function:

  • Firstly, we are decoding the information from the barcode or QR code. And then drawing a rectangle around it. This helps us to see if our machine has detected the barcode/Qr code.
  • Secondly, we are adding text on top of the rectangle that was created. The text will show the decoded information.
  • Thirdly, we are exporting the information into a text document. If you are planning to test with multiple barcodes or QR codes, I recommend changing the document name otherwise it will overwrite.