This Python script showcases a real-time QR code scanner utilizing OpenCV and the pyzbar
library for decoding QR codes from webcam video input. It highlights detected QR codes, prints the data on the console, and displays it in the video feed.
Key Features:
- Captures video from a webcam and decodes QR codes in real time.
- Draws a rectangle around detected QR codes and displays decoded data on the frame.
- Option to stop scanning after reading the first QR code.
- Includes user-friendly controls with a simple ‘ESC’ key exit
import cv2 from pyzbar.pyzbar import decode import numpy as np # Ensure numpy is imported # Initialize the webcam (camera 0 by default) cap = cv2.VideoCapture(0) print("Press 'ESC' to quit.") # Flag to control reading once qr_read = False while True: # Capture frame-by-frame ret, frame = cap.read() if not ret: print("Failed to capture frame.") break # Convert the frame to grayscale for better QR detection (optional) gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Decode the QR code(s) decoded_objects = decode(gray_frame) for obj in decoded_objects: if not qr_read: # Check if the QR code has already been read # Draw a rectangle around the QR code points = obj.polygon if len(points) == 4: pts = points else: pts = cv2.convexHull(np.array([point for point in points], dtype=np.float32)) cv2.polylines(frame, [np.int32(pts)], True, (0, 255, 0), 3) # Display the decoded QR code data on the frame qr_data = obj.data.decode('utf-8') print("QR Code Data:", qr_data) cv2.putText(frame, qr_data, (obj.rect.left, obj.rect.top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) # Set the flag to True after reading the QR code qr_read = True # You can break the loop here if you want to stop once a QR code is found break # Display the frame with QR code highlights cv2.imshow('QR Code Scanner', frame) # Check if the 'ESC' key is pressed to quit the application key = cv2.waitKey(1) & 0xFF if key == 27: # 27 is the ASCII code for the 'ESC' key print("Escape pressed, exiting...") break # Release the capture and close all OpenCV windows cap.release() cv2.destroyAllWindows()