panorama_camera.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. """
  2. 全景摄像头模块
  3. 负责获取视频流和物体检测
  4. """
  5. import os
  6. # 必须在导入cv2之前设置,防止FFmpeg多线程解码崩溃
  7. # pthread_frame.c:167 async_lock assertion
  8. os.environ['OPENCV_FFMPEG_CAPTURE_OPTIONS'] = 'threads;1'
  9. import cv2
  10. import numpy as np
  11. import threading
  12. import queue
  13. import time
  14. from typing import Optional, List, Tuple, Dict, Any
  15. from dataclasses import dataclass
  16. from config import PANORAMA_CAMERA, DETECTION_CONFIG
  17. from dahua_sdk import DahuaSDK, PTZCommand
  18. from video_lock import safe_read, safe_is_opened
  19. @dataclass
  20. class DetectedObject:
  21. """检测到的物体"""
  22. class_name: str # 类别名称
  23. confidence: float # 置信度
  24. bbox: Tuple[int, int, int, int] # 边界框 (x, y, width, height)
  25. center: Tuple[int, int] # 中心点坐标
  26. track_id: Optional[int] = None # 跟踪ID
  27. class PanoramaCamera:
  28. """全景摄像头类"""
  29. def __init__(self, sdk: DahuaSDK, camera_config: Dict = None):
  30. """
  31. 初始化全景摄像头
  32. Args:
  33. sdk: 大华SDK实例
  34. camera_config: 摄像头配置
  35. """
  36. self.sdk = sdk
  37. self.config = camera_config or PANORAMA_CAMERA
  38. self.login_handle = None
  39. self.play_handle = None
  40. self.connected = False
  41. # 视频流
  42. self.frame_queue = queue.Queue(maxsize=10)
  43. self.current_frame = None
  44. self.frame_lock = threading.Lock()
  45. self.rtsp_cap = None # RTSP视频捕获
  46. # 检测器
  47. self.detector = None
  48. # 控制标志
  49. self.running = False
  50. self.stream_thread = None
  51. # 断线重连
  52. self.auto_reconnect = True
  53. self.reconnect_interval = 5.0 # 重连间隔(秒)
  54. self.max_reconnect_attempts = 3 # 最大重连次数
  55. def connect(self) -> bool:
  56. """
  57. 连接摄像头
  58. Returns:
  59. 是否成功
  60. """
  61. login_handle, error = self.sdk.login(
  62. self.config['ip'],
  63. self.config['port'],
  64. self.config['username'],
  65. self.config['password']
  66. )
  67. if login_handle is None:
  68. print(f"连接全景摄像头失败: IP={self.config['ip']}, 错误码={error}")
  69. return False
  70. self.login_handle = login_handle
  71. self.connected = True
  72. print(f"成功连接全景摄像头: {self.config['ip']}")
  73. return True
  74. def disconnect(self):
  75. """断开连接"""
  76. self.stop_stream()
  77. if self.login_handle:
  78. self.sdk.logout(self.login_handle)
  79. self.login_handle = None
  80. self.connected = False
  81. def start_stream(self) -> bool:
  82. """
  83. 开始视频流
  84. Returns:
  85. 是否成功
  86. """
  87. if not self.connected:
  88. return False
  89. self.play_handle = self.sdk.real_play(
  90. self.login_handle,
  91. self.config['channel']
  92. )
  93. if self.play_handle is None:
  94. print("启动视频流失败")
  95. return False
  96. self.running = True
  97. self.stream_thread = threading.Thread(target=self._stream_worker, daemon=True)
  98. self.stream_thread.start()
  99. print("视频流已启动")
  100. return True
  101. def start_stream_rtsp(self, rtsp_url: str = None) -> bool:
  102. if rtsp_url is None:
  103. rtsp_url = self.config.get('rtsp_url') or f"rtsp://{self.config['username']}:{self.config['password']}@{self.config['ip']}:{self.config.get('rtsp_port', 554)}/h264/ch{self.config['channel']}/main/av_stream"
  104. try:
  105. # 先尝试FFmpeg后端
  106. self.rtsp_cap = cv2.VideoCapture(rtsp_url, cv2.CAP_FFMPEG)
  107. if not self.rtsp_cap.isOpened():
  108. # FFmpeg失败,尝试GStreamer后端
  109. print(f"FFmpeg后端无法打开RTSP流,尝试GStreamer后端...")
  110. try:
  111. gst_cap = cv2.VideoCapture(rtsp_url, cv2.CAP_GSTREAMER)
  112. if gst_cap.isOpened():
  113. self.rtsp_cap = gst_cap
  114. print(f"使用GStreamer后端打开RTSP流成功")
  115. else:
  116. print(f"无法打开RTSP流: {rtsp_url}")
  117. return False
  118. except Exception as ge:
  119. print(f"GStreamer后端也不可用: {ge}")
  120. return False
  121. self.rtsp_cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
  122. self.running = True
  123. self.stream_thread = threading.Thread(target=self._rtsp_stream_worker, daemon=True)
  124. self.stream_thread.start()
  125. print(f"RTSP视频流已启动: {rtsp_url}")
  126. return True
  127. except Exception as e:
  128. print(f"RTSP流启动失败: {e}")
  129. return False
  130. def _stream_worker(self):
  131. """视频流工作线程 (SDK模式)"""
  132. retry_count = 0
  133. max_retries = 10
  134. while self.running:
  135. try:
  136. # 尝试从 SDK 帧缓冲区获取帧 (如果可用)
  137. frame_buffer = self.sdk.get_video_frame_buffer(self.config['channel'])
  138. if frame_buffer:
  139. frame_info = frame_buffer.get(timeout=0.1)
  140. if frame_info and frame_info.get('data'):
  141. # 解码帧数据 (如果需要)
  142. # 注意: SDK回调返回的是编码数据,需要解码
  143. # 这里暂时跳过,因为解码需要额外处理
  144. pass
  145. # RTSP 模式获取帧 (推荐方式)
  146. if self.rtsp_cap is not None and safe_is_opened(self.rtsp_cap):
  147. ret, frame = safe_read(self.rtsp_cap)
  148. if ret and frame is not None:
  149. with self.frame_lock:
  150. self.current_frame = frame.copy()
  151. try:
  152. self.frame_queue.put(frame.copy(), block=False)
  153. except queue.Full:
  154. pass
  155. retry_count = 0 # 重置重试计数
  156. time.sleep(0.001) # 减少CPU占用
  157. continue
  158. # 如果 RTSP 不可用,尝试自动连接
  159. if retry_count < max_retries:
  160. rtsp_url = self._build_rtsp_url()
  161. try:
  162. if self.rtsp_cap is None:
  163. self.rtsp_cap = cv2.VideoCapture(rtsp_url, cv2.CAP_FFMPEG)
  164. self.rtsp_cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) # 减少缓冲延迟
  165. if safe_is_opened(self.rtsp_cap):
  166. retry_count = 0
  167. continue
  168. except Exception as e:
  169. pass
  170. retry_count += 1
  171. time.sleep(1.0) # 重试间隔
  172. else:
  173. # 超过最大重试次数,使用模拟帧
  174. frame = np.zeros((1080, 1920, 3), dtype=np.uint8)
  175. with self.frame_lock:
  176. self.current_frame = frame
  177. try:
  178. self.frame_queue.put(frame, block=False)
  179. except queue.Full:
  180. pass
  181. time.sleep(0.1)
  182. except Exception as e:
  183. err_str = str(e)
  184. if 'async_lock' in err_str or 'Assertion' in err_str:
  185. print(f"视频流FFmpeg内部错误,重建连接: {e}")
  186. self._reconnect_rtsp()
  187. else:
  188. print(f"视频流错误: {e}")
  189. time.sleep(0.5)
  190. def _build_rtsp_url(self) -> str:
  191. return self.config.get('rtsp_url') or f"rtsp://{self.config['username']}:{self.config['password']}@{self.config['ip']}:{self.config.get('rtsp_port', 554)}/h264/ch{self.config['channel']}/main/av_stream"
  192. def _rtsp_stream_worker(self):
  193. """RTSP视频流工作线程"""
  194. import signal
  195. # 屏蔽SIGINT在此线程,由主线程处理
  196. if hasattr(signal, 'pthread_sigmask'):
  197. try:
  198. signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGINT})
  199. except (AttributeError, OSError):
  200. pass
  201. max_consecutive_errors = 50
  202. error_count = 0
  203. while self.running:
  204. try:
  205. if self.rtsp_cap is None or not safe_is_opened(self.rtsp_cap):
  206. time.sleep(0.1)
  207. continue
  208. ret, frame = safe_read(self.rtsp_cap)
  209. if not ret or frame is None:
  210. error_count += 1
  211. if error_count > max_consecutive_errors:
  212. print(f"全景RTSP流连续{max_consecutive_errors}次读取失败,尝试重连...")
  213. self._reconnect_rtsp()
  214. error_count = 0
  215. time.sleep(0.01)
  216. continue
  217. error_count = 0
  218. with self.frame_lock:
  219. self.current_frame = frame.copy()
  220. try:
  221. self.frame_queue.put(frame, block=False)
  222. except queue.Full:
  223. pass
  224. except Exception as e:
  225. err_str = str(e)
  226. if 'async_lock' in err_str or 'Assertion' in err_str:
  227. print(f"全景RTSP流FFmpeg内部错误,3秒后重建连接: {e}")
  228. time.sleep(3)
  229. self._reconnect_rtsp()
  230. else:
  231. print(f"全景RTSP视频流错误: {e}")
  232. time.sleep(0.5)
  233. def _reconnect_rtsp(self):
  234. """重建RTSP连接"""
  235. rtsp_url = self._build_rtsp_url()
  236. if self.rtsp_cap is not None:
  237. try:
  238. self.rtsp_cap.release()
  239. except Exception:
  240. pass
  241. self.rtsp_cap = None
  242. time.sleep(1)
  243. try:
  244. self.rtsp_cap = cv2.VideoCapture(rtsp_url, cv2.CAP_FFMPEG)
  245. if safe_is_opened(self.rtsp_cap):
  246. self.rtsp_cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
  247. print("全景RTSP流重连成功")
  248. else:
  249. print("全景RTSP流重连失败")
  250. self.rtsp_cap = None
  251. except Exception as e:
  252. print(f"全景RTSP流重连异常: {e}")
  253. self.rtsp_cap = None
  254. def stop_stream(self):
  255. """停止视频流"""
  256. self.running = False
  257. if self.stream_thread:
  258. self.stream_thread.join(timeout=2)
  259. if self.play_handle:
  260. self.sdk.stop_real_play(self.play_handle)
  261. self.play_handle = None
  262. if self.rtsp_cap:
  263. self.rtsp_cap.release()
  264. self.rtsp_cap = None
  265. def get_frame(self) -> Optional[np.ndarray]:
  266. """
  267. 获取当前帧
  268. Returns:
  269. 当前帧图像
  270. """
  271. with self.frame_lock:
  272. return self.current_frame.copy() if self.current_frame is not None else None
  273. def get_frame_from_queue(self, timeout: float = 0.1) -> Optional[np.ndarray]:
  274. """
  275. 从帧队列获取帧 (用于批量处理)
  276. Args:
  277. timeout: 等待超时时间
  278. Returns:
  279. 帧图像或None
  280. """
  281. try:
  282. return self.frame_queue.get(timeout=timeout)
  283. except:
  284. return None
  285. def get_frame_buffer(self, count: int = 5) -> List[np.ndarray]:
  286. """
  287. 获取帧缓冲 (用于运动检测等需要多帧的场景)
  288. Args:
  289. count: 获取帧数
  290. Returns:
  291. 帧列表
  292. """
  293. frames = []
  294. while len(frames) < count:
  295. frame = self.get_frame_from_queue(timeout=0.05)
  296. if frame is not None:
  297. frames.append(frame)
  298. else:
  299. break
  300. return frames
  301. def set_detector(self, detector):
  302. """设置物体检测器"""
  303. self.detector = detector
  304. def detect_objects(self, frame: np.ndarray = None) -> List[DetectedObject]:
  305. """
  306. 检测物体
  307. Args:
  308. frame: 输入帧,如果为None则使用当前帧
  309. Returns:
  310. 检测到的物体列表
  311. """
  312. if frame is None:
  313. frame = self.get_frame()
  314. if frame is None or self.detector is None:
  315. return []
  316. return self.detector.detect(frame)
  317. def get_detection_position(self, obj: DetectedObject,
  318. frame_size: Tuple[int, int]) -> Tuple[float, float]:
  319. """
  320. 获取检测物体在画面中的相对位置
  321. Args:
  322. obj: 检测到的物体
  323. frame_size: 画面尺寸 (width, height)
  324. Returns:
  325. 相对位置 (x_ratio, y_ratio) 范围0-1
  326. """
  327. width, height = frame_size
  328. x_ratio = obj.center[0] / width
  329. y_ratio = obj.center[1] / height
  330. return (x_ratio, y_ratio)
  331. class ObjectDetector:
  332. """
  333. 物体检测器
  334. 使用YOLO11模型进行人体检测
  335. 支持 YOLO (.pt), RKNN (.rknn), ONNX (.onnx) 模型
  336. """
  337. def __init__(self, model_path: str = None, use_gpu: bool = True, model_size: str = 'n',
  338. model_type: str = 'auto'):
  339. """
  340. 初始化检测器
  341. Args:
  342. model_path: 模型路径 (支持 .pt, .rknn, .onnx)
  343. use_gpu: 是否使用GPU
  344. model_size: 模型尺寸 ('n', 's', 'm', 'l', 'x') - 仅 YOLO 模型有效
  345. model_type: 模型类型 ('auto', 'yolo', 'rknn', 'onnx')
  346. """
  347. self.model = None
  348. self.rknn_detector = None
  349. self.model_path = model_path
  350. self.use_gpu = use_gpu
  351. self.model_size = model_size
  352. self.model_type = model_type
  353. self.config = DETECTION_CONFIG
  354. self.device = 'cuda:0' if use_gpu else 'cpu'
  355. # 根据扩展名自动判断模型类型
  356. if model_path:
  357. ext = os.path.splitext(model_path)[1].lower()
  358. if ext == '.rknn':
  359. self.model_type = 'rknn'
  360. elif ext == '.onnx':
  361. self.model_type = 'onnx'
  362. elif ext == '.pt':
  363. self.model_type = 'yolo'
  364. self._load_model()
  365. def _load_model(self):
  366. """加载检测模型"""
  367. if self.model_type == 'rknn':
  368. self._load_rknn_model()
  369. elif self.model_type == 'onnx':
  370. self._load_onnx_model()
  371. else:
  372. self._load_yolo_model()
  373. def _load_rknn_model(self):
  374. """加载 RKNN 模型"""
  375. if not self.model_path:
  376. raise ValueError("RKNN 模型需要指定 model_path")
  377. try:
  378. from rknnlite.api import RKNNLite
  379. self.rknn = RKNNLite()
  380. ret = self.rknn.load_rknn(self.model_path)
  381. if ret != 0:
  382. raise RuntimeError(f"加载 RKNN 模型失败: {self.model_path}")
  383. ret = self.rknn.init_runtime(core_mask=RKNNLite.NPU_CORE_0_1_2)
  384. if ret != 0:
  385. raise RuntimeError(f"初始化 RKNN 运行时失败")
  386. print(f"RKNN 模型加载成功: {self.model_path}")
  387. except ImportError:
  388. raise ImportError("未安装 rknnlite,请运行: pip install rknnlite2")
  389. def _load_onnx_model(self):
  390. """加载 ONNX 模型"""
  391. if not self.model_path:
  392. raise ValueError("ONNX 模型需要指定 model_path")
  393. try:
  394. import onnxruntime as ort
  395. self.session = ort.InferenceSession(self.model_path)
  396. self.input_name = self.session.get_inputs()[0].name
  397. self.output_name = self.session.get_outputs()[0].name
  398. print(f"ONNX 模型加载成功: {self.model_path}")
  399. except ImportError:
  400. raise ImportError("未安装 onnxruntime,请运行: pip install onnxruntime")
  401. def _load_yolo_model(self):
  402. """加载YOLO11检测模型"""
  403. try:
  404. from ultralytics import YOLO
  405. if self.model_path:
  406. self.model = YOLO(self.model_path)
  407. else:
  408. model_name = f'yolo11{self.model_size}.pt'
  409. self.model = YOLO(model_name)
  410. dummy = np.zeros((640, 640, 3), dtype=np.uint8)
  411. self.model(dummy, device=self.device, verbose=False)
  412. print(f"成功加载YOLO11检测模型 (device={self.device})")
  413. except ImportError:
  414. print("未安装ultralytics,请运行: pip install ultralytics")
  415. self._load_opencv_model()
  416. except Exception as e:
  417. print(f"加载YOLO11模型失败: {e}")
  418. self._load_opencv_model()
  419. def _load_opencv_model(self):
  420. """使用OpenCV加载模型"""
  421. pass
  422. def _letterbox(self, image, size=(640, 640)):
  423. """Letterbox 预处理"""
  424. h0, w0 = image.shape[:2]
  425. ih, iw = size
  426. scale = min(iw / w0, ih / h0)
  427. new_w, new_h = int(w0 * scale), int(h0 * scale)
  428. pad_w = (iw - new_w) // 2
  429. pad_h = (ih - new_h) // 2
  430. resized = cv2.resize(image, (new_w, new_h))
  431. canvas = np.full((ih, iw, 3), 114, dtype=np.uint8)
  432. canvas[pad_h:pad_h+new_h, pad_w:pad_w+new_w] = resized
  433. return canvas, scale, pad_w, pad_h, h0, w0
  434. def _detect_rknn(self, frame: np.ndarray) -> List[DetectedObject]:
  435. """使用 RKNN/ONNX 模型检测"""
  436. results = []
  437. try:
  438. canvas, scale, pad_w, pad_h, h0, w0 = self._letterbox(frame)
  439. if hasattr(self, 'rknn'):
  440. # RKNN
  441. img = canvas[..., ::-1].astype(np.float32) / 255.0
  442. blob = img[None, ...]
  443. outputs = self.rknn.inference(inputs=[blob])
  444. else:
  445. # ONNX
  446. img = canvas[..., ::-1].astype(np.float32) / 255.0
  447. img = img.transpose(2, 0, 1)
  448. blob = img[None, ...]
  449. outputs = self.session.run([self.output_name], {self.input_name: blob})
  450. output = outputs[0]
  451. if len(output.shape) == 3:
  452. output = output[0]
  453. num_boxes = output.shape[1]
  454. conf_threshold = self.config['confidence_threshold']
  455. for i in range(num_boxes):
  456. x_center = float(output[0, i])
  457. y_center = float(output[1, i])
  458. width = float(output[2, i])
  459. height = float(output[3, i])
  460. class_probs = output[4:, i]
  461. best_class = int(np.argmax(class_probs))
  462. confidence = float(class_probs[best_class])
  463. if confidence < conf_threshold:
  464. continue
  465. # 转换到原始图像坐标
  466. x1 = int(((x_center - width / 2) - pad_w) / scale)
  467. y1 = int(((y_center - height / 2) - pad_h) / scale)
  468. x2 = int(((x_center + width / 2) - pad_w) / scale)
  469. y2 = int(((y_center + height / 2) - pad_h) / scale)
  470. x1 = max(0, min(w0, x1))
  471. y1 = max(0, min(h0, y1))
  472. x2 = max(0, min(w0, x2))
  473. y2 = max(0, min(h0, y2))
  474. if x2 - x1 < 10 or y2 - y1 < 10:
  475. continue
  476. # 使用配置的类别映射获取类别名称
  477. class_map = self.config.get('class_map', {0: 'person', 3: '人'})
  478. cls_name = class_map.get(best_class, str(best_class))
  479. # 检查是否为目标类别
  480. if cls_name not in self.config['target_classes']:
  481. continue
  482. obj = DetectedObject(
  483. class_name=cls_name,
  484. confidence=confidence,
  485. bbox=(x1, y1, x2 - x1, y2 - y1),
  486. center=((x1 + x2) // 2, (y1 + y2) // 2)
  487. )
  488. results.append(obj)
  489. except Exception as e:
  490. print(f"RKNN/ONNX 检测错误: {e}")
  491. return results
  492. def detect(self, frame: np.ndarray) -> List[DetectedObject]:
  493. """
  494. 使用YOLO11检测物体
  495. Args:
  496. frame: 输入图像
  497. Returns:
  498. 检测结果列表
  499. """
  500. if frame is None:
  501. return []
  502. # 优先使用 RKNN/ONNX 模型
  503. if hasattr(self, 'rknn') and self.rknn is not None:
  504. return self._detect_rknn(frame)
  505. elif hasattr(self, 'session') and self.session is not None:
  506. return self._detect_rknn(frame)
  507. # 使用 YOLO 模型
  508. elif self.model is not None:
  509. return self._detect_yolo(frame)
  510. else:
  511. print("[错误] 没有可用的检测模型")
  512. return []
  513. def _detect_yolo(self, frame: np.ndarray) -> List[DetectedObject]:
  514. """使用 YOLO 模型检测"""
  515. results = []
  516. try:
  517. detections = self.model(
  518. frame,
  519. device=self.device,
  520. verbose=False,
  521. conf=self.config['confidence_threshold']
  522. )
  523. for det in detections:
  524. boxes = det.boxes
  525. if boxes is None:
  526. continue
  527. for i in range(len(boxes)):
  528. cls_id = int(boxes.cls[i])
  529. cls_name = det.names[cls_id]
  530. if cls_name not in self.config['target_classes']:
  531. continue
  532. conf = float(boxes.conf[i])
  533. xyxy = boxes.xyxy[i].cpu().numpy()
  534. x1, y1, x2, y2 = map(int, xyxy)
  535. width = x2 - x1
  536. height = y2 - y1
  537. if width < 10 or height < 10:
  538. continue
  539. center_x = x1 + width // 2
  540. center_y = y1 + height // 2
  541. obj = DetectedObject(
  542. class_name=cls_name,
  543. confidence=conf,
  544. bbox=(x1, y1, width, height),
  545. center=(center_x, center_y)
  546. )
  547. results.append(obj)
  548. except Exception as e:
  549. print(f"YOLO11检测错误: {e}")
  550. return results
  551. def detect_with_keypoints(self, frame: np.ndarray) -> List[DetectedObject]:
  552. """
  553. 使用YOLO11-pose检测人体并返回关键点
  554. Args:
  555. frame: 输入图像
  556. Returns:
  557. 带关键点的检测结果列表
  558. """
  559. return self.detect(frame)
  560. def detect_persons(self, frame: np.ndarray) -> List[DetectedObject]:
  561. """
  562. 检测人体
  563. Args:
  564. frame: 输入图像
  565. Returns:
  566. 检测到的人体列表
  567. """
  568. results = self.detect(frame)
  569. return [obj for obj in results if obj.class_name == 'person']
  570. def release(self):
  571. """释放模型资源"""
  572. if hasattr(self, 'rknn') and self.rknn:
  573. self.rknn.release()
  574. self.rknn = None
  575. self.model = None
  576. self.session = None
  577. class PersonTracker:
  578. """
  579. 人体跟踪器
  580. 使用简单的质心跟踪算法
  581. """
  582. def __init__(self, max_disappeared: int = 30):
  583. """
  584. 初始化跟踪器
  585. Args:
  586. max_disappeared: 最大消失帧数
  587. """
  588. self.max_disappeared = max_disappeared
  589. self.next_id = 0
  590. self.objects = {} # id -> center
  591. self.disappeared = {} # id -> disappeared count
  592. def update(self, detections: List[DetectedObject]) -> List[DetectedObject]:
  593. """
  594. 更新跟踪状态
  595. Args:
  596. detections: 当前帧检测结果
  597. Returns:
  598. 带有跟踪ID的检测结果
  599. """
  600. # 如果没有检测结果
  601. if len(detections) == 0:
  602. # 标记所有已跟踪对象为消失
  603. for obj_id in list(self.disappeared.keys()):
  604. self.disappeared[obj_id] += 1
  605. if self.disappeared[obj_id] > self.max_disappeared:
  606. self._deregister(obj_id)
  607. return []
  608. # 计算当前检测中心点
  609. input_centers = np.array([d.center for d in detections])
  610. # 如果没有已跟踪对象
  611. if len(self.objects) == 0:
  612. for det in detections:
  613. self._register(det)
  614. else:
  615. # 计算距离矩阵
  616. object_ids = list(self.objects.keys())
  617. object_centers = np.array([self.objects[obj_id] for obj_id in object_ids])
  618. # 计算欧氏距离
  619. distances = np.linalg.norm(
  620. object_centers[:, np.newaxis] - input_centers,
  621. axis=2
  622. )
  623. # 匈牙利算法匹配 (简化版: 贪心匹配)
  624. rows = distances.min(axis=1).argsort()
  625. cols = distances.argmin(axis=1)[rows]
  626. used_rows = set()
  627. used_cols = set()
  628. for (row, col) in zip(rows, cols):
  629. if row in used_rows or col in used_cols:
  630. continue
  631. obj_id = object_ids[row]
  632. self.objects[obj_id] = input_centers[col]
  633. self.disappeared[obj_id] = 0
  634. detections[col].track_id = obj_id
  635. used_rows.add(row)
  636. used_cols.add(col)
  637. # 处理未匹配的已跟踪对象
  638. unused_rows = set(range(len(object_ids))) - used_rows
  639. for row in unused_rows:
  640. obj_id = object_ids[row]
  641. self.disappeared[obj_id] += 1
  642. if self.disappeared[obj_id] > self.max_disappeared:
  643. self._deregister(obj_id)
  644. # 处理未匹配的新检测
  645. unused_cols = set(range(len(input_centers))) - used_cols
  646. for col in unused_cols:
  647. self._register(detections[col])
  648. return [d for d in detections if d.track_id is not None]
  649. def _register(self, detection: DetectedObject):
  650. """注册新对象"""
  651. detection.track_id = self.next_id
  652. self.objects[self.next_id] = detection.center
  653. self.disappeared[self.next_id] = 0
  654. self.next_id += 1
  655. def _deregister(self, obj_id: int):
  656. """注销对象"""
  657. del self.objects[obj_id]
  658. del self.disappeared[obj_id]