- Scan the photo viewfinder with OpenCV's QR detectors (aruco, then plain), off the preview thread, not while recording or in the gallery - A card shows the code's text: Open for web links, Join for Wi-Fi codes (NetworkManager over D-Bus), Copy; nothing happens before a tap - QR pill turns scanning off Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2f404ced5c
commit
e2ba41acca
4 files changed
+386
-1
No files matched your search
@@ -18,6 +18,7 @@ import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
os.environ.setdefault("LIBCAMERA_LOG_LEVELS", "*:ERROR")
|
||||
|
||||
@@ -1189,6 +1190,73 @@ def set_flash_led(on, brightness=96):
|
||||
return False
|
||||
|
||||
|
||||
class QRScanner:
|
||||
"""Reads QR codes from viewfinder frames with OpenCV's own detectors (no extra packages)."""
|
||||
|
||||
MAX_DIM = 800
|
||||
|
||||
def __init__(self, cv2_mod=None):
|
||||
if cv2_mod is None:
|
||||
import cv2 as cv2_mod
|
||||
self.cv2 = cv2_mod
|
||||
# The aruco detector reads small and tilted codes the plain one misses; the plain one does
|
||||
# better on dim ones.
|
||||
self._detectors = []
|
||||
for name in ("QRCodeDetectorAruco", "QRCodeDetector"):
|
||||
if hasattr(cv2_mod, name):
|
||||
self._detectors.append(getattr(cv2_mod, name)())
|
||||
self._centre = False
|
||||
|
||||
def _view(self, bgr):
|
||||
"""Gray view to scan: the whole frame, or every other time its middle at finer scale."""
|
||||
h, w = bgr.shape[:2]
|
||||
if self._centre:
|
||||
bgr = bgr[h // 4:h - h // 4, w // 4:w - w // 4]
|
||||
h, w = bgr.shape[:2]
|
||||
self._centre = not self._centre
|
||||
scale = self.MAX_DIM / float(max(h, w))
|
||||
if scale < 1.0:
|
||||
size = (max(1, int(w * scale)), max(1, int(h * scale)))
|
||||
bgr = self.cv2.resize(bgr, size, interpolation=self.cv2.INTER_AREA)
|
||||
return self.cv2.cvtColor(bgr, self.cv2.COLOR_BGR2GRAY)
|
||||
|
||||
def scan(self, bgr):
|
||||
"""The text of a QR code in `bgr`, or ""."""
|
||||
gray = self._view(bgr)
|
||||
for det in self._detectors:
|
||||
try:
|
||||
text, _, _ = det.detectAndDecode(gray)
|
||||
except (self.cv2.error, UnicodeDecodeError):
|
||||
continue
|
||||
text = text.replace("\0", "").strip()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
class QRReporter:
|
||||
"""Says when a scan result is news: a new code, or one that had been out of view a while."""
|
||||
|
||||
FORGET_S = 3.0
|
||||
|
||||
def __init__(self):
|
||||
self._text = ""
|
||||
self._seen = 0.0
|
||||
|
||||
def update(self, text, now):
|
||||
if not text:
|
||||
return False
|
||||
news = text != self._text or now - self._seen > self.FORGET_S
|
||||
self._text = text
|
||||
self._seen = now
|
||||
return news
|
||||
|
||||
|
||||
def qr_line(text):
|
||||
"""The worker protocol line for a scanned text (percent-encoded: it may hold anything)."""
|
||||
return "qr " + urllib.parse.quote(text, safe="")
|
||||
|
||||
|
||||
def ensure_even_frame(bgr):
|
||||
"""Crop at most 1 pixel from bottom/right edge so width and height are even for H.264."""
|
||||
h, w = bgr.shape[:2]
|
||||
@@ -2331,6 +2399,28 @@ def run_worker(cameras, initial_index):
|
||||
preview_thread = threading.Thread(target=preview_loop, name="chandra-cam-preview", daemon=True)
|
||||
preview_thread.start()
|
||||
|
||||
qr_on = threading.Event()
|
||||
|
||||
def qr_loop():
|
||||
scanner = QRScanner(cv2)
|
||||
reporter = QRReporter()
|
||||
last_seq = -1
|
||||
while not stop_flag.wait(0.2):
|
||||
eng = engine_holder[0]
|
||||
if eng is None or not qr_on.is_set() or eng.is_recording():
|
||||
continue
|
||||
frame, seq = eng.latest_frame()
|
||||
if frame is None or seq == last_seq:
|
||||
continue
|
||||
last_seq = seq
|
||||
text = scanner.scan(frame)
|
||||
# Switched off while scanning: the result is no longer wanted.
|
||||
if qr_on.is_set() and reporter.update(text, time.monotonic()):
|
||||
emit(qr_line(text))
|
||||
|
||||
qr_thread = threading.Thread(target=qr_loop, name="chandra-cam-qr", daemon=True)
|
||||
qr_thread.start()
|
||||
|
||||
def on_frame():
|
||||
if stop_flag.is_set():
|
||||
return
|
||||
@@ -2392,6 +2482,10 @@ def run_worker(cameras, initial_index):
|
||||
if cmd == "switch":
|
||||
set_flash_led(False)
|
||||
engine.cycle_camera()
|
||||
elif cmd == "qr 1":
|
||||
qr_on.set()
|
||||
elif cmd == "qr 0":
|
||||
qr_on.clear()
|
||||
elif cmd.startswith("focus "):
|
||||
parts = cmd.split()
|
||||
if len(parts) >= 3:
|
||||
@@ -2445,6 +2539,7 @@ def run_worker(cameras, initial_index):
|
||||
preview_cond.notify_all()
|
||||
engine.stop()
|
||||
preview_thread.join(timeout=2.0)
|
||||
qr_thread.join(timeout=1.0)
|
||||
set_flash_led(False)
|
||||
return 0
|
||||
|
||||
|
||||
Reference in new issue
Block a user