panorama_camera.py 27 KB

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