""" Serveur Flask pour prendre une photo à distance avec une webcam USB (ex. Creative) sur Raspberry Pi, dans la meilleure résolution supportée par la caméra. Prérequis : sudo apt install v4l-utils python3-opencv python3-flask """ import re import subprocess import threading import cv2 from flask import Flask, jsonify, send_file app = Flask(__name__) PHOTO_PATH = "/tmp/photo.jpg" DEVICE = 0 # /dev/video0 WARMUP_FRAMES = 15 # images jetées le temps que l'auto-exposition / balance des blancs se stabilise JPEG_QUALITY = 95 # 0-100 (OpenCV met 95 par défaut, 100 = fichier plus gros) camera_lock = threading.Lock() # évite deux accès simultanés à la caméra _best_mode = None # cache : (largeur, hauteur, fourcc) def get_best_mode(): """Interroge la caméra via v4l2-ctl et retourne la plus grande résolution supportée, avec le format (MJPG ou YUYV) qui la permet.""" global _best_mode if _best_mode: return _best_mode best = None # (pixels, largeur, hauteur, fourcc) try: out = subprocess.run( ["v4l2-ctl", "-d", f"/dev/video{DEVICE}", "--list-formats-ext"], capture_output=True, text=True, timeout=5, ).stdout fmt = None for line in out.splitlines(): m = re.search(r"\[\d+\]:\s*'(\w{4})'", line) if m: fmt = m.group(1) continue m = re.search(r"Size: Discrete (\d+)x(\d+)", line) if m and fmt: w, h = int(m.group(1)), int(m.group(2)) candidate = (w * h, w, h, fmt) # À résolution égale, on préfère MJPG (moins de bande passante USB) if (best is None or candidate[0] > best[0] or (candidate[0] == best[0] and fmt == "MJPG")): best = candidate except (FileNotFoundError, subprocess.TimeoutExpired): pass if best: _best_mode = (best[1], best[2], best[3]) else: # Repli : on demande une résolution énorme, le pilote choisira le max possible _best_mode = (9999, 9999, "MJPG") return _best_mode def capture(): """Prend une photo à la résolution max et l'enregistre dans PHOTO_PATH. Retourne la résolution réellement obtenue.""" width, height, fourcc = get_best_mode() with camera_lock: cam = cv2.VideoCapture(DEVICE, cv2.CAP_V4L2) if not cam.isOpened(): raise RuntimeError("Impossible d'accéder à la caméra") try: # Le format doit être défini AVANT la résolution cam.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*fourcc)) cam.set(cv2.CAP_PROP_FRAME_WIDTH, width) cam.set(cv2.CAP_PROP_FRAME_HEIGHT, height) cam.set(cv2.CAP_PROP_BUFFERSIZE, 1) # Laisser l'auto-exposition / le focus se régler for _ in range(WARMUP_FRAMES): cam.grab() ret, frame = cam.read() if not ret or frame is None: raise RuntimeError("Échec de la capture") real_w = int(cam.get(cv2.CAP_PROP_FRAME_WIDTH)) real_h = int(cam.get(cv2.CAP_PROP_FRAME_HEIGHT)) finally: cam.release() cv2.imwrite(PHOTO_PATH, frame, [cv2.IMWRITE_JPEG_QUALITY, JPEG_QUALITY]) return real_w, real_h @app.route("/photo") def take_photo(): try: w, h = capture() except RuntimeError as e: return str(e), 500 return jsonify(status="ok", width=w, height=h, path=PHOTO_PATH) @app.route("/capture") def capture_photo(): try: capture() except RuntimeError as e: return str(e), 500 return send_file(PHOTO_PATH, mimetype="image/jpeg") @app.route("/old") def use_old_photo(): return send_file(PHOTO_PATH, mimetype="image/jpeg") @app.route("/info") def info(): w, h, fourcc = get_best_mode() return jsonify(width=w, height=h, format=fourcc) if __name__ == "__main__": app.run(host="0.0.0.0", port=5000, threaded=True)