- Counter writes stream_meta.json with processing FPS and frame dimensions - Dashboard reads it instead of static defaults
1847 lines
65 KiB
Python
1847 lines
65 KiB
Python
"""
|
||
Edge production live counter — RTSP + YOLO RKNN + ByteTrack + line crossing.
|
||
Runs on RK3588 hardware with RKNN model (320×320 input).
|
||
Uses ByteTrack (Kalman filter + two-stage IoU association) for tracking.
|
||
"""
|
||
|
||
import contextlib
|
||
import numpy as np
|
||
import cv2
|
||
import csv
|
||
import os
|
||
import signal
|
||
import sys
|
||
import time
|
||
import json
|
||
from collections import deque
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
from dotenv import load_dotenv
|
||
|
||
load_dotenv()
|
||
|
||
from rknnlite.api import RKNNLite
|
||
from batch_store import BatchStore
|
||
from counter_control import start_control_server
|
||
|
||
# --- config (override via env / .env) ---
|
||
OUTPUT_DIR = os.getenv("OUTPUT_DIR", "/opt/feedmill")
|
||
DB_PATH = os.getenv("DB_PATH", f"{OUTPUT_DIR}/feedmill.db")
|
||
STATE_FILE = os.getenv("STATE_FILE", f"{OUTPUT_DIR}/current_batch.json")
|
||
SOURCE = os.getenv("SOURCE", "rtsp://user:pass@192.168.0.100:554/stream1")
|
||
MODEL_PATH = os.getenv("MODEL_PATH", "/opt/models/yolo11n.rknn")
|
||
CAMERA_NAME = os.getenv("CAMERA_NAME", "CC1")
|
||
OBJECT_LABEL = os.getenv("OBJECT_LABEL", "sack")
|
||
CLASS_COUNTED_OBJECT = os.getenv(
|
||
"CLASS_COUNTED_OBJECT", os.getenv("CLASS_AYAM", "sack")
|
||
)
|
||
|
||
LINE_X = int(os.getenv("LINE_X")) if os.getenv("LINE_X") else None
|
||
LINE_X_FRAC = float(os.getenv("LINE_X_FRAC", "0.5"))
|
||
LINE_Y = int(os.getenv("LINE_Y")) if os.getenv("LINE_Y") else None
|
||
LINE_Y_FRAC = float(os.getenv("LINE_Y_FRAC", "0.5"))
|
||
CROSS_DIRECTION = os.getenv("CROSS_DIRECTION", "down").lower()
|
||
COUNT_AXIS = os.getenv("COUNT_AXIS", "auto").lower()
|
||
|
||
# Horizontal counting zone (covers full vertical height 0..h)
|
||
ZONE_MODE = os.getenv("ZONE_MODE", "auto").strip().lower()
|
||
ZONE_X_MIN = int(os.getenv("ZONE_X_MIN")) if os.getenv("ZONE_X_MIN") else None
|
||
ZONE_X_MAX = int(os.getenv("ZONE_X_MAX")) if os.getenv("ZONE_X_MAX") else None
|
||
ZONE_X_MIN_FRAC = float(os.getenv("ZONE_X_MIN_FRAC", "0.30"))
|
||
ZONE_X_MAX_FRAC = float(os.getenv("ZONE_X_MAX_FRAC", "0.80"))
|
||
TRUCK_ZONE_PAD_X = int(os.getenv("TRUCK_ZONE_PAD_X", "10"))
|
||
TRUCK_ZONE_HOLD_SEC = float(os.getenv("TRUCK_ZONE_HOLD_SEC", "300.0"))
|
||
IMGSZ = int(os.getenv("IMGSZ", "320"))
|
||
HALF = os.getenv("HALF", "false").lower() == "true"
|
||
CONF = float(os.getenv("CONF", "0.3"))
|
||
SACK_CONF = float(os.getenv("SACK_CONF")) if os.getenv("SACK_CONF") else CONF
|
||
BOX_CONF = float(os.getenv("BOX_CONF")) if os.getenv("BOX_CONF") else CONF
|
||
TRUCK_CONF = float(os.getenv("TRUCK_CONF")) if os.getenv("TRUCK_CONF") else CONF
|
||
IOU = float(os.getenv("IOU", "0.45"))
|
||
DEVICE = int(os.getenv("DEVICE", "0"))
|
||
|
||
# RKNN NPU core mask
|
||
CORE_MASK = int(os.getenv("CORE_MASK", "1"))
|
||
|
||
# YOLO decoder config
|
||
NUM_CLASSES = int(os.getenv("NUM_CLASSES", "1"))
|
||
SCORE_SIGMOID = os.getenv("SCORE_SIGMOID", "false").lower() == "true"
|
||
|
||
# ByteTrack settings (counted object / sack, class index 0)
|
||
TRACK_HIGH_THRESH_0 = float(os.getenv("TRACK_HIGH_THRESH_0", "0.25"))
|
||
TRACK_LOW_THRESH_0 = float(os.getenv("TRACK_LOW_THRESH_0", "0.1"))
|
||
TRACK_MATCH_THRESH_0 = float(os.getenv("TRACK_MATCH_THRESH_0", "0.3"))
|
||
TRACK_BUFFER_0 = int(os.getenv("TRACK_BUFFER_0", "30"))
|
||
TRACK_MIN_HITS_0 = int(os.getenv("TRACK_MIN_HITS_0", "3"))
|
||
|
||
# Dedup guard against ID-switch double counts: ignore a second crossing in the
|
||
# same direction that happens within DEDUP_FRAMES and DEDUP_PX (distance along
|
||
# the counting line) of a recent crossing from a now-inactive track.
|
||
DEDUP_FRAMES = int(os.getenv("DEDUP_FRAMES", "4"))
|
||
DEDUP_PX = float(os.getenv("DEDUP_PX", "35"))
|
||
|
||
DAILY_CUTOFF_TIME = os.getenv("DAILY_CUTOFF_TIME", "06:00")
|
||
BATCH_TIMEOUT_SECONDS = float(os.getenv("BATCH_TIMEOUT_SECONDS", "30"))
|
||
MIN_OBJECT_PER_BATCH = int(os.getenv("MIN_OBJECT_PER_BATCH", "60"))
|
||
MIN_DURATION_PER_BATCH = int(os.getenv("MIN_DURATION_PER_BATCH", "60"))
|
||
BATCH_MODE = os.getenv("BATCH_MODE", "manual").strip().lower()
|
||
COUNTER_CONTROL_HOST = os.getenv("COUNTER_CONTROL_HOST", "127.0.0.1")
|
||
COUNTER_CONTROL_PORT = int(os.getenv("COUNTER_CONTROL_PORT", "5001"))
|
||
|
||
EXPORT_CSV = os.getenv("EXPORT_CSV", "true").lower() == "true"
|
||
CROSS_CSV = os.getenv("CROSS_CSV", f"{OUTPUT_DIR}/batch_crossings.csv")
|
||
|
||
RATE_WINDOW_SEC = int(os.getenv("RATE_WINDOW_SEC", "60"))
|
||
WARMUP_FRAMES = int(os.getenv("WARMUP_FRAMES", "30"))
|
||
RECONNECT_DELAY_SEC = int(os.getenv("RECONNECT_DELAY_SEC", "3"))
|
||
MAX_RECONNECT_ATTEMPTS = int(os.getenv("MAX_RECONNECT_ATTEMPTS", "0"))
|
||
# Cap user-facing stream error messages per outage (0 = unlimited, keeps FFmpeg stderr)
|
||
STREAM_ERROR_LOG_MAX = int(os.getenv("STREAM_ERROR_LOG_MAX", "3"))
|
||
FLUSH_EVERY_N_FRAMES = int(os.getenv("FLUSH_EVERY_N_FRAMES", "100"))
|
||
TRACKED_PRUNE_SEC = int(os.getenv("TRACKED_PRUNE_SEC", "300"))
|
||
RECORD_VIDEO = os.getenv("RECORD_VIDEO", "false").lower() == "true"
|
||
VIDEO_SEGMENT_SEC = int(os.getenv("VIDEO_SEGMENT_SEC", "3600"))
|
||
OUTPUT_FPS = int(os.getenv("OUTPUT_FPS", "15"))
|
||
|
||
LIVE_STREAM_ENABLED = os.getenv("LIVE_STREAM_ENABLED", "false").lower() == "true"
|
||
LIVE_STREAM_FRAME_PATH = os.getenv(
|
||
"LIVE_STREAM_FRAME_PATH", "/dev/shm/feedmill/live_frame.jpg"
|
||
)
|
||
LIVE_STREAM_META_PATH = os.getenv(
|
||
"LIVE_STREAM_META_PATH", "/dev/shm/feedmill/stream_meta.json"
|
||
)
|
||
LIVE_STREAM_QUALITY = int(os.getenv("LIVE_STREAM_QUALITY", "75"))
|
||
LIVE_STREAM_EVERY_N = int(os.getenv("LIVE_STREAM_EVERY_N", "2"))
|
||
|
||
RTSP_FFMPEG_OPTIONS = os.getenv(
|
||
"OPENCV_FFMPEG_CAPTURE_OPTIONS",
|
||
"rtsp_transport;tcp|fflags;nobuffer|flags;low_delay",
|
||
)
|
||
|
||
IS_LIVE = SOURCE.lower().startswith(("rtsp://", "http://"))
|
||
|
||
MOTION_DETECTION_ENABLED = os.getenv("MOTION_DETECTION_ENABLED", "false").lower() == "true"
|
||
MOTION_THRESHOLD = float(os.getenv("MOTION_THRESHOLD", "5.0"))
|
||
|
||
CROSS_FLASH_FRAMES = 12
|
||
POPUP_LIFETIME = 20
|
||
LINE_PULSE_FRAMES = 12
|
||
COUNT_PULSE_FRAMES = 15
|
||
BATCH_PULSE_FRAMES = 20
|
||
|
||
SKELETON = [(0, 1), (4, 3), (1, 2), (3, 2), (2, 6), (2, 5), (2, 7), (7, 8)]
|
||
SK_COLORS = [
|
||
(0, 255, 255),
|
||
(0, 255, 255),
|
||
(255, 0, 255),
|
||
(255, 0, 255),
|
||
(0, 255, 0),
|
||
(255, 255, 0),
|
||
(0, 0, 255),
|
||
(200, 200, 0),
|
||
]
|
||
|
||
C_PANEL = (28, 24, 18)
|
||
C_BORDER = (90, 85, 75)
|
||
C_ACCENT = (255, 200, 60)
|
||
C_GREEN = (80, 220, 100)
|
||
C_TEXT = (235, 235, 235)
|
||
C_MUTED = (150, 150, 150)
|
||
C_COUNTED_BOX = (0, 165, 255)
|
||
C_LINE_CORE = (180, 220, 255)
|
||
C_LINE_GLOW = (100, 160, 220)
|
||
|
||
shutdown_requested = False
|
||
|
||
|
||
def request_shutdown(signum, frame):
|
||
global shutdown_requested
|
||
shutdown_requested = True
|
||
print("\nShutdown requested — finishing current frame...")
|
||
|
||
|
||
signal.signal(signal.SIGINT, request_shutdown)
|
||
signal.signal(signal.SIGTERM, request_shutdown)
|
||
|
||
|
||
# =============================================================================
|
||
# YOLO output decoder (NMS only — boxes are pre-decoded by the model)
|
||
# =============================================================================
|
||
|
||
|
||
def _nms(boxes, scores, iou_thr=0.45):
|
||
order = np.argsort(scores)[::-1]
|
||
keep = []
|
||
while len(order) > 0:
|
||
idx = order[0]
|
||
keep.append(idx)
|
||
if len(order) == 1:
|
||
break
|
||
xx1 = np.maximum(boxes[idx, 0], boxes[order[1:], 0])
|
||
yy1 = np.maximum(boxes[idx, 1], boxes[order[1:], 1])
|
||
xx2 = np.minimum(boxes[idx, 2], boxes[order[1:], 2])
|
||
yy2 = np.minimum(boxes[idx, 3], boxes[order[1:], 3])
|
||
w = np.maximum(0.0, xx2 - xx1)
|
||
h = np.maximum(0.0, yy2 - yy1)
|
||
inter = w * h
|
||
area_i = (boxes[idx, 2] - boxes[idx, 0]) * (boxes[idx, 3] - boxes[idx, 1])
|
||
area_o = (boxes[order[1:], 2] - boxes[order[1:], 0]) * (
|
||
boxes[order[1:], 3] - boxes[order[1:], 1]
|
||
)
|
||
iou = inter / (area_i + area_o - inter + 1e-16)
|
||
order = order[1:][iou < iou_thr]
|
||
return np.array(keep)
|
||
|
||
|
||
# =============================================================================
|
||
# IoU helpers (xyxy format)
|
||
# =============================================================================
|
||
|
||
|
||
def _ious_xyxy(boxes_a, boxes_b):
|
||
"""Pairwise IoU: (N,4) vs (M,4) → (N,M) matrix."""
|
||
n, m = len(boxes_a), len(boxes_b)
|
||
if n == 0 or m == 0:
|
||
return np.zeros((n, m), dtype=np.float32)
|
||
xx1 = np.maximum(boxes_a[:, None, 0], boxes_b[None, :, 0])
|
||
yy1 = np.maximum(boxes_a[:, None, 1], boxes_b[None, :, 1])
|
||
xx2 = np.minimum(boxes_a[:, None, 2], boxes_b[None, :, 2])
|
||
yy2 = np.minimum(boxes_a[:, None, 3], boxes_b[None, :, 3])
|
||
iw = np.maximum(0.0, xx2 - xx1)
|
||
ih = np.maximum(0.0, yy2 - yy1)
|
||
inter = iw * ih
|
||
area_a = (boxes_a[:, 2] - boxes_a[:, 0]) * (boxes_a[:, 3] - boxes_a[:, 1])
|
||
area_b = (boxes_b[:, 2] - boxes_b[:, 0]) * (boxes_b[:, 3] - boxes_b[:, 1])
|
||
return inter / (area_a[:, None] + area_b[None, :] - inter + 1e-16)
|
||
|
||
|
||
def _greedy_match(cost_matrix, threshold=0.3):
|
||
"""Greedy linear assignment. Returns pairs (row_idx, col_idx)."""
|
||
if cost_matrix.size == 0:
|
||
return []
|
||
n, m = cost_matrix.shape
|
||
flat = [(cost_matrix[i, j], i, j) for i in range(n) for j in range(m)]
|
||
flat.sort()
|
||
row_used = set()
|
||
col_used = set()
|
||
pairs = []
|
||
for cost, i, j in flat:
|
||
if cost >= threshold:
|
||
break
|
||
if i in row_used or j in col_used:
|
||
continue
|
||
row_used.add(i)
|
||
col_used.add(j)
|
||
pairs.append((i, j))
|
||
return pairs
|
||
|
||
|
||
# =============================================================================
|
||
# Kalman filter box tracker (state: x, y, w, h, vx, vy, vw, vh)
|
||
# =============================================================================
|
||
|
||
|
||
class KalmanBoxTracker:
|
||
count = 0
|
||
|
||
def __init__(self, bbox_xyxy):
|
||
KalmanBoxTracker.count += 1
|
||
self.track_id = KalmanBoxTracker.count
|
||
|
||
x1, y1, x2, y2 = bbox_xyxy
|
||
w, h = x2 - x1, y2 - y1
|
||
x, y = x1 + w / 2, y1 + h / 2
|
||
|
||
self.kf = _KalmanFilter()
|
||
self.kf.x[:4, 0] = np.array([x, y, w, h], dtype=np.float32)
|
||
|
||
self.time_since_update = 0
|
||
self.hits = 1
|
||
self.hit_streak = 1
|
||
self.age = 1
|
||
|
||
def predict(self):
|
||
if self.kf.x[6] + self.kf.x[2] <= 0:
|
||
self.kf.x[6] *= 0.0
|
||
self.kf.predict()
|
||
self.age += 1
|
||
self.time_since_update += 1
|
||
|
||
def update(self, bbox_xyxy):
|
||
self.time_since_update = 0
|
||
self.hits += 1
|
||
self.hit_streak += 1
|
||
|
||
x1, y1, x2, y2 = bbox_xyxy
|
||
w, h = x2 - x1, y2 - y1
|
||
x, y = x1 + w / 2, y1 + h / 2
|
||
self.kf.update(np.array([x, y, w, h], dtype=np.float32))
|
||
|
||
def get_state(self):
|
||
"""Returns xyxy bbox from Kalman state."""
|
||
xx = self.kf.x[:4, 0]
|
||
x, y, w, h = xx[0], xx[1], xx[2], xx[3]
|
||
x1 = x - w / 2
|
||
y1 = y - h / 2
|
||
x2 = x + w / 2
|
||
y2 = y + h / 2
|
||
return np.array([x1, y1, x2, y2], dtype=np.float32)
|
||
|
||
def get_center(self):
|
||
return float(self.kf.x[0, 0]), float(self.kf.x[1, 0])
|
||
|
||
|
||
class _KalmanFilter:
|
||
"""8-state constant-velocity Kalman filter for bounding box tracking."""
|
||
|
||
def __init__(self):
|
||
ndim, dt = 4, 1.0
|
||
self.motion_mat = np.eye(2 * ndim, 2 * ndim, dtype=np.float32)
|
||
for i in range(ndim):
|
||
self.motion_mat[i, ndim + i] = dt
|
||
self.update_mat = np.eye(ndim, 2 * ndim, dtype=np.float32)
|
||
|
||
self._std_weight_position = 1.0 / 20
|
||
self._std_weight_velocity = 1.0 / 160
|
||
|
||
self.x = np.zeros((8, 1), dtype=np.float32)
|
||
self.P = np.eye(8, dtype=np.float32) * 10.0
|
||
self.P[4:6, 4:6] *= 100.0
|
||
|
||
def predict(self):
|
||
w = float(self.x[2, 0])
|
||
h = float(self.x[3, 0])
|
||
std_pos = [
|
||
self._std_weight_position * w,
|
||
self._std_weight_position * h,
|
||
self._std_weight_position * w,
|
||
self._std_weight_position * h,
|
||
]
|
||
std_vel = [
|
||
self._std_weight_velocity * w,
|
||
self._std_weight_velocity * h,
|
||
self._std_weight_velocity * w,
|
||
self._std_weight_velocity * h,
|
||
]
|
||
Q = np.diag(np.square(np.array(std_pos + std_vel, dtype=np.float32)))
|
||
|
||
self.x = self.motion_mat @ self.x
|
||
self.P = self.motion_mat @ self.P @ self.motion_mat.T + Q
|
||
|
||
def update(self, z):
|
||
R = np.diag(
|
||
np.square(
|
||
[
|
||
self._std_weight_position * z[2],
|
||
self._std_weight_position * z[3],
|
||
self._std_weight_position * z[2],
|
||
self._std_weight_position * z[3],
|
||
]
|
||
)
|
||
)
|
||
|
||
H = self.update_mat
|
||
S = H @ self.P @ H.T + R
|
||
K = self.P @ H.T @ np.linalg.inv(S)
|
||
|
||
y = z.reshape(4, 1) - H @ self.x
|
||
self.x = self.x + K @ y
|
||
I_KH = np.eye(8) - K @ H
|
||
self.P = I_KH @ self.P @ I_KH.T + K @ R @ K.T
|
||
|
||
|
||
# =============================================================================
|
||
# ByteTrack multi-object tracker
|
||
# =============================================================================
|
||
|
||
|
||
class ByteTracker:
|
||
"""ByteTrack: two-stage association with Kalman filter prediction."""
|
||
|
||
def __init__(
|
||
self,
|
||
track_high_thresh=0.5,
|
||
track_low_thresh=0.1,
|
||
match_thresh=0.8,
|
||
track_buffer=30,
|
||
min_hits=3,
|
||
):
|
||
self.high_thresh = track_high_thresh
|
||
self.low_thresh = track_low_thresh
|
||
self.match_thresh = match_thresh
|
||
self.track_buffer = track_buffer
|
||
self.min_hits = min_hits
|
||
self.tracked_tracks = []
|
||
self.lost_tracks = []
|
||
self.removed_tracks = []
|
||
self.frame_id = 0
|
||
|
||
def update(self, boxes_xyxy, scores, high_thresholds=None):
|
||
self.frame_id += 1
|
||
|
||
# --- separate detections by score ---
|
||
if len(boxes_xyxy) > 0:
|
||
remain = scores >= self.low_thresh
|
||
remain_orig_idx = np.where(remain)[0]
|
||
dets = boxes_xyxy[remain]
|
||
det_scores = scores[remain]
|
||
if high_thresholds is not None:
|
||
det_high_thr = np.maximum(
|
||
np.asarray(high_thresholds, dtype=np.float32)[remain],
|
||
self.high_thresh,
|
||
)
|
||
is_high = det_scores >= det_high_thr
|
||
else:
|
||
is_high = det_scores >= self.high_thresh
|
||
is_low = ~is_high
|
||
else:
|
||
remain_orig_idx = np.zeros(0, dtype=np.int64)
|
||
dets = np.zeros((0, 4), dtype=np.float32)
|
||
det_scores = np.zeros(0, dtype=np.float32)
|
||
is_high = np.zeros(0, dtype=bool)
|
||
is_low = np.zeros(0, dtype=bool)
|
||
|
||
# --- Kalman predict all existing tracks ---
|
||
track_pool = self.tracked_tracks + self.lost_tracks
|
||
num_tracks = len(track_pool)
|
||
|
||
# Per-frame tracking results
|
||
matched_track_idx = set()
|
||
det_to_track = {}
|
||
tracked_map = {}
|
||
lost_map = {}
|
||
|
||
# Pre-allocate these for scoping
|
||
high_idx = np.array([], dtype=np.int64)
|
||
low_idx = np.array([], dtype=np.int64)
|
||
match_pairs_high = []
|
||
|
||
if num_tracks > 0:
|
||
track_boxes = np.zeros((num_tracks, 4), dtype=np.float32)
|
||
for ti, trk in enumerate(track_pool):
|
||
trk.predict()
|
||
track_boxes[ti] = trk.get_state()
|
||
|
||
# --- first association: high-score ↔ all tracks ---
|
||
high_idx = np.where(is_high)[0]
|
||
high_dets = dets[is_high]
|
||
|
||
unmatched_tracks = list(range(num_tracks))
|
||
|
||
if len(high_dets) > 0:
|
||
iou_mat = _ious_xyxy(high_dets, track_boxes)
|
||
cost_mat = 1.0 - iou_mat
|
||
matches = _greedy_match(cost_mat, threshold=1.0 - self.match_thresh)
|
||
|
||
for di, ti in matches:
|
||
det_global = int(high_idx[di])
|
||
orig_idx = int(remain_orig_idx[det_global])
|
||
track_pool[ti].update(dets[det_global])
|
||
track_pool[ti].hit_streak = max(1, track_pool[ti].hit_streak)
|
||
matched_track_idx.add(ti)
|
||
det_to_track[orig_idx] = track_pool[ti].track_id
|
||
tracked_map[track_pool[ti].track_id] = track_pool[ti].get_center()
|
||
match_pairs_high.append((det_global, ti))
|
||
|
||
unmatched_tracks = [
|
||
t for t in range(num_tracks) if t not in matched_track_idx
|
||
]
|
||
|
||
# --- second association: low-score ↔ unmatched tracks ---
|
||
low_idx = np.where(is_low)[0]
|
||
low_dets = dets[is_low]
|
||
|
||
if len(low_dets) > 0 and len(unmatched_tracks) > 0:
|
||
unmatched_boxes = track_boxes[unmatched_tracks]
|
||
iou_mat = _ious_xyxy(low_dets, unmatched_boxes)
|
||
cost_mat = 1.0 - iou_mat
|
||
matches2 = _greedy_match(
|
||
cost_mat, threshold=1.0 - self.match_thresh
|
||
)
|
||
|
||
for di, uti in matches2:
|
||
det_global = int(low_idx[di])
|
||
pool_idx = unmatched_tracks[uti]
|
||
orig_idx = int(remain_orig_idx[det_global])
|
||
track_pool[pool_idx].update(dets[det_global])
|
||
track_pool[pool_idx].hit_streak = max(
|
||
1, track_pool[pool_idx].hit_streak
|
||
)
|
||
matched_track_idx.add(pool_idx)
|
||
det_to_track[orig_idx] = track_pool[pool_idx].track_id
|
||
tracked_map[track_pool[pool_idx].track_id] = track_pool[
|
||
pool_idx
|
||
].get_center()
|
||
|
||
# --- reset hit_streak for unmatched tracks ---
|
||
for ti, trk in enumerate(track_pool):
|
||
if ti not in matched_track_idx:
|
||
trk.hit_streak = 0
|
||
|
||
# --- lifecycle management ---
|
||
new_tracked = []
|
||
new_lost = []
|
||
for trk in track_pool:
|
||
if trk.time_since_update > self.track_buffer:
|
||
self.removed_tracks.append(trk)
|
||
elif trk.time_since_update > 0:
|
||
new_lost.append(trk)
|
||
else:
|
||
new_tracked.append(trk)
|
||
self.tracked_tracks = new_tracked
|
||
self.lost_tracks = new_lost
|
||
|
||
# --- confirmed tracks (both tracked and lost) ---
|
||
for trk in self.tracked_tracks + self.lost_tracks:
|
||
if trk.hit_streak >= self.min_hits or trk.hits >= self.min_hits:
|
||
tracked_map.setdefault(trk.track_id, trk.get_center())
|
||
|
||
for trk in self.lost_tracks:
|
||
if trk.hit_streak >= self.min_hits or trk.hits >= self.min_hits:
|
||
lost_map[trk.track_id] = trk.get_center()
|
||
|
||
# --- new tracks from unmatched high-score dets ---
|
||
high_all = np.where(is_high)[0]
|
||
matched_det_ids = set(det_to_track.keys())
|
||
for dg in high_all:
|
||
orig_idx = int(remain_orig_idx[int(dg)])
|
||
if orig_idx not in matched_det_ids:
|
||
trk = KalmanBoxTracker(dets[int(dg)])
|
||
self.tracked_tracks.append(trk)
|
||
det_to_track[orig_idx] = trk.track_id
|
||
tracked_map[trk.track_id] = trk.get_center()
|
||
|
||
return tracked_map, det_to_track, lost_map
|
||
|
||
|
||
# =============================================================================
|
||
# RKNN YOLO wrapper (supports both Detect (B, 4+nc, N) and OBB (B, 4+nc+1, N))
|
||
# =============================================================================
|
||
|
||
|
||
def _xywhr_to_corners(cx, cy, w, h, angle):
|
||
"""Convert (N,) arrays of cx, cy, w, h, angle (radians) to (N, 4, 2) corner points."""
|
||
cos_a = np.cos(angle)
|
||
sin_a = np.sin(angle)
|
||
wx = (w / 2.0) * cos_a
|
||
wy = (w / 2.0) * sin_a
|
||
hx = -(h / 2.0) * sin_a
|
||
hy = (h / 2.0) * cos_a
|
||
p1 = np.stack([cx + wx + hx, cy + wy + hy], axis=-1)
|
||
p2 = np.stack([cx + wx - hx, cy + wy - hy], axis=-1)
|
||
p3 = np.stack([cx - wx - hx, cy - wy - hy], axis=-1)
|
||
p4 = np.stack([cx - wx + hx, cy - wy + hy], axis=-1)
|
||
return np.stack([p1, p2, p3, p4], axis=1)
|
||
|
||
|
||
class RKNNYOLO:
|
||
def __init__(
|
||
self,
|
||
model_path,
|
||
core_mask=1,
|
||
imgsz=320,
|
||
conf=0.3,
|
||
iou=0.45,
|
||
num_classes=1,
|
||
num_keypoints=0,
|
||
score_sigmoid=False,
|
||
):
|
||
self.imgsz = imgsz
|
||
self.conf = conf
|
||
self.iou = iou
|
||
self.num_classes = num_classes
|
||
self.num_keypoints = num_keypoints
|
||
self.score_sigmoid = score_sigmoid
|
||
|
||
self.rknn = RKNNLite(verbose=False)
|
||
ret = self.rknn.load_rknn(model_path)
|
||
if ret != 0:
|
||
raise RuntimeError(f"Failed to load RKNN model: {model_path}")
|
||
ret = self.rknn.init_runtime(core_mask=core_mask)
|
||
if ret != 0:
|
||
raise RuntimeError(f"Failed to init RKNN runtime (core_mask={core_mask})")
|
||
|
||
try:
|
||
sdk_ver = self.rknn.get_sdk_version()
|
||
print(f"RKNN SDK version: {sdk_ver}")
|
||
except Exception:
|
||
pass
|
||
|
||
print(f"RKNN model loaded: {model_path} imgsz={imgsz} core_mask={core_mask}")
|
||
|
||
def _preprocess(self, frame):
|
||
h0, w0 = frame.shape[:2]
|
||
scale = min(self.imgsz / h0, self.imgsz / w0)
|
||
nh, nw = int(h0 * scale), int(w0 * scale)
|
||
resized = cv2.resize(frame, (nw, nh), interpolation=cv2.INTER_LINEAR)
|
||
|
||
letterbox = np.full((self.imgsz, self.imgsz, 3), 114, dtype=np.uint8)
|
||
dy = (self.imgsz - nh) // 2
|
||
dx = (self.imgsz - nw) // 2
|
||
letterbox[dy : dy + nh, dx : dx + nw] = resized
|
||
|
||
rgb = cv2.cvtColor(letterbox, cv2.COLOR_BGR2RGB)
|
||
gains = np.array([scale, scale, dy, dx], dtype=np.float32)
|
||
return rgb, gains
|
||
|
||
def _decode_multibranch(self, outputs):
|
||
"""Decode multi-branch 4D RKNN outputs: 3 scales x [box_dfl(64), cls(nc), optional angle(1)]."""
|
||
n_outs = len(outputs)
|
||
if (
|
||
n_outs >= 3
|
||
and n_outs % 3 == 0
|
||
and outputs[0].shape[-2:] == outputs[2].shape[-2:]
|
||
):
|
||
step = 3
|
||
else:
|
||
step = 2
|
||
n_scales = n_outs // step
|
||
is_obb = step == 3
|
||
reg_max = 16
|
||
dfl_proj = np.arange(reg_max, dtype=np.float32)
|
||
|
||
boxes_list = []
|
||
scores_list = []
|
||
clses_list = []
|
||
angles_list = []
|
||
|
||
for i in range(n_scales):
|
||
b_raw = outputs[i * step]
|
||
c_raw = outputs[i * step + 1]
|
||
a_raw = outputs[i * step + 2] if is_obb else None
|
||
|
||
if b_raw.ndim == 4:
|
||
b_raw = b_raw[0]
|
||
if c_raw.ndim == 4:
|
||
c_raw = c_raw[0]
|
||
if a_raw is not None and a_raw.ndim == 4:
|
||
a_raw = a_raw[0]
|
||
|
||
c_ch, H, W = b_raw.shape
|
||
reg_max_s = c_ch // 4
|
||
if reg_max_s != reg_max:
|
||
dfl_proj = np.arange(reg_max_s, dtype=np.float32)
|
||
reg_max = reg_max_s
|
||
stride = self.imgsz / float(H)
|
||
|
||
if self.score_sigmoid or c_raw.min() < -0.001 or c_raw.max() > 1.001:
|
||
c_scores = 1.0 / (1.0 + np.exp(-np.clip(c_raw, -50.0, 50.0)))
|
||
else:
|
||
c_scores = c_raw
|
||
|
||
max_s = c_scores.max(axis=0)
|
||
mask = max_s >= self.conf
|
||
if not np.any(mask):
|
||
continue
|
||
|
||
gy, gx = np.where(mask)
|
||
cls_ids = c_scores.argmax(axis=0)[gy, gx]
|
||
sc = max_s[gy, gx].astype(np.float32)
|
||
|
||
b_sel = b_raw[:, gy, gx].T.reshape(-1, 4, reg_max)
|
||
b_exp = np.exp(b_sel - b_sel.max(axis=2, keepdims=True))
|
||
b_prob = b_exp / b_exp.sum(axis=2, keepdims=True)
|
||
lt_rb = (b_prob * dfl_proj).sum(axis=2)
|
||
l, t, r, b = lt_rb[:, 0], lt_rb[:, 1], lt_rb[:, 2], lt_rb[:, 3]
|
||
|
||
gx_f = gx.astype(np.float32) + 0.5
|
||
gy_f = gy.astype(np.float32) + 0.5
|
||
|
||
if is_obb and a_raw is not None:
|
||
a_sel = a_raw[0, gy, gx].astype(np.float32)
|
||
ang = (1.0 / (1.0 + np.exp(-np.clip(a_sel, -50.0, 50.0))) - 0.25) * np.pi
|
||
xf = (r - l) / 2.0
|
||
yf = (b - t) / 2.0
|
||
cos_a = np.cos(ang)
|
||
sin_a = np.sin(ang)
|
||
dx_r = xf * cos_a - yf * sin_a
|
||
dy_r = xf * sin_a + yf * cos_a
|
||
cx = (gx_f + dx_r) * stride
|
||
cy = (gy_f + dy_r) * stride
|
||
angles_list.append(ang.astype(np.float32))
|
||
else:
|
||
cx = (gx_f + (r - l) / 2.0) * stride
|
||
cy = (gy_f + (b - t) / 2.0) * stride
|
||
|
||
bw = (l + r) * stride
|
||
bh = (t + b) * stride
|
||
boxes_list.append(np.stack([cx, cy, bw, bh], axis=1))
|
||
scores_list.append(sc)
|
||
clses_list.append(cls_ids)
|
||
|
||
if not boxes_list:
|
||
return None
|
||
|
||
boxes_cxcywh = np.concatenate(boxes_list, axis=0)
|
||
scores = np.concatenate(scores_list, axis=0)
|
||
clses = np.concatenate(clses_list, axis=0)
|
||
angles = np.concatenate(angles_list, axis=0) if (is_obb and angles_list) else None
|
||
return boxes_cxcywh, scores, clses, angles, is_obb
|
||
|
||
def __call__(self, frame):
|
||
h0, w0 = frame.shape[:2]
|
||
rgb, gains = self._preprocess(frame)
|
||
scale, _, pad_y, pad_x = gains
|
||
|
||
inp = np.expand_dims(rgb, axis=0)
|
||
inp = np.ascontiguousarray(inp.astype(np.uint8))
|
||
|
||
outputs = self.rknn.inference(inputs=[inp])
|
||
|
||
if len(outputs) == 0:
|
||
return []
|
||
|
||
if len(outputs) > 1 and outputs[0].ndim == 4:
|
||
decoded = self._decode_multibranch(outputs)
|
||
if decoded is None:
|
||
return []
|
||
boxes_filtered, scores, clses, angles, is_obb = decoded
|
||
cx = (boxes_filtered[:, 0] - pad_x) / scale
|
||
cy = (boxes_filtered[:, 1] - pad_y) / scale
|
||
bw = boxes_filtered[:, 2] / scale
|
||
bh = boxes_filtered[:, 3] / scale
|
||
else:
|
||
out = outputs[0]
|
||
if out.ndim == 3:
|
||
out = out[0]
|
||
|
||
if out.shape[0] in (self.num_classes + 4, self.num_classes + 5) or out.shape[0] < out.shape[1]:
|
||
out = out.T
|
||
|
||
is_obb = out.shape[1] >= self.num_classes + 5
|
||
boxes_cxcywh = out[:, :4].copy()
|
||
cls_raw = out[:, 4 : 4 + self.num_classes].copy()
|
||
angles_raw = out[:, 4 + self.num_classes].copy() if is_obb else None
|
||
|
||
if self.score_sigmoid:
|
||
cls_scores = 1.0 / (1.0 + np.exp(-np.clip(cls_raw, -10, 10)))
|
||
else:
|
||
cls_scores = cls_raw
|
||
|
||
max_scores = cls_scores.max(axis=1)
|
||
class_ids = cls_scores.argmax(axis=1)
|
||
mask = max_scores >= self.conf
|
||
|
||
if mask.sum() == 0:
|
||
return []
|
||
|
||
scores = max_scores[mask].astype(np.float32)
|
||
clses = class_ids[mask]
|
||
cx = (boxes_cxcywh[mask, 0] - pad_x) / scale
|
||
cy = (boxes_cxcywh[mask, 1] - pad_y) / scale
|
||
bw = boxes_cxcywh[mask, 2] / scale
|
||
bh = boxes_cxcywh[mask, 3] / scale
|
||
angles = angles_raw[mask].astype(np.float32) if is_obb else None
|
||
|
||
if is_obb:
|
||
obb_corners = _xywhr_to_corners(cx, cy, bw, bh, angles)
|
||
bboxes = np.stack(
|
||
[
|
||
obb_corners[:, :, 0].min(axis=1),
|
||
obb_corners[:, :, 1].min(axis=1),
|
||
obb_corners[:, :, 0].max(axis=1),
|
||
obb_corners[:, :, 1].max(axis=1),
|
||
],
|
||
axis=1,
|
||
).astype(np.float32)
|
||
else:
|
||
angles = None
|
||
obb_corners = None
|
||
bboxes = np.stack(
|
||
[cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2], axis=1
|
||
).astype(np.float32)
|
||
bboxes[:, 0] = np.clip(bboxes[:, 0], 0, w0)
|
||
bboxes[:, 1] = np.clip(bboxes[:, 1], 0, h0)
|
||
bboxes[:, 2] = np.clip(bboxes[:, 2], 0, w0)
|
||
bboxes[:, 3] = np.clip(bboxes[:, 3], 0, h0)
|
||
|
||
detections = []
|
||
for cls_id in range(self.num_classes):
|
||
idx = np.where(clses == cls_id)[0]
|
||
if len(idx) == 0:
|
||
continue
|
||
if is_obb:
|
||
rboxes = [
|
||
(
|
||
(float(cx[i]), float(cy[i])),
|
||
(float(bw[i]), float(bh[i])),
|
||
float(np.degrees(angles[i])),
|
||
)
|
||
for i in idx
|
||
]
|
||
keep = cv2.dnn.NMSBoxesRotated(
|
||
rboxes,
|
||
scores[idx].tolist(),
|
||
max(0.0, float(self.conf) - 1e-5),
|
||
float(self.iou),
|
||
)
|
||
keep = np.array(keep).flatten() if len(keep) > 0 else np.array([], dtype=int)
|
||
else:
|
||
keep = _nms(bboxes[idx], scores[idx], iou_thr=self.iou)
|
||
for k in keep:
|
||
j = idx[k]
|
||
detections.append(
|
||
{
|
||
"bbox": bboxes[j].tolist(),
|
||
"obb": obb_corners[j].tolist() if is_obb else None,
|
||
"score": float(scores[j]),
|
||
"cls": int(clses[j]),
|
||
"keypoints": None,
|
||
}
|
||
)
|
||
return detections
|
||
|
||
def release(self):
|
||
self.rknn.release()
|
||
|
||
|
||
# =============================================================================
|
||
# Drawing helpers
|
||
# =============================================================================
|
||
|
||
|
||
def resolve_count_axis():
|
||
if COUNT_AXIS in {"x", "horizontal"}:
|
||
return "x"
|
||
if COUNT_AXIS in {"y", "vertical"}:
|
||
return "y"
|
||
if CROSS_DIRECTION in {"up", "down"} or LINE_Y is not None or LINE_Y_FRAC != 0.5:
|
||
return "y"
|
||
return "x"
|
||
|
||
|
||
def resolve_count_line(frame_width, frame_height, axis):
|
||
if axis == "y":
|
||
if LINE_Y is not None:
|
||
return LINE_Y
|
||
if LINE_Y_FRAC != 0.5:
|
||
return int(frame_height * LINE_Y_FRAC)
|
||
return frame_height // 2
|
||
if LINE_X is not None:
|
||
return LINE_X
|
||
if LINE_X_FRAC != 0.5:
|
||
return int(frame_width * LINE_X_FRAC)
|
||
return frame_width // 2
|
||
|
||
|
||
def resolve_manual_zone_x(frame_width):
|
||
x1 = ZONE_X_MIN if ZONE_X_MIN is not None else int(frame_width * ZONE_X_MIN_FRAC)
|
||
x2 = ZONE_X_MAX if ZONE_X_MAX is not None else int(frame_width * ZONE_X_MAX_FRAC)
|
||
x1 = max(0, min(frame_width - 1, x1))
|
||
x2 = max(x1 + 1, min(frame_width, x2))
|
||
return x1, x2
|
||
|
||
|
||
def crossed_line(prev_pos, curr_pos, line_pos, direction=CROSS_DIRECTION):
|
||
if direction in {"ltr", "right"}:
|
||
return prev_pos < line_pos <= curr_pos
|
||
if direction in {"rtl", "left"}:
|
||
return prev_pos > line_pos >= curr_pos
|
||
if direction == "up":
|
||
return prev_pos > line_pos >= curr_pos
|
||
if direction == "both":
|
||
return (prev_pos > line_pos >= curr_pos) or (prev_pos < line_pos <= curr_pos)
|
||
return prev_pos < line_pos <= curr_pos
|
||
|
||
|
||
def is_duplicate_cross(recent, along_pos, frame_idx, active_tids=None):
|
||
"""True if a crossing near along_pos happened within the dedup window from a now-inactive track."""
|
||
while recent and frame_idx - recent[0][0] > DEDUP_FRAMES:
|
||
recent.popleft()
|
||
for entry in recent:
|
||
prev_along = entry[1]
|
||
prev_tid = entry[2] if len(entry) > 2 else None
|
||
if prev_tid is not None and active_tids and prev_tid in active_tids:
|
||
continue
|
||
if abs(prev_along - along_pos) <= DEDUP_PX:
|
||
return True
|
||
return False
|
||
|
||
|
||
def now_str():
|
||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||
|
||
|
||
@contextlib.contextmanager
|
||
def _quiet_opencv_stderr():
|
||
"""Silence OpenCV/FFmpeg stderr (DESCRIBE failed, cap.cpp WARN, etc.)."""
|
||
saved_fd = None
|
||
devnull_fd = None
|
||
try:
|
||
stderr_fd = sys.stderr.fileno()
|
||
saved_fd = os.dup(stderr_fd)
|
||
devnull_fd = os.open(os.devnull, os.O_WRONLY)
|
||
os.dup2(devnull_fd, stderr_fd)
|
||
except (AttributeError, OSError, ValueError):
|
||
yield
|
||
return
|
||
try:
|
||
yield
|
||
finally:
|
||
os.dup2(saved_fd, stderr_fd)
|
||
os.close(saved_fd)
|
||
os.close(devnull_fd)
|
||
|
||
|
||
def open_capture(source):
|
||
if source.lower().startswith(("rtsp://", "http://")):
|
||
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = RTSP_FFMPEG_OPTIONS
|
||
# When STREAM_ERROR_LOG_MAX > 0, native OpenCV/FFmpeg stderr is suppressed;
|
||
# stream_error_log emits at most that many user-facing messages per outage.
|
||
if STREAM_ERROR_LOG_MAX > 0:
|
||
with _quiet_opencv_stderr():
|
||
cap = cv2.VideoCapture(source, cv2.CAP_FFMPEG)
|
||
else:
|
||
cap = cv2.VideoCapture(source, cv2.CAP_FFMPEG)
|
||
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
|
||
return cap
|
||
|
||
|
||
def warmup_stream(cap, n=WARMUP_FRAMES):
|
||
print("Warming up stream...")
|
||
for _ in range(n):
|
||
cap.read()
|
||
print("Stream ready!")
|
||
|
||
|
||
def open_video_writer(path, w, h, fps):
|
||
return cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*"avc1"), fps, (w, h))
|
||
|
||
|
||
class CsvLogger:
|
||
def __init__(self, path, header):
|
||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||
new_file = not Path(path).exists() or Path(path).stat().st_size == 0
|
||
self.file = open(path, "a", newline="", buffering=1)
|
||
self.writer = csv.writer(self.file)
|
||
if new_file:
|
||
self.writer.writerow(header)
|
||
self.file.flush()
|
||
|
||
def write_row(self, row):
|
||
self.writer.writerow(row)
|
||
self.file.flush()
|
||
|
||
def close(self):
|
||
self.file.close()
|
||
|
||
|
||
class VideoSegmentWriter:
|
||
def __init__(self, output_dir, w, h, fps, segment_sec):
|
||
self.output_dir = Path(output_dir)
|
||
self.output_dir.mkdir(parents=True, exist_ok=True)
|
||
self.w, self.h, self.fps = w, h, fps
|
||
self.segment_sec = segment_sec
|
||
self.segment_start = time.monotonic()
|
||
self.writer = None
|
||
self._open_next()
|
||
|
||
def _segment_path(self):
|
||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||
return str(self.output_dir / f"live_{ts}.mp4")
|
||
|
||
def _open_next(self):
|
||
if self.writer is not None:
|
||
self.writer.release()
|
||
path = self._segment_path()
|
||
self.writer = open_video_writer(path, self.w, self.h, self.fps)
|
||
self.segment_start = time.monotonic()
|
||
print(f"Recording segment: {path}")
|
||
|
||
def write(self, frame):
|
||
if time.monotonic() - self.segment_start >= self.segment_sec:
|
||
self._open_next()
|
||
self.writer.write(frame)
|
||
|
||
def release(self):
|
||
if self.writer is not None:
|
||
self.writer.release()
|
||
|
||
|
||
def prune_stale_tracks(tracked, now_mono):
|
||
stale = [
|
||
tid for tid, (_, _, ts) in tracked.items() if now_mono - ts > TRACKED_PRUNE_SEC
|
||
]
|
||
for tid in stale:
|
||
del tracked[tid]
|
||
|
||
|
||
def overlay_rect(img, x1, y1, x2, y2, color, alpha=0.65):
|
||
x1, y1 = max(0, x1), max(0, y1)
|
||
x2, y2 = min(img.shape[1], x2), min(img.shape[0], y2)
|
||
if x2 <= x1 or y2 <= y1:
|
||
return
|
||
roi = img[y1:y2, x1:x2]
|
||
patch = np.full_like(roi, color, dtype=np.uint8)
|
||
cv2.addWeighted(patch, alpha, roi, 1 - alpha, 0, roi)
|
||
|
||
|
||
def draw_pill(img, text, x, y, bg, fg=C_TEXT, font_scale=0.45, pad_x=6, pad_y=4):
|
||
font = cv2.FONT_HERSHEY_SIMPLEX
|
||
(tw, th), baseline = cv2.getTextSize(text, font, font_scale, 1)
|
||
x1, y1 = x, y - th - pad_y
|
||
x2, y2 = x + tw + pad_x * 2, y + baseline + pad_y
|
||
cv2.rectangle(img, (x1, y1), (x2, y2), bg, -1)
|
||
cv2.rectangle(img, (x1, y1), (x2, y2), C_BORDER, 1)
|
||
cv2.putText(img, text, (x + pad_x, y), font, font_scale, fg, 1, cv2.LINE_AA)
|
||
|
||
|
||
def draw_elegant_counting_line(img, axis, line_pos, w, h, pulse_remaining=0):
|
||
strength = pulse_remaining / max(LINE_PULSE_FRAMES, 1)
|
||
glow_alpha = 0.12 + 0.18 * strength
|
||
color = tuple(int(c * glow_alpha) for c in C_LINE_GLOW)
|
||
if axis == "y":
|
||
for offset in (14, 9, 5):
|
||
cv2.line(
|
||
img, (0, line_pos - offset), (w, line_pos - offset), color, 1, cv2.LINE_AA
|
||
)
|
||
cv2.line(
|
||
img, (0, line_pos + offset), (w, line_pos + offset), color, 1, cv2.LINE_AA
|
||
)
|
||
dash_len, gap = 18, 12
|
||
x = 0
|
||
while x < w:
|
||
x_end = min(x + dash_len, w)
|
||
cv2.line(img, (x, line_pos), (x_end, line_pos), C_LINE_CORE, 2, cv2.LINE_AA)
|
||
x += dash_len + gap
|
||
text_origin = (12, max(24, line_pos - 10))
|
||
else:
|
||
for offset in (14, 9, 5):
|
||
cv2.line(
|
||
img, (line_pos - offset, 0), (line_pos - offset, h), color, 1, cv2.LINE_AA
|
||
)
|
||
cv2.line(
|
||
img, (line_pos + offset, 0), (line_pos + offset, h), color, 1, cv2.LINE_AA
|
||
)
|
||
dash_len, gap = 18, 12
|
||
y = 0
|
||
while y < h:
|
||
y_end = min(y + dash_len, h)
|
||
cv2.line(img, (line_pos, y), (line_pos, y_end), C_LINE_CORE, 2, cv2.LINE_AA)
|
||
y += dash_len + gap
|
||
text_origin = (max(12, line_pos - 46), 24)
|
||
|
||
cv2.putText(
|
||
img, "COUNT LINE", text_origin, cv2.FONT_HERSHEY_SIMPLEX, 0.42, C_LINE_CORE, 1, cv2.LINE_AA
|
||
)
|
||
|
||
|
||
def draw_counting_zone_x(img, zone_x1, zone_x2, w, h, zone_source="AUTO"):
|
||
top_y = 40
|
||
bot_y = h - 28
|
||
if zone_x1 > 0:
|
||
overlay_rect(img, 0, top_y, zone_x1, bot_y, (10, 10, 10), alpha=0.28)
|
||
if zone_x2 < w:
|
||
overlay_rect(img, zone_x2, top_y, w, bot_y, (10, 10, 10), alpha=0.28)
|
||
|
||
zone_color = (255, 220, 60) if "MANUAL" not in zone_source else (100, 200, 255)
|
||
dash_len, gap = 14, 10
|
||
for zx in (zone_x1, zone_x2):
|
||
if 0 < zx < w:
|
||
y = top_y
|
||
while y < bot_y:
|
||
y_end = min(y + dash_len, bot_y)
|
||
cv2.line(img, (zx, y), (zx, y_end), zone_color, 2, cv2.LINE_AA)
|
||
y += dash_len + gap
|
||
|
||
label_x = max(8, min(w - 220, zone_x1 + 8))
|
||
draw_pill(
|
||
img,
|
||
f"ZONE X: {zone_x1}-{zone_x2} [{zone_source}]",
|
||
label_x,
|
||
top_y + 20,
|
||
(35, 35, 30),
|
||
fg=zone_color,
|
||
font_scale=0.40,
|
||
)
|
||
|
||
|
||
def draw_hero_count(img, axis, line_pos, w, h, count, pulse_remaining=0):
|
||
text = str(count)
|
||
font = cv2.FONT_HERSHEY_SIMPLEX
|
||
boost = 0.35 * (pulse_remaining / max(COUNT_PULSE_FRAMES, 1))
|
||
font_scale, thickness = 1.4 + boost, 3
|
||
(tw, th), _ = cv2.getTextSize(text, font, font_scale, thickness)
|
||
pad = 14
|
||
if axis == "y":
|
||
tx = max(18, w - tw - 32)
|
||
ty = max(th + pad + 8, line_pos - 18)
|
||
else:
|
||
tx, ty = line_pos - tw // 2, h // 3 + th // 2
|
||
overlay_rect(
|
||
img, tx - pad, ty - th - pad, tx + tw + pad, ty + pad, C_PANEL, alpha=0.78
|
||
)
|
||
cv2.rectangle(
|
||
img, (tx - pad, ty - th - pad), (tx + tw + pad, ty + pad), C_LINE_CORE, 2
|
||
)
|
||
cv2.putText(img, text, (tx, ty), font, font_scale, C_GREEN, thickness, cv2.LINE_AA)
|
||
|
||
|
||
def draw_hud(img, w, batch_num, batch_count, total_count, elapsed_sec, rate, batch_type=None):
|
||
bar_h = 40
|
||
overlay_rect(img, 0, 0, w, bar_h, C_PANEL, alpha=0.72)
|
||
cv2.line(img, (0, bar_h), (w, bar_h), C_BORDER, 1)
|
||
cv2.putText(
|
||
img, "BATCH", (14, 14), cv2.FONT_HERSHEY_SIMPLEX, 0.32, C_MUTED, 1, cv2.LINE_AA
|
||
)
|
||
if batch_num:
|
||
btype_str = f" {batch_type.upper()}" if batch_type else ""
|
||
batch_label = f"#{batch_num}{btype_str}"
|
||
else:
|
||
batch_label = "STOPPED"
|
||
batch_color = C_ACCENT if batch_num else (130, 130, 130)
|
||
cv2.putText(
|
||
img,
|
||
batch_label,
|
||
(14, 32),
|
||
cv2.FONT_HERSHEY_SIMPLEX,
|
||
0.46 if batch_num else 0.42,
|
||
batch_color,
|
||
1,
|
||
cv2.LINE_AA,
|
||
)
|
||
cv2.putText(
|
||
img, "COUNT", (90, 14), cv2.FONT_HERSHEY_SIMPLEX, 0.32, C_MUTED, 1, cv2.LINE_AA
|
||
)
|
||
cv2.putText(
|
||
img,
|
||
str(batch_count),
|
||
(90, 32),
|
||
cv2.FONT_HERSHEY_SIMPLEX,
|
||
0.55,
|
||
C_GREEN,
|
||
1,
|
||
cv2.LINE_AA,
|
||
)
|
||
cv2.putText(
|
||
img, "TOTAL", (170, 14), cv2.FONT_HERSHEY_SIMPLEX, 0.32, C_MUTED, 1, cv2.LINE_AA
|
||
)
|
||
cv2.putText(
|
||
img,
|
||
str(total_count),
|
||
(170, 32),
|
||
cv2.FONT_HERSHEY_SIMPLEX,
|
||
0.45,
|
||
C_TEXT,
|
||
1,
|
||
cv2.LINE_AA,
|
||
)
|
||
cv2.putText(
|
||
img,
|
||
"UPTIME",
|
||
(250, 14),
|
||
cv2.FONT_HERSHEY_SIMPLEX,
|
||
0.32,
|
||
C_MUTED,
|
||
1,
|
||
cv2.LINE_AA,
|
||
)
|
||
cv2.putText(
|
||
img,
|
||
f"{elapsed_sec / 3600:.1f}h",
|
||
(250, 32),
|
||
cv2.FONT_HERSHEY_SIMPLEX,
|
||
0.45,
|
||
C_TEXT,
|
||
1,
|
||
cv2.LINE_AA,
|
||
)
|
||
cv2.putText(
|
||
img, "RATE", (340, 14), cv2.FONT_HERSHEY_SIMPLEX, 0.32, C_MUTED, 1, cv2.LINE_AA
|
||
)
|
||
cv2.putText(
|
||
img,
|
||
f"{rate:.1f}/min",
|
||
(340, 32),
|
||
cv2.FONT_HERSHEY_SIMPLEX,
|
||
0.45,
|
||
C_ACCENT,
|
||
1,
|
||
cv2.LINE_AA,
|
||
)
|
||
|
||
|
||
def draw_footer(img, w, h, frame_idx, live_tag, inf_ms=0.0, model_name=""):
|
||
bar_h = 28
|
||
overlay_rect(img, 0, h - bar_h, w, h, C_PANEL, alpha=0.55)
|
||
cv2.putText(
|
||
img,
|
||
f"{live_tag} | {model_name} | Frame {frame_idx} | Inf {inf_ms:.1f}ms",
|
||
(12, h - 9),
|
||
cv2.FONT_HERSHEY_SIMPLEX,
|
||
0.45,
|
||
C_MUTED,
|
||
1,
|
||
cv2.LINE_AA,
|
||
)
|
||
|
||
|
||
def draw_skeleton_bold(img, kpts):
|
||
for (a, b), color in zip(SKELETON, SK_COLORS):
|
||
if a < len(kpts) and b < len(kpts):
|
||
xa, ya = int(kpts[a][0]), int(kpts[a][1])
|
||
xb, yb = int(kpts[b][0]), int(kpts[b][1])
|
||
if xa > 0 and ya > 0 and xb > 0 and yb > 0:
|
||
cv2.line(img, (xa, ya), (xb, yb), color, 3, cv2.LINE_AA)
|
||
for kp in kpts:
|
||
x, y = int(kp[0]), int(kp[1])
|
||
if x > 0 and y > 0:
|
||
cv2.circle(img, (x, y), 6, (255, 255, 255), -1, cv2.LINE_AA)
|
||
cv2.circle(img, (x, y), 6, (40, 40, 40), 2, cv2.LINE_AA)
|
||
|
||
|
||
def draw_popups(img, popups, frame_idx):
|
||
alive = []
|
||
for pop in popups:
|
||
age = frame_idx - pop["born"]
|
||
if age > POPUP_LIFETIME:
|
||
continue
|
||
alive.append(pop)
|
||
fade = 1.0 - age / POPUP_LIFETIME
|
||
y = pop["y"] - int(age * 1.8)
|
||
color = (int(C_GREEN[0] * fade), int(C_GREEN[1] * fade), int(C_GREEN[2] * fade))
|
||
cv2.putText(
|
||
img,
|
||
pop["text"],
|
||
(pop["x"], y),
|
||
cv2.FONT_HERSHEY_SIMPLEX,
|
||
0.7,
|
||
color,
|
||
2,
|
||
cv2.LINE_AA,
|
||
)
|
||
return alive
|
||
|
||
|
||
def draw_batch_banner(img, w, batch_num, pulse_remaining, batch_type=None):
|
||
if pulse_remaining <= 0:
|
||
return
|
||
btype_str = f" ({batch_type.upper()})" if batch_type else ""
|
||
text = f"NEW BATCH {batch_num}{btype_str}"
|
||
font = cv2.FONT_HERSHEY_SIMPLEX
|
||
(tw, th), _ = cv2.getTextSize(text, font, 0.8, 2)
|
||
x1, y1 = w // 2 - tw // 2 - 16, 62
|
||
x2, y2 = w // 2 + tw // 2 + 16, 62 + th + 20
|
||
overlay_rect(img, x1, y1, x2, y2, C_PANEL, alpha=0.7)
|
||
cv2.rectangle(img, (x1, y1), (x2, y2), C_ACCENT, 2)
|
||
cv2.putText(
|
||
img, text, (w // 2 - tw // 2, 62 + th + 4), font, 0.8, C_ACCENT, 2, cv2.LINE_AA
|
||
)
|
||
|
||
|
||
class StreamErrorLog:
|
||
"""Rate-limit stream error prints to STREAM_ERROR_LOG_MAX per outage.
|
||
|
||
After the cap, messages are suppressed until note_up() when the stream
|
||
is healthy again; the next drop starts a fresh budget.
|
||
"""
|
||
|
||
def __init__(self, max_logs=STREAM_ERROR_LOG_MAX):
|
||
self.max_logs = int(max_logs)
|
||
self._emitted = 0
|
||
self._suppressed = 0
|
||
|
||
def emit(self, msg: str) -> None:
|
||
if self.max_logs <= 0:
|
||
print(msg)
|
||
return
|
||
if self._emitted < self.max_logs:
|
||
self._emitted += 1
|
||
print(msg)
|
||
if self._emitted >= self.max_logs:
|
||
print(
|
||
f"[{now_str()}] Stream errors capped at {self.max_logs} "
|
||
f"this outage — further messages suppressed until stream recovers"
|
||
)
|
||
else:
|
||
self._suppressed += 1
|
||
|
||
def note_up(self) -> None:
|
||
if self._suppressed > 0:
|
||
print(
|
||
f"[{now_str()}] Stream recovered "
|
||
f"(suppressed {self._suppressed} error log(s) during outage)"
|
||
)
|
||
self._emitted = 0
|
||
self._suppressed = 0
|
||
|
||
|
||
stream_error_log = StreamErrorLog()
|
||
|
||
|
||
def connect_stream(source, warmup=WARMUP_FRAMES):
|
||
attempts = 0
|
||
while not shutdown_requested:
|
||
cap = open_capture(source)
|
||
if not cap.isOpened():
|
||
attempts += 1
|
||
if MAX_RECONNECT_ATTEMPTS and attempts >= MAX_RECONNECT_ATTEMPTS:
|
||
raise RuntimeError(
|
||
f"Cannot open source after {attempts} attempts: {source}"
|
||
)
|
||
stream_error_log.emit(
|
||
f"Cannot open source, retry in {RECONNECT_DELAY_SEC}s..."
|
||
)
|
||
time.sleep(RECONNECT_DELAY_SEC)
|
||
continue
|
||
if warmup > 0 and source.lower().startswith(("rtsp://", "http://")):
|
||
warmup_stream(cap, warmup)
|
||
w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||
fps = cap.get(cv2.CAP_PROP_FPS)
|
||
if not fps or fps <= 1:
|
||
fps = OUTPUT_FPS
|
||
stream_error_log.note_up()
|
||
return cap, w, h, fps
|
||
return None, 0, 0, OUTPUT_FPS
|
||
|
||
|
||
# =============================================================================
|
||
# Main loop
|
||
# =============================================================================
|
||
|
||
|
||
def run():
|
||
global shutdown_requested
|
||
|
||
store = BatchStore(
|
||
db_path=DB_PATH,
|
||
state_file=STATE_FILE,
|
||
camera_name=CAMERA_NAME,
|
||
object_label=OBJECT_LABEL,
|
||
cutoff_time=DAILY_CUTOFF_TIME,
|
||
batch_timeout=BATCH_TIMEOUT_SECONDS,
|
||
min_object_per_batch=MIN_OBJECT_PER_BATCH,
|
||
min_duration_per_batch=MIN_DURATION_PER_BATCH,
|
||
batch_mode=BATCH_MODE,
|
||
logger=lambda msg: print(f"[{now_str()}] {msg}"),
|
||
)
|
||
store.start_cutoff_watcher()
|
||
|
||
control_server = start_control_server(
|
||
store,
|
||
host=COUNTER_CONTROL_HOST,
|
||
port=COUNTER_CONTROL_PORT,
|
||
logger=lambda msg: print(f"[{now_str()}] {msg}"),
|
||
)
|
||
|
||
cross_logger = None
|
||
if EXPORT_CSV:
|
||
cross_logger = CsvLogger(
|
||
CROSS_CSV, ["batch", "frame", "timestamp", "object_id"]
|
||
)
|
||
|
||
model = RKNNYOLO(
|
||
model_path=MODEL_PATH,
|
||
core_mask=CORE_MASK,
|
||
imgsz=IMGSZ,
|
||
conf=min(CONF, SACK_CONF, BOX_CONF, TRUCK_CONF, TRACK_LOW_THRESH_0),
|
||
num_classes=NUM_CLASSES,
|
||
score_sigmoid=SCORE_SIGMOID,
|
||
iou=IOU,
|
||
)
|
||
|
||
raw_cls_names = [
|
||
c.strip()
|
||
for c in (CLASS_COUNTED_OBJECT or OBJECT_LABEL or "sack,box,truck").split(",")
|
||
if c.strip()
|
||
]
|
||
class_names_map = {i: name.upper() for i, name in enumerate(raw_cls_names)}
|
||
class_names_map.setdefault(0, "SACK")
|
||
class_names_map.setdefault(1, "BOX")
|
||
class_names_map.setdefault(2, "TRUCK")
|
||
|
||
counted_cls_env = os.getenv(
|
||
"COUNTED_CLASS_IDS",
|
||
os.getenv("COUNTED_CLASS_ID", os.getenv("AYAM_CLASS_ID", "0,1")),
|
||
)
|
||
counted_cls_ids = {
|
||
int(x.strip()) for x in counted_cls_env.split(",") if x.strip().isdigit()
|
||
}
|
||
if not counted_cls_ids:
|
||
counted_cls_ids = {0, 1}
|
||
truck_cls = int(os.getenv("TRUCK_CLASS_ID", "2"))
|
||
class_conf_map = {
|
||
0: SACK_CONF,
|
||
1: BOX_CONF,
|
||
truck_cls: TRUCK_CONF,
|
||
}
|
||
|
||
counted_tracker = ByteTracker(
|
||
track_high_thresh=TRACK_HIGH_THRESH_0,
|
||
track_low_thresh=TRACK_LOW_THRESH_0,
|
||
match_thresh=TRACK_MATCH_THRESH_0,
|
||
track_buffer=TRACK_BUFFER_0,
|
||
min_hits=TRACK_MIN_HITS_0,
|
||
)
|
||
|
||
counted_line_crossed = set()
|
||
recent_crossings = deque()
|
||
|
||
counted_cross_flash = {}
|
||
line_pulse = count_pulse = batch_pulse = 0
|
||
popups = []
|
||
|
||
session_start = time.time()
|
||
frame_idx = 0
|
||
inf_ms = 0.0
|
||
prev_frame_time = time.monotonic()
|
||
proc_fps = 0.0
|
||
prev_gray = None
|
||
video_writer = None
|
||
crossing_times = deque()
|
||
|
||
cap, w, h, fps = connect_stream(SOURCE)
|
||
if cap is None:
|
||
store.shutdown()
|
||
model.release()
|
||
return
|
||
|
||
count_axis = resolve_count_axis()
|
||
line_pos = resolve_count_line(w, h, count_axis)
|
||
manual_x1, manual_x2 = resolve_manual_zone_x(w)
|
||
last_truck_zone = None
|
||
last_truck_mono = 0.0
|
||
prev_batch_key = (store.current_batch_number or 0, store.current_batch_object_label)
|
||
|
||
print(
|
||
f"RKNN+ByteTrack counter | {w}x{h} @ {fps}fps | axis={count_axis} line={line_pos} | cross={CROSS_DIRECTION}"
|
||
)
|
||
print(f"Model: {MODEL_PATH} | imgsz={IMGSZ} | core_mask={CORE_MASK}")
|
||
print(
|
||
f"Classes: counted={sorted(counted_cls_ids)} ({[class_names_map.get(c, str(c)) for c in sorted(counted_cls_ids)]}) | "
|
||
f"truck_cls={truck_cls} | zone_mode={ZONE_MODE} manual_x=[{manual_x1}, {manual_x2}]"
|
||
)
|
||
print(
|
||
f"Confidence: default={CONF} | sack={SACK_CONF} | box={BOX_CONF} | truck={TRUCK_CONF}"
|
||
)
|
||
print(
|
||
f"ByteTrack: high_thresh={TRACK_HIGH_THRESH_0} low_thresh={TRACK_LOW_THRESH_0} "
|
||
f"match_thresh={TRACK_MATCH_THRESH_0} buffer={TRACK_BUFFER_0} | "
|
||
f"dedup=({DEDUP_FRAMES}f, {DEDUP_PX}px)"
|
||
)
|
||
print(f"DB: {DB_PATH}")
|
||
print(f"State: {STATE_FILE}")
|
||
|
||
if RECORD_VIDEO:
|
||
video_writer = VideoSegmentWriter(OUTPUT_DIR, w, h, fps, VIDEO_SEGMENT_SEC)
|
||
|
||
reconnect_count = 0
|
||
|
||
while not shutdown_requested:
|
||
ret, frame = cap.read()
|
||
if not ret:
|
||
if not IS_LIVE:
|
||
break
|
||
reconnect_count += 1
|
||
stream_error_log.emit(
|
||
f"Stream dropped (attempt {reconnect_count}), reconnecting in {RECONNECT_DELAY_SEC}s..."
|
||
)
|
||
cap.release()
|
||
time.sleep(RECONNECT_DELAY_SEC)
|
||
cap, w, h, fps = connect_stream(SOURCE)
|
||
if cap is None:
|
||
break
|
||
line_pos = resolve_count_line(w, h, count_axis)
|
||
manual_x1, manual_x2 = resolve_manual_zone_x(w)
|
||
continue
|
||
|
||
now = time.time()
|
||
elapsed = now - session_start
|
||
mono = time.monotonic()
|
||
counted_crossed_frame = batch_started_frame = False
|
||
|
||
curr_batch_num = store.current_batch_number or 0
|
||
active_batch_label = store.current_batch_object_label
|
||
curr_batch_key = (curr_batch_num, active_batch_label)
|
||
if curr_batch_key != prev_batch_key:
|
||
if curr_batch_num > 0:
|
||
counted_line_crossed.clear()
|
||
counted_tracked.clear()
|
||
recent_crossings.clear()
|
||
counted_tracker = ByteTracker(
|
||
track_high_thresh=TRACK_HIGH_THRESH_0,
|
||
track_low_thresh=TRACK_LOW_THRESH_0,
|
||
match_thresh=TRACK_MATCH_THRESH_0,
|
||
track_buffer=TRACK_BUFFER_0,
|
||
min_hits=TRACK_MIN_HITS_0,
|
||
)
|
||
batch_started_frame = True
|
||
prev_batch_key = curr_batch_key
|
||
|
||
if active_batch_label == "sack":
|
||
active_cls_ids = {0}
|
||
elif active_batch_label == "box":
|
||
active_cls_ids = {1}
|
||
else:
|
||
active_cls_ids = counted_cls_ids
|
||
|
||
skip_inference = False
|
||
if MOTION_DETECTION_ENABLED:
|
||
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
||
if prev_gray is not None:
|
||
diff = cv2.absdiff(gray, prev_gray)
|
||
mean_diff = cv2.mean(diff)[0]
|
||
skip_inference = mean_diff < MOTION_THRESHOLD
|
||
prev_gray = gray
|
||
|
||
detections = []
|
||
if not skip_inference:
|
||
inf_start = time.time()
|
||
detections = model(frame)
|
||
inf_ms = inf_ms * 0.9 + (time.time() - inf_start) * 1000 * 0.1
|
||
|
||
truck_dets = [
|
||
d for d in detections if d["cls"] == truck_cls and d["score"] >= TRUCK_CONF
|
||
]
|
||
|
||
zone_truck = None
|
||
if ZONE_MODE in {"manual", "fixed"}:
|
||
zone_x1, zone_x2 = manual_x1, manual_x2
|
||
zone_source = "MANUAL"
|
||
else:
|
||
if truck_dets:
|
||
best_truck = max(truck_dets, key=lambda d: d["score"])
|
||
zone_truck = best_truck
|
||
tb = best_truck["bbox"]
|
||
tx1 = max(0, int(tb[0]) - TRUCK_ZONE_PAD_X)
|
||
tx2 = min(w, int(tb[2]) + TRUCK_ZONE_PAD_X)
|
||
if tx2 > tx1:
|
||
if (
|
||
last_truck_zone is not None
|
||
and abs(tx1 - last_truck_zone[0]) < w * 0.25
|
||
and abs(tx2 - last_truck_zone[1]) < w * 0.25
|
||
):
|
||
zone_x1 = int(round(0.75 * last_truck_zone[0] + 0.25 * tx1))
|
||
zone_x2 = int(round(0.75 * last_truck_zone[1] + 0.25 * tx2))
|
||
else:
|
||
zone_x1, zone_x2 = tx1, tx2
|
||
last_truck_zone = (zone_x1, zone_x2)
|
||
last_truck_mono = mono
|
||
zone_x1, zone_x2 = last_truck_zone or (manual_x1, manual_x2)
|
||
zone_source = "AUTO:TRUCK"
|
||
elif (
|
||
last_truck_zone is not None
|
||
and (mono - last_truck_mono) <= TRUCK_ZONE_HOLD_SEC
|
||
):
|
||
zone_x1, zone_x2 = last_truck_zone
|
||
zone_source = "AUTO:HOLD"
|
||
else:
|
||
zone_x1, zone_x2 = manual_x1, manual_x2
|
||
zone_source = "AUTO:MANUAL"
|
||
|
||
if not skip_inference:
|
||
truck_in_zone = any(
|
||
zone_x1 <= ((td["bbox"][0] + td["bbox"][2]) / 2.0) <= zone_x2
|
||
for td in truck_dets
|
||
)
|
||
store.set_truck_present(truck_in_zone)
|
||
|
||
draw_counting_zone_x(frame, zone_x1, zone_x2, w, h, zone_source)
|
||
|
||
for tdet in truck_dets:
|
||
tb = tdet["bbox"]
|
||
tcx = (tb[0] + tb[2]) / 2.0
|
||
if tdet is not zone_truck and not (zone_x1 <= tcx <= zone_x2):
|
||
continue
|
||
tx1, ty1, tx2, ty2 = int(tb[0]), int(tb[1]), int(tb[2]), int(tb[3])
|
||
t_color = (255, 200, 0)
|
||
t_obb = tdet.get("obb")
|
||
if t_obb is not None:
|
||
pts = np.array(t_obb, dtype=np.int32).reshape((-1, 1, 2))
|
||
cv2.polylines(frame, [pts], True, t_color, 2, cv2.LINE_AA)
|
||
else:
|
||
cv2.rectangle(frame, (tx1, ty1), (tx2, ty2), t_color, 2)
|
||
draw_pill(
|
||
frame,
|
||
f"{class_names_map.get(truck_cls, 'TRUCK')} {tdet['score']:.2f}",
|
||
tx1,
|
||
max(60, ty1 - 4),
|
||
t_color,
|
||
fg=(20, 20, 20),
|
||
)
|
||
|
||
counted_boxes_xyxy = []
|
||
counted_scores = []
|
||
counted_high_thr_list = []
|
||
counted_cls_list = []
|
||
counted_kpts_list = []
|
||
counted_obb_list = []
|
||
counted_cx_list = []
|
||
counted_cy_list = []
|
||
counted_pos_list = []
|
||
|
||
for det in detections:
|
||
bbox = det["bbox"]
|
||
score = det["score"]
|
||
cls_id = det["cls"]
|
||
kpts = det["keypoints"]
|
||
obb = det.get("obb")
|
||
cx = (bbox[0] + bbox[2]) / 2.0
|
||
cy = (bbox[1] + bbox[3]) / 2.0
|
||
pos = cy if count_axis == "y" else cx
|
||
|
||
cls_conf_thr = class_conf_map.get(cls_id, CONF)
|
||
low_conf_thr = min(cls_conf_thr, TRACK_LOW_THRESH_0)
|
||
if (
|
||
cls_id in active_cls_ids
|
||
and score >= low_conf_thr
|
||
and (zone_x1 <= cx <= zone_x2)
|
||
):
|
||
counted_boxes_xyxy.append(bbox)
|
||
counted_scores.append(score)
|
||
counted_high_thr_list.append(cls_conf_thr)
|
||
counted_cls_list.append(cls_id)
|
||
counted_kpts_list.append(kpts)
|
||
counted_obb_list.append(obb)
|
||
counted_cx_list.append(cx)
|
||
counted_cy_list.append(cy)
|
||
counted_pos_list.append(pos)
|
||
|
||
counted_boxes_xyxy = np.array(counted_boxes_xyxy, dtype=np.float32).reshape(-1, 4)
|
||
counted_scores = np.array(counted_scores, dtype=np.float32)
|
||
counted_high_thrs = np.array(counted_high_thr_list, dtype=np.float32)
|
||
|
||
counted_track_map, counted_det_to_track, counted_lost_map = counted_tracker.update(
|
||
counted_boxes_xyxy, counted_scores, high_thresholds=counted_high_thrs
|
||
)
|
||
|
||
if os.getenv("DEBUG_TRACKING", "").lower() == "true":
|
||
if len(counted_boxes_xyxy) > 0:
|
||
counted_scores_str = (
|
||
f" object scores: {counted_scores.round(3).tolist()}"
|
||
if len(counted_scores) > 0
|
||
else ""
|
||
)
|
||
counted_tracks_str = (
|
||
f" object det→track: {dict(counted_det_to_track)}"
|
||
if counted_det_to_track
|
||
else ""
|
||
)
|
||
crossing_str = (
|
||
f" counted_line_crossed: {sorted(counted_line_crossed)}"
|
||
if counted_line_crossed
|
||
else ""
|
||
)
|
||
pos_sample = ""
|
||
if len(counted_pos_list) > 0 and counted_det_to_track:
|
||
sample_tid = list(counted_det_to_track.values())[0]
|
||
sample_pos = counted_pos_list[list(counted_det_to_track.keys())[0]]
|
||
prev = (
|
||
(
|
||
counted_tracked[sample_tid][1]
|
||
if count_axis == "y"
|
||
else counted_tracked[sample_tid][0]
|
||
)
|
||
if counted_tracked.get(sample_tid)
|
||
else None
|
||
)
|
||
pos_sample = (
|
||
f" sample tid={sample_tid} prev_pos={prev} pos={sample_pos:.1f}"
|
||
)
|
||
print(
|
||
f"[DEBUG F{frame_idx}] object_dets={len(counted_boxes_xyxy)} "
|
||
f"line={line_pos}{counted_scores_str}"
|
||
f"{counted_tracks_str}{crossing_str}"
|
||
f"{pos_sample}"
|
||
)
|
||
|
||
# --- crossing detection only on DETECTED objects this frame ---
|
||
active_tids = set(counted_det_to_track.values())
|
||
for di in range(len(counted_boxes_xyxy)):
|
||
tid = counted_det_to_track.get(di)
|
||
if tid is None:
|
||
continue
|
||
cx = counted_cx_list[di]
|
||
cy = counted_cy_list[di]
|
||
pos = counted_pos_list[di]
|
||
along_pos = cx if count_axis == "y" else cy
|
||
|
||
if tid in counted_tracked:
|
||
prev_cx, prev_cy, _ = counted_tracked[tid]
|
||
prev_pos = prev_cy if count_axis == "y" else prev_cx
|
||
can_count_now = (curr_batch_num > 0) or (BATCH_MODE != "manual")
|
||
if (
|
||
can_count_now
|
||
and crossed_line(prev_pos, pos, line_pos)
|
||
and tid not in counted_line_crossed
|
||
):
|
||
if is_duplicate_cross(
|
||
recent_crossings, along_pos, frame_idx, active_tids=active_tids
|
||
):
|
||
counted_line_crossed.add(tid)
|
||
if os.getenv("DEBUG_TRACKING", "").lower() == "true":
|
||
print(
|
||
f"[DEBUG F{frame_idx}] DUP CROSS IGNORED: tid={tid} "
|
||
f"along_pos={along_pos:.1f} pos={pos:.1f}"
|
||
)
|
||
counted_tracked[tid] = (cx, cy, mono)
|
||
continue
|
||
|
||
if os.getenv("DEBUG_TRACKING", "").lower() == "true":
|
||
print(
|
||
f"[DEBUG F{frame_idx}] CROSS DETECTED: tid={tid} "
|
||
f"prev_pos={prev_pos:.1f} → pos={pos:.1f} line={line_pos}"
|
||
)
|
||
recent_crossings.append((frame_idx, along_pos, tid))
|
||
counted_line_crossed.add(tid)
|
||
det_obj_label = "box" if counted_cls_list[di] == 1 else "sack"
|
||
_, started_new = store.record_counted_object_crossing(
|
||
tid, object_label=det_obj_label
|
||
)
|
||
if cross_logger:
|
||
cross_logger.write_row(
|
||
[
|
||
store.current_batch_number,
|
||
frame_idx,
|
||
datetime.now().isoformat(),
|
||
tid,
|
||
]
|
||
)
|
||
counted_crossed_frame = True
|
||
if started_new:
|
||
batch_started_frame = True
|
||
crossing_times.append(mono)
|
||
counted_cross_flash[tid] = CROSS_FLASH_FRAMES
|
||
popups.append(
|
||
{
|
||
"x": int(cx) - 12,
|
||
"y": int(cy),
|
||
"born": frame_idx,
|
||
"text": "+1",
|
||
}
|
||
)
|
||
counted_tracked[tid] = (cx, cy, mono)
|
||
|
||
for di in range(len(counted_boxes_xyxy)):
|
||
tid = counted_det_to_track.get(di)
|
||
if tid is None:
|
||
continue
|
||
bbox = counted_boxes_xyxy[di]
|
||
cls_id = counted_cls_list[di]
|
||
cls_label = class_names_map.get(cls_id, "OBJ")
|
||
x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
|
||
flash = counted_cross_flash.get(tid, 0)
|
||
# mark counted center point: white dot with thin blue outline
|
||
cx_i = int((x1 + x2) / 2)
|
||
cy_i = int((y1 + y2) / 2)
|
||
cv2.circle(frame, (cx_i, cy_i), 4, (255, 255, 255), -1, cv2.LINE_AA)
|
||
cv2.circle(frame, (cx_i, cy_i), 4, (255, 140, 40) if cls_id == 1 else (0, 165, 255), 1, cv2.LINE_AA)
|
||
base_color = (255, 140, 40) if cls_id == 1 else C_COUNTED_BOX
|
||
color = C_GREEN if flash > 0 else base_color
|
||
obb = counted_obb_list[di] if di < len(counted_obb_list) else None
|
||
if obb is not None:
|
||
pts = np.array(obb, dtype=np.int32).reshape((-1, 1, 2))
|
||
cv2.polylines(
|
||
frame, [pts], True, color, 3 if flash > 0 else 2, cv2.LINE_AA
|
||
)
|
||
else:
|
||
cv2.rectangle(frame, (x1, y1), (x2, y2), color, 3 if flash > 0 else 2)
|
||
draw_pill(frame, f"{cls_label} {tid}", x1, y1 - 4, color)
|
||
kpts = counted_kpts_list[di] if di < len(counted_kpts_list) else None
|
||
if kpts is not None:
|
||
draw_skeleton_bold(frame, kpts)
|
||
|
||
if counted_crossed_frame:
|
||
line_pulse = LINE_PULSE_FRAMES
|
||
count_pulse = COUNT_PULSE_FRAMES
|
||
if batch_started_frame:
|
||
batch_pulse = BATCH_PULSE_FRAMES
|
||
|
||
batch_num = store.current_batch_number or 0
|
||
batch_type = store.current_batch_object_label
|
||
batch_count = store.current_batch_count
|
||
display_total = store.display_total()
|
||
while crossing_times and mono - crossing_times[0] > RATE_WINDOW_SEC:
|
||
crossing_times.popleft()
|
||
rate = (len(crossing_times) / RATE_WINDOW_SEC * 60) if crossing_times else 0.0
|
||
|
||
draw_elegant_counting_line(frame, count_axis, line_pos, w, h, line_pulse)
|
||
draw_hero_count(frame, count_axis, line_pos, w, h, batch_count, count_pulse)
|
||
draw_hud(
|
||
frame,
|
||
w,
|
||
batch_num,
|
||
batch_count,
|
||
display_total,
|
||
elapsed,
|
||
rate,
|
||
batch_type=batch_type,
|
||
)
|
||
draw_batch_banner(frame, w, batch_num, batch_pulse, batch_type=batch_type)
|
||
draw_footer(
|
||
frame,
|
||
w,
|
||
h,
|
||
frame_idx,
|
||
"LIVE" if IS_LIVE else "FILE",
|
||
inf_ms,
|
||
Path(MODEL_PATH).name,
|
||
)
|
||
popups = draw_popups(frame, popups, frame_idx)
|
||
|
||
for tid in list(counted_cross_flash):
|
||
counted_cross_flash[tid] -= 1
|
||
if counted_cross_flash[tid] <= 0:
|
||
del counted_cross_flash[tid]
|
||
line_pulse = max(0, line_pulse - 1)
|
||
count_pulse = max(0, count_pulse - 1)
|
||
batch_pulse = max(0, batch_pulse - 1)
|
||
|
||
if video_writer is not None:
|
||
video_writer.write(frame)
|
||
|
||
if LIVE_STREAM_ENABLED and frame_idx % LIVE_STREAM_EVERY_N == 0:
|
||
try:
|
||
Path(LIVE_STREAM_FRAME_PATH).parent.mkdir(parents=True, exist_ok=True)
|
||
ok, jpeg = cv2.imencode(
|
||
".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, LIVE_STREAM_QUALITY]
|
||
)
|
||
if ok:
|
||
tmp_path = f"{LIVE_STREAM_FRAME_PATH}.tmp"
|
||
with open(tmp_path, "wb") as f:
|
||
f.write(jpeg.tobytes())
|
||
os.replace(tmp_path, LIVE_STREAM_FRAME_PATH)
|
||
now_mono = time.monotonic()
|
||
dt = now_mono - prev_frame_time
|
||
if dt > 0:
|
||
inst = 1.0 / dt
|
||
proc_fps = (proc_fps * 0.9 + inst * 0.1) if proc_fps else inst
|
||
prev_frame_time = now_mono
|
||
try:
|
||
with open(LIVE_STREAM_META_PATH, "w") as mf:
|
||
json.dump({"fps": round(proc_fps, 1), "width": w, "height": h}, mf)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
frame_idx += 1
|
||
if frame_idx % FLUSH_EVERY_N_FRAMES == 0:
|
||
print(
|
||
f"[{now_str()}] Frame {frame_idx} | Batch {batch_num}: {batch_count} "
|
||
f"| Total: {display_total} | Uptime {elapsed / 3600:.2f}h"
|
||
)
|
||
prune_stale_tracks(counted_tracked, mono)
|
||
|
||
cap.release()
|
||
if video_writer is not None:
|
||
video_writer.release()
|
||
if cross_logger:
|
||
cross_logger.close()
|
||
model.release()
|
||
if control_server:
|
||
control_server.shutdown()
|
||
store.shutdown()
|
||
|
||
print("\n=== Batch Summary (SQLite) ===")
|
||
print(f"Database: {DB_PATH}")
|
||
|
||
|
||
counted_tracked = {}
|
||
|
||
|
||
if __name__ == "__main__":
|
||
run()
|