Spaces:
Sleeping
Sleeping
| """ | |
| webcam_stub.py | |
| -------------- | |
| NOT wired into app.py — this is a reference/starting point in case the | |
| supervisor later asks for live webcam detection. | |
| Streamlit does not have a built-in "video loop" the way a desktop GUI does, | |
| so live webcam detection needs either: | |
| Option A (simplest, local machine only): | |
| Use OpenCV directly to open the webcam (cv2.VideoCapture(0)) inside | |
| a `while st.session_state.running:` loop, calling | |
| st.image(...) repeatedly to refresh a placeholder. Works, but is a bit | |
| choppy and only works when Streamlit runs on the SAME machine as the | |
| webcam (fine for a local project demo / defense). | |
| Option B (proper, works in a real browser/deployed app): | |
| Use the `streamlit-webrtc` package, which streams frames from the | |
| BROWSER's webcam to the Python backend over WebRTC. This is the | |
| correct approach if the app will be accessed remotely (e.g. deployed | |
| to Streamlit Cloud) rather than run locally during a defense. | |
| pip install streamlit-webrtc | |
| Below is a minimal Option A example, since most project defenses happen | |
| on the student's own laptop. | |
| """ | |
| import cv2 | |
| import streamlit as st | |
| from detector import TrafficDetector | |
| def webcam_tab(detector: TrafficDetector): | |
| st.header("Live Webcam Detection (experimental)") | |
| st.caption("Runs locally using your machine's webcam. Click Stop to end the session.") | |
| run = st.checkbox("Start Webcam") | |
| frame_placeholder = st.empty() | |
| if run: | |
| cap = cv2.VideoCapture(0) | |
| while run and cap.isOpened(): | |
| ok, frame = cap.read() | |
| if not ok: | |
| st.warning("Could not read from webcam.") | |
| break | |
| annotated, _counts = detector.detect_frame(frame) | |
| annotated_rgb = cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB) | |
| frame_placeholder.image(annotated_rgb, use_container_width=True) | |
| # Re-check the checkbox each loop so "Stop" actually stops it. | |
| run = st.session_state.get("Start Webcam", run) | |
| cap.release() | |