Python 3 Script to Make a Barcode Reader Using pyzbar and python-opencv library Full Project For Beginners

Python 3 Script to Make a Barcode Reader Using pyzbar and python-opencv library Full Project For Beginners

 

Welcome folks today in this post we will be making a barcode reader using python using the pyzbar and python-opencv library. All the source code of the application is given below.

 

 

 

Get Started

 

 

 

In order to get started we need to install python-opencv and pyzbar library by using the pip command

 

pip install pyzbar

 

pip install python-opencv

 

 

Now after that make an app.py file and copy paste the following code

 

app.py

 

 

from pyzbar import pyzbar
import cv2


def decode(image):
    # decodes all barcodes from an image
    decoded_objects = pyzbar.decode(image)
    for obj in decoded_objects:
        # draw the barcode
        print("detected barcode:", obj)
        image = draw_barcode(obj, image)
        # print barcode type & data
        print("Type:", obj.type)
        print("Data:", obj.data)
        print()

    return image


def draw_barcode(decoded, image):
    # n_points = len(decoded.polygon)
    # for i in range(n_points):
    #     image = cv2.line(image, decoded.polygon[i], decoded.polygon[(i+1) % n_points], color=(0, 255, 0), thickness=5)
    # uncomment above and comment below if you want to draw a polygon and not a rectangle
    image = cv2.rectangle(image, (decoded.rect.left, decoded.rect.top), 
                            (decoded.rect.left + decoded.rect.width, decoded.rect.top + decoded.rect.height),
                            color=(0, 255, 0),
                            thickness=5)
    return image


if __name__ == "__main__":
    from glob import glob

    barcodes = glob("barcode*.png")
    for barcode_file in barcodes:
        # load the image to opencv
        img = cv2.imread(barcode_file)
        # decode detected barcodes & get the image
        # that is drawn
        img = decode(img)
        # show the image
        cv2.imshow("img", img)
        cv2.waitKey(0)

 

See also  Python 3 PyGame 2048 Sliding Puzzle Game Script GUI Desktop App Full Project For Beginners

 

Now if you run this python app by typing the below command

 

python app.py

 

 

 

Leave a Reply