Bar and QR Code Reader using Python
To create a bar and QR code reader using Python, we'll use the pyzbar library for decoding barcodes and QR codes and the opencv-python library for capturing and processing images.F
irst, you need to install the required libraries. Open your terminal or command prompt and run the following commands:
pip install pyzbar pip install opencv-python
Once the libraries are installed, you can use the following code:
import cv2 from pyzbar import pyzbar def read_barcodes(image): # Convert the image to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Use the pyzbar library to decode the barcodes barcodes = pyzbar.decode(gray) for barcode in barcodes: # Extract the barcode's bounding box coordinates and draw a rectangle around it (x, y, w, h) = barcode.rect cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) # Extract the barcode data and type from the barcode object barcode_data = barcode.data.decode("utf-8") barcode_type = barcode.type # Display the barcode data and type on the image text = "{} ({})".format(barcode_data, barcode_type) cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) # Print the barcode data and type print("Found {} barcode: {}".format(barcode_type, barcode_data)) # Display the image cv2.imshow("Barcode Reader", image) cv2.waitKey(0) # Open the camera for video capture cap = cv2.VideoCapture(0) while True: # Read a frame from the camera _, frame = cap.read() # Call the function to read barcodes in the frame read_barcodes(frame) # Break the loop if the 'q' key is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break # Release the camera cap.release() # Close all OpenCV windows cv2.destroyAllWindows()
Save the code in a Python file (e.g., barcode_reader.py), and then run it. It will open your computer's camera and start reading barcodes and QR codes in real-time. When a barcode or QR code is detected, it will draw a rectangle around it and display the decoded information on the image.
To stop the program, press the 'q' key.
Please note that you'll need a webcam or a camera connected to your computer to run this code.