完成走廊迁移

This commit is contained in:
zqc
2026-03-06 12:26:38 +08:00
parent 845814e6c1
commit 4efe7aa3eb
2 changed files with 16 additions and 115 deletions

View File

@@ -7,6 +7,8 @@ import time
import queue
import requests
from biz.base_frame_processor import BaseFrameProcessorWorker
# -------------------------- Kadian 检测相关导入 --------------------------
from algorithm.common.npu_yolo_onnx_person_car_phone import YOLOv8_ONNX # 主检测模型(人/车/后备箱/手机)
from common.constants import ALERT_PUSH_URL
@@ -19,7 +21,7 @@ from yolox.tracker.byte_tracker import BYTETracker
detector_model_path = 'YOLO_Weight/prisoner_model.onnx'
# 输入尺寸
input_size = 1280
input_size = 640
RTSP_TARGET_FPS = 10.0
@@ -28,9 +30,11 @@ ALERT_PUSH_INTERVAL = 5.0 # 相同action 5秒内仅推送一次
class ZoulangDetector:
def __init__(self):
# 模型加载
def __init__(self, params=None):
# 摄像头额外参数
self.params = params if params is not None else {}
# 模型加载
self.police_prisoner_detector = YOLOv8_ONNX(detector_model_path, conf_threshold=0.5, iou_threshold=0.45,
input_size=input_size)
@@ -41,8 +45,6 @@ class ZoulangDetector:
match_thresh = 0.8
mot20 = False
self.police_prisoner_track_role = {}
self.fps = RTSP_TARGET_FPS
@@ -334,114 +336,11 @@ class ZoulangDetector:
}
# ========================= 帧处理线程 =========================
class FrameProcessorWorker(threading.Thread):
def __init__(self,
raw_frame_queue: "queue.Queue[Dict[str, Any]]",
ws_send_queue: "queue.Queue[Dict[str, Any]]",
stop_event: threading.Event):
super().__init__(daemon=True)
self.raw_queue = raw_frame_queue
self.ws_queue = ws_send_queue
self.stop_event = stop_event
class FrameProcessorWorker(BaseFrameProcessorWorker):
"""轨迹检测帧处理线程"""
self.last_ts: Dict[int, float] = {}
# 每个摄像头一个独立的 Kadian 检测器实例
self.kadian_detectors: Dict[int, ZoulangDetector] = {}
# 新增维护每个摄像头每个action的最后推送时间 {camera_id: {action: last_push_time}}
self.last_alert_push_time: Dict[int, Dict[str, float]] = {}
def _encode_image_to_base64(self, image) -> str:
ok, buf = cv2.imencode(".jpg", image)
if not ok:
raise RuntimeError("Failed to encode image to JPEG")
return base64.b64encode(buf.tobytes()).decode("ascii")
def run(self):
target_interval = 1.0 / RTSP_TARGET_FPS
while not self.stop_event.is_set():
try:
item = self.raw_queue.get(timeout=0.5)
except queue.Empty:
continue
cam_id = item["camera_id"]
ts = item["timestamp"]
frame = item["frame"]
# 抽帧控制
if ts - self.last_ts.get(cam_id, 0) < target_interval:
self.raw_queue.task_done()
continue
self.last_ts[cam_id] = ts
# 获取检测器实例
if cam_id not in self.kadian_detectors:
self.kadian_detectors[cam_id] = ZoulangDetector()
detector = self.kadian_detectors[cam_id]
# 执行检测
result = detector.process_frame(frame.copy(), cam_id, ts)
result_img = result["image"]
result_type = result["alerts"]
# ========= 核心修改过滤5秒内重复的action =========
# 初始化当前摄像头的推送时间记录
if cam_id not in self.last_alert_push_time:
self.last_alert_push_time[cam_id] = {}
# 筛选出符合推送条件的action5秒内未推送过
push_actions = []
current_time = time.time()
for alert in result_type:
action = alert['action']
last_push = self.last_alert_push_time[cam_id].get(action, 0)
# 检查是否超过推送间隔
if current_time - last_push >= ALERT_PUSH_INTERVAL:
push_actions.append(action)
# 更新该action的最后推送时间
self.last_alert_push_time[cam_id][action] = current_time
# 通过 WebSocket 发送帧结果
try:
img_b64 = self._encode_image_to_base64(result_img)
except Exception as e:
print(f"[ERROR] Encode image failed: {e}")
img_b64 = None
if img_b64 is not None:
# 将abnormal_actions对象数组转换为字符串数组
#action_names = [action_info['action'] for action_info in push_actions]
msg = {
"msg_type": "frame",
"camera_id": item["camera_index"],
"timestamp": ts,
#"result_type": action_names,
"result_type": push_actions,
"image_base64": img_b64,
}
try:
self.ws_queue.put(msg, timeout=1.0)
if push_actions and len(push_actions) > 0:
# 发送POST请求
post_msg = msg.copy()
post_msg['type'] = 2
try:
response = requests.post(ALERT_PUSH_URL, json=post_msg, timeout=5.0)
if response.status_code == 200:
print(f"[INFO] POST alert sent successfully for actions: {push_actions}")
else:
print(f"[WARN] POST alert failed with status: {response.status_code}")
except Exception as e:
print(f"[ERROR] POST alert request failed: {e}")
except queue.Full:
print("[WARN] ws_send_queue full, drop frame message")
self.raw_queue.task_done()
# 子类配置
DETECTOR_FACTORY = lambda params: ZoulangDetector(params)
POST_TYPE = 2
TARGET_FPS = RTSP_TARGET_FPS