You are currently viewing How to Build real-time OpenCV barcode reader or scanner using python
Output Window for How to Build real-time OpenCV barcode reader or scanner using python

How to Build real-time OpenCV barcode reader or scanner using python

Spread the love

In this article we will learn How to Build real-time OpenCV barcode reader or scanner using python so let’s see: The program is written in Python 3.7. Detailed source code is as follows:

Method 01)

We need to install all reuired Libraries

Pillow
pip install Pillow
OpenCV
pip install opencv-python
Pyzbar
# Windows OS version
pip install pyzbar

Decoding the Function

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 libraries
import 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
        #1
        barcode_info = barcode.data.decode('utf-8')
        cv2.rectangle(frame, (x, y),(x+w, y+h), (0, 255, 0), 2)
        
        #2
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, barcode_info, (x + 6, y - 6), font, 2.0, (255, 255, 255), 1)
        #3
        with open("barcode_result.txt", mode ='w') as file:
            file.write("Recognized Barcode:" + barcode_info)
    return frame

Main Function

The main function will turn on the video camera of the computer, and the then call the decoding function. Here is the code:
def main():
    #1
    camera = cv2.VideoCapture(0)
    ret, frame = camera.read()
    #2
    while ret:
        ret, frame = camera.read()
        frame = read_barcodes(frame)
        cv2.imshow('Barcode/QR code reader', frame)
        if cv2.waitKey(1) & 0xFF == 27:
            break
    #3
    camera.release()
    cv2.destroyAllWindows()
#4
if __name__ == '__main__':
    main()

Congrats ! We are done with the programming part

Barcode reader

Method 02 )

Importing necessary libraries

Importing necessary libraries
Importing necessary libraries

Defining function to scan barcodes

Defining function to scan barcodes
Defining function to scan barcodes

Here, pyzbar.decode() takes the input frame as an argument, and outputs the decoded barcode. scanBarcodes() also contains arguments like snap, barcodeList and log which are the frames, set containing unique barcodes, and log file respectively received from the main() function.

How to Build real-time OpenCV barcode reader or scanner using python
How to Build real-time OpenCV barcode reader or scanner using python

Now we iterate over the scanned barcodes, and perform the following functions:


● Store the barcode data & type in variables
● Store the bounding box locations in variables
● Draw the bounding box on the frame, with desired coordinates, color and thickness.
● Put text (barcode data & type) on the output frame
● Write every uniquely found barcode information to the log file & also print it. Finally add this barcode data to the set.

How to Build real-time OpenCV barcode reader or scanner using python
How to Build real-time OpenCV barcode reader or scanner using python

We choose our desired font and store it in the variable font. Similarly, we also store the barcode type and barcode data in the variables text1 and text2. The putText() in-built function of openCV is used to display text on the output frame. Syntax for this is

cv2.putText(frame, text, coordinates, font, fontScale, color, thickness)

We adjust the y coordinates in the two text variables, so as to display the barcode type above the bounding box and barcode data below the bounding box.

How to Build real-time OpenCV barcode reader or scanner using python
How to Build real-time OpenCV barcode reader or scanner using python

barcodeList is a set declared in the main() function, that gets reset on every run of the program. So, the above block first checks if the scanned barcode is unique. If it is unique, it then proceeds to write this barcode information (data & type) in the log file and also print it. Finally, this unique barcode data is added to the set barcodeList.
At last, this function returns snap (the output frame).

Main function to drive the program

In the main() function, we first start with the ArgumentParser() in-built function from the argparse library. The job of this block of the code is to parse the arguments from the command line (when the program is run) and extract the source of the video stream (like IP Camera, Computer Webcam, etc.) from the user.

In the first line, we initialize the ArgumentParser() object. Then, we add the necessary arguments along with its help clause. Next, we perform the actual parsing and store our required information (video source) in the args variable.

How to Build real-time OpenCV barcode reader or scanner using python
How to Build real-time OpenCV barcode reader or scanner using python

Finally, we check if the entered video source is 0 or 1 (for sources other than IP camera) and convert it into an integer.

How to Build real-time OpenCV barcode reader or scanner using python
How to Build real-time OpenCV barcode reader or scanner using python

Next, we declare a set barcodeList for storing unique barcodes. We print some message indicating the start of the program. Then initialize an object of the VideoCapture class to capture the video. Syntax for this is

var_name = cv2.VideoCapture(src)

where src is the source of the video stream, which we have already obtained by parsing the user’s command line arguments.

Now, we open a text file log.txt and write the session’s timestamp into it. This way the user will know the exact time when they last ran the program. Using the read() in-built function of OpenCV, we extract the frame and a variable ret which obtains the boolean return value from getting the frame.

How to Build real-time OpenCV barcode reader or scanner using python
How to Build real-time OpenCV barcode reader or scanner using python

While ret is true, we keep calling the scanBarcodes() function to detect barcodes. For each frame passed, the scanBarcodes() function returns the box-bounded output frame with barcode details. This process is repeated for all frames received from the video stream, until the user presses the ESC key.

Basically, the ASCII code for ESC is 27. So this block of code closes the log text file and breaks from this while loop when the ESC key is pressed. Then, we release the VideoCapture object and terminate the program.

How to Build real-time OpenCV barcode reader or scanner using python
How to Build real-time OpenCV barcode reader or scanner using python

Finally, this is the main() function call which basically triggers the start of the program.

How to Build real-time OpenCV barcode reader or scanner using python
How to Build real-time OpenCV barcode reader or scanner using python

Output Window for How to Build real-time OpenCV barcode reader or scanner using python

Output Window for How to Build real-time OpenCV barcode reader or scanner using python
Output Window for How to Build real-time OpenCV barcode reader or scanner using python

Summary :

In this article we saw How to Build real-time OpenCV barcode reader or scanner using python so about this article you have any query then free to ask me.

sachin Pagar

I am Mr. Sachin pagar Embedded software engineer, the founder of Sach Educational Support(Pythonslearning), a Passionate Educational Blogger and Author, who love to share the informative content on educational resources.

Leave a Reply