panorama_camera.py 27 KB

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