कोड में QR Code पढ़ना और डिकोड करना
Programmatic QR code reading: zbar, pyzbar, jsQR, and OpenCV. Camera integration, batch processing, and error handling.
QR Code Reading and Decoding in Code
Programmatic QR code reading enables batch processing, automated workflows, and custom scanning applications.
Python: pyzbar
from pyzbar.pyzbar import decode
from PIL import Image
image = Image.open("qrcode.png")
results = decode(image)
for result in results:
print(result.data.decode("utf-8"))
print(f"Type: {result.type}, Rect: {result.rect}")
pyzbar wraps the ZBar library — fast and reliable for static image decoding.
Python: OpenCV + pyzbar
For camera-based scanning:
import cv2
from pyzbar.pyzbar import decode
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
codes = decode(frame)
for code in codes:
data = code.data.decode("utf-8")
print(f"Decoded: {data}")
JavaScript: jsQR
Browser-based decoding from Canvas image data:
const imageData = context.getImageData(0, 0, width, height);
const code = jsQR(imageData.data, width, height);
if (code) {
console.log("Decoded:", code.data);
}
Batch Processing
For processing thousands of QR code images:
import os
from pyzbar.pyzbar import decode
from PIL import Image
results = {}
for filename in os.listdir("qr_images/"):
if filename.endswith(".png"):
image = Image.open(f"qr_images/{filename}")
codes = decode(image)
results[filename] = [c.data.decode("utf-8") for c in codes]
Error Handling
QR code reading can fail for multiple reasons:
- Image quality too low — increase resolution or preprocessing
- QR code too small in the image — crop or zoom
- Multiple QR codes in one image — most libraries return all found codes
- Damaged or partially obscured — error correction limits apply
Preprocessing for Better Results
- Convert to greyscale before decoding
- Apply adaptive thresholding for uneven lighting
- Increase contrast for faded or low-contrast codes
- Sharpen blurry images before attempting decode
Key Takeaways
- pyzbar (Python) wraps ZBar for fast, reliable static image decoding
- OpenCV + pyzbar enables real-time camera-based scanning in Python
- jsQR provides browser-based decoding from Canvas image data
- Batch processing scripts can decode thousands of QR images
- Image preprocessing (greyscale, contrast, sharpening) improves decode success