From 80bc288a888d1926f81489921037ba825e0c4c34 Mon Sep 17 00:00:00 2001 From: zqc <835569504@qq.com> Date: Thu, 5 Mar 2026 14:41:49 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E8=AD=A6=E5=91=8A?= =?UTF-8?q?=E4=BF=A1=E6=81=AF=E6=94=B9=E4=B8=BA=E4=BC=A0=E8=A7=86=E9=A2=91?= =?UTF-8?q?=EF=BC=8C=E5=B7=B2=E6=B5=8B=E8=AF=95=E4=BF=9D=E5=AD=98=E8=A7=86?= =?UTF-8?q?=E9=A2=91=EF=BC=8C=E6=9C=AA=E4=B8=8E=E6=8E=A5=E5=8F=A3=E8=81=94?= =?UTF-8?q?=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- biz/base_frame_processor.py | 245 +++++++++++++++++++++++++++++++++++- common/constants.py | 14 +++ config.yaml | 8 +- utils/hls_utils.py | 126 +++++++++++++++++++ 4 files changed, 386 insertions(+), 7 deletions(-) diff --git a/biz/base_frame_processor.py b/biz/base_frame_processor.py index 1fdef68..5e68a6f 100644 --- a/biz/base_frame_processor.py +++ b/biz/base_frame_processor.py @@ -4,6 +4,9 @@ import cv2 import base64 +import json +import os +import subprocess import time import threading import queue @@ -13,6 +16,7 @@ from concurrent.futures import ThreadPoolExecutor from common import constants from utils.logger import get_logger +from utils.hls_utils import get_segments_before_current, parse_segment_info logger = get_logger(__name__) @@ -67,6 +71,12 @@ class BaseFrameProcessorWorker(threading.Thread): max_workers=post_workers, thread_name_prefix="alert_post" ) + + # MP4缓存 {segment_path: mp4_path} + self._mp4_cache: Dict[str, str] = {} + + # 启动视频文件清理线程 + self._start_cleanup_thread() def _encode_image_to_base64(self, img) -> str: """图像编码为 Base64""" @@ -102,7 +112,7 @@ class BaseFrameProcessorWorker(threading.Thread): return result def _post_alert(self, msg: dict): - """异步发送告警 POST 请求(在线程池中执行)""" + """异步发送告警 POST 请求(在线程池中执行)- 旧接口,保留备用""" try: response = requests.post(constants.ALERT_PUSH_URL, json=msg, timeout=5.0) if response.status_code == 200: @@ -112,6 +122,218 @@ class BaseFrameProcessorWorker(threading.Thread): except Exception as e: print(f"[ERROR] POST alert request failed: {e}") + def _post_alert_with_video(self, msg: dict, video_path: str = None): + """ + 异步发送告警 POST 请求(带视频,multipart/form-data) + + Args: + msg: 消息内容 + video_path: 视频文件路径(可选) + """ + try: + if video_path and os.path.exists(video_path): + # 有视频,使用 multipart/form-data 上传 + with open(video_path, 'rb') as f: + files = { + 'video': f, + 'metadata': (None, json.dumps(msg)) + } + response = requests.post(constants.ALERT_PUSH_URL, files=files, timeout=10.0) + else: + # 无视频,也使用 multipart/form-data + files = { + 'metadata': (None, json.dumps(msg)) + } + response = requests.post(constants.ALERT_PUSH_URL, files=files, timeout=5.0) + + if response.status_code == 200: + logger.info(f"[INFO] POST alert sent successfully for actions: {msg.get('result_type')}") + else: + logger.warning(f"[WARN] POST alert failed with status: {response.status_code}") + except Exception as e: + logger.error(f"[ERROR] POST alert request failed: {e}") + + def _start_cleanup_thread(self): + """启动视频文件清理线程""" + def cleanup_loop(): + while not self.stop_event.is_set(): + try: + self._cleanup_expired_files() + except Exception as e: + logger.error(f"[ERROR] Cleanup thread error: {e}") + # 每10分钟检查一次 + self.stop_event.wait(600) + + thread = threading.Thread(target=cleanup_loop, daemon=True, name="video_cleanup") + thread.start() + logger.info("[INFO] Video cleanup thread started") + + def _cleanup_expired_files(self): + """清理过期的视频文件""" + output_dir = constants.VIDEO_CLIP_OUTPUT_DIR + if not output_dir or not os.path.exists(output_dir): + return + + retention_seconds = constants.VIDEO_CLIP_RETENTION_SECONDS + current_time = time.time() + + try: + for filename in os.listdir(output_dir): + if not filename.endswith('.mp4'): + continue + filepath = os.path.join(output_dir, filename) + if os.path.isfile(filepath): + file_mtime = os.path.getmtime(filepath) + if current_time - file_mtime > retention_seconds: + try: + os.remove(filepath) + logger.info(f"[INFO] Cleaned up expired video: {filename}") + except Exception as e: + logger.error(f"[ERROR] Failed to delete {filename}: {e}") + except Exception as e: + logger.error(f"[ERROR] Cleanup expired files error: {e}") + + def _create_or_get_video_clip(self, segment_path: str, segment_duration: float = None) -> str | None: + """ + 创建或获取视频剪辑 + + Args: + segment_path: 当前TS分片路径 + segment_duration: 当前分片时长(秒) + + Returns: + MP4文件路径,失败返回 None + """ + if not segment_path: + return None + + # 检查缓存 + if segment_path in self._mp4_cache: + cached_path = self._mp4_cache[segment_path] + if os.path.exists(cached_path): + return cached_path + else: + # 缓存失效,移除 + del self._mp4_cache[segment_path] + + # 解析分片信息,构建MP4路径 + camera_id, timestamp, seq = parse_segment_info(segment_path) + if not camera_id: + logger.warning(f"[WARN] Failed to parse segment info: {segment_path}") + return None + + output_dir = constants.VIDEO_CLIP_OUTPUT_DIR + if not output_dir: + logger.warning("[WARN] VIDEO_CLIP_OUTPUT_DIR not configured") + return None + + # 确保输出目录存在 + os.makedirs(output_dir, exist_ok=True) + + # MP4文件名 + mp4_filename = f"{camera_id}_{timestamp}_{seq}.mp4" + mp4_path = os.path.join(output_dir, mp4_filename) + + # 检查是否已存在 + if os.path.exists(mp4_path): + self._mp4_cache[segment_path] = mp4_path + return mp4_path + + # 计算需要回溯的分片数量 + clip_duration = constants.VIDEO_CLIP_DURATION_SECONDS + default_segment_duration = constants.VIDEO_CLIP_DEFAULT_SEGMENT_DURATION + + effective_duration = segment_duration if segment_duration else default_segment_duration + if effective_duration <= 0: + effective_duration = default_segment_duration + + n_segments = int(clip_duration / effective_duration) + 1 + + # 获取需要合并的分片 + ts_files = get_segments_before_current(segment_path, n_segments) + if not ts_files: + logger.warning(f"[WARN] No segments found for clip: {segment_path}") + return None + + # 合并TS为MP4 + if self._merge_ts_to_mp4(ts_files, mp4_path): + self._mp4_cache[segment_path] = mp4_path + return mp4_path + + return None + + def _merge_ts_to_mp4(self, ts_files: list, output_path: str) -> bool: + """ + 使用 ffmpeg 合并 TS 分片为 MP4 + + Args: + ts_files: TS文件路径列表(按时间顺序) + output_path: 输出MP4路径 + + Returns: + 是否成功 + """ + if not ts_files: + return False + + try: + # 构建 concat 字符串 + concat_str = "|".join(ts_files) + + # ffmpeg 命令 + cmd = [ + 'ffmpeg', + '-i', f'concat:{concat_str}', + '-c', 'copy', + '-y', # 覆盖输出文件 + output_path + ] + + # 执行命令 + result = subprocess.run( + cmd, + capture_output=True, + timeout=60 # 60秒超时 + ) + + if result.returncode == 0: + logger.info(f"[INFO] Created video clip: {output_path}") + return True + else: + logger.error(f"[ERROR] ffmpeg failed: {result.stderr.decode()}") + return False + + except subprocess.TimeoutExpired: + logger.error(f"[ERROR] ffmpeg timeout for {output_path}") + return False + except FileNotFoundError: + logger.error("[ERROR] ffmpeg not found, please install ffmpeg") + return False + except Exception as e: + logger.error(f"[ERROR] Failed to merge TS files: {e}") + return False + + def _process_alert_with_video(self, msg: dict, segment_path: str, segment_duration: float): + """ + 处理告警(含视频剪辑)- 在线程池中执行 + + Args: + msg: 基础消息 + segment_path: 当前TS分片路径 + segment_duration: 当前分片时长 + """ + # 尝试创建/获取视频剪辑 + mp4_path = None + if segment_path: + mp4_path = self._create_or_get_video_clip(segment_path, segment_duration) + + # 展开 result_type + expanded_msgs = self._expand_msg_by_result_type(msg) + + # 发送每个展开后的消息 + for expanded_msg in expanded_msgs: + self._post_alert_with_video(expanded_msg, mp4_path) + def _create_detector(self, params): """创建检测器实例""" # 使用 type(self) 访问类属性,避免 lambda 被绑定 self 参数 @@ -203,13 +425,24 @@ class BaseFrameProcessorWorker(threading.Thread): 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'] = self.POST_TYPE - # 展开 result_type 为多个独立的 msg - expanded_msgs = self._expand_msg_by_result_type(post_msg) - for expanded_msg in expanded_msgs: - self.post_executor.submit(self._post_alert, expanded_msg) + + #备用backup + #self.post_executor.submit(self._post_alert, post_msg) + + # 获取视频相关信息(仅HLS模式有) + segment_path = item.get("segment_path") + segment_duration = item.get("segment_duration") + + # 提交到线程池执行(包含视频剪辑和POST) + self.post_executor.submit( + self._process_alert_with_video, + post_msg, + segment_path, + segment_duration + ) except queue.Full: logger.warning("[WARN] ws_send_queue full, drop frame message") diff --git a/common/constants.py b/common/constants.py index 6ea183d..d75a3bf 100644 --- a/common/constants.py +++ b/common/constants.py @@ -9,6 +9,12 @@ HLS_ROOT_PATH = "" HLS_SEGMENT_PATTERN = "segment_%09d.ts" # TS文件命名模式 +# 视频剪辑配置 +VIDEO_CLIP_OUTPUT_DIR = "" +VIDEO_CLIP_DURATION_SECONDS = 30 +VIDEO_CLIP_RETENTION_SECONDS = 3600 +VIDEO_CLIP_DEFAULT_SEGMENT_DURATION = 2 + def init_config(config_path: str = "config.yaml"): """ @@ -18,6 +24,7 @@ def init_config(config_path: str = "config.yaml"): config_path: 配置文件路径,默认为 config.yaml """ global ALERT_PUSH_URL, HLS_ROOT_PATH + global VIDEO_CLIP_OUTPUT_DIR, VIDEO_CLIP_DURATION_SECONDS, VIDEO_CLIP_RETENTION_SECONDS, VIDEO_CLIP_DEFAULT_SEGMENT_DURATION try: with open(config_path, "r", encoding="utf-8") as f: @@ -25,6 +32,13 @@ def init_config(config_path: str = "config.yaml"): ALERT_PUSH_URL = cfg.get("alert_push_url", "") # HLS_ROOT_PATH = cfg.get("hls_root_path", "") + + # 视频剪辑配置 + VIDEO_CLIP_OUTPUT_DIR = cfg.get("video_clip_output_dir", "") + VIDEO_CLIP_DURATION_SECONDS = cfg.get("video_clip_duration_seconds", 30) + VIDEO_CLIP_RETENTION_SECONDS = cfg.get("video_clip_retention_seconds", 3600) + VIDEO_CLIP_DEFAULT_SEGMENT_DURATION = cfg.get("video_clip_default_segment_duration", 2) + logger.info(f"[INFO] Config initialized from {config_path}, alert_push_url={ALERT_PUSH_URL}") except Exception as e: diff --git a/config.yaml b/config.yaml index f930980..c87bed1 100644 --- a/config.yaml +++ b/config.yaml @@ -41,6 +41,12 @@ hls_downloader_daily_rotate_hour: 3 # 凌晨轮换时间 hls_downloader_retention_days: 3 # 文件保留天数 hls_downloader_retry_interval_seconds: 10 # 重试等待秒数 +# 视频剪辑配置 +video_clip_output_dir: "D:/ProjectDoc/Police/data/video_clips" # 视频剪辑输出目录 +video_clip_duration_seconds: 30 # 回溯时长(秒) +video_clip_retention_seconds: 3600 # 视频文件保留时长(秒) +video_clip_default_segment_duration: 2 # 默认分片时长fallback(秒) + service_groups: - name: "kadian_group" # 服务组名称 video_source_type: "hls" @@ -49,7 +55,7 @@ service_groups: algorithm: "checkpoint" # 算法类型 cameras: # 该组下的摄像头列表 - id: 8 - index: 12345 + index: "12345" name: Entrance params: roi_points: diff --git a/utils/hls_utils.py b/utils/hls_utils.py index e6b79c3..5f9ae3a 100644 --- a/utils/hls_utils.py +++ b/utils/hls_utils.py @@ -1,5 +1,6 @@ import os import glob +import re from common import constants @@ -67,3 +68,128 @@ def get_latest_n_segments_by_camera_id(camera_id: str, n: int) -> list: """ camera_root_dir = os.path.join(constants.HLS_ROOT_PATH, camera_id) return get_latest_n_segments(camera_root_dir, n) + + +def parse_segment_info(segment_path: str) -> tuple: + """ + 从TS分片路径解析出 camera_id, timestamp, sequence + + Args: + segment_path: TS分片路径,格式如: hls_root_path/camera_id/timestamp/segment_xxxxx.ts + + Returns: + (camera_id, timestamp, sequence) 或 (None, None, None) 解析失败时 + """ + try: + # 获取文件名和目录结构 + # 路径格式: .../camera_id/timestamp/segment_00001.ts + abs_path = os.path.abspath(segment_path) + parts = abs_path.split(os.sep) + + # 从后往前找 + # parts[-1] = segment_00001.ts + # parts[-2] = timestamp + # parts[-3] = camera_id + + if len(parts) < 3: + return None, None, None + + # 解析序号 + filename = parts[-1] + match = re.search(r'segment_(\d+)\.ts$', filename) + if not match: + return None, None, None + sequence = match.group(1) + + # 时间戳 + timestamp = parts[-2] + + # camera_id + camera_id = parts[-3] + + return camera_id, timestamp, sequence + + except Exception: + return None, None, None + + +def get_segments_before_current(current_segment_path: str, n: int) -> list: + """ + 获取当前分片之前的n个分片(包括当前分片) + + Args: + current_segment_path: 当前TS分片路径 + n: 需要获取的分片数量 + + Returns: + 分片路径列表(按时间顺序,旧的在前),如果不够n个则返回现有的 + """ + if not current_segment_path or not os.path.exists(current_segment_path): + return [] + + # 解析当前分片信息 + camera_id, timestamp, current_seq = parse_segment_info(current_segment_path) + if not camera_id: + return [] + + # 构建摄像头根目录和时间戳目录 + camera_root_dir = os.path.join(constants.HLS_ROOT_PATH, camera_id) + timestamp_dir = os.path.join(camera_root_dir, timestamp) + + if not os.path.exists(timestamp_dir): + return [] + + # 获取当前时间戳文件夹下的所有分片 + pattern = os.path.join(timestamp_dir, "segment_*.ts") + segment_files = glob.glob(pattern) + + # 按分片序号排序 + segment_files.sort(key=lambda x: int(os.path.basename(x).split('_')[-1].split('.')[0])) + + # 找到当前分片的位置 + try: + current_index = segment_files.index(current_segment_path) + except ValueError: + # 当前分片不在列表中 + return [] + + # 计算起始位置 + start_index = max(0, current_index - n + 1) + + # 返回从起始位置到当前位置的所有分片 + result = segment_files[start_index:current_index + 1] + + # 如果不够n个,需要从之前的时间戳文件夹获取 + if len(result) < n: + # 获取所有时间戳文件夹 + timestamp_folders = [] + for folder_name in os.listdir(camera_root_dir): + folder_path = os.path.join(camera_root_dir, folder_name) + if os.path.isdir(folder_path): + timestamp_folders.append(folder_name) + + # 排序,找到当前时间戳之前的时间戳 + timestamp_folders.sort() + try: + current_ts_index = timestamp_folders.index(timestamp) + except ValueError: + current_ts_index = len(timestamp_folders) + + # 从之前的时间戳文件夹获取分片 + needed_count = n - len(result) + for i in range(current_ts_index - 1, -1, -1): + prev_ts_dir = os.path.join(camera_root_dir, timestamp_folders[i]) + prev_pattern = os.path.join(prev_ts_dir, "segment_*.ts") + prev_segments = glob.glob(prev_pattern) + prev_segments.sort(key=lambda x: int(os.path.basename(x).split('_')[-1].split('.')[0])) + + # 取最后 needed_count 个 + take_count = min(needed_count, len(prev_segments)) + if take_count > 0: + result = prev_segments[-take_count:] + result + needed_count -= take_count + + if needed_count <= 0: + break + + return result From 8bcb586b536cadd8846eef11a91b6dc0f57bd72c Mon Sep 17 00:00:00 2001 From: zqc <835569504@qq.com> Date: Thu, 5 Mar 2026 16:05:58 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E5=AE=8C=E6=88=90=E8=AD=A6=E5=91=8A?= =?UTF-8?q?=E6=B6=88=E6=81=AF=E5=AF=B9=E5=BA=94=E4=B8=AD=E6=96=87=E6=98=BE?= =?UTF-8?q?=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- biz/base_frame_processor.py | 12 ++-- biz/checkpoint/checkpoint_biz.py | 4 +- common/type_mapping.py | 96 ++++++++++++++++++++++++++++++++ config.yaml | 17 ++++++ 4 files changed, 123 insertions(+), 6 deletions(-) create mode 100644 common/type_mapping.py diff --git a/biz/base_frame_processor.py b/biz/base_frame_processor.py index 5e68a6f..4a43084 100644 --- a/biz/base_frame_processor.py +++ b/biz/base_frame_processor.py @@ -15,6 +15,7 @@ from typing import Dict, Any, Callable from concurrent.futures import ThreadPoolExecutor from common import constants +from common.type_mapping import get_alert_label from utils.logger import get_logger from utils.hls_utils import get_segments_before_current, parse_segment_info @@ -90,10 +91,10 @@ class BaseFrameProcessorWorker(threading.Thread): 将 msg 中的 result_type 从数组展开为多个独立的 msg Args: - msg: 原始消息,result_type 为数组 + msg: 原始消息,result_type 为 action code 字符串数组 Returns: - msg 列表,每个 msg 的 result_type 为数组中的单个元素 + msg 列表,每个 msg 的 result_type 为包含 action_code 和 action_name 的对象 """ result_types = msg.get("result_type", []) if not isinstance(result_types, list): @@ -104,9 +105,12 @@ class BaseFrameProcessorWorker(threading.Thread): return [msg] result = [] - for r_type in result_types: + for action_code in result_types: new_msg = msg.copy() - new_msg["result_type"] = r_type + new_msg["result_type"] = { + "action_code": action_code, + "action_name": get_alert_label(action_code) + } result.append(new_msg) return result diff --git a/biz/checkpoint/checkpoint_biz.py b/biz/checkpoint/checkpoint_biz.py index d024c03..1dc18a5 100644 --- a/biz/checkpoint/checkpoint_biz.py +++ b/biz/checkpoint/checkpoint_biz.py @@ -371,12 +371,12 @@ class KadianDetector: # 情况1:通过时间太短 -> Ignore (Too Fast) if duration_frames < self.frame_thresh_car_min_duration: - print(f"ALARM: Car {car_id} passed too fast -> Regarded as Ignore Checked!") + logger.info(f"ALARM: Car {car_id} passed too fast -> Regarded as Ignore Checked!") self.fast_pass_alerts[car_id] = self.current_frame_idx + int(self.ignore_show_seconds * self.fps) # 情况2:时间够长,但没检查后备箱 -> Unchecked Trunk elif not car_info['is_checked']: - print(f"ALARM: Car {car_id} left without checking trunk!") + logger.info(f"ALARM: Car {car_id} left without checking trunk!") self.unchecked_trunk_alerts[car_id] = self.current_frame_idx + int( self.openTrunk_show_seconds * self.fps) diff --git a/common/type_mapping.py b/common/type_mapping.py new file mode 100644 index 0000000..491822c --- /dev/null +++ b/common/type_mapping.py @@ -0,0 +1,96 @@ +# common/type_mapping.py +""" +告警类型映射配置模块 +从 config.yaml 加载告警 code 到 label 的映射关系 +""" + +import yaml +from typing import Dict, Optional +from utils.logger import get_logger + +logger = get_logger(__name__) + + +class TypeMapping: + """类型映射类""" + + def __init__(self, mapping: Dict[str, str], name: str = ""): + self._mapping = mapping or {} + self._name = name + + def get(self, code: str, default: Optional[str] = None) -> str: + """获取label,支持自定义默认值""" + if default is None: + default = f"{code}" + return self._mapping.get(code, default) + + def __getitem__(self, code: str) -> str: + """支持 [] 语法访问""" + return self.get(code) + + def __contains__(self, code: str) -> bool: + """支持 in 操作符""" + return code in self._mapping + + def all(self) -> Dict[str, str]: + """获取所有映射""" + return self._mapping.copy() + + def codes(self) -> list: + """获取所有code""" + return list(self._mapping.keys()) + + def labels(self) -> list: + """获取所有label""" + return list(self._mapping.values()) + + +# 全局映射实例 +_alert_types: Optional[TypeMapping] = None + + +def init_type_mappings(config_path: str = "config.yaml"): + """ + 从配置文件初始化类型映射 + + Args: + config_path: 配置文件路径 + """ + global _alert_types + + try: + with open(config_path, "r", encoding="utf-8") as f: + cfg = yaml.safe_load(f) + + _alert_types = TypeMapping( + cfg.get("alert_types", {}), + name="告警类型" + ) + + logger.info(f"[INFO] Alert type mappings initialized from {config_path}") + logger.info(f" - alert_types: {len(_alert_types.codes())} items") + + except Exception as e: + logger.error(f"[ERROR] Failed to load type mappings from {config_path}: {e}") + _alert_types = TypeMapping({}, "告警类型") + + +def alert_types() -> TypeMapping: + """获取告警类型映射""" + if _alert_types is None: + init_type_mappings() + return _alert_types + + +def get_alert_label(code: str, default: str = None) -> str: + """ + 快捷获取告警类型label + + Args: + code: 告警类型代码 + default: 默认值,未提供时返回 "未知告警类型(code)" + + Returns: + 告警类型中文名称 + """ + return alert_types().get(code, default) diff --git a/config.yaml b/config.yaml index c87bed1..d565ed0 100644 --- a/config.yaml +++ b/config.yaml @@ -78,3 +78,20 @@ service_groups: # - [0.5, 0.001] # - [1.0, 0.8] # - [0.35, 1.0] + +# 告警类型映射 (code -> 中文名称) +alert_types: + # 卡点检测 (checkpoint) + "Unchecked Trunk": "未检查后备箱" + "Ignore": "漏检" + "Nobody": "无人在场" + "Only One": "单人单检" + + # 监狱检测 (prison) + "prisoner": "带出犯人" + "violation": "路线违规" + + # 监控室检测 (supervision_room) + "Playing Phone": "玩手机" + "Smoke": "吸烟" + "Nobody Checking": "无人在场" From 124672332fd02f110e726032cb8a9b5f0f952190 Mon Sep 17 00:00:00 2001 From: zqc <835569504@qq.com> Date: Fri, 6 Mar 2026 09:46:40 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=E6=96=B0=E5=A2=9Eab=E9=97=A8biz?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- biz/checkpoint/checkpoint_biz_02.py | 515 ---------------------------- biz/prison/ab_biz.py | 447 ++++++++++++++++++++++++ 2 files changed, 447 insertions(+), 515 deletions(-) delete mode 100644 biz/checkpoint/checkpoint_biz_02.py create mode 100644 biz/prison/ab_biz.py diff --git a/biz/checkpoint/checkpoint_biz_02.py b/biz/checkpoint/checkpoint_biz_02.py deleted file mode 100644 index f0a372f..0000000 --- a/biz/checkpoint/checkpoint_biz_02.py +++ /dev/null @@ -1,515 +0,0 @@ - -import cv2 -import numpy as np -from typing import Dict, Any -import threading -import queue - -from biz.base_frame_processor import BaseFrameProcessorWorker - -# -------------------------- Kadian 检测相关导入 -------------------------- -from algorithm.common.npu_yolo_onnx_person_car_phone import YOLOv8_ONNX # 主检测模型(人/车/后备箱/手机) -from algorithm.common.npu_yolo_pose_onnx import YOLOv8_Pose_ONNX # Pose 专用模型 -from yolox.tracker.byte_tracker import BYTETracker - -from utils.logger import get_logger -logger = get_logger(__name__) - -# ========================= 配置区 ========================= -# Kadian 模型路径与ROI(可根据实际情况修改) -DETECT_MODEL_PATH = 'YOLO_Weight/Kadian.onnx' -#POSE_MODEL_PATH = 'YOLO_Weight/yolov8l-pose.onnx' - -# 默认相对ROI(与原文件一致) -#ROI_RELATIVE = np.array([ -# [0.10989583333333333, 0.006481481481481481], -# [0.421875, 0.005555555555555556], -# [0.9921875, 0.9888888888888889], -# [0.3411458333333333, 0.9861111111111112] -#]) - -# ROI_RELATIVE=np.array([ -# [0.15,0.001], -# [0.5,0.001], -# [1.0,0.8], -# [0.35,1.0] -# ]) - -ROI_RELATIVE=np.array([ - [0.12,0.0], - [0.3,0.0], - [0.5,0.2], - [1.0, 0.95], - [1.0,1.0], - [0.42,1.0] -]) - - -ALERT_PUSH_INTERVAL = 5.0 - -# 输入尺寸 -PERSON_CAR_INPUT_SIZE = 640 - - - -RTSP_TARGET_FPS = 10.0 - - - -class KadianDetector: - def __init__(self, roi_points=ROI_RELATIVE): - # 模型加载 - 仅保留主检测器,删除pose_detector - self.detector = YOLOv8_ONNX( - DETECT_MODEL_PATH, - conf_threshold=0.25, - iou_threshold=0.45, - input_size=PERSON_CAR_INPUT_SIZE - ) - - # 跟踪器配置 - class TrackerArgs: - track_thresh = 0.3 # 必须大于等于yolo的conf_threshold - track_buffer = 40 - match_thresh = 0.85 - mot20 = True - - self.fps = RTSP_TARGET_FPS - self.tracker = BYTETracker(TrackerArgs(), frame_rate=self.fps) - self.track_role = {} # 跟踪ID到类别的映射 - - - # ROI 处理(支持相对/绝对) - self.roi_points = np.array(roi_points, dtype=np.float64) if roi_points is not None else None - - # ===================== 超参数设置 (仅保留车/后备箱相关) ===================== - # 后备箱检查判定阈值 - self.TIME_THRESHOLD_TRUNK_OPEN = 0.1 - # 车辆最小停留时间阈值 (小于此时间视为无人检查/直接通过) - self.TIME_THRESHOLD_CAR_MIN_DURATION = 3.0 - # Car 丢帧/ID维持缓冲 - self.TIME_TOLERANCE_CAR = 2.0 - - # police丢失阈值 - self.TIME_TOLERANCE_POLICE = 3.0 - # police状态判定阈值 (累计秒数) - self.TIME_THRESHOLD_NOBODY = 5.0 - self.TIME_THRESHOLD_ONLY_ONE = 5.0 - - # --- 计算对应的帧数阈值 --- - self.frame_thresh_trunk_valid = int(self.TIME_THRESHOLD_TRUNK_OPEN * self.fps) - self.frame_thresh_car_min_duration = int(self.TIME_THRESHOLD_CAR_MIN_DURATION * self.fps) - self.frame_buffer_limit_car = int(self.TIME_TOLERANCE_CAR * self.fps) - self.frame_buffer_limit_police = int(self.TIME_TOLERANCE_POLICE * self.fps) - self.frame_thresh_nobody = int(self.TIME_THRESHOLD_NOBODY * self.fps) - self.frame_thresh_only_one = int(self.TIME_THRESHOLD_ONLY_ONE * self.fps) - - # 显示相关阈值 - self.ignore_show_seconds = 0.2 # 未检测的警告显示时长 - self.openTrunk_show_seconds = 0.2 # 打开后备箱的警告显示时长 - self.police_show_seconds = 0.2 # 警察在场警告显示时长 - - # 状态变量初始化 - self.current_frame_idx = 0 - self.width = 0 - self.height = 0 - - - # 车辆注册表 (字典) - self.roi_car_registry = {} - # 违规车辆记录 - self.unchecked_trunk_alerts = {} # 后备箱未检 - self.fast_pass_alerts = {} # 通过过快 - - # 警察注册表 (字典) - self.roi_police_registry = {} - # 警察在场告警记录 - self.nobody_alerts = {} # 无人在场 - self.only_one_alerts = {} # 单人在场 - # 累计帧数计数器 - self.nobody_frames = 0 # 累计无人在场帧数 - self.only_one_frames = 0 # 累计单人在场帧数 - - # 打印超参数 - print(f"\n超参数设置:") - print(f" FPS: {self.fps:.2f}") - print(f" 判定 'Trunk Checked' 需累计检测: {self.frame_thresh_trunk_valid} 帧") - print(f" 判定 'Too Fast' 最小停留: {self.frame_thresh_car_min_duration} 帧") - - def _get_roi_points(self, frame_width: int, frame_height: int): - """ - 每帧动态计算正确的 ROI 绝对坐标,并确保类型为 np.int32 - 用于 pointPolygonTest 和 polylines - """ - if self.roi_points is None: - raise ValueError("ROI points must be provided; cannot be None.") - - if self.roi_points.max() <= 1.0: - # 相对坐标 → 转换为绝对 - roi_abs = self.roi_points * np.array([frame_width, frame_height]) - else: - # 绝对坐标,直接使用 - roi_abs = self.roi_points.copy() - - # 强制转为 int32(关键!解决 OpenCV 断言错误) - return roi_abs.astype(np.int32) - - def check_point_in_roi(self, roi_points, point): - """判断点是否在ROI内""" - return cv2.pointPolygonTest(roi_points, point, False) >= 0 - - def compute_iou(self, boxA, boxB): - """计算两个框的IOU""" - # box = [x1, y1, x2, y2] - xA = max(boxA[0], boxB[0]) - yA = max(boxA[1], boxB[1]) - xB = min(boxA[2], boxB[2]) - yB = min(boxA[3], boxB[3]) - - interW = max(0, xB - xA) - interH = max(0, yB - yA) - interArea = interW * interH - - boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1]) - boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1]) - - unionArea = boxAArea + boxBArea - interArea - if unionArea == 0: - return 0.0 - - return interArea / unionArea - - def draw_alert(self, frame, text, color=(0, 0, 255), sub_text=None, offset_y=0): - """在右上角绘制警告文字 (支持垂直偏移,防止文字重叠)""" - font_scale = 1.5 - thickness = 3 - font = cv2.FONT_HERSHEY_SIMPLEX - - (text_w, text_h), _ = cv2.getTextSize(text, font, font_scale, thickness) - x = self.width - text_w - 20 - y = 50 + text_h + offset_y # 增加 Y 轴偏移 - - cv2.rectangle(frame, (x - 10, y - text_h - 10), (x + text_w + 10, y + 10), (0, 0, 0), -1) - cv2.putText(frame, text, (x, y), font, font_scale, color, thickness) - - if sub_text: - cv2.putText(frame, sub_text, (x, y + 40), font, 0.7, (200, 200, 200), 2) - - def is_point_in_box(self, point, box): - """判断点是否在框内""" - px, py = point - x1, y1, x2, y2 = box - return x1 < px < x2 and y1 < py < y2 - - def process_frame(self, frame, camera_id: int, timestamp: float) -> Dict[str, Any]: - h, w = frame.shape[:2] - self.width, self.height = w, h - - self.current_frame_idx += 1 - # ========= 每帧动态获取正确的 ROI(int32)========= - roi_points_int32 = self._get_roi_points(w, h) # shape: (4, 2), dtype: int32 - roi_points_draw = roi_points_int32.reshape((-1, 1, 2)) # shape: (4, 1, 2) 用于绘制 - - current_time_sec = timestamp - - # ========= 主检测(删除pose检测)========= - detections = self.detector(frame) - - dets_xyxy = [] - dets_roles = [] - dets_for_tracker = [] - - # ========= 当前帧所有警告列表 ========== - current_frame_alerts = [] # 每帧清空,重新收集 - - if detections: - for det in detections: - x1, y1, x2, y2, conf, cls_id = det # x1,y1:左上角,x2,y2:右下角 - dets_xyxy.append([x1, y1, x2, y2]) - dets_for_tracker.append([x1, y1, x2, y2, conf]) - - # 更新类别映射:0=Car,1=OpenTrunk,2=Passerby,3=Police - if cls_id == 0: - dets_roles.append("car") - elif cls_id == 1: - dets_roles.append("opentrunk") - elif cls_id == 2: - dets_roles.append("passerby") # 路人 - elif cls_id == 3: - dets_roles.append("police") # 警察 - - dets = np.array(dets_for_tracker, dtype=np.float32) if len(dets_for_tracker) else np.empty((0, 5)) - - # 跟踪器更新 - tracks = self.tracker.update( - dets, - [self.height, self.width], - [self.height, self.width] - ) - - # ========= 绘制 ROI ========= - cv2.polylines(frame, [roi_points_draw], isClosed=True, color=(255, 0, 0), thickness=3) - - # ========= 单帧统计变量 ========= - current_roi_trunk_count = 0 # 仅保留后备箱统计 - current_roi_police_count = 0 # ROI内警察数量 - - # 临时存储本帧的目标,用于后续关联分析 - current_cars = [] # {'id':, 'box':} - current_trunks = [] # (cx, cy) - - # ========= 处理跟踪结果 ========= - for t in tracks: - tid = t.track_id - REVALIDATE_FRAME_INTERVAL = 10 - - # 定期重新匹配跟踪ID的类别 - if (self.current_frame_idx % REVALIDATE_FRAME_INTERVAL == 0) or (tid not in self.track_role): - best_iou = 0 - best_role = "unknown" - t_box = list(map(float, t.tlbr)) # [x1,y1,x2,y2] - - for i, box in enumerate(dets_xyxy): - iou_val = self.compute_iou(t_box, box) - if iou_val > best_iou: - best_iou = iou_val - best_role = dets_roles[i] - if best_iou > 0.1: - self.track_role[tid] = best_role - else: - self.track_role[tid] = "unknown" - - role = self.track_role.get(tid, "unknown") - x1, y1, x2, y2 = map(int, t.tlbr) - cx, cy = (x1 + x2) // 2, (y1 + y2) // 2 - - # 定义不同类别的颜色(仅标框,不告警) - if role == "car": - color = (0, 255, 0) # 绿色 - label = f"Car:{tid}" - # 仅处理ROI内的车辆 - if self.check_point_in_roi(roi_points_int32, (cx, cy)): - current_cars.append({'id': tid, 'box': [x1, y1, x2, y2]}) - # 车辆注册表初始化 - if tid not in self.roi_car_registry: - self.roi_car_registry[tid] = { - 'first_seen': self.current_frame_idx, - 'last_seen': self.current_frame_idx, - 'trunk_frames': 0, - 'is_checked': False, - } - else: - self.roi_car_registry[tid]['last_seen'] = self.current_frame_idx - label += " IN" - elif role == "opentrunk": - color = (255, 165, 0) # 橙色 - label = "OpenTrunk" - if self.check_point_in_roi(roi_points_int32, (cx, cy)): - current_roi_trunk_count += 1 - current_trunks.append((cx, cy)) - label += " IN" - elif role == "passerby": - color = (255, 255, 0) # 黄色(仅标框,不告警) - label = "Passerby" - elif role == "police": - color = (0, 255, 255) # 青色 - label = "Police" - if self.check_point_in_roi(roi_points_int32, (cx, cy)): - current_roi_police_count += 1 - # 警察注册表初始化 - if tid not in self.roi_police_registry: - self.roi_police_registry[tid] = { - 'first_seen': self.current_frame_idx, - 'last_seen': self.current_frame_idx, - } - else: - self.roi_police_registry[tid]['last_seen'] = self.current_frame_idx - label += " IN" - else: - color = (255, 255, 255) # 白色 - label = "Unknown" - - # 绘制检测框和标签(所有类别都标框,仅车/后备箱有逻辑) - cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) - cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2) - - # ========================================== - # 关联分析: 哪个后备箱属于哪辆车? - # ========================================== - for car_info in current_cars: - c_id = car_info['id'] - c_box = car_info['box'] - trunk_found_for_this_car = False - - for t_pt in current_trunks: - if self.is_point_in_box(t_pt, c_box): - trunk_found_for_this_car = True - break - - if trunk_found_for_this_car: - self.roi_car_registry[c_id]['trunk_frames'] += 1 - if self.roi_car_registry[c_id]['trunk_frames'] >= self.frame_thresh_trunk_valid: - self.roi_car_registry[c_id]['is_checked'] = True - - # ========================================== - # 维护车辆注册表 & 生成离场报警 - # ========================================== - active_car_ids = [] - cars_to_remove = [] - - for car_id, info in self.roi_car_registry.items(): - last_seen = info['last_seen'] - if (self.current_frame_idx - last_seen) <= self.frame_buffer_limit_car: - active_car_ids.append(car_id) - else: - cars_to_remove.append(car_id) - - # 处理离场车辆,生成违规告警 - for car_id in cars_to_remove: - car_info = self.roi_car_registry[car_id] - duration_frames = car_info['last_seen'] - car_info['first_seen'] - - # 情况1:通过时间太短 -> Ignore (Too Fast) - if duration_frames < self.frame_thresh_car_min_duration: - print(f"ALARM: Car {car_id} passed too fast -> Regarded as Ignore Checked!") - self.fast_pass_alerts[car_id] = self.current_frame_idx + int(self.ignore_show_seconds * self.fps) - - # 情况2:时间够长,但没检查后备箱 -> Unchecked Trunk - elif not car_info['is_checked']: - print(f"ALARM: Car {car_id} left without checking trunk!") - self.unchecked_trunk_alerts[car_id] = self.current_frame_idx + int( - self.openTrunk_show_seconds * self.fps) - - del self.roi_car_registry[car_id] - - effective_car_count = len(active_car_ids) - - # ========================================== - # 维护警察注册表 - # ========================================== - active_police_ids = [] - polices_to_remove = [] - - for police_id, info in self.roi_police_registry.items(): - last_seen = info['last_seen'] - if (self.current_frame_idx - last_seen) <= self.frame_buffer_limit_police: - active_police_ids.append(police_id) - else: - polices_to_remove.append(police_id) - - for police_id in polices_to_remove: - del self.roi_police_registry[police_id] - - effective_police_count = len(active_police_ids) - - # ========================================== - # 显示调试信息和报警 (仅保留车/后备箱相关) - # ========================================== - # 调试信息 - debug_info = f"Cars: {len(active_car_ids)} | Trunk: {current_roi_trunk_count} | Police: {effective_police_count} | Nobody:{self.nobody_frames}/{self.frame_thresh_nobody} | OnlyOne:{self.only_one_frames}/{self.frame_thresh_only_one}" - cv2.putText(frame, debug_info, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) - - # 报警偏移量(防止重叠) - alert_offset = 0 - - # A. 显示 Trunk Checked (车辆已检查后备箱) - # for car_id in active_car_ids: - # if car_id in self.roi_car_registry and self.roi_car_registry[car_id]['is_checked']: - # current_frame_alerts.append({ - # 'time': current_time_sec, - # 'action': "Trunk Checked", - # }) - # self.draw_alert(frame, "Trunk Checked!!", (0, 255, 0), offset_y=alert_offset) - # alert_offset += 100 - # break # 只显示一次 - - # B. 显示 Unchecked Trunk (离场未检查后备箱) - expired_alerts = [cid for cid, end_frame in self.unchecked_trunk_alerts.items() if - self.current_frame_idx > end_frame] - for cid in expired_alerts: - del self.unchecked_trunk_alerts[cid] - - if len(self.unchecked_trunk_alerts) > 0: - alert_text = f"Unchecked Trunk! (ID:{list(self.unchecked_trunk_alerts.keys())})" - current_frame_alerts.append({ - 'time': current_time_sec, - 'action': "Unchecked Trunk", - }) - self.draw_alert(frame, alert_text, (0, 0, 255), offset_y=alert_offset) - alert_offset += 100 - - # C. 显示 Ignore (通过过快) - expired_fast_alerts = [cid for cid, end_frame in self.fast_pass_alerts.items() if - self.current_frame_idx > end_frame] - for cid in expired_fast_alerts: - del self.fast_pass_alerts[cid] - - if len(self.fast_pass_alerts) > 0: - alert_text = f"Ignore: (ID:{list(self.fast_pass_alerts.keys())})" - current_frame_alerts.append({ - 'time': current_time_sec, - 'action': "Ignore", - }) - self.draw_alert(frame, alert_text, (0, 0, 255), offset_y=alert_offset) - alert_offset += 100 - - # D. 显示警察在场状态 (Nobody/Only One) - # 清理过期的 Nobody 告警 - expired_nobody = [k for k, v in self.nobody_alerts.items() if self.current_frame_idx > v] - for k in expired_nobody: - del self.nobody_alerts[k] - - # 清理过期的 Only One 告警 - expired_only_one = [k for k, v in self.only_one_alerts.items() if self.current_frame_idx > v] - for k in expired_only_one: - del self.only_one_alerts[k] - - if effective_car_count > 0: - # 更新累计帧数 - if effective_police_count == 0: - self.nobody_frames += 1 - self.only_one_frames = 0 - elif effective_police_count == 1: - self.only_one_frames += 1 - self.nobody_frames = 0 - else: - self.nobody_frames = 0 - self.only_one_frames = 0 - else: - self.nobody_frames = 0 - self.only_one_frames = 0 - - if effective_police_count == 0 and self.nobody_frames >= self.frame_thresh_nobody: - alert_text = "Nobody" - if "Nobody" not in self.nobody_alerts: - self.nobody_alerts["Nobody"] = self.current_frame_idx + int(self.police_show_seconds * self.fps) - current_frame_alerts.append({ - 'time': current_time_sec, - 'action': "Nobody", - }) - #self.draw_alert(frame, alert_text, (0, 0, 255), offset_y=alert_offset) - alert_offset += 100 - elif effective_police_count == 1 and self.only_one_frames >= self.frame_thresh_only_one: - alert_text = "Only One" - if "Only One" not in self.only_one_alerts: - self.only_one_alerts["Only One"] = self.current_frame_idx + int(self.police_show_seconds * self.fps) - current_frame_alerts.append({ - 'time': current_time_sec, - 'action': "Only One", - }) - #self.draw_alert(frame, alert_text, (255, 165, 0), offset_y=alert_offset) - alert_offset += 100 - - return { - "image": frame, - "alerts": current_frame_alerts, - } - - -# ========================= 帧处理线程 ========================= -class FrameProcessorWorker(BaseFrameProcessorWorker): - """卡点检测帧处理线程""" - - # 子类配置 - DETECTOR_FACTORY = lambda params: KadianDetector(params) - POST_TYPE = 1 - TARGET_FPS = RTSP_TARGET_FPS diff --git a/biz/prison/ab_biz.py b/biz/prison/ab_biz.py new file mode 100644 index 0000000..d43aa28 --- /dev/null +++ b/biz/prison/ab_biz.py @@ -0,0 +1,447 @@ +import cv2 +import numpy as np +import base64 +from typing import Dict, Any +import threading +import time +import queue +import requests + +# -------------------------- Kadian 检测相关导入 -------------------------- +from algorithm.common.npu_yolo_onnx_person_car_phone import YOLOv8_ONNX # 主检测模型(人/车/后备箱/手机) +from common.constants import ALERT_PUSH_URL + +from yolox.tracker.byte_tracker import BYTETracker + + +# ========================= 配置区 ========================= +# Kadian 模型路径与ROI(可根据实际情况修改) +detector_model_path = 'YOLO_Weight/prisoner_model.onnx' + +# 输入尺寸 +input_size = 1280 + +RTSP_TARGET_FPS = 10.0 + +# 新增:告警推送频率限制(秒) +ALERT_PUSH_INTERVAL = 5.0 # 相同action 5秒内仅推送一次 + + +class ZoulangDetector: + def __init__(self): + # 模型加载 + + self.police_prisoner_detector = YOLOv8_ONNX(detector_model_path, conf_threshold=0.5, iou_threshold=0.45, + input_size=input_size) + + # ByteTracker + class TrackerArgs: + track_thresh = 0.25 + track_buffer = 30 + match_thresh = 0.8 + mot20 = False + + + + self.police_prisoner_track_role = {} + + self.fps = RTSP_TARGET_FPS + + self.tracker = BYTETracker(TrackerArgs(), frame_rate=self.fps) + + # ========================================== + # 超参数设置 (Hyperparameters) + # ========================================== + + # 1. 业务判定时间阈值 + # self.TIME_THRESHOLD_NOBODY = 2.0 # 无人在场判定时长 + + self.TIME_THRESHOLD_POLICE = 1.0 # 警察判定时长 + self.TIME_TOLERANCE_POLICE = 0.5 # 警察失缓冲时间(防抖动) + + self.TIME_THRESHOLD_PRISONER = 1.0 # 犯人判定时长 + self.TIME_TOLERANCE_PRISONER = 0.5 # 犯人丢失缓冲时间(防抖动) + + # 无人在场帧数阈值 + # self.frame_thresh_nobody = int(self.TIME_THRESHOLD_NOBODY * self.fps) + + # 警察检测帧数阈值 + self.frame_thresh_police = int(self.TIME_THRESHOLD_POLICE * self.fps) + self.frame_buffer_police = int(self.TIME_TOLERANCE_POLICE * self.fps) + + # 犯人检测帧数阈值 + self.frame_thresh_prisoner = int(self.TIME_THRESHOLD_PRISONER * self.fps) + self.frame_buffer_prisoner = int(self.TIME_TOLERANCE_PRISONER * self.fps) + + print(f"\n超参数设置:") + print(f" FPS: {self.fps:.2f}") + # print(f" 判定 'Nobody' 需连续: {self.frame_thresh_nobody} 帧") + print(f" 判定 'police Detected' 需累计检测: {self.frame_thresh_police} 帧") + print(f" 警察丢失缓冲帧数: {self.frame_buffer_police} 帧") + print(f" 判定 'prisoner Detected' 需累计检测: {self.frame_thresh_prisoner} 帧") + print(f" 犯人丢失缓冲帧数: {self.frame_buffer_prisoner} 帧") + + # ========================================== + # 状态变量初始化 + # ========================================== + + self.current_frame_idx = 0 + + # 无人在场检测状态变量 + self.cnt_frame_nobody = 0 + + # 警察检测状态变量 + self.police_detection_frames = 0 # 连续检测到警察的帧数 + self.police_missing_frames = 0 # 连续未检测到警察的帧数 + self.police_alert_active = False # 警察报警是否激活 + + # 犯人检测状态变量 + self.prisoner_detection_frames = 0 # 连续检测到犯人的帧数 + self.prisoner_missing_frames = 0 # 连续未检测到犯人的帧数 + self.prisoner_alert_active = False # 犯人报警是否激活 + + + def compute_iou(self,boxA, boxB): + # box = [x1, y1, x2, y2] + xA = max(boxA[0], boxB[0]) + yA = max(boxA[1], boxB[1]) + xB = min(boxA[2], boxB[2]) + yB = min(boxA[3], boxB[3]) + + interW = max(0, xB - xA) + interH = max(0, yB - yA) + interArea = interW * interH + + boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1]) + boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1]) + + unionArea = boxAArea + boxBArea - interArea + if unionArea == 0: + return 0.0 + + return interArea / unionArea + + def draw_alert(self, frame, text, color=(0, 0, 255), sub_text=None, offset_y=0): + """在右上角绘制警告文字 (支持垂直偏移,防止文字重叠)""" + font_scale = 1.5 + thickness = 3 + font = cv2.FONT_HERSHEY_SIMPLEX + + (text_w, text_h), _ = cv2.getTextSize(text, font, font_scale, thickness) + x = self.width - text_w - 20 + y = 50 + text_h + offset_y # 增加 Y 轴偏移 + + cv2.rectangle(frame, (x - 10, y - text_h - 10), (x + text_w + 10, y + 10), (0, 0, 0), -1) + cv2.putText(frame, text, (x, y), font, font_scale, color, thickness) + + if sub_text: + cv2.putText(frame, sub_text, (x, y + 40), font, 0.7, (200, 200, 200), 2) + + def process_frame(self, frame, camera_id: int, timestamp: float) -> Dict[str, Any]: + h, w = frame.shape[:2] + self.width, self.height = w, h + + self.current_frame_idx += 1 + + current_time_sec = timestamp + + # ========= 警察和犯人检测 ========= + police_prisoner_results = self.police_prisoner_detector(frame) + + police_prisoner_dets_xyxy = [] + police_prisoner_dets_roles = [] + police_prisoner_dets_for_tracker = [] + + # ========= 当前帧所有警告列表(关键改动)========== + current_frame_alerts = [] # 每帧清空,重新收集 + + if police_prisoner_results: + for det in police_prisoner_results: + x1, y1, x2, y2, conf, cls_id = det # x1, y1, x2, y2为角点坐标,x1 y1为左上角,x2 y2为右下角 + police_prisoner_dets_xyxy.append([x1, y1, x2, y2]) + police_prisoner_dets_for_tracker.append([x1, y1, x2, y2, conf]) + if cls_id == 0: + police_prisoner_dets_roles.append("police") + elif cls_id == 1: + police_prisoner_dets_roles.append("prisoner") + + ppolice_prisoner_dets = np.array(police_prisoner_dets_for_tracker, dtype=np.float32) if len( + police_prisoner_dets_for_tracker) else np.empty((0, 5)) + + police_prisoner_dets_tracks = self.tracker.update( + ppolice_prisoner_dets, + [self.height, self.width], + [self.height, self.width] + ) + # ========= 单帧统计变量 ========= + current_police_count = 0 + current_prisoner_count = 0 + + # ========= 警察和犯人检测 ========= + for t in police_prisoner_dets_tracks: + # print("t: {}".format(t)) + tid = t.track_id + # cls_id = -1 + + # IoU 匹配角色 + + REVALIDATE_FRAME_INTERVAL = 10 + if (self.current_frame_idx % REVALIDATE_FRAME_INTERVAL == 0) or ( + tid not in self.police_prisoner_track_role): + best_iou = 0 + best_role = "unknown" + + t_box = list(map(float, t.tlbr)) # [x1,y1,x2,y2] + + for i, box in enumerate(police_prisoner_dets_xyxy): + iou_val = self.compute_iou(t_box, box) + if iou_val > best_iou: + best_iou = iou_val + best_role = police_prisoner_dets_roles[i] + if best_iou > 0.1: + self.police_prisoner_track_role[tid] = best_role + else: + self.police_prisoner_track_role[tid] = "unknown" + + role = self.police_prisoner_track_role.get(tid, "unknown") + cls_id = -1 + if role == "police": + cls_id = 0 + elif role == "prisoner": + cls_id = 1 + # print("tid: {}, role: {}, cls: {}".format(tid, role,cls_id)) + + x1, y1, x2, y2 = map(int, t.tlbr) + + cx, cy = (x1 + x2) // 2, (y1 + y2) // 2 + + color = None + label = None + + if cls_id == 0: # Person + current_police_count += 1 + color = (255, 0, 255) + label = "police" + + elif cls_id == 1: # Phone(主模型已支持) + current_prisoner_count += 1 + color = (0, 0, 139) + label = "prisoner" + else: + color = (255, 255, 255) + label = "Unknown" + + # label = f"ID:{tid} IN" + + cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) + cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2) + + # ========================================== + # 犯人检测 + # ========================================== + if current_prisoner_count > 0: + # 检测到犯人框 + self.prisoner_detection_frames += 1 + self.prisoner_missing_frames = 0 # 重置丢失计数器 + + # 当检测累计达到阈值时,激活报警 + if self.prisoner_detection_frames >= self.frame_thresh_prisoner: + self.prisoner_alert_active = True + else: + # 未检测到犯人框 + self.prisoner_missing_frames += 1 + + # 如果之前检测到手机,重置检测计数器 + if self.prisoner_detection_frames > 0: + # 只有在连续丢失超过缓冲帧数时才重置 + if self.prisoner_missing_frames >= self.frame_buffer_prisoner: + self.prisoner_detection_frames = 0 + self.prisoner_alert_active = False + else: + # 从未检测到犯人,保持状态 + pass + # ========================================== + # 警察检测 + # ========================================== + if current_police_count > 0: + # 检测到犯人框 + self.police_detection_frames += 1 + self.police_missing_frames = 0 # 重置丢失计数器 + + # 当检测累计达到阈值时,激活报警 + if self.police_detection_frames >= self.frame_thresh_police: + self.police_alert_active = True + else: + # 未检测到犯人框 + self.police_missing_frames += 1 + + # 如果之前检测到手机,重置检测计数器 + if self.police_detection_frames > 0: + # 只有在连续丢失超过缓冲帧数时才重置 + if self.police_missing_frames >= self.frame_buffer_police: + self.police_detection_frames = 0 + self.police_alert_active = False + else: + # 从未检测到犯人,保持状态 + pass + + + + alert_offset = 0 + + # A. 有犯人 + if self.prisoner_alert_active: + duration_seconds = self.prisoner_detection_frames / self.fps + current_frame_alerts.append( + { + 'time': current_time_sec, + 'action': 'prisoner', + 'confidence': 1.0, # 固定为1.0(规则判定) + 'details': f"Detected for {duration_seconds:.1f}s" + } + ) + self.draw_alert(frame, "prisoner", (0, 0, 255), offset_y=alert_offset) + alert_offset += 100 + + # ========================================== + # 11. 统一显示当前帧所有警告(可替换原分层显示) + # ========================================== + debug_info = f" prisoner: {current_prisoner_count}" + cv2.putText(frame, debug_info, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) + + # 统一警告显示区 + alert_y_start = 150 + for i, alert in enumerate(current_frame_alerts): + action = alert['action'] + details = alert.get('details', '') + color = (0, 0, 255) # 默认红色警告 + + if action == 'prisoner': + color = (255, 255, 255) + + main_text = action + if details: + main_text += f" ({details})" + + y_pos = alert_y_start + i * 50 + cv2.rectangle(frame, (20, y_pos - 40), (900, y_pos + 10), (0, 0, 0), -1) + cv2.putText(frame, main_text, (30, y_pos), cv2.FONT_HERSHEY_SIMPLEX, 1.0, color, 2) + + return { + "image": frame, + + "alerts":current_frame_alerts + } + + + +# ========================= 帧处理线程 ========================= +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 + + 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] = {} + + # 筛选出符合推送条件的action(5秒内未推送过) + 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() \ No newline at end of file From 845814e6c1a3167bd303a8a1a35707e9b1915185 Mon Sep 17 00:00:00 2001 From: zqc <835569504@qq.com> Date: Fri, 6 Mar 2026 11:11:09 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=E5=AE=8C=E6=88=90ab=E9=97=A8=E8=BF=81?= =?UTF-8?q?=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- biz/prison/ab_biz.py | 386 +++++++++--------------------------- common/processor_factory.py | 3 + 2 files changed, 102 insertions(+), 287 deletions(-) diff --git a/biz/prison/ab_biz.py b/biz/prison/ab_biz.py index d43aa28..6af6432 100644 --- a/biz/prison/ab_biz.py +++ b/biz/prison/ab_biz.py @@ -6,6 +6,7 @@ import threading 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 # 主检测模型(人/车/后备箱/手机) @@ -16,10 +17,10 @@ from yolox.tracker.byte_tracker import BYTETracker # ========================= 配置区 ========================= # Kadian 模型路径与ROI(可根据实际情况修改) -detector_model_path = 'YOLO_Weight/prisoner_model.onnx' +detector_model_path = 'YOLO_Weight/bag_model.onnx' # 输入尺寸 -input_size = 1280 +input_size = 640 RTSP_TARGET_FPS = 10.0 @@ -27,12 +28,15 @@ RTSP_TARGET_FPS = 10.0 ALERT_PUSH_INTERVAL = 5.0 # 相同action 5秒内仅推送一次 -class ZoulangDetector: - def __init__(self): +class AbDetector: + 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) + self.detector = YOLOv8_ONNX(detector_model_path, conf_threshold=0.5, iou_threshold=0.45, + input_size=input_size) # ByteTracker class TrackerArgs: @@ -41,9 +45,7 @@ class ZoulangDetector: match_thresh = 0.8 mot20 = False - - - self.police_prisoner_track_role = {} + self.track_role = {} self.fps = RTSP_TARGET_FPS @@ -52,53 +54,30 @@ class ZoulangDetector: # ========================================== # 超参数设置 (Hyperparameters) # ========================================== + self.TIME_THRESHOLD_BLACKBAG = 1.0 # 黑包判定时长(秒) + self.TIME_TOLERANCE_BLACKBAG = 0.5 # 黑包丢失缓冲时间 - # 1. 业务判定时间阈值 - # self.TIME_THRESHOLD_NOBODY = 2.0 # 无人在场判定时长 - - self.TIME_THRESHOLD_POLICE = 1.0 # 警察判定时长 - self.TIME_TOLERANCE_POLICE = 0.5 # 警察失缓冲时间(防抖动) - - self.TIME_THRESHOLD_PRISONER = 1.0 # 犯人判定时长 - self.TIME_TOLERANCE_PRISONER = 0.5 # 犯人丢失缓冲时间(防抖动) - - # 无人在场帧数阈值 - # self.frame_thresh_nobody = int(self.TIME_THRESHOLD_NOBODY * self.fps) - - # 警察检测帧数阈值 - self.frame_thresh_police = int(self.TIME_THRESHOLD_POLICE * self.fps) - self.frame_buffer_police = int(self.TIME_TOLERANCE_POLICE * self.fps) - - # 犯人检测帧数阈值 - self.frame_thresh_prisoner = int(self.TIME_THRESHOLD_PRISONER * self.fps) - self.frame_buffer_prisoner = int(self.TIME_TOLERANCE_PRISONER * self.fps) + # 转换为帧数阈值 + self.frame_thresh_blackbag = int(self.TIME_THRESHOLD_BLACKBAG * self.fps) + self.frame_buffer_blackbag = int(self.TIME_TOLERANCE_BLACKBAG * self.fps) print(f"\n超参数设置:") print(f" FPS: {self.fps:.2f}") - # print(f" 判定 'Nobody' 需连续: {self.frame_thresh_nobody} 帧") - print(f" 判定 'police Detected' 需累计检测: {self.frame_thresh_police} 帧") - print(f" 警察丢失缓冲帧数: {self.frame_buffer_police} 帧") - print(f" 判定 'prisoner Detected' 需累计检测: {self.frame_thresh_prisoner} 帧") - print(f" 犯人丢失缓冲帧数: {self.frame_buffer_prisoner} 帧") + print(f" 判定 'BlackBag Detected' 需累计检测: {self.frame_thresh_blackbag} 帧") + print(f" 黑包丢失缓冲帧数: {self.frame_buffer_blackbag} 帧") # ========================================== # 状态变量初始化 # ========================================== - self.current_frame_idx = 0 - # 无人在场检测状态变量 - self.cnt_frame_nobody = 0 + # 黑包检测状态 + self.blackbag_detection_frames = 0 + self.blackbag_missing_frames = 0 + self.blackbag_alert_active = False - # 警察检测状态变量 - self.police_detection_frames = 0 # 连续检测到警察的帧数 - self.police_missing_frames = 0 # 连续未检测到警察的帧数 - self.police_alert_active = False # 警察报警是否激活 - - # 犯人检测状态变量 - self.prisoner_detection_frames = 0 # 连续检测到犯人的帧数 - self.prisoner_missing_frames = 0 # 连续未检测到犯人的帧数 - self.prisoner_alert_active = False # 犯人报警是否激活 + # 人员统计变量 + self.current_person_count = 0 def compute_iou(self,boxA, boxB): @@ -145,184 +124,120 @@ class ZoulangDetector: current_time_sec = timestamp - # ========= 警察和犯人检测 ========= - police_prisoner_results = self.police_prisoner_detector(frame) + # ========= 检测推理(黑包+人)========= + detect_results = self.detector(frame) - police_prisoner_dets_xyxy = [] - police_prisoner_dets_roles = [] - police_prisoner_dets_for_tracker = [] + # 初始化检测结果存储 + dets_xyxy = [] + dets_roles = [] + dets_for_tracker = [] + current_frame_alerts = [] - # ========= 当前帧所有警告列表(关键改动)========== - current_frame_alerts = [] # 每帧清空,重新收集 - - if police_prisoner_results: - for det in police_prisoner_results: - x1, y1, x2, y2, conf, cls_id = det # x1, y1, x2, y2为角点坐标,x1 y1为左上角,x2 y2为右下角 - police_prisoner_dets_xyxy.append([x1, y1, x2, y2]) - police_prisoner_dets_for_tracker.append([x1, y1, x2, y2, conf]) + # 解析检测结果(黑包cls_id=0,人员cls_id=1) + if detect_results: + for det in detect_results: + x1, y1, x2, y2, conf, cls_id = det + dets_xyxy.append([x1, y1, x2, y2]) + dets_for_tracker.append([x1, y1, x2, y2, conf]) if cls_id == 0: - police_prisoner_dets_roles.append("police") + dets_roles.append("black_bag") elif cls_id == 1: - police_prisoner_dets_roles.append("prisoner") + dets_roles.append("person") - ppolice_prisoner_dets = np.array(police_prisoner_dets_for_tracker, dtype=np.float32) if len( - police_prisoner_dets_for_tracker) else np.empty((0, 5)) - - police_prisoner_dets_tracks = self.tracker.update( - ppolice_prisoner_dets, + # 跟踪器更新 + dets = np.array(dets_for_tracker, dtype=np.float32) if len(dets_for_tracker) else np.empty((0, 5)) + tracks = self.tracker.update( + dets, [self.height, self.width], [self.height, self.width] ) - # ========= 单帧统计变量 ========= - current_police_count = 0 - current_prisoner_count = 0 - # ========= 警察和犯人检测 ========= - for t in police_prisoner_dets_tracks: - # print("t: {}".format(t)) + # ========= 单帧统计初始化 ========= + self.current_person_count = 0 + current_blackbag_count = 0 + + # ========= 跟踪结果绘制与统计 ========= + for t in tracks: tid = t.track_id - # cls_id = -1 - # IoU 匹配角色 + # IoU匹配跟踪ID和类别 + REVALIDATE_FRAME_INTERVAL = 10 - REVALIDATE_FRAME_INTERVAL = 10 - if (self.current_frame_idx % REVALIDATE_FRAME_INTERVAL == 0) or ( - tid not in self.police_prisoner_track_role): + + #if tid not in self.track_role: + if (self.current_frame_idx % REVALIDATE_FRAME_INTERVAL == 0) or (tid not in self.track_role): best_iou = 0 best_role = "unknown" - - t_box = list(map(float, t.tlbr)) # [x1,y1,x2,y2] - - for i, box in enumerate(police_prisoner_dets_xyxy): + t_box = list(map(float, t.tlbr)) + for i, box in enumerate(dets_xyxy): iou_val = self.compute_iou(t_box, box) if iou_val > best_iou: best_iou = iou_val - best_role = police_prisoner_dets_roles[i] - if best_iou > 0.1: - self.police_prisoner_track_role[tid] = best_role - else: - self.police_prisoner_track_role[tid] = "unknown" - - role = self.police_prisoner_track_role.get(tid, "unknown") - cls_id = -1 - if role == "police": - cls_id = 0 - elif role == "prisoner": - cls_id = 1 - # print("tid: {}, role: {}, cls: {}".format(tid, role,cls_id)) + best_role = dets_roles[i] + self.track_role[tid] = best_role if best_iou > 0.1 else "unknown" + role = self.track_role.get(tid, "unknown") x1, y1, x2, y2 = map(int, t.tlbr) + color = (255, 255, 255) + label = "Unknown" - cx, cy = (x1 + x2) // 2, (y1 + y2) // 2 - - color = None - label = None - - if cls_id == 0: # Person - current_police_count += 1 - color = (255, 0, 255) - label = "police" - - elif cls_id == 1: # Phone(主模型已支持) - current_prisoner_count += 1 - color = (0, 0, 139) - label = "prisoner" - else: - color = (255, 255, 255) - label = "Unknown" - - # label = f"ID:{tid} IN" + # 人员检测(cls_id=1) + if role == "person": + self.current_person_count += 1 + color = (255, 0, 255) # 紫色框 + label = "Person" + # 黑包检测(cls_id=0) + elif role == "black_bag": + current_blackbag_count += 1 + color = (0, 128, 0) # 绿色框 + label = "Black Bag" + # 绘制检测框和标签 cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2) # ========================================== - # 犯人检测 + # 黑包状态更新 # ========================================== - if current_prisoner_count > 0: - # 检测到犯人框 - self.prisoner_detection_frames += 1 - self.prisoner_missing_frames = 0 # 重置丢失计数器 - - # 当检测累计达到阈值时,激活报警 - if self.prisoner_detection_frames >= self.frame_thresh_prisoner: - self.prisoner_alert_active = True + if current_blackbag_count > 0: + self.blackbag_detection_frames += 1 + self.blackbag_missing_frames = 0 + if self.blackbag_detection_frames >= self.frame_thresh_blackbag: + self.blackbag_alert_active = True else: - # 未检测到犯人框 - self.prisoner_missing_frames += 1 + self.blackbag_missing_frames += 1 + if self.blackbag_missing_frames >= self.frame_buffer_blackbag: + self.blackbag_detection_frames = 0 + self.blackbag_alert_active = False - # 如果之前检测到手机,重置检测计数器 - if self.prisoner_detection_frames > 0: - # 只有在连续丢失超过缓冲帧数时才重置 - if self.prisoner_missing_frames >= self.frame_buffer_prisoner: - self.prisoner_detection_frames = 0 - self.prisoner_alert_active = False - else: - # 从未检测到犯人,保持状态 - pass # ========================================== - # 警察检测 + # 警告信息收集 # ========================================== - if current_police_count > 0: - # 检测到犯人框 - self.police_detection_frames += 1 - self.police_missing_frames = 0 # 重置丢失计数器 - - # 当检测累计达到阈值时,激活报警 - if self.police_detection_frames >= self.frame_thresh_police: - self.police_alert_active = True - else: - # 未检测到犯人框 - self.police_missing_frames += 1 - - # 如果之前检测到手机,重置检测计数器 - if self.police_detection_frames > 0: - # 只有在连续丢失超过缓冲帧数时才重置 - if self.police_missing_frames >= self.frame_buffer_police: - self.police_detection_frames = 0 - self.police_alert_active = False - else: - # 从未检测到犯人,保持状态 - pass - - - - alert_offset = 0 - - # A. 有犯人 - if self.prisoner_alert_active: - duration_seconds = self.prisoner_detection_frames / self.fps + if self.blackbag_alert_active: + duration_seconds = self.blackbag_detection_frames / self.fps current_frame_alerts.append( { 'time': current_time_sec, - 'action': 'prisoner', - 'confidence': 1.0, # 固定为1.0(规则判定) + 'action': 'Black Bag', 'details': f"Detected for {duration_seconds:.1f}s" } ) - self.draw_alert(frame, "prisoner", (0, 0, 255), offset_y=alert_offset) - alert_offset += 100 + self.draw_alert(frame, "Black Bag Alert", (0, 0, 255), sub_text=f"Detected for {duration_seconds:.1f}s") # ========================================== - # 11. 统一显示当前帧所有警告(可替换原分层显示) + # 绘制信息 # ========================================== - debug_info = f" prisoner: {current_prisoner_count}" + # 实时统计 + debug_info = f"Person: {self.current_person_count} | BlackBag: {current_blackbag_count}" cv2.putText(frame, debug_info, (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) - # 统一警告显示区 + # 警告信息 alert_y_start = 150 for i, alert in enumerate(current_frame_alerts): action = alert['action'] details = alert.get('details', '') - color = (0, 0, 255) # 默认红色警告 - - if action == 'prisoner': - color = (255, 255, 255) - - main_text = action - if details: - main_text += f" ({details})" - + color = (0, 0, 255) # 红色警告 + main_text = f"{action} ({details})" y_pos = alert_y_start + i * 50 cv2.rectangle(frame, (20, y_pos - 40), (900, y_pos + 10), (0, 0, 0), -1) cv2.putText(frame, main_text, (30, y_pos), cv2.FONT_HERSHEY_SIMPLEX, 1.0, color, 2) @@ -334,114 +249,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] = {} - - # 筛选出符合推送条件的action(5秒内未推送过) - 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() \ No newline at end of file + # 子类配置 + DETECTOR_FACTORY = lambda params: AbDetector(params) + POST_TYPE = 2 + TARGET_FPS = RTSP_TARGET_FPS diff --git a/common/processor_factory.py b/common/processor_factory.py index c404bd8..fd70ce4 100644 --- a/common/processor_factory.py +++ b/common/processor_factory.py @@ -1,12 +1,15 @@ from biz.checkpoint.checkpoint_biz import FrameProcessorWorker as CheckpointWorker from biz.prison.trajectory02_biz import FrameProcessorWorker as TrajectoryWorker from biz.prison.supervision_room_biz import FrameProcessorWorker as SupervisionWorker +from biz.prison.ab_biz import FrameProcessorWorker as AbWorker + # ... 其他导入 PROCESSOR_MAP = { "checkpoint": CheckpointWorker, "trajectory": TrajectoryWorker, "supervision_room": SupervisionWorker, + "ab": AbWorker } def get_processor(processor_type: str): From 4efe7aa3eb23db0fc6d54d0332e7ccfe9a3a5a46 Mon Sep 17 00:00:00 2001 From: zqc <835569504@qq.com> Date: Fri, 6 Mar 2026 12:26:38 +0800 Subject: [PATCH 5/5] =?UTF-8?q?=E5=AE=8C=E6=88=90=E8=B5=B0=E5=BB=8A?= =?UTF-8?q?=E8=BF=81=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- biz/prison/prison_biz.py | 127 ++++-------------------------------- common/processor_factory.py | 4 +- 2 files changed, 16 insertions(+), 115 deletions(-) diff --git a/biz/prison/prison_biz.py b/biz/prison/prison_biz.py index d43aa28..c7bf6d1 100644 --- a/biz/prison/prison_biz.py +++ b/biz/prison/prison_biz.py @@ -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] = {} - - # 筛选出符合推送条件的action(5秒内未推送过) - 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() \ No newline at end of file + # 子类配置 + DETECTOR_FACTORY = lambda params: ZoulangDetector(params) + POST_TYPE = 2 + TARGET_FPS = RTSP_TARGET_FPS diff --git a/common/processor_factory.py b/common/processor_factory.py index fd70ce4..565adb7 100644 --- a/common/processor_factory.py +++ b/common/processor_factory.py @@ -2,6 +2,7 @@ from biz.checkpoint.checkpoint_biz import FrameProcessorWorker as CheckpointWork from biz.prison.trajectory02_biz import FrameProcessorWorker as TrajectoryWorker from biz.prison.supervision_room_biz import FrameProcessorWorker as SupervisionWorker from biz.prison.ab_biz import FrameProcessorWorker as AbWorker +from biz.prison.prison_biz import FrameProcessorWorker as CorridorWorker # ... 其他导入 @@ -9,7 +10,8 @@ PROCESSOR_MAP = { "checkpoint": CheckpointWorker, "trajectory": TrajectoryWorker, "supervision_room": SupervisionWorker, - "ab": AbWorker + "ab": AbWorker, + "corridor": CorridorWorker } def get_processor(processor_type: str):