import cv2 import numpy as np from config import CAMERA_INDICES_TO_CHECK, FRAME_WIDTH, FRAME_HEIGHT def _preview_camera(capture: cv2.VideoCapture, cameraID: int) -> str: """Show a live preview and return the user's choice: 'add', 'skip', or 'quit'.""" window_name = f"Camera {cameraID}" cv2.namedWindow(window_name, cv2.WINDOW_NORMAL) print(f"[Camera {cameraID}] Press 'y' to add, 'n' to skip, 'q' to stop scanning.") try: while True: ok, frame = capture.read() if not ok: print(f"[Camera {cameraID}] Failed to read frame; skipping.") return "skip" cv2.imshow(window_name, frame) key = cv2.waitKey(1) & 0xFF if key == ord("y"): print(f"[Camera {cameraID}] Selected.") return "add" if key == ord("n"): print(f"[Camera {cameraID}] Skipped.") return "skip" if key == ord("q") or key == 27: # 27 == ESC print(f"[Camera {cameraID}] Stopping camera scan.") return "quit" finally: cv2.destroyWindow(window_name) def InitCameras(): allCaptures = [] setup_window = "Camera Setup" instructions = np.zeros((240, 560, 3), dtype=np.uint8) cv2.putText(instructions, "Camera Setup", (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 200, 255), 2) cv2.putText(instructions, "Each camera will preview in its own window.", (20, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (200, 200, 200), 1) cv2.putText(instructions, "Use 'y' to add, 'n' to skip, 'q'/ESC to finish.", (20, 125), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (200, 200, 200), 1) cv2.putText(instructions, "Close this window when you're done.", (20, 160), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (200, 200, 200), 1) cv2.namedWindow(setup_window, cv2.WINDOW_AUTOSIZE) cv2.imshow(setup_window, instructions) cv2.waitKey(1) try: for cameraID in range(CAMERA_INDICES_TO_CHECK): capture = cv2.VideoCapture(cameraID) if not capture.isOpened(): capture.release() continue capture.set(cv2.CAP_PROP_FRAME_WIDTH, FRAME_WIDTH) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT) decision = _preview_camera(capture, cameraID) if decision == "add": allCaptures.append(capture) else: capture.release() if decision == "quit": break if not all(capture.isOpened() for capture in allCaptures): print("Error: could not open all selected cameras.") return if not allCaptures: print("No cameras selected.") return return allCaptures finally: cv2.destroyWindow(setup_window)