Project
Function
Sample CLI
gway qr scan-img
Full Code
def scan_img(source):
"""
Scan the given image (file‑path or PIL.Image) for QR codes and return
a list of decoded string values. Returns [] if nothing’s found.
"""
import cv2
import numpy as np
# 1) Load image into an OpenCV BGR array
if isinstance(source, str):
img_bgr = cv2.imread(source)
if img_bgr is None:
raise FileNotFoundError(f"Could not open image file: {source}")
else:
# assume PIL.Image
pil_img = source
# convert to RGB array, then to BGR
rgb = np.array(pil_img)
img_bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
# 2) Detect & decode (multi‑code capable)
detector = cv2.QRCodeDetector()
# OpenCV ≥4.7 supports detectAndDecodeMulti:
try:
ok, decoded_texts, points, _ = detector.detectAndDecodeMulti(img_bgr)
if ok:
return [text for text in decoded_texts if text]
except AttributeError:
# fallback for older OpenCV: single‑code only
data, points, _ = detector.detectAndDecode(img_bgr)
return [data] if data else []
return []