A Python library for detecting and processing QR codes and Data Matrix codes using a Raspberry Pi camera.
This library provides a simple and robust interface for real-time code detection on Raspberry Pi systems equipped with a camera. It supports multiple detection modes, thread-safe operation, and comprehensive error handling.
- QR Code detection using the pyzbar library
- Data Matrix detection using the pylibdmtx library
- Multiple detection modes:
- Single: Detect one code, then wait for it to be removed
- Continuous: Detect codes continuously
- Triggered: Only detect when explicitly triggered
- Adaptive image processing for better detection in various lighting conditions
- Thread-safe operation with proper resource management
- Comprehensive logging for debugging and monitoring
- Simple callback mechanism for detection events
- Terminal application for testing and demonstration
- Raspberry Pi with camera module
- Python 3.6+
- libcamera and picamera2 (Raspberry Pi camera interface)
- OpenCV for image processing
- pyzbar for QR code detection
- pylibdmtx for Data Matrix code detection
- Install system dependencies:
# For Raspberry Pi OS
sudo apt-get update
sudo apt-get install -y python3-pip python3-opencv libzbar0 libdmtx0a- Install Python dependencies:
pip install -r requirements.txtfrom code_scanner import CodeScanner, DetectionMode
import time
# Define callback function
def on_code_detected(code_info):
if code_info is None:
print("Code removed")
else:
print(f"Detected {code_info.type} code: {code_info.data}")
print(f"Position: {code_info.rect}")
# Create scanner
scanner = CodeScanner()
# Start scanner in single mode
scanner.set_mode(DetectionMode.SINGLE)
scanner.start(on_code_detected)
try:
# Application logic
print("Waiting for codes...")
time.sleep(60) # Run for 60 seconds
finally:
# Clean up resources
scanner.stop()# Single mode: Detect one code, wait for removal, then detect next
scanner.set_mode(DetectionMode.SINGLE)
# Continuous mode: Continuously detect all codes
scanner.set_mode(DetectionMode.CONTINUOUS)
# Triggered mode: Only scan when explicitly triggered
scanner.set_mode(DetectionMode.TRIGGERED)
scanner.trigger_scan() # Manually trigger a scanThe library includes a simple terminal application (scanner_app.py) for testing and demonstration:
# Run the terminal application
python scanner_app.pyThe main class for code detection.
__init__(logger=None): Initialize the scanner with optional custom loggerstart(code_callback=None): Start code scanning with optional callbackstop(): Stop scanning and release resourcesset_mode(mode): Set the detection modetrigger_scan(): Manually trigger a scan (for TRIGGERED mode)
DetectionMode.SINGLE: Detect one code, then wait for removalDetectionMode.CONTINUOUS: Continuously detect all codesDetectionMode.TRIGGERED: Only scan when manually triggered
Contains information about a detected code.
data: The decoded content of the codetype: Type of code ('qr' or 'datamatrix')rect: Rectangle coordinates (x, y, width, height)points: Polygon points (corners) of the code if availabletimestamp: Time when the code was detected
-
Camera not available
- Ensure the Raspberry Pi camera is enabled in raspi-config
- Check camera cable connection
- Verify picamera2 is installed properly
-
Poor detection quality
- Improve lighting conditions
- Ensure code is within camera view and not blurry
- Try adjusting camera position or distance
-
Missing dependencies
- Ensure all required libraries are installed
- Check if libzbar0 and libdmtx0a system packages are installed
To enable detailed logging for troubleshooting:
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("code_scanner_app")
scanner = CodeScanner(logger=logger)For better detection performance:
- Position the camera 10-20 cm from the codes for optimal resolution
- Ensure good, even lighting (avoid glare and shadows)
- Use higher contrast codes when possible (black on white)
- Adjust camera resolution for better performance:
# Modify in code_scanner.py CAMERA_RESOLUTION = (640, 480) # Higher resolution for better detection
Contributions are welcome! Please feel free to submit a Pull Request.