Spaces:
Build error
Build error
Improved + Stable + Confidence (#15)
Browse files- Improved + Stable + Confidence (9c32c096d1949df40ca23c870d86970a8799f79c)
1234526 unmodified lines3233343536375 unmodified lines434445464748495069 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471486 unmodified lines1551561571581591601611621631641653 unmodified lines169170171172173174175176# ============================================================# π¦ Stage 3 β Wrong Direction Detection (Improved + Toggle)# ============================================================import os, cv2, json, tempfile, numpy as np, gradio as gr26 unmodified linesself.history = []self.frames_seen = 0self.status = "OK"def update(self, bbox):self.kf.predict()5 unmodified linesself.frames_seen += 1return [x, y]# ============================================================# βοΈ Utility Functions# ============================================================def compute_cosine_similarity(v1, v2):v1 = v1 / (np.linalg.norm(v1) + 1e-6)69 unmodified linesfor i in range(1, len(pts)):cv2.line(frame, tuple(np.int32(pts[i-1])), tuple(np.int32(pts[i])), (0, 0, 255), 1)# compute smooth directionmotion = smooth_direction(pts)if motion is None:continueif np.linalg.norm(motion) < MIN_FLOW_SPEED:continue# cosine similarity to closest lane flowsims = [compute_cosine_similarity(motion, f) for f in lane_flows]best_sim = max(sims)# only classify after some framesif trk.frames_seen > DELAY_FRAMES:if best_sim < SIM_THRESH:trk.status = "WRONG"else:trk.status = "OK"# draw depending on toggleif (not show_only_wrong) or (trk.status == "WRONG"):color = (0, 0, 255) if trk.status == "WRONG" else (0, 255, 0)cv2.putText(frame, f"ID:{tid} {trk.status}",tuple(np.int32(pos)),cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)out.write(frame)6 unmodified lines# ποΈ Gradio Interface# ============================================================description = """### π¦ Stage 3 β Wrong Direction Detection (Improved)- β Cosine similarity instead of raw angle- β Lane-wise flow support for curved roads- β Temporal smoothing & delayed classification- β Toggle to show only WRONG vehicles"""demo = gr.Interface(3 unmodified linesgr.File(label="Stage 2 Flow JSON"),gr.Checkbox(label="Show ONLY Wrong Labels Overlay", value=False)],outputs=gr.Video(label="Output (with WRONG/OK labels)"),title="π Stage 3 β Improved Wrong-Direction Detection",description=description)1234526 unmodified lines32333435363738395 unmodified lines454647484950515253545556575859606162636469 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571586 unmodified lines1651661671681691701711721731741751761773 unmodified lines181182183184185186187188# ============================================================# π¦ Stage 3 β Wrong Direction Detection (Improved + Stable + Confidence)# ============================================================import os, cv2, json, tempfile, numpy as np, gradio as gr26 unmodified linesself.history = []self.frames_seen = 0self.status = "OK"self.status_history = [] # πΈ maintain recent decision historyself.confidence = 1.0def update(self, bbox):self.kf.predict()5 unmodified linesself.frames_seen += 1return [x, y]def stable_status(self, new_status, new_conf, window=6, agree_ratio=0.7):"""Debounce flicker using recent window consensus."""self.status_history.append(new_status)if len(self.status_history) > window:self.status_history.pop(0)# majority consensusif self.status_history.count(new_status) >= int(agree_ratio * len(self.status_history)):self.status = new_statusself.confidence = new_confreturn self.status, self.confidence# ============================================================# βοΈ Utilities# ============================================================def compute_cosine_similarity(v1, v2):v1 = v1 / (np.linalg.norm(v1) + 1e-6)69 unmodified linesfor i in range(1, len(pts)):cv2.line(frame, tuple(np.int32(pts[i-1])), tuple(np.int32(pts[i])), (0, 0, 255), 1)motion = smooth_direction(pts)if motion is None:continueif np.linalg.norm(motion) < MIN_FLOW_SPEED:continue# cosine similarity vs lane flowssims = [compute_cosine_similarity(motion, f) for f in lane_flows]best_sim = max(sims)if trk.frames_seen > DELAY_FRAMES:new_status = "WRONG" if best_sim < SIM_THRESH else "OK"trk.stable_status(new_status, new_conf=best_sim)# draw if toggle allowsif (not show_only_wrong) or (trk.status == "WRONG"):color = (0, 0, 255) if trk.status == "WRONG" else (0, 255, 0)label = f"ID:{tid} {trk.status} ({trk.confidence:.2f})"cv2.putText(frame, label, tuple(np.int32(pos)),cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)out.write(frame)6 unmodified lines# ποΈ Gradio Interface# ============================================================description = """### π¦ Stage 3 β Wrong Direction Detection (Improved + Stable + Confidence)- β Cosine similarity instead of raw angle- β Lane-wise flow support for curved roads- β Temporal smoothing & delayed classification- β Flicker-free labels using consensus window- β Confidence score display (cosine similarity)- β Toggle to show only WRONG overlays"""demo = gr.Interface(3 unmodified linesgr.File(label="Stage 2 Flow JSON"),gr.Checkbox(label="Show ONLY Wrong Labels Overlay", value=False)],outputs=gr.Video(label="Output Video"),title="π Stage 3 β Stable Wrong-Direction Detection (with Confidence)",description=description)
app.py+28-16