coordinator.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. """
  2. 联动控制器
  3. 协调全景摄像头和球机的工作
  4. """
  5. import time
  6. import threading
  7. import queue
  8. import logging
  9. from typing import Optional, List, Dict, Tuple, Callable
  10. from dataclasses import dataclass, field
  11. from enum import Enum
  12. import numpy as np
  13. from config import COORDINATOR_CONFIG, SYSTEM_CONFIG, PTZ_CONFIG, DETECTION_CONFIG
  14. from panorama_camera import PanoramaCamera, ObjectDetector, PersonTracker, DetectedObject
  15. from ptz_camera import PTZCamera, PTZController
  16. from ocr_recognizer import NumberDetector, PersonInfo
  17. from ptz_person_tracker import PTZPersonDetector, PTZAutoZoomController
  18. from paired_image_saver import PairedImageSaver, get_paired_saver
  19. logger = logging.getLogger(__name__)
  20. class TrackingState(Enum):
  21. """跟踪状态"""
  22. IDLE = 0 # 空闲
  23. SEARCHING = 1 # 搜索目标
  24. TRACKING = 2 # 跟踪中
  25. ZOOMING = 3 # 变焦中
  26. OCR_PROCESSING = 4 # OCR处理中
  27. @dataclass
  28. class TrackingTarget:
  29. """跟踪目标"""
  30. track_id: int # 跟踪ID
  31. position: Tuple[float, float] # 位置比例 (x_ratio, y_ratio)
  32. last_update: float # 最后更新时间
  33. person_info: Optional[PersonInfo] = None # 人员信息
  34. priority: int = 0 # 优先级
  35. area: int = 0 # 目标面积(像素²)
  36. confidence: float = 0.0 # 置信度
  37. center_distance: float = 1.0 # 到画面中心的距离比例(0-1)
  38. score: float = 0.0 # 综合得分
  39. class TargetSelector:
  40. """
  41. 目标选择策略类
  42. 支持按面积、置信度、混合模式排序,支持优先级切换
  43. """
  44. def __init__(self, config: Dict = None):
  45. """
  46. 初始化目标选择器
  47. Args:
  48. config: 目标选择配置
  49. """
  50. self.config = config or {
  51. 'strategy': 'area',
  52. 'area_weight': 0.6,
  53. 'confidence_weight': 0.4,
  54. 'min_area_threshold': 5000,
  55. 'prefer_center': True,
  56. 'center_weight': 0.2,
  57. 'switch_on_lost': True,
  58. 'stickiness': 0.3,
  59. }
  60. self.current_target_id: Optional[int] = None
  61. self.current_target_score: float = 0.0
  62. def calculate_score(self, target: TrackingTarget, frame_size: Tuple[int, int] = None) -> float:
  63. """
  64. 计算目标综合得分
  65. Args:
  66. target: 跟踪目标
  67. frame_size: 帧尺寸(w, h),用于计算中心距离
  68. Returns:
  69. 综合得分(0-1)
  70. """
  71. strategy = self.config.get('strategy', 'area')
  72. area_weight = self.config.get('area_weight', 0.6)
  73. conf_weight = self.config.get('confidence_weight', 0.4)
  74. min_area = self.config.get('min_area_threshold', 5000)
  75. prefer_center = self.config.get('prefer_center', False)
  76. center_weight = self.config.get('center_weight', 0.2)
  77. # 归一化面积得分 (对数缩放,避免大目标得分过高)
  78. import math
  79. area_score = min(1.0, math.log10(max(target.area, 1)) / 5.0) # 100000像素² ≈ 1.0
  80. # 小面积惩罚
  81. if target.area < min_area:
  82. area_score *= 0.5
  83. # 置信度得分直接使用
  84. conf_score = target.confidence
  85. # 中心距离得分 (距离中心越近得分越高)
  86. center_score = 1.0 - target.center_distance
  87. # 根据策略计算综合得分
  88. if strategy == 'area':
  89. score = area_score * 0.8 + conf_score * 0.2
  90. elif strategy == 'confidence':
  91. score = conf_score * 0.8 + area_score * 0.2
  92. else: # hybrid
  93. score = area_score * area_weight + conf_score * conf_weight
  94. # 加入中心距离权重
  95. if prefer_center:
  96. score = score * (1 - center_weight) + center_score * center_weight
  97. return score
  98. def select_target(self, targets: Dict[int, TrackingTarget],
  99. frame_size: Tuple[int, int] = None) -> Optional[TrackingTarget]:
  100. """
  101. 从多个目标中选择最优目标
  102. Args:
  103. targets: 目标字典 {track_id: TrackingTarget}
  104. frame_size: 帧尺寸
  105. Returns:
  106. 最优目标
  107. """
  108. if not targets:
  109. self.current_target_id = None
  110. return None
  111. stickiness = self.config.get('stickiness', 0.3)
  112. switch_on_lost = self.config.get('switch_on_lost', True)
  113. # 计算所有目标得分
  114. scored_targets = []
  115. for track_id, target in targets.items():
  116. target.score = self.calculate_score(target, frame_size)
  117. scored_targets.append((track_id, target, target.score))
  118. # 按得分排序
  119. scored_targets.sort(key=lambda x: x[2], reverse=True)
  120. # 检查当前目标是否仍在列表中
  121. if self.current_target_id is not None:
  122. current_exists = self.current_target_id in targets
  123. if current_exists:
  124. # 应用粘性:当前目标得分需要显著低于最优目标才切换
  125. best_id, best_target, best_score = scored_targets[0]
  126. current_target = targets[self.current_target_id]
  127. # 粘性阈值: 当前目标得分 > 最优得分 * (1 - stickiness) 时保持
  128. stickiness_threshold = best_score * (1 - stickiness)
  129. if current_target.score > stickiness_threshold:
  130. return current_target
  131. # 选择得分最高的目标
  132. best_id, best_target, best_score = scored_targets[0]
  133. self.current_target_id = best_id
  134. self.current_target_score = best_score
  135. logger.debug(
  136. f"[目标选择] 选择目标ID={best_id} 得分={best_score:.3f} "
  137. f"面积={best_target.area} 置信度={best_target.confidence:.2f}"
  138. )
  139. return best_target
  140. def get_sorted_targets(self, targets: Dict[int, TrackingTarget],
  141. frame_size: Tuple[int, int] = None) -> List[Tuple[TrackingTarget, float]]:
  142. """
  143. 获取按得分排序的目标列表
  144. Args:
  145. targets: 目标字典
  146. frame_size: 帧尺寸
  147. Returns:
  148. 排序后的目标列表 [(target, score), ...]
  149. """
  150. scored = []
  151. for target in targets.values():
  152. target.score = self.calculate_score(target, frame_size)
  153. scored.append((target, target.score))
  154. scored.sort(key=lambda x: x[1], reverse=True)
  155. return scored
  156. def set_strategy(self, strategy: str):
  157. """设置选择策略"""
  158. self.config['strategy'] = strategy
  159. logger.info(f"[目标选择] 策略已切换为: {strategy}")
  160. def set_stickiness(self, stickiness: float):
  161. """设置目标粘性"""
  162. self.config['stickiness'] = max(0.0, min(1.0, stickiness))
  163. logger.info(f"[目标选择] 粘性已设置为: {self.config['stickiness']}")
  164. class Coordinator:
  165. """
  166. 联动控制器
  167. 协调全景摄像头和球机实现联动抓拍
  168. """
  169. def __init__(self, panorama_camera: PanoramaCamera,
  170. ptz_camera: PTZCamera,
  171. detector: ObjectDetector = None,
  172. number_detector: NumberDetector = None,
  173. calibrator = None):
  174. """
  175. 初始化联动控制器
  176. Args:
  177. panorama_camera: 全景摄像头
  178. ptz_camera: 球机
  179. detector: 物体检测器
  180. number_detector: 编号检测器
  181. calibrator: 校准器 (用于坐标转换)
  182. """
  183. self.panorama = panorama_camera
  184. self.ptz = ptz_camera
  185. self.detector = detector
  186. self.number_detector = number_detector
  187. self.calibrator = calibrator
  188. self.config = COORDINATOR_CONFIG
  189. # 功能开关 - 从 SYSTEM_CONFIG 读取
  190. self.enable_ptz_camera = SYSTEM_CONFIG.get('enable_ptz_camera', True)
  191. self.enable_ptz_tracking = SYSTEM_CONFIG.get('enable_ptz_tracking', True)
  192. self.enable_calibration = SYSTEM_CONFIG.get('enable_calibration', True)
  193. self.enable_detection = SYSTEM_CONFIG.get('enable_detection', True)
  194. self.enable_ocr = SYSTEM_CONFIG.get('enable_ocr', True)
  195. # 球机端人体检测与自动对焦
  196. self.enable_ptz_detection = PTZ_CONFIG.get('enable_ptz_detection', False)
  197. self.auto_zoom_config = PTZ_CONFIG.get('auto_zoom', {})
  198. self.ptz_detector = None
  199. self.auto_zoom_controller = None
  200. # 跟踪器
  201. self.tracker = PersonTracker()
  202. # 状态
  203. self.state = TrackingState.IDLE
  204. self.state_lock = threading.Lock()
  205. # 跟踪目标
  206. self.tracking_targets: Dict[int, TrackingTarget] = {}
  207. self.targets_lock = threading.Lock()
  208. # 当前跟踪目标
  209. self.current_target: Optional[TrackingTarget] = None
  210. # 回调函数
  211. self.on_person_detected: Optional[Callable] = None
  212. self.on_number_recognized: Optional[Callable] = None
  213. self.on_tracking_started: Optional[Callable] = None
  214. self.on_tracking_stopped: Optional[Callable] = None
  215. # 控制标志
  216. self.running = False
  217. self.coordinator_thread = None
  218. # OCR频率控制
  219. self.last_ocr_time = 0
  220. self.ocr_interval = 1.0 # OCR间隔(秒),避免过于频繁调用API
  221. # PTZ优化 - 避免频繁发送相同位置的命令
  222. self.last_ptz_position = None
  223. self.ptz_position_threshold = self.config.get('ptz_position_threshold', 0.03)
  224. # 目标选择器
  225. self.target_selector = TargetSelector(
  226. self.config.get('target_selection', {})
  227. )
  228. # 结果队列
  229. self.result_queue = queue.Queue()
  230. # 性能统计
  231. self.stats = {
  232. 'frames_processed': 0,
  233. 'persons_detected': 0,
  234. 'ocr_attempts': 0,
  235. 'ocr_success': 0,
  236. 'start_time': None,
  237. 'last_frame_time': None,
  238. }
  239. self.stats_lock = threading.Lock()
  240. def set_calibrator(self, calibrator):
  241. """设置校准器"""
  242. self.calibrator = calibrator
  243. def _transform_position(self, x_ratio: float, y_ratio: float) -> Tuple[float, float, int]:
  244. """
  245. 将全景坐标转换为PTZ角度
  246. Args:
  247. x_ratio: X方向比例
  248. y_ratio: Y方向比例
  249. Returns:
  250. (pan, tilt, zoom)
  251. """
  252. if self.enable_calibration and self.calibrator and self.calibrator.is_calibrated():
  253. # 使用校准结果进行转换
  254. pan, tilt = self.calibrator.transform(x_ratio, y_ratio)
  255. zoom = 8 # 默认变倍
  256. else:
  257. # 使用默认估算
  258. pan, tilt, zoom = self.ptz.calculate_ptz_position(x_ratio, y_ratio)
  259. return (pan, tilt, zoom)
  260. def start(self) -> bool:
  261. """
  262. 启动联动系统
  263. Returns:
  264. 是否成功
  265. """
  266. # 连接全景摄像头
  267. if not self.panorama.connect():
  268. print("连接全景摄像头失败")
  269. return False
  270. # 连接 PTZ 球机 (可选)
  271. if self.enable_ptz_camera:
  272. if not self.ptz.connect():
  273. print("连接球机失败")
  274. self.panorama.disconnect()
  275. return False
  276. else:
  277. print("PTZ 球机功能已禁用")
  278. # 启动视频流(优先RTSP,SDK回调不可用时回退)
  279. if not self.panorama.start_stream_rtsp():
  280. print("RTSP视频流启动失败,尝试SDK方式...")
  281. if not self.panorama.start_stream():
  282. print("启动视频流失败")
  283. self.panorama.disconnect()
  284. if self.enable_ptz_camera:
  285. self.ptz.disconnect()
  286. return False
  287. # 启动联动线程
  288. self.running = True
  289. self.coordinator_thread = threading.Thread(target=self._coordinator_worker, daemon=True)
  290. self.coordinator_thread.start()
  291. print("联动系统已启动")
  292. return True
  293. def stop(self):
  294. """停止联动系统"""
  295. self.running = False
  296. if self.coordinator_thread:
  297. self.coordinator_thread.join(timeout=3)
  298. self.panorama.disconnect()
  299. if self.enable_ptz_camera:
  300. self.ptz.disconnect()
  301. # 打印统计信息
  302. self._print_stats()
  303. print("联动系统已停止")
  304. def _update_stats(self, key: str, value: int = 1):
  305. """更新统计信息"""
  306. with self.stats_lock:
  307. if key in self.stats:
  308. self.stats[key] += value
  309. def _print_stats(self):
  310. """打印统计信息"""
  311. with self.stats_lock:
  312. if self.stats['start_time'] and self.stats['frames_processed'] > 0:
  313. elapsed = time.time() - self.stats['start_time']
  314. fps = self.stats['frames_processed'] / elapsed
  315. print("\n=== 性能统计 ===")
  316. print(f"运行时长: {elapsed:.1f}秒")
  317. print(f"处理帧数: {self.stats['frames_processed']}")
  318. print(f"平均帧率: {fps:.1f} fps")
  319. print(f"检测人体: {self.stats['persons_detected']}次")
  320. print(f"OCR尝试: {self.stats['ocr_attempts']}次")
  321. print(f"OCR成功: {self.stats['ocr_success']}次")
  322. print("================\n")
  323. def get_stats(self) -> dict:
  324. """获取统计信息"""
  325. with self.stats_lock:
  326. return self.stats.copy()
  327. def _coordinator_worker(self):
  328. """联动工作线程"""
  329. last_detection_time = 0
  330. # 优先使用 detection_fps,默认每秒2帧
  331. detection_fps = self.config.get('detection_fps', 2)
  332. detection_interval = 1.0 / detection_fps # 根据FPS计算间隔
  333. # 初始化统计
  334. with self.stats_lock:
  335. self.stats['start_time'] = time.time()
  336. while self.running:
  337. try:
  338. current_time = time.time()
  339. # 获取当前帧
  340. frame = self.panorama.get_frame()
  341. if frame is None:
  342. time.sleep(0.01)
  343. continue
  344. # 更新帧统计
  345. self._update_stats('frames_processed')
  346. frame_size = (frame.shape[1], frame.shape[0])
  347. # 周期性检测
  348. if current_time - last_detection_time >= detection_interval:
  349. last_detection_time = current_time
  350. # 检测人体
  351. detections = self._detect_persons(frame)
  352. # 更新检测统计
  353. if detections:
  354. self._update_stats('persons_detected', len(detections))
  355. # 更新跟踪
  356. tracked = self.tracker.update(detections)
  357. # 更新跟踪目标
  358. self._update_tracking_targets(tracked, frame_size)
  359. # 处理检测结果
  360. if tracked:
  361. self._process_detections(tracked, frame, frame_size)
  362. # 处理当前跟踪目标
  363. self._process_current_target(frame, frame_size)
  364. # 清理过期目标
  365. self._cleanup_expired_targets()
  366. time.sleep(0.01)
  367. except Exception as e:
  368. print(f"联动处理错误: {e}")
  369. time.sleep(0.1)
  370. def _detect_persons(self, frame: np.ndarray) -> List[DetectedObject]:
  371. """检测人体"""
  372. if not self.enable_detection or self.detector is None:
  373. return []
  374. return self.detector.detect_persons(frame)
  375. def _update_tracking_targets(self, detections: List[DetectedObject],
  376. frame_size: Tuple[int, int]):
  377. """更新跟踪目标"""
  378. current_time = time.time()
  379. frame_w, frame_h = frame_size
  380. center_x, center_y = frame_w / 2, frame_h / 2
  381. with self.targets_lock:
  382. # 更新现有目标
  383. for det in detections:
  384. if det.track_id is None:
  385. continue
  386. x_ratio = det.center[0] / frame_w
  387. y_ratio = det.center[1] / frame_h
  388. # 计算面积
  389. _, _, width, height = det.bbox
  390. area = width * height
  391. # 计算到画面中心的距离比例
  392. dx = abs(det.center[0] - center_x) / center_x
  393. dy = abs(det.center[1] - center_y) / center_y
  394. center_distance = (dx + dy) / 2 # 归一化到0-1
  395. if det.track_id in self.tracking_targets:
  396. # 更新位置
  397. target = self.tracking_targets[det.track_id]
  398. target.position = (x_ratio, y_ratio)
  399. target.last_update = current_time
  400. target.area = area
  401. target.confidence = det.confidence
  402. target.center_distance = center_distance
  403. else:
  404. # 新目标
  405. if len(self.tracking_targets) < self.config['max_tracking_targets']:
  406. self.tracking_targets[det.track_id] = TrackingTarget(
  407. track_id=det.track_id,
  408. position=(x_ratio, y_ratio),
  409. last_update=current_time,
  410. area=area,
  411. confidence=det.confidence,
  412. center_distance=center_distance
  413. )
  414. def _process_detections(self, detections: List[DetectedObject],
  415. frame: np.ndarray, frame_size: Tuple[int, int]):
  416. """处理检测结果"""
  417. if self.on_person_detected:
  418. for det in detections:
  419. self.on_person_detected(det, frame)
  420. def _process_current_target(self, frame: np.ndarray, frame_size: Tuple[int, int]):
  421. """处理当前跟踪目标"""
  422. with self.targets_lock:
  423. if not self.tracking_targets:
  424. self._set_state(TrackingState.IDLE)
  425. self.current_target = None
  426. return
  427. # 使用目标选择器选择最优目标
  428. self.current_target = self.target_selector.select_target(
  429. self.tracking_targets, frame_size
  430. )
  431. if self.current_target:
  432. # 移动球机到目标位置 (仅在 PTZ 跟踪启用时)
  433. if self.enable_ptz_tracking and self.enable_ptz_camera:
  434. self._set_state(TrackingState.TRACKING)
  435. x_ratio, y_ratio = self.current_target.position
  436. # 检查位置是否变化超过阈值
  437. should_move = True
  438. if self.last_ptz_position is not None:
  439. last_x, last_y = self.last_ptz_position
  440. if (abs(x_ratio - last_x) < self.ptz_position_threshold and
  441. abs(y_ratio - last_y) < self.ptz_position_threshold):
  442. should_move = False
  443. if should_move:
  444. if self.enable_calibration and self.calibrator and self.calibrator.is_calibrated():
  445. pan, tilt = self.calibrator.transform(x_ratio, y_ratio)
  446. if self.ptz.ptz_config.get('pan_flip', False):
  447. pan = (pan + 180) % 360
  448. zoom = self.ptz.ptz_config.get('default_zoom', 8)
  449. self.ptz.goto_exact_position(pan, tilt, zoom)
  450. else:
  451. self.ptz.track_target(x_ratio, y_ratio)
  452. self.last_ptz_position = (x_ratio, y_ratio)
  453. # 执行OCR识别 (仅在 OCR 启用时)
  454. if self.enable_ocr:
  455. self._perform_ocr(frame, self.current_target)
  456. def _perform_ocr(self, frame: np.ndarray, target: TrackingTarget):
  457. """执行OCR识别"""
  458. if not self.enable_ocr or self.number_detector is None:
  459. return
  460. # 频率控制 - 避免过于频繁调用OCR API
  461. current_time = time.time()
  462. if current_time - self.last_ocr_time < self.ocr_interval:
  463. return
  464. self.last_ocr_time = current_time
  465. # 更新OCR尝试统计
  466. self._update_stats('ocr_attempts')
  467. # 计算人体边界框 (基于位置估算)
  468. frame_h, frame_w = frame.shape[:2]
  469. # 人体占画面比例 (可配置,默认宽20%、高40%)
  470. person_width_ratio = self.config.get('person_width_ratio', 0.2)
  471. person_height_ratio = self.config.get('person_height_ratio', 0.4)
  472. person_width = int(frame_w * person_width_ratio)
  473. person_height = int(frame_h * person_height_ratio)
  474. x_ratio, y_ratio = target.position
  475. center_x = int(x_ratio * frame_w)
  476. center_y = int(y_ratio * frame_h)
  477. # 计算边界框,确保不超出画面范围
  478. x1 = max(0, center_x - person_width // 2)
  479. y1 = max(0, center_y - person_height // 2)
  480. x2 = min(frame_w, x1 + person_width)
  481. y2 = min(frame_h, y1 + person_height)
  482. # 更新实际宽高 (可能因边界裁剪而变小)
  483. actual_width = x2 - x1
  484. actual_height = y2 - y1
  485. person_bbox = (x1, y1, actual_width, actual_height)
  486. # 检测编号
  487. self._set_state(TrackingState.OCR_PROCESSING)
  488. person_info = self.number_detector.detect_number(frame, person_bbox)
  489. person_info.person_id = target.track_id
  490. # 更新OCR成功统计
  491. if person_info.number_text:
  492. self._update_stats('ocr_success')
  493. # 更新目标信息
  494. with self.targets_lock:
  495. if target.track_id in self.tracking_targets:
  496. self.tracking_targets[target.track_id].person_info = person_info
  497. # 回调
  498. if self.on_number_recognized and person_info.number_text:
  499. self.on_number_recognized(person_info)
  500. # 放入结果队列
  501. self.result_queue.put(person_info)
  502. def _cleanup_expired_targets(self):
  503. """清理过期目标"""
  504. current_time = time.time()
  505. timeout = self.config['tracking_timeout']
  506. with self.targets_lock:
  507. expired_ids = [
  508. target_id for target_id, target in self.tracking_targets.items()
  509. if current_time - target.last_update > timeout
  510. ]
  511. for target_id in expired_ids:
  512. del self.tracking_targets[target_id]
  513. if self.current_target and self.current_target.track_id == target_id:
  514. self.current_target = None
  515. def _set_state(self, state: TrackingState):
  516. """设置状态"""
  517. with self.state_lock:
  518. self.state = state
  519. def get_state(self) -> TrackingState:
  520. """获取状态"""
  521. with self.state_lock:
  522. return self.state
  523. def get_results(self) -> List[PersonInfo]:
  524. """
  525. 获取识别结果
  526. Returns:
  527. 人员信息列表
  528. """
  529. results = []
  530. while not self.result_queue.empty():
  531. try:
  532. results.append(self.result_queue.get_nowait())
  533. except queue.Empty:
  534. break
  535. return results
  536. def get_tracking_targets(self) -> List[TrackingTarget]:
  537. """获取当前跟踪目标"""
  538. with self.targets_lock:
  539. return list(self.tracking_targets.values())
  540. def force_track_position(self, x_ratio: float, y_ratio: float, zoom: int = None):
  541. """
  542. 强制跟踪指定位置
  543. Args:
  544. x_ratio: X方向比例
  545. y_ratio: Y方向比例
  546. zoom: 变倍
  547. """
  548. if self.enable_ptz_tracking and self.enable_ptz_camera:
  549. if self.enable_calibration and self.calibrator and self.calibrator.is_calibrated():
  550. pan, tilt = self.calibrator.transform(x_ratio, y_ratio)
  551. if self.ptz.ptz_config.get('pan_flip', False):
  552. pan = (pan + 180) % 360
  553. self.ptz.goto_exact_position(pan, tilt, zoom or self.ptz.ptz_config.get('default_zoom', 8))
  554. else:
  555. self.ptz.move_to_target(x_ratio, y_ratio, zoom)
  556. def capture_snapshot(self) -> Optional[np.ndarray]:
  557. """
  558. 抓拍快照
  559. Returns:
  560. 快照图像
  561. """
  562. return self.panorama.get_frame()
  563. class EventDrivenCoordinator(Coordinator):
  564. """事件驱动联动控制器,当全景摄像头检测到事件时触发联动"""
  565. def __init__(self, *args, **kwargs):
  566. super().__init__(*args, **kwargs)
  567. self.event_types = {
  568. 'intruder': True,
  569. 'crossline': True,
  570. 'motion': True,
  571. }
  572. self.event_queue = queue.Queue()
  573. def on_event(self, event_type: str, event_data: dict):
  574. if not self.event_types.get(event_type, False):
  575. return
  576. self.event_queue.put({'type': event_type, 'data': event_data, 'time': time.time()})
  577. def _coordinator_worker(self):
  578. while self.running:
  579. try:
  580. try:
  581. event = self.event_queue.get(timeout=0.1)
  582. self._process_event(event)
  583. except queue.Empty:
  584. pass
  585. frame = self.panorama.get_frame()
  586. if frame is not None:
  587. frame_size = (frame.shape[1], frame.shape[0])
  588. detections = self._detect_persons(frame)
  589. if detections:
  590. tracked = self.tracker.update(detections)
  591. self._update_tracking_targets(tracked, frame_size)
  592. self._process_current_target(frame, frame_size)
  593. self._cleanup_expired_targets()
  594. except Exception as e:
  595. print(f"事件处理错误: {e}")
  596. time.sleep(0.1)
  597. def _process_event(self, event: dict):
  598. event_type = event['type']
  599. event_data = event['data']
  600. print(f"处理事件: {event_type}")
  601. if event_type == 'intruder' and 'position' in event_data:
  602. x_ratio, y_ratio = event_data['position']
  603. self.force_track_position(x_ratio, y_ratio)
  604. @dataclass
  605. class PTZCommand:
  606. """PTZ控制命令"""
  607. pan: float
  608. tilt: float
  609. zoom: int
  610. x_ratio: float = 0.0
  611. y_ratio: float = 0.0
  612. use_calibration: bool = True
  613. track_id: Optional[int] = None # 跟踪目标ID(用于配对图片保存)
  614. class AsyncCoordinator(Coordinator):
  615. """
  616. 异步联动控制器 — 检测线程与PTZ控制线程分离
  617. 改进:
  618. 1. 检测线程:持续读取全景帧 + YOLO推理
  619. 2. PTZ控制线程:通过命令队列接收目标位置,独立控制球机
  620. 3. 两线程通过 queue 通信,互不阻塞
  621. 4. PTZ位置确认:移动后等待球机到位并验证帧
  622. """
  623. PTZ_CONFIRM_WAIT = 0.3 # PTZ命令后等待稳定的秒数
  624. PTZ_CONFIRM_TIMEOUT = 2.0 # PTZ位置确认超时
  625. PTZ_COMMAND_COOLDOWN = 0.15 # PTZ命令最小间隔秒数
  626. def __init__(self, *args, **kwargs):
  627. super().__init__(*args, **kwargs)
  628. # PTZ命令队列(检测→PTZ)
  629. self._ptz_queue: queue.Queue = queue.Queue(maxsize=10)
  630. # 线程
  631. self._detection_thread = None
  632. self._ptz_thread = None
  633. # PTZ确认回调
  634. self._on_ptz_confirmed: Optional[Callable] = None
  635. # 上次PTZ命令时间
  636. self._last_ptz_time = 0.0
  637. # 配对图片保存器
  638. self._enable_paired_saving = DETECTION_CONFIG.get('enable_paired_saving', False)
  639. self._paired_saver: Optional[PairedImageSaver] = None
  640. self._current_batch_id: Optional[str] = None
  641. self._person_ptz_index: Dict[int, int] = {} # track_id -> person_index
  642. if self._enable_paired_saving:
  643. save_dir = DETECTION_CONFIG.get('paired_image_dir', '/home/admin/dsh/paired_images')
  644. time_window = DETECTION_CONFIG.get('paired_time_window', 5.0)
  645. self._paired_saver = get_paired_saver(base_dir=save_dir, time_window=time_window)
  646. logger.info(f"[AsyncCoordinator] 配对图片保存已启用: 目录={save_dir}, 时间窗口={time_window}s")
  647. def start(self) -> bool:
  648. """启动联动(覆盖父类,启动双线程)"""
  649. if not self.panorama.connect():
  650. print("连接全景摄像头失败")
  651. return False
  652. if self.enable_ptz_camera:
  653. if not self.ptz.connect():
  654. print("连接球机失败")
  655. self.panorama.disconnect()
  656. return False
  657. # 启动球机RTSP流(用于球机端人体检测)
  658. if self.enable_ptz_detection:
  659. if not self.ptz.start_stream_rtsp():
  660. print("球机RTSP流启动失败,禁用球机端检测功能")
  661. self.enable_ptz_detection = False
  662. else:
  663. # 初始化球机端人体检测器
  664. self._init_ptz_detector()
  665. else:
  666. print("PTZ球机功能已禁用")
  667. if not self.panorama.start_stream_rtsp():
  668. print("RTSP视频流启动失败,尝试SDK方式...")
  669. if not self.panorama.start_stream():
  670. print("启动视频流失败")
  671. self.panorama.disconnect()
  672. if self.enable_ptz_camera:
  673. self.ptz.disconnect()
  674. return False
  675. self.running = True
  676. # 启动检测线程
  677. self._detection_thread = threading.Thread(
  678. target=self._detection_worker, name="detection-worker", daemon=True)
  679. self._detection_thread.start()
  680. # 启动PTZ控制线程
  681. if self.enable_ptz_camera and self.enable_ptz_tracking:
  682. self._ptz_thread = threading.Thread(
  683. target=self._ptz_worker, name="ptz-worker", daemon=True)
  684. self._ptz_thread.start()
  685. print("异步联动系统已启动 (检测线程 + PTZ控制线程)")
  686. return True
  687. def stop(self):
  688. """停止联动"""
  689. self.running = False
  690. # 清空PTZ队列,让工作线程退出
  691. while not self._ptz_queue.empty():
  692. try:
  693. self._ptz_queue.get_nowait()
  694. except queue.Empty:
  695. break
  696. if self._detection_thread:
  697. self._detection_thread.join(timeout=3)
  698. if self._ptz_thread:
  699. self._ptz_thread.join(timeout=3)
  700. # 停止父类线程(如果有的话)
  701. if self.coordinator_thread:
  702. self.coordinator_thread.join(timeout=1)
  703. # 关闭配对保存器
  704. if self._paired_saver is not None:
  705. self._paired_saver.close()
  706. self._paired_saver = None
  707. self.panorama.disconnect()
  708. if self.enable_ptz_camera:
  709. self.ptz.disconnect()
  710. self._print_stats()
  711. print("异步联动系统已停止")
  712. def _detection_worker(self):
  713. """检测线程:持续读帧 + YOLO推理 + 发送PTZ命令 + 打印检测日志"""
  714. last_detection_time = 0
  715. # 优先使用 detection_fps,默认每秒2帧
  716. detection_fps = self.config.get('detection_fps', 2)
  717. detection_interval = 1.0 / detection_fps # 根据FPS计算间隔
  718. ptz_cooldown = self.config.get('ptz_command_cooldown', 0.5)
  719. ptz_threshold = self.config.get('ptz_position_threshold', 0.03)
  720. frame_count = 0
  721. last_log_time = time.time()
  722. log_interval = 5.0 # 每5秒打印一次帧率统计
  723. detection_run_count = 0
  724. detection_person_count = 0
  725. last_no_detect_log_time = 0
  726. no_detect_log_interval = 30.0
  727. with self.stats_lock:
  728. self.stats['start_time'] = time.time()
  729. if self.detector is None:
  730. logger.warning("[检测线程] ⚠️ 人体检测器未初始化! 检测功能不可用, 请检查 YOLO 模型是否正确加载")
  731. elif not self.enable_detection:
  732. logger.warning("[检测线程] ⚠️ 人体检测已禁用 (enable_detection=False)")
  733. else:
  734. logger.info(f"[检测线程] ✓ 人体检测器已就绪, 检测帧率={detection_fps}fps(间隔={detection_interval:.2f}s), PTZ冷却={ptz_cooldown}s")
  735. while self.running:
  736. try:
  737. current_time = time.time()
  738. frame = self.panorama.get_frame()
  739. if frame is None:
  740. time.sleep(0.01)
  741. continue
  742. frame_count += 1
  743. self._update_stats('frames_processed')
  744. frame_size = (frame.shape[1], frame.shape[0])
  745. if current_time - last_log_time >= log_interval:
  746. elapsed = current_time - last_log_time
  747. fps = frame_count / elapsed if elapsed > 0 else 0
  748. state_str = self.state.name if hasattr(self.state, 'name') else str(self.state)
  749. stats_parts = [f"帧率={fps:.1f}fps", f"处理帧={frame_count}", f"状态={state_str}"]
  750. if self.detector is None:
  751. stats_parts.append("检测器=未加载")
  752. elif not self.enable_detection:
  753. stats_parts.append("检测=已禁用")
  754. else:
  755. stats_parts.append(f"检测轮次={detection_run_count}(有人={detection_person_count})")
  756. with self.targets_lock:
  757. target_count = len(self.tracking_targets)
  758. stats_parts.append(f"跟踪目标={target_count}")
  759. logger.info(f"[检测线程] {', '.join(stats_parts)}")
  760. frame_count = 0
  761. last_log_time = current_time
  762. # 周期性检测(约1次/秒)
  763. if current_time - last_detection_time >= detection_interval:
  764. last_detection_time = current_time
  765. detection_run_count += 1
  766. # YOLO 人体检测
  767. detections = self._detect_persons(frame)
  768. if detections:
  769. self._update_stats('persons_detected', len(detections))
  770. detection_person_count += 1
  771. # 更新跟踪
  772. tracked = self.tracker.update(detections)
  773. self._update_tracking_targets(tracked, frame_size)
  774. # 配对图片保存:创建新批次
  775. if tracked and self._enable_paired_saving and self._paired_saver is not None:
  776. self._create_detection_batch(frame, tracked, frame_size)
  777. # 打印检测日志
  778. if tracked:
  779. for t in tracked:
  780. # tracked 是 DetectedObject,使用 center 计算位置
  781. x_ratio = t.center[0] / frame_size[0]
  782. y_ratio = t.center[1] / frame_size[1]
  783. _, _, w, h = t.bbox
  784. area = w * h
  785. logger.info(
  786. f"[检测] ✓ 目标ID={t.track_id} "
  787. f"位置=({x_ratio:.3f}, {y_ratio:.3f}) "
  788. f"面积={area} 置信度={t.confidence:.2f}"
  789. )
  790. elif detections:
  791. # 有检测但没跟踪上
  792. for d in detections:
  793. logger.debug(f"[检测] 未跟踪: {d.class_name} @ {d.center}")
  794. else:
  795. if current_time - last_no_detect_log_time >= no_detect_log_interval:
  796. logger.info(
  797. f"[检测] · YOLO检测运行正常, 本轮未检测到人员 "
  798. f"(累计检测{detection_run_count}轮, 检测到人{detection_person_count}轮)"
  799. )
  800. last_no_detect_log_time = current_time
  801. if tracked:
  802. self._process_detections(tracked, frame, frame_size)
  803. # 选择跟踪目标并发送PTZ命令
  804. target = self._select_tracking_target()
  805. if target and self.enable_ptz_tracking and self.enable_ptz_camera:
  806. self._send_ptz_command_with_log(target, frame_size)
  807. elif not tracked and self.current_target:
  808. # 目标消失,切回IDLE
  809. self._set_state(TrackingState.IDLE)
  810. logger.info("[检测] 目标丢失,球机进入IDLE状态")
  811. self.current_target = None
  812. self._cleanup_expired_targets()
  813. time.sleep(0.01)
  814. except Exception as e:
  815. logger.error(f"检测线程错误: {e}")
  816. time.sleep(0.1)
  817. def _init_ptz_detector(self):
  818. """初始化球机端人体检测器"""
  819. try:
  820. model_path = DETECTION_CONFIG.get('model_path')
  821. model_type = DETECTION_CONFIG.get('model_type', 'auto')
  822. conf_threshold = DETECTION_CONFIG.get('person_threshold', 0.5)
  823. if model_path:
  824. self.ptz_detector = PTZPersonDetector(
  825. model_path=model_path,
  826. model_type=model_type,
  827. confidence_threshold=conf_threshold
  828. )
  829. self.auto_zoom_controller = PTZAutoZoomController(
  830. ptz_camera=self.ptz,
  831. detector=self.ptz_detector,
  832. config=self.auto_zoom_config
  833. )
  834. print(f"[AsyncCoordinator] 球机端人体检测器初始化成功")
  835. else:
  836. print("[AsyncCoordinator] 未配置球机检测模型路径,禁用球机端检测")
  837. self.enable_ptz_detection = False
  838. except Exception as e:
  839. print(f"[AsyncCoordinator] 球机端检测器初始化失败: {e}")
  840. self.enable_ptz_detection = False
  841. def _create_detection_batch(self, frame: np.ndarray,
  842. tracked: List[DetectedObject],
  843. frame_size: Tuple[int, int]):
  844. """
  845. 创建检测批次,用于配对图片保存
  846. Args:
  847. frame: 全景帧
  848. tracked: 跟踪到的人员列表
  849. frame_size: 帧尺寸
  850. """
  851. if self._paired_saver is None:
  852. return
  853. # 构建人员信息列表
  854. persons = []
  855. self._person_ptz_index = {} # 重置索引映射
  856. for i, det in enumerate(tracked):
  857. x_ratio = det.center[0] / frame_size[0]
  858. y_ratio = det.center[1] / frame_size[1]
  859. person_info = {
  860. 'track_id': det.track_id,
  861. 'position': (x_ratio, y_ratio),
  862. 'bbox': (det.bbox[0], det.bbox[1],
  863. det.bbox[0] + det.bbox[2],
  864. det.bbox[1] + det.bbox[3]),
  865. 'confidence': det.confidence
  866. }
  867. persons.append(person_info)
  868. self._person_ptz_index[det.track_id] = i
  869. # 创建新批次
  870. batch_id = self._paired_saver.start_new_batch(frame, persons)
  871. if batch_id:
  872. self._current_batch_id = batch_id
  873. logger.info(f"[配对保存] 创建批次: {batch_id}, 人员={len(persons)}")
  874. def _save_ptz_image_for_person(self, track_id: int,
  875. ptz_frame: np.ndarray,
  876. ptz_position: Tuple[float, float, int]):
  877. """
  878. 保存球机聚焦图片到对应批次
  879. Args:
  880. track_id: 人员跟踪ID
  881. ptz_frame: 球机帧
  882. ptz_position: PTZ位置 (pan, tilt, zoom)
  883. """
  884. if (self._paired_saver is None or
  885. self._current_batch_id is None or
  886. track_id not in self._person_ptz_index):
  887. return
  888. person_index = self._person_ptz_index[track_id]
  889. self._paired_saver.save_ptz_image(
  890. batch_id=self._current_batch_id,
  891. person_index=person_index,
  892. ptz_frame=ptz_frame,
  893. ptz_position=ptz_position
  894. )
  895. def _ptz_worker(self):
  896. """PTZ控制线程:从队列接收命令并控制球机"""
  897. while self.running:
  898. try:
  899. try:
  900. cmd = self._ptz_queue.get(timeout=0.1)
  901. except queue.Empty:
  902. continue
  903. # 从命令中提取 track_id 并传递
  904. self._execute_ptz_command(cmd, track_id=cmd.track_id)
  905. except Exception as e:
  906. print(f"PTZ控制线程错误: {e}")
  907. time.sleep(0.05)
  908. def _select_tracking_target(self) -> Optional[TrackingTarget]:
  909. """选择当前跟踪目标"""
  910. with self.targets_lock:
  911. if not self.tracking_targets:
  912. self._set_state(TrackingState.IDLE)
  913. self.current_target = None
  914. return None
  915. # 使用目标选择器选择最优目标
  916. self.current_target = self.target_selector.select_target(
  917. self.tracking_targets
  918. )
  919. return self.current_target
  920. def _send_ptz_command(self, target: TrackingTarget, frame_size: Tuple[int, int]):
  921. """将跟踪目标转化为PTZ命令放入队列"""
  922. x_ratio, y_ratio = target.position
  923. # 检查位置变化是否超过阈值
  924. if self.last_ptz_position is not None:
  925. last_x, last_y = self.last_ptz_position
  926. if abs(x_ratio - last_x) < self.ptz_position_threshold and \
  927. abs(y_ratio - last_y) < self.ptz_position_threshold:
  928. return
  929. # 冷却检查
  930. current_time = time.time()
  931. if current_time - self._last_ptz_time < self.PTZ_COMMAND_COOLDOWN:
  932. return
  933. cmd = PTZCommand(
  934. pan=0, tilt=0, zoom=0,
  935. x_ratio=x_ratio, y_ratio=y_ratio,
  936. use_calibration=self.enable_calibration
  937. )
  938. try:
  939. self._ptz_queue.put_nowait(cmd)
  940. self.last_ptz_position = (x_ratio, y_ratio)
  941. except queue.Full:
  942. pass # 丢弃命令,下一个检测周期会重发
  943. def _send_ptz_command_with_log(self, target: TrackingTarget, frame_size: Tuple[int, int]):
  944. """发送PTZ命令并打印日志"""
  945. x_ratio, y_ratio = target.position
  946. # 计算PTZ角度(用于日志)
  947. if self.enable_calibration and self.calibrator and self.calibrator.is_calibrated():
  948. pan, tilt = self.calibrator.transform(x_ratio, y_ratio)
  949. zoom = self.ptz.ptz_config.get('default_zoom', 8)
  950. coord_type = "校准坐标"
  951. else:
  952. pan, tilt, zoom = self.ptz.calculate_ptz_position(x_ratio, y_ratio)
  953. coord_type = "估算坐标"
  954. logger.info(
  955. f"[PTZ] 发送命令: 目标ID={target.track_id} "
  956. f"全景位置=({x_ratio:.3f}, {y_ratio:.3f}) → "
  957. f"PTZ角度=(pan={pan:.1f}°, tilt={tilt:.1f}°, zoom={zoom}) [{coord_type}]"
  958. )
  959. # 检查位置变化是否超过阈值
  960. ptz_threshold = self.config.get('ptz_position_threshold', 0.03)
  961. if self.last_ptz_position is not None:
  962. last_x, last_y = self.last_ptz_position
  963. dx = abs(x_ratio - last_x)
  964. dy = abs(y_ratio - last_y)
  965. if dx < ptz_threshold and dy < ptz_threshold:
  966. logger.debug(f"[PTZ] 位置变化太小(dx={dx:.4f}, dy={dy:.4f}),跳过")
  967. return
  968. # 冷却检查
  969. current_time = time.time()
  970. ptz_cooldown = self.config.get('ptz_command_cooldown', 0.5)
  971. if current_time - self._last_ptz_time < ptz_cooldown:
  972. logger.debug(f"[PTZ] 冷却中,跳过 (间隔={current_time - self._last_ptz_time:.2f}s < {ptz_cooldown}s)")
  973. return
  974. cmd = PTZCommand(
  975. pan=0, tilt=0, zoom=0,
  976. x_ratio=x_ratio, y_ratio=y_ratio,
  977. use_calibration=self.enable_calibration,
  978. track_id=target.track_id # 传递跟踪ID
  979. )
  980. try:
  981. self._ptz_queue.put_nowait(cmd)
  982. self.last_ptz_position = (x_ratio, y_ratio)
  983. self._update_stats('ptz_commands_sent' if 'ptz_commands_sent' in self.stats else 'persons_detected')
  984. except queue.Full:
  985. logger.warning("[PTZ] 命令队列满,丢弃本次命令")
  986. def _execute_ptz_command(self, cmd: PTZCommand, track_id: int = None):
  987. """
  988. 执行PTZ命令(在PTZ线程中)
  989. Args:
  990. cmd: PTZ命令
  991. track_id: 跟踪目标ID(用于配对图片保存)
  992. """
  993. self._last_ptz_time = time.time()
  994. if cmd.use_calibration and self.calibrator and self.calibrator.is_calibrated():
  995. pan, tilt = self.calibrator.transform(cmd.x_ratio, cmd.y_ratio)
  996. if self.ptz.ptz_config.get('pan_flip', False):
  997. pan = (pan + 180) % 360
  998. zoom = self.ptz.ptz_config.get('default_zoom', 8)
  999. else:
  1000. pan, tilt, zoom = self.ptz.calculate_ptz_position(cmd.x_ratio, cmd.y_ratio)
  1001. self._set_state(TrackingState.TRACKING)
  1002. logger.info(
  1003. f"[PTZ] 执行: pan={pan:.1f}° tilt={tilt:.1f}° zoom={zoom} "
  1004. f"(全景位置=({cmd.x_ratio:.3f}, {cmd.y_ratio:.3f}))"
  1005. )
  1006. success = self.ptz.goto_exact_position(pan, tilt, zoom)
  1007. if success:
  1008. time.sleep(self.PTZ_CONFIRM_WAIT)
  1009. # 球机端人体检测与自动对焦
  1010. if self.enable_ptz_detection and self.auto_zoom_config.get('enabled', False):
  1011. final_zoom = self._auto_zoom_person(pan, tilt, zoom)
  1012. if final_zoom != zoom:
  1013. zoom = final_zoom
  1014. # 保存球机图片到配对批次
  1015. if self._enable_paired_saving and track_id is not None:
  1016. ptz_frame = self.ptz.get_frame()
  1017. if ptz_frame is not None:
  1018. self._save_ptz_image_for_person(track_id, ptz_frame, (pan, tilt, zoom))
  1019. logger.info(f"[PTZ] 到位确认完成: pan={pan:.1f}° tilt={tilt:.1f}°")
  1020. else:
  1021. logger.warning(f"[PTZ] 命令执行失败: pan={pan:.1f}° tilt={tilt:.1f}° zoom={zoom}")
  1022. def _auto_zoom_person(self, initial_pan: float, initial_tilt: float, initial_zoom: int) -> int:
  1023. """
  1024. 自动对焦人体
  1025. 在球机画面中检测人体,自动调整zoom使人体居中且大小合适
  1026. Returns:
  1027. 最终的 zoom 值
  1028. """
  1029. if self.auto_zoom_controller is None:
  1030. return initial_zoom
  1031. logger.info("[AutoZoom] 开始自动对焦...")
  1032. try:
  1033. success, final_zoom = self.auto_zoom_controller.auto_focus_loop(
  1034. get_frame_func=self.ptz.get_frame,
  1035. max_attempts=self.auto_zoom_config.get('max_adjust_attempts', 3)
  1036. )
  1037. if success:
  1038. logger.info(f"[AutoZoom] 自动对焦成功: zoom={final_zoom}")
  1039. return final_zoom
  1040. else:
  1041. logger.warning("[AutoZoom] 自动对焦未能定位人体")
  1042. return initial_zoom
  1043. except Exception as e:
  1044. logger.error(f"[AutoZoom] 自动对焦异常: {e}")
  1045. return initial_zoom
  1046. def _confirm_ptz_position(self, x_ratio: float, y_ratio: float):
  1047. """PTZ位置确认:读取球机帧验证目标是否可见"""
  1048. if not hasattr(self.ptz, 'get_frame') or self.ptz.get_frame() is None:
  1049. return
  1050. ptz_frame = self.ptz.get_frame()
  1051. if ptz_frame is None:
  1052. return
  1053. # 未来可以在这里添加球机帧目标验证逻辑
  1054. # 例如:在球机帧中检测目标是否在画面中心附近
  1055. def on_ptz_confirmed(self, callback: Callable):
  1056. """注册PTZ位置确认回调"""
  1057. self._on_ptz_confirmed = callback