How to Make a Barcode Reader in Python?
Last Updated :
21 Mar, 2024
Barcode represents data in graphical representation and is machine-readable. For making Barcode Reader in Python we are using pyzbar library. Using pyzbar we can decode the one-dimensional barcode and QR code.
This pyzbar can return 3 fields based on the barcode object:
- Type: There are several kinds of barcodes available. Which are differentiated by unique code names like CODE-128, Code-11, CODE-39, etc. If the symbol detected by pyzabr then is QRcode for that type is QR-CODE.
- Data: This is data that is embedded inside the barcode. This data is of various kinds ( alphanumerical, numerical, binary, etc..) depending on the type of barcode.
- Location: This is the collection of points that are located in the code. For barcodes, these points are starting and ending line boundaries. and for QRcode, is a list of four points corresponding to the four corners of the QR code quad.
For installation:
pip install pyzbar
pip install opencv-python
pry bar Provides the rect method to locate the barcode in the image. Rect stands for a rectangle that will give you the coordinates of the barcode. We can also decode the multiple barcodes included in one image. Using the following steps we are going to make a barcode recorder. (ensure that you are having both libraries installed)
Approach:
- Import cv2.
- Import decode function from pyzbar
- Take the image from the user.
- Decode that image using pyzbar
- Locate the barcode in the given Image
- Print the data and type of image
- Display located barcode.
Below is the Implementation
Python3
import cv2
from pyzbar.pyzbar import decode
def BarcodeReader(image):
img = cv2.imread(image)
detectedBarcodes = decode(img)
if not detectedBarcodes:
print ( "Barcode Not Detected or your barcode is blank/corrupted!" )
else :
for barcode in detectedBarcodes:
(x, y, w, h) = barcode.rect
cv2.rectangle(img, (x - 10 , y - 10 ),
(x + w + 10 , y + h + 10 ),
( 255 , 0 , 0 ), 2 )
if barcode.data! = "":
print (barcode.data)
print (barcode. type )
cv2.imshow( "Image" , img)
cv2.waitKey( 0 )
cv2.destroyAllWindows()
if __name__ = = "__main__" :
image = "Img.jpg"
BarcodeReader(image)
|
Output:
b'GeeksForGeek-112021'
CODE128
Output
Share your thoughts in the comments
Please Login to comment...