diff --git a/src/dashboard.py b/src/dashboard.py index b5df24d..6d49e2d 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -67,7 +67,7 @@ class DashboardOverlay: return frame def _draw_roi(self, frame: np.ndarray, roi: TruckROI) -> None: - if roi.confidence >= 1.0: + if roi.fixed: # Fixed zone — dashed cyan border on all edges dash_len, gap_len = 12, 8 for edge in [ @@ -87,8 +87,12 @@ class DashboardOverlay: cv2.rectangle( frame, (roi.x1, roi.y1), (roi.x2, roi.y2), ORANGE, 2, ) + if roi.frozen: + label = f"ROI FROZEN ({roi.confidence:.0%})" + else: + label = f"TRUCK ROI ({roi.confidence:.0%})" cv2.putText( - frame, f"TRUCK ROI ({roi.confidence:.0%})", + frame, label, (roi.x1, roi.y1 - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.5, ORANGE, 1, ) diff --git a/src/job.py b/src/job.py index a9a1da7..6abda6c 100644 --- a/src/job.py +++ b/src/job.py @@ -209,6 +209,7 @@ class JobQueue: class_filter=class_filter, truck_model_config=truck_model_config, fixed_zone=job.fixed_zone, + freeze_roi=(job.zone_mode == "freeze"), preview_path=job.preview_path, preview_enabled=job.preview_enabled, preview_every_n=2, @@ -256,6 +257,7 @@ class JobQueue: class_filters=job.class_filters, truck_model_config=truck_model_config, fixed_zone=job.fixed_zone, + freeze_roi=(job.zone_mode == "freeze"), preview_path=job.preview_path, preview_enabled=job.preview_enabled, preview_every_n=2, diff --git a/src/pipeline.py b/src/pipeline.py index 632870b..5f41b67 100644 --- a/src/pipeline.py +++ b/src/pipeline.py @@ -108,6 +108,7 @@ def run_pipeline( preview_max_dim: int = 480, preview_jpeg_quality: int = 60, live_stats_callback: Callable[[dict], None] | None = None, + freeze_roi: bool = False, ) -> PipelineResult: """Process a video file through the counting pipeline. @@ -128,6 +129,8 @@ def run_pipeline( preview_jpeg_quality: JPEG quality for preview frames (1-100). live_stats_callback: Optional fn(dict) called every 10 frames with {fps, loading, unloading, frame} for live UI stats. + freeze_roi: Lock the auto-detected truck ROI after 3 consecutive + detections (zone_mode "freeze"); False = plain auto-detect. Returns: PipelineResult with counting summary. @@ -176,7 +179,9 @@ def run_pipeline( tracker = ByteTrackTracker(shared_model, conf=sack_conf) stabilizer = BboxStabilizer() - roi_tracker = TruckROITracker(frame_width=w, frame_height=h) + roi_tracker = TruckROITracker( + frame_width=w, frame_height=h, freeze_after=(3 if freeze_roi else None) + ) counter = MultiClassLineCounter( line_y=int(h * 0.50), line_x_start=int(w * 0.38), @@ -235,7 +240,7 @@ def run_pipeline( # Batch lifecycle truck_centroid = None - if roi is not None: + if truck_present: truck_centroid = ((roi.x1 + roi.x2) / 2.0, (roi.y1 + roi.y2) / 2.0) if frame_idx % truck_det_interval == 0: @@ -398,8 +403,13 @@ def run_merged_pipeline( preview_max_dim: int = 480, preview_jpeg_quality: int = 60, live_stats_callback: Callable[[dict], None] | None = None, + freeze_roi: bool = False, ) -> MergedPipelineResult: - """Run multiple models on the same video, merge detections into one output.""" + """Run multiple models on the same video, merge detections into one output. + + freeze_roi: Lock the auto-detected truck ROI after 3 consecutive + detections (zone_mode "freeze"); False = plain auto-detect. + """ cap = cv2.VideoCapture(video_path) if not cap.isOpened(): raise RuntimeError(f"Cannot open video: {video_path}") @@ -441,7 +451,9 @@ def run_merged_pipeline( tracker_model = YOLO(model_configs[0].path) tracker = ByteTrackTracker(tracker_model, conf=sack_conf) stabilizer = BboxStabilizer() - roi_tracker = TruckROITracker(frame_width=w, frame_height=h) + roi_tracker = TruckROITracker( + frame_width=w, frame_height=h, freeze_after=(3 if freeze_roi else None) + ) counter = MultiClassLineCounter( line_y=int(h * 0.50), line_x_start=int(w * 0.38), @@ -494,7 +506,7 @@ def run_merged_pipeline( counter.line_x_end = roi.x2 truck_centroid = None - if roi is not None: + if truck_present: truck_centroid = ((roi.x1 + roi.x2) / 2.0, (roi.y1 + roi.y2) / 2.0) if frame_idx % truck_det_interval == 0: diff --git a/src/truck_roi.py b/src/truck_roi.py index 17fdfcd..8f01d71 100644 --- a/src/truck_roi.py +++ b/src/truck_roi.py @@ -3,10 +3,18 @@ Uses exponential moving average (EMA) to smooth the bounding box across frames, preventing jitter from frame-to-frame detection variance. -For y2-based counting (bottom edge of sack bbox), the counting line is -placed `LINE_OFFSET_PX` pixels relative to the truck bottom edge (`roi.y2`). -With `offset = +20`, the line sits at `roi.y2 + 20` (~620px), cleanly -separating sacks on the ground (`y2 > 650`) from loaded sacks (`y2 < 580`). +A deadband (`deadband_px`) skips the EMA entirely when every bbox edge +moved less than that many pixels, so the ROI and counting line stay still +under tiny detection jitter. + +The counting line is placed `LINE_OFFSET_PX` pixels relative to the truck +top edge (`roi.y1`), i.e. the line sits at `roi.y1 + LINE_OFFSET_PX`. +With `offset = +20` the line sits 20px below the truck top edge, into +the truck body. + +Optional freeze (`freeze_after`): after that many consecutive detections +the smoothed box is locked; geometry never moves again, while presence +(confidence) stays live. """ from __future__ import annotations @@ -20,6 +28,9 @@ from src.interfaces import Detection # Negative = above truck top edge (towards the camera). LINE_OFFSET_PX = 0 +# Minimum IoU for the sticky main-truck pick to keep the previous truck. +STICKY_IOU = 0.3 + @dataclass class TruckROI: @@ -31,6 +42,8 @@ class TruckROI: y2: int line_y: int # counting line Y position (pixels) confidence: float + fixed: bool = False # True for zones built from zones.json (never moves) + frozen: bool = False # True when auto ROI is locked after freeze_after hits @property def width(self) -> int: @@ -49,10 +62,13 @@ class TruckROITracker: """Tracks the main truck and provides a smoothed ROI + counting line. Main truck = largest truck detection whose center X falls in the - expected lane (center region of the frame). + expected lane (center region of the frame). The pick is sticky: a + detection overlapping the previous main truck (IoU >= 0.3) wins over + the largest-in-lane rule, so the ROI does not jump between parked + trucks. - The counting line is placed `line_offset` pixels below the truck - bottom edge (`roi.y2`). + The counting line is placed `line_offset` pixels relative to the truck + top edge (`roi.y1`). """ def __init__( @@ -63,6 +79,8 @@ class TruckROITracker: lane_x_max: float = 0.80, ema_alpha: float = 0.15, line_offset: int = LINE_OFFSET_PX, + deadband_px: float = 10.0, + freeze_after: int | None = None, ) -> None: self._fw = frame_width self._fh = frame_height @@ -70,6 +88,8 @@ class TruckROITracker: self._lane_x_max = int(lane_x_max * frame_width) self._alpha = ema_alpha self._line_offset = line_offset + self._deadband = deadband_px + self._freeze_after = freeze_after # Smoothed bbox (None until first detection) self._sx1: float | None = None @@ -77,6 +97,14 @@ class TruckROITracker: self._sx2: float | None = None self._sy2: float | None = None + # Sticky pick: raw bbox of the last chosen main truck + self._prev_raw_bbox: tuple[float, float, float, float] | None = None + + # Freeze state + self._hit_streak = 0 + self._frozen = False + self._frozen_box: tuple[float, float, float, float] | None = None + self._last_roi: TruckROI | None = None self._frames_without_truck = 0 @@ -85,37 +113,60 @@ class TruckROITracker: main = self._pick_main_truck(truck_detections) if main is None: + self._hit_streak = 0 self._frames_without_truck += 1 + if self._frozen: + # Frozen: geometry never resets, only presence goes away. + if self._frames_without_truck > 5: + # >5 misses: signal truck departure, keep frozen geometry. + self._last_roi = self._build_roi(self._frozen_box, 0.0) + return self._last_roi + return self._last_roi # hold last known confidence briefly if self._frames_without_truck > 5: # Clear ROI if truck is missing for >5 updates (~3 seconds) self.reset() return None return self._last_roi # hold last known ROI briefly self._frames_without_truck = 0 + self._hit_streak += 1 + + if self._frozen: + # Geometry locked; presence stays live. + self._last_roi = self._build_roi(self._frozen_box, main.confidence) + return self._last_roi + x1, y1, x2, y2 = main.bbox - # EMA smoothing + # EMA smoothing (skipped while all edges moved < deadband) if self._sx1 is None: self._sx1, self._sy1 = float(x1), float(y1) self._sx2, self._sy2 = float(x2), float(y2) - else: + elif ( + abs(x1 - self._sx1) >= self._deadband + or abs(y1 - self._sy1) >= self._deadband + or abs(x2 - self._sx2) >= self._deadband + or abs(y2 - self._sy2) >= self._deadband + ): a = self._alpha self._sx1 = a * x1 + (1 - a) * self._sx1 self._sy1 = a * y1 + (1 - a) * self._sy1 self._sx2 = a * x2 + (1 - a) * self._sx2 self._sy2 = a * y2 + (1 - a) * self._sy2 - # Build ROI — line placed at truck top edge - roi_x1 = max(0, int(self._sx1)) - roi_y1 = max(0, int(self._sy1)) - roi_x2 = min(self._fw, int(self._sx2)) - roi_y2 = min(self._fh, int(self._sy2)) - line_y = roi_y1 + self._line_offset + if ( + self._freeze_after is not None + and self._hit_streak >= self._freeze_after + and not self._frozen + ): + self._frozen = True + self._frozen_box = (self._sx1, self._sy1, self._sx2, self._sy2) - self._last_roi = TruckROI( - x1=roi_x1, y1=roi_y1, x2=roi_x2, y2=roi_y2, - line_y=line_y, confidence=main.confidence, - ) + if self._frozen: + self._last_roi = self._build_roi(self._frozen_box, main.confidence) + else: + self._last_roi = self._build_roi( + (self._sx1, self._sy1, self._sx2, self._sy2), main.confidence + ) return self._last_roi @property @@ -130,11 +181,40 @@ class TruckROITracker: self._sx1 = self._sy1 = self._sx2 = self._sy2 = None self._last_roi = None self._frames_without_truck = 0 + self._prev_raw_bbox = None + self._hit_streak = 0 + self._frozen = False + self._frozen_box = None + + def _build_roi( + self, + box: tuple[float, float, float, float], + confidence: float, + ) -> TruckROI: + """Build a TruckROI from a smoothed/frozen box (line at top edge).""" + sx1, sy1, sx2, sy2 = box + roi_x1 = max(0, int(sx1)) + roi_y1 = max(0, int(sy1)) + roi_x2 = min(self._fw, int(sx2)) + roi_y2 = min(self._fh, int(sy2)) + return TruckROI( + x1=roi_x1, y1=roi_y1, x2=roi_x2, y2=roi_y2, + line_y=roi_y1 + self._line_offset, + confidence=confidence, + frozen=self._frozen, + ) def _pick_main_truck( self, detections: list[Detection] ) -> Detection | None: - """Select the largest truck whose center X is in the expected lane.""" + """Select the main truck: sticky overlap with previous, else largest in lane.""" + # Sticky: keep the previous main truck if any detection still overlaps it. + if self._prev_raw_bbox is not None: + for det in detections: + if _iou(det.bbox, self._prev_raw_bbox) >= STICKY_IOU: + self._prev_raw_bbox = tuple(det.bbox) + return det + best: Detection | None = None best_area = 0 @@ -148,4 +228,23 @@ class TruckROITracker: best = det best_area = area + if best is not None: + self._prev_raw_bbox = tuple(best.bbox) return best + + +def _iou( + a: tuple[float, float, float, float], + b: tuple[float, float, float, float], +) -> float: + """Intersection-over-union of two (x1, y1, x2, y2) boxes.""" + ax1, ay1, ax2, ay2 = a + bx1, by1, bx2, by2 = b + ix1, iy1 = max(ax1, bx1), max(ay1, by1) + ix2, iy2 = min(ax2, bx2), min(ay2, by2) + iw, ih = max(0.0, ix2 - ix1), max(0.0, iy2 - iy1) + inter = iw * ih + if inter <= 0.0: + return 0.0 + union = (ax2 - ax1) * (ay2 - ay1) + (bx2 - bx1) * (by2 - by1) - inter + return inter / union if union > 0.0 else 0.0 diff --git a/src/zone_config.py b/src/zone_config.py index 9bdb64c..88fea25 100644 --- a/src/zone_config.py +++ b/src/zone_config.py @@ -59,6 +59,7 @@ def build_static_roi(zone: dict[str, Any], video_w: int, video_h: int) -> TruckR x1=x1, y1=y1, x2=x2, y2=y2, line_y=line_y, confidence=1.0, + fixed=True, ) diff --git a/templates/index.html b/templates/index.html index e2f62fc..ff1558e 100644 --- a/templates/index.html +++ b/templates/index.html @@ -406,6 +406,10 @@ Fixed Zone +