Spaces:
Sleeping
Sleeping
Download ui/scene_editor.py from Abhyuday-06/VisionGuard-AI: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/Abhyuday-06/VisionGuard-AI/resolve/main/ui/scene_editor.py
- Command line
-
hf download hf://spaces/Abhyuday-06/VisionGuard-AI/ui/scene_editor.py
-
curl -L -o scene_editor.py https://huggingface.co/spaces/Abhyuday-06/VisionGuard-AI/resolve/main/ui/scene_editor.py
10.1 kB
| """Click-to-draw camera setup: lanes + direction, stop line + traffic flow, no-parking zones, signal box.""" | |
| from __future__ import annotations | |
| import cv2 | |
| import numpy as np | |
| import streamlit as st | |
| from core.scene import SceneConfig | |
| from core.visualize import draw_scene | |
| try: | |
| from streamlit_image_coordinates import streamlit_image_coordinates as image_click | |
| except ImportError: # pragma: no cover | |
| image_click = None | |
| DISPLAY_W = 900 | |
| TOOLS = { | |
| "Lane + direction": "Click the corners of one lane (3+ points), press **Next: direction**, then click two points " | |
| "along the legal direction of travel (from → to).", | |
| "Stop line": "Click the two ends of the stop line, then two points showing the direction traffic moves " | |
| "when it crosses the line (from → to).", | |
| "No-parking zone": "Click the corners of the zone (3+ points), then press **Save zone**.", | |
| "Signal light box": "Click two opposite corners around the traffic signal lamp so its colour can be read.", | |
| } | |
| def _state() -> dict: | |
| if "editor" not in st.session_state: | |
| st.session_state.editor = {"draft": [], "arrow": [], "stage": "shape", "last_click": None} | |
| return st.session_state.editor | |
| def get_scene() -> SceneConfig: | |
| if "scene" not in st.session_state: | |
| st.session_state.scene = SceneConfig() | |
| return st.session_state.scene | |
| def suggest_stop_line(frame: np.ndarray) -> list[list[float]] | None: | |
| """Longest near-horizontal painted line in the lower 2/3 of the frame (Canny + Hough).""" | |
| h, w = frame.shape[:2] | |
| gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
| _, bright = cv2.threshold(gray, 170, 255, cv2.THRESH_BINARY) | |
| edges = cv2.Canny(cv2.GaussianBlur(bright, (5, 5), 0), 50, 150) | |
| lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 80, minLineLength=int(w * 0.2), maxLineGap=25) | |
| if lines is None: | |
| return None | |
| best, best_len = None, 0.0 | |
| for x1, y1, x2, y2 in lines[:, 0]: | |
| if min(y1, y2) < h / 3 or abs(np.degrees(np.arctan2(y2 - y1, x2 - x1))) > 15: | |
| continue | |
| length = float(np.hypot(x2 - x1, y2 - y1)) | |
| if length > best_len: | |
| best, best_len = (x1, y1, x2, y2), length | |
| if best is None: | |
| return None | |
| x1, y1, x2, y2 = best | |
| return [[x1 / w, y1 / h], [x2 / w, y2 / h]] | |
| def _render_preview(frame: np.ndarray, scene: SceneConfig, ed: dict) -> np.ndarray: | |
| img = frame.copy() | |
| lanes = scene.build_lanes(img.shape) | |
| stop = scene.build_stop_line(img.shape) | |
| zones = scene.build_parking_zones(img.shape) | |
| draw_scene(img, lanes, stop, zones, scene.signal_mode if scene.signal_mode != "auto" else "UNKNOWN", | |
| scene.traffic_light_box(img.shape)) | |
| if stop is not None: | |
| mid = ((stop.a[0] + stop.b[0]) / 2, (stop.a[1] + stop.b[1]) / 2) | |
| L = 0.08 * img.shape[0] | |
| cv2.arrowedLine(img, (int(mid[0] - stop.flow[0] * L), int(mid[1] - stop.flow[1] * L)), | |
| (int(mid[0] + stop.flow[0] * L), int(mid[1] + stop.flow[1] * L)), (255, 255, 255), 3, | |
| tipLength=0.35) | |
| H, W = img.shape[:2] | |
| pts = [(int(x * W), int(y * H)) for x, y in ed["draft"]] | |
| for i, p in enumerate(pts): | |
| cv2.circle(img, p, 7, (0, 255, 255), -1) | |
| cv2.putText(img, str(i + 1), (p[0] + 8, p[1] - 6), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2) | |
| if len(pts) >= 2: | |
| cv2.polylines(img, [np.array(pts)], False, (0, 255, 255), 2) | |
| arrow = [(int(x * W), int(y * H)) for x, y in ed["arrow"]] | |
| for p in arrow: | |
| cv2.circle(img, p, 7, (255, 255, 255), -1) | |
| if len(arrow) == 2: | |
| cv2.arrowedLine(img, arrow[0], arrow[1], (255, 255, 255), 3, tipLength=0.3) | |
| return img | |
| def scene_editor(frame: np.ndarray) -> SceneConfig: | |
| """Render the editor and return the current SceneConfig (kept in session_state).""" | |
| scene = get_scene() | |
| ed = _state() | |
| top = st.columns([2, 2, 1.3, 1.3]) | |
| saved = SceneConfig.list_saved() | |
| with top[0]: | |
| choice = st.selectbox("Camera profile", ["(current)"] + saved, key="scene_profile", | |
| help="Saved camera setups live in configs/scenes/*.json") | |
| if choice != "(current)" and st.session_state.get("_loaded_profile") != choice: | |
| st.session_state.scene = scene = SceneConfig.load(choice) | |
| st.session_state._loaded_profile = choice | |
| with top[1]: | |
| tool = st.radio("Draw", list(TOOLS), horizontal=False, key="scene_tool", label_visibility="visible") | |
| with top[2]: | |
| modes = ["auto", "RED", "YELLOW", "GREEN"] | |
| scene.signal_mode = st.selectbox("Signal state", modes, index=modes.index(scene.signal_mode), | |
| help="'auto' reads the lamp colour (signal box or detected light). " | |
| "Pick a fixed state when the signal is not visible in the frame.") | |
| with top[3]: | |
| scene.parking_dwell_s = float(st.number_input("Parking limit (s)", 5, 1800, int(scene.parking_dwell_s), 5, | |
| help="Seconds a vehicle may stand still in a no-parking zone")) | |
| st.caption(TOOLS[tool]) | |
| if st.session_state.get("_last_tool") != tool: | |
| ed.update(draft=[], arrow=[], stage="shape") | |
| st.session_state._last_tool = tool | |
| b = st.columns(6) | |
| needs_polygon = tool in ("Lane + direction", "No-parking zone") | |
| if tool == "Lane + direction": | |
| if ed["stage"] == "shape" and b[0].button("Next: direction", disabled=len(ed["draft"]) < 3, width="stretch"): | |
| ed["stage"] = "arrow" | |
| st.rerun() | |
| if ed["stage"] == "arrow" and b[0].button("Save lane", type="primary", disabled=len(ed["arrow"]) < 2, | |
| width="stretch"): | |
| scene.lanes.append({"name": f"lane {len(scene.lanes) + 1}", "polygon": ed["draft"], "direction": ed["arrow"]}) | |
| ed.update(draft=[], arrow=[], stage="shape") | |
| st.rerun() | |
| elif tool == "No-parking zone": | |
| if b[0].button("Save zone", type="primary", disabled=len(ed["draft"]) < 3, width="stretch"): | |
| scene.no_parking_zones.append(ed["draft"]) | |
| ed.update(draft=[], arrow=[]) | |
| st.rerun() | |
| elif tool == "Stop line": | |
| if b[0].button("Suggest line", width="stretch", help="Detect the painted line automatically"): | |
| sug = suggest_stop_line(frame) | |
| if sug: | |
| ed.update(draft=sug, stage="arrow", arrow=[]) | |
| st.toast("Line suggested. Now click two points for the traffic direction.") | |
| else: | |
| st.toast("No clear stop line found; click the two ends manually.") | |
| st.rerun() | |
| if b[1].button("Undo point", width="stretch"): | |
| if ed["arrow"]: | |
| ed["arrow"].pop() | |
| elif ed["draft"]: | |
| ed["draft"].pop() | |
| if needs_polygon: | |
| ed["stage"] = "shape" | |
| st.rerun() | |
| if b[2].button("Remove last", width="stretch", help="Delete the last saved item of this type"): | |
| if tool == "Lane + direction" and scene.lanes: | |
| scene.lanes.pop() | |
| elif tool == "No-parking zone" and scene.no_parking_zones: | |
| scene.no_parking_zones.pop() | |
| elif tool == "Stop line": | |
| scene.stop_line = None | |
| elif tool == "Signal light box": | |
| scene.traffic_light_roi = None | |
| st.rerun() | |
| if b[3].button("Clear all", width="stretch"): | |
| st.session_state.scene = SceneConfig(name=scene.name, signal_mode=scene.signal_mode, | |
| parking_dwell_s=scene.parking_dwell_s) | |
| ed.update(draft=[], arrow=[], stage="shape") | |
| st.rerun() | |
| name = b[4].text_input("Profile name", value=scene.name, label_visibility="collapsed", placeholder="profile name") | |
| if b[5].button("Save profile", width="stretch"): | |
| scene.name = "".join(c for c in name if c.isalnum() or c in "-_") or "camera" | |
| path = scene.save() | |
| st.toast(f"Saved {path.name}") | |
| preview = _render_preview(frame, scene, ed) | |
| scale = DISPLAY_W / preview.shape[1] | |
| disp = cv2.resize(preview, (DISPLAY_W, int(preview.shape[0] * scale))) | |
| disp_rgb = cv2.cvtColor(disp, cv2.COLOR_BGR2RGB) | |
| if image_click is None: | |
| st.image(disp_rgb, width="stretch") | |
| st.warning("Install streamlit-image-coordinates to draw zones.") | |
| return scene | |
| # JPEG keeps each rerun's payload small (the default is uncompressed PNG, several MB per click) | |
| click = image_click(disp_rgb, key="scene_click", image_format="JPEG", jpeg_quality=85) | |
| if click and click != ed["last_click"]: | |
| ed["last_click"] = click | |
| pt = [round(click["x"] / disp.shape[1], 4), round(click["y"] / disp.shape[0], 4)] | |
| if tool == "Lane + direction": | |
| (ed["draft"] if ed["stage"] == "shape" else ed["arrow"]).append(pt) | |
| ed["arrow"] = ed["arrow"][-2:] | |
| elif tool == "No-parking zone": | |
| ed["draft"].append(pt) | |
| elif tool == "Stop line": | |
| if ed["stage"] == "shape": | |
| ed["draft"].append(pt) | |
| if len(ed["draft"]) == 2: | |
| ed["stage"] = "arrow" | |
| else: | |
| ed["arrow"].append(pt) | |
| if len(ed["arrow"]) == 2: | |
| scene.stop_line = {"points": ed["draft"], "flow": ed["arrow"]} | |
| ed.update(draft=[], arrow=[], stage="shape") | |
| st.toast("Stop line saved") | |
| elif tool == "Signal light box": | |
| ed["draft"].append(pt) | |
| if len(ed["draft"]) == 2: | |
| scene.traffic_light_roi = ed["draft"] | |
| ed.update(draft=[]) | |
| st.toast("Signal box saved") | |
| st.rerun() | |
| s = scene.summary() | |
| st.caption(f"Configured: {s['lanes']} lane(s) · stop line: {'yes' if s['stop_line'] else 'no'} · " | |
| f"{s['no_parking_zones']} no-parking zone(s) · signal box: {'yes' if s['traffic_light_roi'] else 'no'} · " | |
| f"signal: {s['signal_mode']}") | |
| return scene | |