coordinator.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. """
  2. 联动控制器
  3. 协调全景摄像头和球机的工作
  4. """
  5. import time
  6. import threading
  7. import queue
  8. import logging
  9. import math
  10. from typing import Optional, List, Dict, Tuple, Callable
  11. from dataclasses import dataclass, field
  12. from enum import Enum
  13. import numpy as np
  14. import cv2
  15. from config import COORDINATOR_CONFIG, SYSTEM_CONFIG, PTZ_CONFIG, DETECTION_CONFIG
  16. from panorama_camera import PanoramaCamera, ObjectDetector, DetectedObject
  17. from ptz_camera import PTZCamera, PTZController
  18. from ocr_recognizer import NumberDetector, PersonInfo
  19. from ptz_person_tracker import PTZPersonDetector, PTZAutoZoomController
  20. from paired_image_saver import PairedImageSaver, get_paired_saver
  21. logger = logging.getLogger(__name__)
  22. class TrackingState(Enum):
  23. """跟踪状态"""
  24. IDLE = 0 # 空闲
  25. SEARCHING = 1 # 搜索目标
  26. TRACKING = 2 # 跟踪中
  27. ZOOMING = 3 # 变焦中
  28. OCR_PROCESSING = 4 # OCR处理中
  29. @dataclass
  30. class TrackingTarget:
  31. """跟踪目标"""
  32. track_id: int # 跟踪ID
  33. position: Tuple[float, float] # 位置比例 (x_ratio, y_ratio)
  34. last_update: float # 最后更新时间
  35. person_info: Optional[PersonInfo] = None # 人员信息
  36. priority: int = 0 # 优先级
  37. area: int = 0 # 目标面积(像素²)
  38. confidence: float = 0.0 # 置信度
  39. center_distance: float = 1.0 # 到画面中心的距离比例(0-1)
  40. score: float = 0.0 # 综合得分
  41. class TargetSelector:
  42. """
  43. 目标选择策略类
  44. 支持按面积、置信度、混合模式排序,支持优先级切换
  45. """
  46. def __init__(self, config: Dict = None):
  47. """
  48. 初始化目标选择器
  49. Args:
  50. config: 目标选择配置
  51. """
  52. self.config = config or {
  53. 'strategy': 'area',
  54. 'area_weight': 0.6,
  55. 'confidence_weight': 0.4,
  56. 'min_area_threshold': 5000,
  57. 'prefer_center': True,
  58. 'center_weight': 0.2,
  59. 'switch_on_lost': True,
  60. 'stickiness': 0.3,
  61. }
  62. self.current_target_id: Optional[int] = None
  63. self.current_target_score: float = 0.0
  64. def calculate_score(self, target: TrackingTarget, frame_size: Tuple[int, int] = None) -> float:
  65. """
  66. 计算目标综合得分
  67. Args:
  68. target: 跟踪目标
  69. frame_size: 帧尺寸(w, h),用于计算中心距离
  70. Returns:
  71. 综合得分(0-1)
  72. """
  73. strategy = self.config.get('strategy', 'area')
  74. area_weight = self.config.get('area_weight', 0.6)
  75. conf_weight = self.config.get('confidence_weight', 0.4)
  76. min_area = self.config.get('min_area_threshold', 5000)
  77. prefer_center = self.config.get('prefer_center', False)
  78. center_weight = self.config.get('center_weight', 0.2)
  79. # 归一化面积得分 (对数缩放,避免大目标得分过高)
  80. import math
  81. area_score = min(1.0, math.log10(max(target.area, 1)) / 5.0) # 100000像素² ≈ 1.0
  82. # 小面积惩罚
  83. if target.area < min_area:
  84. area_score *= 0.5
  85. # 置信度得分直接使用
  86. conf_score = target.confidence
  87. # 中心距离得分 (距离中心越近得分越高)
  88. center_score = 1.0 - target.center_distance
  89. # 根据策略计算综合得分
  90. if strategy == 'area':
  91. score = area_score * 0.8 + conf_score * 0.2
  92. elif strategy == 'confidence':
  93. score = conf_score * 0.8 + area_score * 0.2
  94. else: # hybrid
  95. score = area_score * area_weight + conf_score * conf_weight
  96. # 加入中心距离权重
  97. if prefer_center:
  98. score = score * (1 - center_weight) + center_score * center_weight
  99. return score
  100. def select_target(self, targets: Dict[int, TrackingTarget],
  101. frame_size: Tuple[int, int] = None) -> Optional[TrackingTarget]:
  102. """
  103. 从多个目标中选择最优目标
  104. Args:
  105. targets: 目标字典 {track_id: TrackingTarget}
  106. frame_size: 帧尺寸
  107. Returns:
  108. 最优目标
  109. """
  110. if not targets:
  111. self.current_target_id = None
  112. return None
  113. stickiness = self.config.get('stickiness', 0.3)
  114. switch_on_lost = self.config.get('switch_on_lost', True)
  115. # 计算所有目标得分
  116. scored_targets = []
  117. for track_id, target in targets.items():
  118. target.score = self.calculate_score(target, frame_size)
  119. scored_targets.append((track_id, target, target.score))
  120. # 按得分排序
  121. scored_targets.sort(key=lambda x: x[2], reverse=True)
  122. # 检查当前目标是否仍在列表中
  123. if self.current_target_id is not None:
  124. current_exists = self.current_target_id in targets
  125. if current_exists:
  126. # 应用粘性:当前目标得分需要显著低于最优目标才切换
  127. best_id, best_target, best_score = scored_targets[0]
  128. current_target = targets[self.current_target_id]
  129. # 粘性阈值: 当前目标得分 > 最优得分 * (1 - stickiness) 时保持
  130. stickiness_threshold = best_score * (1 - stickiness)
  131. if current_target.score > stickiness_threshold:
  132. return current_target
  133. # 选择得分最高的目标
  134. best_id, best_target, best_score = scored_targets[0]
  135. self.current_target_id = best_id
  136. self.current_target_score = best_score
  137. logger.debug(
  138. f"[目标选择] 选择目标ID={best_id} 得分={best_score:.3f} "
  139. f"面积={best_target.area} 置信度={best_target.confidence:.2f}"
  140. )
  141. return best_target
  142. def get_sorted_targets(self, targets: Dict[int, TrackingTarget],
  143. frame_size: Tuple[int, int] = None) -> List[Tuple[TrackingTarget, float]]:
  144. """
  145. 获取按得分排序的目标列表
  146. Args:
  147. targets: 目标字典
  148. frame_size: 帧尺寸
  149. Returns:
  150. 排序后的目标列表 [(target, score), ...]
  151. """
  152. scored = []
  153. for target in targets.values():
  154. target.score = self.calculate_score(target, frame_size)
  155. scored.append((target, target.score))
  156. scored.sort(key=lambda x: x[1], reverse=True)
  157. return scored
  158. def set_strategy(self, strategy: str):
  159. """设置选择策略"""
  160. self.config['strategy'] = strategy
  161. logger.info(f"[目标选择] 策略已切换为: {strategy}")
  162. def set_stickiness(self, stickiness: float):
  163. """设置目标粘性"""
  164. self.config['stickiness'] = max(0.0, min(1.0, stickiness))
  165. logger.info(f"[目标选择] 粘性已设置为: {self.config['stickiness']}")
  166. class Coordinator:
  167. """
  168. 联动控制器
  169. 协调全景摄像头和球机实现联动抓拍
  170. """
  171. def __init__(self, panorama_camera: PanoramaCamera,
  172. ptz_camera: PTZCamera,
  173. detector: ObjectDetector = None,
  174. number_detector: NumberDetector = None,
  175. calibrator = None):
  176. """
  177. 初始化联动控制器
  178. Args:
  179. panorama_camera: 全景摄像头
  180. ptz_camera: 球机
  181. detector: 物体检测器
  182. number_detector: 编号检测器
  183. calibrator: 校准器 (用于坐标转换)
  184. """
  185. self.panorama = panorama_camera
  186. self.ptz = ptz_camera
  187. self.detector = detector
  188. self.number_detector = number_detector
  189. self.calibrator = calibrator
  190. self.config = COORDINATOR_CONFIG
  191. # 功能开关 - 从 SYSTEM_CONFIG 读取
  192. self.enable_ptz_camera = SYSTEM_CONFIG.get('enable_ptz_camera', True)
  193. self.enable_ptz_tracking = SYSTEM_CONFIG.get('enable_ptz_tracking', True)
  194. self.enable_calibration = SYSTEM_CONFIG.get('enable_calibration', True)
  195. self.enable_detection = SYSTEM_CONFIG.get('enable_detection', True)
  196. self.enable_ocr = SYSTEM_CONFIG.get('enable_ocr', True)
  197. # 球机端人体检测与自动对焦
  198. self.enable_ptz_detection = PTZ_CONFIG.get('enable_ptz_detection', False)
  199. self.auto_zoom_config = PTZ_CONFIG.get('auto_zoom', {})
  200. self.ptz_detector = None
  201. self.auto_zoom_controller = None
  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_CONFIG 获取检测帧率,默认每秒2帧
  331. detection_fps = self.config.get('detection_fps', DETECTION_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. # 更新跟踪目标(track_id 在此方法内分配)
  356. self._update_tracking_targets(detections, frame_size)
  357. # 处理检测结果
  358. if detections:
  359. self._process_detections(detections, frame, frame_size)
  360. # 处理当前跟踪目标
  361. self._process_current_target(frame, frame_size)
  362. # 清理过期目标
  363. self._cleanup_expired_targets()
  364. time.sleep(0.01)
  365. except Exception as e:
  366. print(f"联动处理错误: {e}")
  367. time.sleep(0.1)
  368. def _detect_persons(self, frame: np.ndarray) -> List[DetectedObject]:
  369. """检测人体"""
  370. if not self.enable_detection or self.detector is None:
  371. return []
  372. return self.detector.detect_persons(frame)
  373. def _update_tracking_targets(self, detections: List[DetectedObject],
  374. frame_size: Tuple[int, int]):
  375. """更新跟踪目标(跨帧匹配,支持粘性跟踪)
  376. 改进:不再每轮清空目标,而是使用位置匹配关联连续帧的目标
  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. # 获取人员置信度阈值
  382. person_threshold = DETECTION_CONFIG.get('person_threshold', 0.8)
  383. # 过滤有效人员
  384. valid_detections = []
  385. for det in detections:
  386. if det.class_name != 'person':
  387. continue
  388. if det.confidence < person_threshold:
  389. continue
  390. valid_detections.append(det)
  391. with self.targets_lock:
  392. # 匹配阈值:位置距离小于此值认为是同一目标
  393. MATCH_THRESHOLD = 0.15 # 画面比例
  394. # 已匹配的检测索引
  395. matched_det_indices = set()
  396. # 步骤1:尝试匹配现有目标
  397. for track_id, target in list(self.tracking_targets.items()):
  398. best_match_idx = None
  399. best_match_dist = MATCH_THRESHOLD
  400. for idx, det in enumerate(valid_detections):
  401. if idx in matched_det_indices:
  402. continue
  403. det_x = det.center[0] / frame_w
  404. det_y = det.center[1] / frame_h
  405. # 计算位置距离
  406. dist = math.sqrt(
  407. (det_x - target.position[0]) ** 2 +
  408. (det_y - target.position[1]) ** 2
  409. )
  410. if dist < best_match_dist:
  411. best_match_dist = dist
  412. best_match_idx = idx
  413. if best_match_idx is not None:
  414. # 找到匹配,更新目标
  415. det = valid_detections[best_match_idx]
  416. matched_det_indices.add(best_match_idx)
  417. x_ratio = det.center[0] / frame_w
  418. y_ratio = det.center[1] / frame_h
  419. _, _, width, height = det.bbox
  420. area = width * height
  421. dx = abs(det.center[0] - center_x) / center_x
  422. dy = abs(det.center[1] - center_y) / center_y
  423. center_distance = (dx + dy) / 2
  424. # 更新目标属性
  425. self.tracking_targets[track_id] = TrackingTarget(
  426. track_id=track_id,
  427. position=(x_ratio, y_ratio),
  428. last_update=current_time,
  429. area=area,
  430. confidence=det.confidence,
  431. center_distance=center_distance,
  432. person_info=target.person_info # 保留之前识别的信息
  433. )
  434. # 步骤2:为未匹配的检测创建新目标
  435. for idx, det in enumerate(valid_detections):
  436. if idx in matched_det_indices:
  437. continue
  438. x_ratio = det.center[0] / frame_w
  439. y_ratio = det.center[1] / frame_h
  440. _, _, width, height = det.bbox
  441. area = width * height
  442. dx = abs(det.center[0] - center_x) / center_x
  443. dy = abs(det.center[1] - center_y) / center_y
  444. center_distance = (dx + dy) / 2
  445. # 分配全局唯一track_id
  446. with self._track_id_lock:
  447. new_track_id = self._next_track_id
  448. self._next_track_id += 1
  449. det.track_id = new_track_id # 更新检测对象的track_id
  450. self.tracking_targets[new_track_id] = TrackingTarget(
  451. track_id=new_track_id,
  452. position=(x_ratio, y_ratio),
  453. last_update=current_time,
  454. area=area,
  455. confidence=det.confidence,
  456. center_distance=center_distance
  457. )
  458. def _process_detections(self, detections: List[DetectedObject],
  459. frame: np.ndarray, frame_size: Tuple[int, int]):
  460. """处理检测结果"""
  461. if self.on_person_detected:
  462. for det in detections:
  463. self.on_person_detected(det, frame)
  464. def _process_current_target(self, frame: np.ndarray, frame_size: Tuple[int, int]):
  465. """处理当前跟踪目标"""
  466. with self.targets_lock:
  467. if not self.tracking_targets:
  468. self._set_state(TrackingState.IDLE)
  469. self.current_target = None
  470. return
  471. # 使用目标选择器选择最优目标
  472. self.current_target = self.target_selector.select_target(
  473. self.tracking_targets, frame_size
  474. )
  475. if self.current_target:
  476. # 移动球机到目标位置 (仅在 PTZ 跟踪启用时)
  477. if self.enable_ptz_tracking and self.enable_ptz_camera:
  478. self._set_state(TrackingState.TRACKING)
  479. x_ratio, y_ratio = self.current_target.position
  480. # 检查位置是否变化超过阈值
  481. should_move = True
  482. if self.last_ptz_position is not None:
  483. last_x, last_y = self.last_ptz_position
  484. if (abs(x_ratio - last_x) < self.ptz_position_threshold and
  485. abs(y_ratio - last_y) < self.ptz_position_threshold):
  486. should_move = False
  487. if should_move:
  488. if self.enable_calibration and self.calibrator and self.calibrator.is_calibrated():
  489. pan, tilt = self.calibrator.transform(x_ratio, y_ratio)
  490. if self.ptz.ptz_config.get('pan_flip', False):
  491. pan = (pan + 180) % 360
  492. zoom = self.ptz.ptz_config.get('default_zoom', 8)
  493. self.ptz.goto_exact_position(pan, tilt, zoom)
  494. else:
  495. self.ptz.track_target(x_ratio, y_ratio)
  496. self.last_ptz_position = (x_ratio, y_ratio)
  497. # 执行OCR识别 (仅在 OCR 启用时)
  498. if self.enable_ocr:
  499. self._perform_ocr(frame, self.current_target)
  500. def _perform_ocr(self, frame: np.ndarray, target: TrackingTarget):
  501. """执行OCR识别"""
  502. if not self.enable_ocr or self.number_detector is None:
  503. return
  504. # 频率控制 - 避免过于频繁调用OCR API
  505. current_time = time.time()
  506. if current_time - self.last_ocr_time < self.ocr_interval:
  507. return
  508. self.last_ocr_time = current_time
  509. # 更新OCR尝试统计
  510. self._update_stats('ocr_attempts')
  511. # 计算人体边界框 (基于位置估算)
  512. frame_h, frame_w = frame.shape[:2]
  513. # 人体占画面比例 (可配置,默认宽20%、高40%)
  514. person_width_ratio = self.config.get('person_width_ratio', 0.2)
  515. person_height_ratio = self.config.get('person_height_ratio', 0.4)
  516. person_width = int(frame_w * person_width_ratio)
  517. person_height = int(frame_h * person_height_ratio)
  518. x_ratio, y_ratio = target.position
  519. center_x = int(x_ratio * frame_w)
  520. center_y = int(y_ratio * frame_h)
  521. # 计算边界框,确保不超出画面范围
  522. x1 = max(0, center_x - person_width // 2)
  523. y1 = max(0, center_y - person_height // 2)
  524. x2 = min(frame_w, x1 + person_width)
  525. y2 = min(frame_h, y1 + person_height)
  526. # 更新实际宽高 (可能因边界裁剪而变小)
  527. actual_width = x2 - x1
  528. actual_height = y2 - y1
  529. person_bbox = (x1, y1, actual_width, actual_height)
  530. # 检测编号
  531. self._set_state(TrackingState.OCR_PROCESSING)
  532. person_info = self.number_detector.detect_number(frame, person_bbox)
  533. person_info.person_id = target.track_id
  534. # 更新OCR成功统计
  535. if person_info.number_text:
  536. self._update_stats('ocr_success')
  537. # 更新目标信息
  538. with self.targets_lock:
  539. if target.track_id in self.tracking_targets:
  540. self.tracking_targets[target.track_id].person_info = person_info
  541. # 回调
  542. if self.on_number_recognized and person_info.number_text:
  543. self.on_number_recognized(person_info)
  544. # 放入结果队列
  545. self.result_queue.put(person_info)
  546. def _cleanup_expired_targets(self):
  547. """清理过期目标"""
  548. current_time = time.time()
  549. timeout = self.config['tracking_timeout']
  550. with self.targets_lock:
  551. expired_ids = [
  552. target_id for target_id, target in self.tracking_targets.items()
  553. if current_time - target.last_update > timeout
  554. ]
  555. for target_id in expired_ids:
  556. del self.tracking_targets[target_id]
  557. if self.current_target and self.current_target.track_id == target_id:
  558. self.current_target = None
  559. def _set_state(self, state: TrackingState):
  560. """设置状态"""
  561. with self.state_lock:
  562. self.state = state
  563. def get_state(self) -> TrackingState:
  564. """获取状态"""
  565. with self.state_lock:
  566. return self.state
  567. def get_results(self) -> List[PersonInfo]:
  568. """
  569. 获取识别结果
  570. Returns:
  571. 人员信息列表
  572. """
  573. results = []
  574. while not self.result_queue.empty():
  575. try:
  576. results.append(self.result_queue.get_nowait())
  577. except queue.Empty:
  578. break
  579. return results
  580. def get_tracking_targets(self) -> List[TrackingTarget]:
  581. """获取当前跟踪目标"""
  582. with self.targets_lock:
  583. return list(self.tracking_targets.values())
  584. def force_track_position(self, x_ratio: float, y_ratio: float, zoom: int = None):
  585. """
  586. 强制跟踪指定位置
  587. Args:
  588. x_ratio: X方向比例
  589. y_ratio: Y方向比例
  590. zoom: 变倍
  591. """
  592. if self.enable_ptz_tracking and self.enable_ptz_camera:
  593. if self.enable_calibration and self.calibrator and self.calibrator.is_calibrated():
  594. pan, tilt = self.calibrator.transform(x_ratio, y_ratio)
  595. if self.ptz.ptz_config.get('pan_flip', False):
  596. pan = (pan + 180) % 360
  597. self.ptz.goto_exact_position(pan, tilt, zoom or self.ptz.ptz_config.get('default_zoom', 8))
  598. else:
  599. self.ptz.move_to_target(x_ratio, y_ratio, zoom)
  600. def capture_snapshot(self) -> Optional[np.ndarray]:
  601. """
  602. 抓拍快照
  603. Returns:
  604. 快照图像
  605. """
  606. return self.panorama.get_frame()
  607. class EventDrivenCoordinator(Coordinator):
  608. """事件驱动联动控制器,当全景摄像头检测到事件时触发联动"""
  609. def __init__(self, *args, **kwargs):
  610. super().__init__(*args, **kwargs)
  611. self.event_types = {
  612. 'intruder': True,
  613. 'crossline': True,
  614. 'motion': True,
  615. }
  616. self.event_queue = queue.Queue()
  617. def on_event(self, event_type: str, event_data: dict):
  618. if not self.event_types.get(event_type, False):
  619. return
  620. self.event_queue.put({'type': event_type, 'data': event_data, 'time': time.time()})
  621. def _coordinator_worker(self):
  622. while self.running:
  623. try:
  624. try:
  625. event = self.event_queue.get(timeout=0.1)
  626. self._process_event(event)
  627. except queue.Empty:
  628. pass
  629. frame = self.panorama.get_frame()
  630. if frame is not None:
  631. frame_size = (frame.shape[1], frame.shape[0])
  632. detections = self._detect_persons(frame)
  633. if detections:
  634. # 更新跟踪目标(track_id 在此方法内分配)
  635. self._update_tracking_targets(detections, frame_size)
  636. self._process_current_target(frame, frame_size)
  637. self._cleanup_expired_targets()
  638. except Exception as e:
  639. print(f"事件处理错误: {e}")
  640. time.sleep(0.1)
  641. def _process_event(self, event: dict):
  642. event_type = event['type']
  643. event_data = event['data']
  644. print(f"处理事件: {event_type}")
  645. if event_type == 'intruder' and 'position' in event_data:
  646. x_ratio, y_ratio = event_data['position']
  647. self.force_track_position(x_ratio, y_ratio)
  648. @dataclass
  649. class PTZCommand:
  650. """PTZ控制命令"""
  651. pan: float
  652. tilt: float
  653. zoom: int
  654. x_ratio: float = 0.0
  655. y_ratio: float = 0.0
  656. use_calibration: bool = True
  657. track_id: Optional[int] = None # 跟踪目标ID(用于配对图片保存)
  658. batch_id: Optional[str] = None # 批次ID(用于配对图片保存)
  659. person_index: int = -1 # 人员在批次中的序号(用于配对图片保存)
  660. class AsyncCoordinator(Coordinator):
  661. """
  662. 异步联动控制器 — 检测线程与PTZ控制线程分离
  663. 改进:
  664. 1. 检测线程:持续读取全景帧 + YOLO推理
  665. 2. PTZ控制线程:通过命令队列接收目标位置,独立控制球机
  666. 3. 两线程通过 queue 通信,互不阻塞
  667. 4. PTZ位置确认:移动后等待球机到位并验证帧
  668. """
  669. PTZ_CONFIRM_WAIT = 0.3 # PTZ命令后等待稳定的秒数
  670. PTZ_CONFIRM_TIMEOUT = 2.0 # PTZ位置确认超时
  671. PTZ_COMMAND_COOLDOWN = 0.15 # PTZ命令最小间隔秒数
  672. def __init__(self, *args, **kwargs):
  673. super().__init__(*args, **kwargs)
  674. # PTZ命令队列(检测→PTZ)
  675. self._ptz_queue: queue.Queue = queue.Queue(maxsize=10)
  676. # 线程
  677. self._detection_thread = None
  678. self._ptz_thread = None
  679. # PTZ确认回调
  680. self._on_ptz_confirmed: Optional[Callable] = None
  681. # 上次PTZ命令时间(添加线程锁保护)
  682. self._last_ptz_time = 0.0
  683. self._last_ptz_time_lock = threading.Lock()
  684. # 跨帧跟踪:全局track_id计数器
  685. self._next_track_id = 1
  686. self._track_id_lock = threading.Lock()
  687. # 配对图片保存器
  688. self._enable_paired_saving = DETECTION_CONFIG.get('enable_paired_saving', False)
  689. self._paired_saver: Optional[PairedImageSaver] = None
  690. self._current_batch_id: Optional[str] = None
  691. self._person_ptz_index: Dict[int, int] = {} # track_id -> person_index
  692. if self._enable_paired_saving:
  693. save_dir = DETECTION_CONFIG.get('paired_image_dir', '/home/admin/dsh/paired_images')
  694. time_window = DETECTION_CONFIG.get('paired_time_window', 5.0)
  695. self._paired_saver = get_paired_saver(base_dir=save_dir, time_window=time_window)
  696. logger.info(f"[AsyncCoordinator] 配对图片保存已启用: 目录={save_dir}, 时间窗口={time_window}s")
  697. def start(self) -> bool:
  698. """启动联动(覆盖父类,启动双线程)"""
  699. if not self.panorama.connect():
  700. print("连接全景摄像头失败")
  701. return False
  702. if self.enable_ptz_camera:
  703. if not self.ptz.connect():
  704. print("连接球机失败")
  705. self.panorama.disconnect()
  706. return False
  707. # 启动球机RTSP流(用于球机端人体检测)
  708. if self.enable_ptz_detection:
  709. if not self.ptz.start_stream_rtsp():
  710. print("球机RTSP流启动失败,禁用球机端检测功能")
  711. self.enable_ptz_detection = False
  712. else:
  713. # 初始化球机端人体检测器
  714. self._init_ptz_detector()
  715. else:
  716. print("PTZ球机功能已禁用")
  717. if not self.panorama.start_stream_rtsp():
  718. print("RTSP视频流启动失败,尝试SDK方式...")
  719. if not self.panorama.start_stream():
  720. print("启动视频流失败")
  721. self.panorama.disconnect()
  722. if self.enable_ptz_camera:
  723. self.ptz.disconnect()
  724. return False
  725. self.running = True
  726. # 启动检测线程
  727. self._detection_thread = threading.Thread(
  728. target=self._detection_worker, name="detection-worker", daemon=True)
  729. self._detection_thread.start()
  730. # 启动PTZ控制线程
  731. if self.enable_ptz_camera and self.enable_ptz_tracking:
  732. self._ptz_thread = threading.Thread(
  733. target=self._ptz_worker, name="ptz-worker", daemon=True)
  734. self._ptz_thread.start()
  735. print("异步联动系统已启动 (检测线程 + PTZ控制线程)")
  736. return True
  737. def stop(self):
  738. """停止联动"""
  739. self.running = False
  740. # 清空PTZ队列,让工作线程退出
  741. while not self._ptz_queue.empty():
  742. try:
  743. self._ptz_queue.get_nowait()
  744. except queue.Empty:
  745. break
  746. if self._detection_thread:
  747. self._detection_thread.join(timeout=3)
  748. if self._ptz_thread:
  749. self._ptz_thread.join(timeout=3)
  750. # 停止父类线程(如果有的话)
  751. if self.coordinator_thread:
  752. self.coordinator_thread.join(timeout=1)
  753. # 关闭配对保存器
  754. if self._paired_saver is not None:
  755. self._paired_saver.close()
  756. self._paired_saver = None
  757. self.panorama.disconnect()
  758. if self.enable_ptz_camera:
  759. self.ptz.disconnect()
  760. self._print_stats()
  761. print("异步联动系统已停止")
  762. def _detection_worker(self):
  763. """检测线程:持续读帧 + YOLO推理 + 发送PTZ命令 + 打印检测日志"""
  764. last_detection_time = 0
  765. # 从 DETECTION_CONFIG 获取检测帧率,默认每秒2帧
  766. detection_fps = self.config.get('detection_fps', DETECTION_CONFIG.get('detection_fps', 2))
  767. detection_interval = 1.0 / detection_fps # 根据FPS计算间隔
  768. ptz_cooldown = self.config.get('ptz_command_cooldown', 0.5)
  769. ptz_threshold = self.config.get('ptz_position_threshold', 0.03)
  770. frame_count = 0
  771. last_log_time = time.time()
  772. log_interval = 5.0 # 每5秒打印一次帧率统计
  773. detection_run_count = 0
  774. detection_person_count = 0
  775. last_no_detect_log_time = 0
  776. no_detect_log_interval = 30.0
  777. with self.stats_lock:
  778. self.stats['start_time'] = time.time()
  779. if self.detector is None:
  780. logger.warning("[检测线程] ⚠️ 人体检测器未初始化! 检测功能不可用, 请检查 YOLO 模型是否正确加载")
  781. elif not self.enable_detection:
  782. logger.warning("[检测线程] ⚠️ 人体检测已禁用 (enable_detection=False)")
  783. else:
  784. logger.info(f"[检测线程] ✓ 人体检测器已就绪, 检测帧率={detection_fps}fps(间隔={detection_interval:.2f}s), PTZ冷却={ptz_cooldown}s")
  785. while self.running:
  786. try:
  787. current_time = time.time()
  788. frame = self.panorama.get_frame()
  789. if frame is None:
  790. time.sleep(0.01)
  791. continue
  792. frame_count += 1
  793. self._update_stats('frames_processed')
  794. frame_size = (frame.shape[1], frame.shape[0])
  795. if current_time - last_log_time >= log_interval:
  796. elapsed = current_time - last_log_time
  797. fps = frame_count / elapsed if elapsed > 0 else 0
  798. state_str = self.state.name if hasattr(self.state, 'name') else str(self.state)
  799. stats_parts = [f"帧率={fps:.1f}fps", f"处理帧={frame_count}", f"状态={state_str}"]
  800. if self.detector is None:
  801. stats_parts.append("检测器=未加载")
  802. elif not self.enable_detection:
  803. stats_parts.append("检测=已禁用")
  804. else:
  805. stats_parts.append(f"检测轮次={detection_run_count}(有人={detection_person_count})")
  806. with self.targets_lock:
  807. target_count = len(self.tracking_targets)
  808. stats_parts.append(f"跟踪目标={target_count}")
  809. logger.info(f"[检测线程] {', '.join(stats_parts)}")
  810. frame_count = 0
  811. last_log_time = current_time
  812. # 周期性检测(约1次/秒)
  813. if current_time - last_detection_time >= detection_interval:
  814. last_detection_time = current_time
  815. detection_run_count += 1
  816. # YOLO 人体检测
  817. detections = self._detect_persons(frame)
  818. if detections:
  819. self._update_stats('persons_detected', len(detections))
  820. detection_person_count += 1
  821. # 更新跟踪目标(track_id 在此方法内分配)
  822. self._update_tracking_targets(detections, frame_size)
  823. # 配对图片保存:创建新批次(在 _update_tracking_targets 之后,使用正确的 track_id)
  824. if detections and self._enable_paired_saving and self._paired_saver is not None:
  825. self._create_detection_batch(frame, detections, frame_size)
  826. # 打印检测日志(使用连续序号,与图片标记一致)
  827. if detections:
  828. person_threshold = DETECTION_CONFIG.get('person_threshold', 0.8)
  829. person_idx = 0
  830. for t in detections:
  831. # detections 是 DetectedObject,使用 center 计算位置
  832. x_ratio = t.center[0] / frame_size[0]
  833. y_ratio = t.center[1] / frame_size[1]
  834. _, _, w, h = t.bbox
  835. area = w * h
  836. # 只对达到阈值的人员打印日志并分配序号
  837. if t.class_name == 'person' and t.confidence >= person_threshold:
  838. logger.info(
  839. f"[检测] ✓ person_{person_idx} "
  840. f"位置=({x_ratio:.3f}, {y_ratio:.3f}) "
  841. f"面积={area} 置信度={t.confidence:.2f}"
  842. )
  843. person_idx += 1
  844. else:
  845. logger.debug(
  846. f"[检测] · 目标ID={t.track_id}({t.class_name}) "
  847. f"位置=({x_ratio:.3f}, {y_ratio:.3f}) "
  848. f"置信度={t.confidence:.2f}(低于阈值{person_threshold})"
  849. )
  850. else:
  851. if current_time - last_no_detect_log_time >= no_detect_log_interval:
  852. logger.info(
  853. f"[检测] · YOLO检测运行正常, 本轮未检测到人员 "
  854. f"(累计检测{detection_run_count}轮, 检测到人{detection_person_count}轮)"
  855. )
  856. last_no_detect_log_time = current_time
  857. if detections:
  858. self._process_detections(detections, frame, frame_size)
  859. # 为每个检测到的人发送PTZ命令(不再只选一个)
  860. if self.enable_ptz_tracking and self.enable_ptz_camera:
  861. targets = self._get_all_valid_targets()
  862. for target in targets:
  863. self._send_ptz_command_with_log(target, frame_size)
  864. elif not detections and self.current_target:
  865. # 目标消失,切回IDLE
  866. self._set_state(TrackingState.IDLE)
  867. logger.info("[检测] 目标丢失,球机进入IDLE状态")
  868. self.current_target = None
  869. self._cleanup_expired_targets()
  870. time.sleep(0.01)
  871. except Exception as e:
  872. logger.error(f"检测线程错误: {e}")
  873. time.sleep(0.1)
  874. def _init_ptz_detector(self):
  875. """初始化球机端人体检测器"""
  876. try:
  877. model_path = DETECTION_CONFIG.get('model_path')
  878. model_type = DETECTION_CONFIG.get('model_type', 'auto')
  879. conf_threshold = DETECTION_CONFIG.get('person_threshold', 0.5)
  880. if model_path:
  881. self.ptz_detector = PTZPersonDetector(
  882. model_path=model_path,
  883. model_type=model_type,
  884. confidence_threshold=conf_threshold
  885. )
  886. self.auto_zoom_controller = PTZAutoZoomController(
  887. ptz_camera=self.ptz,
  888. detector=self.ptz_detector,
  889. config=self.auto_zoom_config
  890. )
  891. print(f"[AsyncCoordinator] 球机端人体检测器初始化成功")
  892. else:
  893. print("[AsyncCoordinator] 未配置球机检测模型路径,禁用球机端检测")
  894. self.enable_ptz_detection = False
  895. except Exception as e:
  896. print(f"[AsyncCoordinator] 球机端检测器初始化失败: {e}")
  897. self.enable_ptz_detection = False
  898. def _create_detection_batch(self, frame: np.ndarray,
  899. detections: List[DetectedObject],
  900. frame_size: Tuple[int, int]):
  901. """
  902. 创建检测批次,用于配对图片保存
  903. Args:
  904. frame: 全景帧
  905. detections: 检测到的人员列表
  906. frame_size: 帧尺寸
  907. """
  908. if self._paired_saver is None:
  909. return
  910. # 过滤有效人员(必须是 person 且置信度 >= 阈值)
  911. person_threshold = DETECTION_CONFIG.get('person_threshold', 0.8)
  912. valid_persons = []
  913. for det in detections:
  914. # 只处理 class_name 为 person 的目标,排除安全帽、反光衣等
  915. if det.class_name == 'person' and det.confidence >= person_threshold:
  916. valid_persons.append(det)
  917. # 【关键修复】去重:按位置合并重叠的检测框
  918. # 如果两个检测框的中心距离小于阈值,只保留置信度更高的
  919. DEDUP_DISTANCE = 0.05 # 画面比例 5%
  920. dedup_persons = []
  921. for det in valid_persons:
  922. det_x = det.center[0] / frame_size[0]
  923. det_y = det.center[1] / frame_size[1]
  924. # 检查是否与已有人员重叠
  925. is_duplicate = False
  926. for i, existing in enumerate(dedup_persons):
  927. ex_x = existing.center[0] / frame_size[0]
  928. ex_y = existing.center[1] / frame_size[1]
  929. dist = math.sqrt((det_x - ex_x)**2 + (det_y - ex_y)**2)
  930. if dist < DEDUP_DISTANCE:
  931. # 重叠,保留置信度更高的
  932. is_duplicate = True
  933. if det.confidence > existing.confidence:
  934. dedup_persons[i] = det
  935. break
  936. if not is_duplicate:
  937. dedup_persons.append(det)
  938. if not dedup_persons:
  939. logger.debug(f"[配对保存] 无有效人员(阈值={person_threshold}),跳过批次创建")
  940. return
  941. logger.info(f"[配对保存] 检测结果去重: {len(valid_persons)} -> {len(dedup_persons)} 个人员")
  942. # 构建人员信息列表(只包含去重后的人员)
  943. persons = []
  944. self._person_ptz_index = {} # 重置索引映射
  945. for i, det in enumerate(dedup_persons):
  946. x_ratio = det.center[0] / frame_size[0]
  947. y_ratio = det.center[1] / frame_size[1]
  948. person_info = {
  949. 'track_id': det.track_id,
  950. 'position': (x_ratio, y_ratio),
  951. 'bbox': (det.bbox[0], det.bbox[1],
  952. det.bbox[0] + det.bbox[2],
  953. det.bbox[1] + det.bbox[3]),
  954. 'confidence': det.confidence
  955. }
  956. persons.append(person_info)
  957. self._person_ptz_index[det.track_id] = i
  958. # 创建新批次
  959. batch_id = self._paired_saver.start_new_batch(frame, persons)
  960. if batch_id:
  961. self._current_batch_id = batch_id
  962. logger.info(f"[配对保存] 创建批次: {batch_id}, 有效人员={len(persons)}/{len(detections)}")
  963. def _save_ptz_image_for_person(self, track_id: int,
  964. ptz_frame: np.ndarray,
  965. ptz_position: Tuple[float, float, int]):
  966. """
  967. 保存球机聚焦图片到对应批次
  968. Args:
  969. track_id: 人员跟踪ID
  970. ptz_frame: 球机帧
  971. ptz_position: PTZ位置 (pan, tilt, zoom)
  972. """
  973. if (self._paired_saver is None or
  974. self._current_batch_id is None or
  975. track_id not in self._person_ptz_index):
  976. return
  977. person_index = self._person_ptz_index[track_id]
  978. self._paired_saver.save_ptz_image(
  979. batch_id=self._current_batch_id,
  980. person_index=person_index,
  981. ptz_frame=ptz_frame,
  982. ptz_position=ptz_position,
  983. ptz_bbox=getattr(self, '_last_ptz_bbox', None)
  984. )
  985. def _save_ptz_image_for_person_batch(self, batch_id: str, person_index: int,
  986. ptz_frame: np.ndarray,
  987. ptz_position: Tuple[float, float, int]):
  988. """
  989. 保存球机聚焦图片到指定批次(直接使用 batch_id,不依赖当前批次)
  990. Args:
  991. batch_id: 批次ID
  992. person_index: 人员序号
  993. ptz_frame: 球机帧
  994. ptz_position: PTZ位置 (pan, tilt, zoom)
  995. """
  996. if self._paired_saver is None:
  997. return
  998. self._paired_saver.save_ptz_image(
  999. batch_id=batch_id,
  1000. person_index=person_index,
  1001. ptz_frame=ptz_frame,
  1002. ptz_position=ptz_position,
  1003. ptz_bbox=getattr(self, '_last_ptz_bbox', None)
  1004. )
  1005. def _ptz_worker(self):
  1006. """PTZ控制线程:从队列接收命令并控制球机"""
  1007. while self.running:
  1008. try:
  1009. try:
  1010. cmd = self._ptz_queue.get(timeout=0.1)
  1011. except queue.Empty:
  1012. continue
  1013. # 执行PTZ命令(batch_id 和 person_index 已在命令中)
  1014. self._execute_ptz_command(cmd)
  1015. except Exception as e:
  1016. print(f"PTZ控制线程错误: {e}")
  1017. time.sleep(0.05)
  1018. def _select_tracking_target(self) -> Optional[TrackingTarget]:
  1019. """选择当前跟踪目标"""
  1020. with self.targets_lock:
  1021. if not self.tracking_targets:
  1022. self._set_state(TrackingState.IDLE)
  1023. self.current_target = None
  1024. return None
  1025. # 使用目标选择器选择最优目标
  1026. self.current_target = self.target_selector.select_target(
  1027. self.tracking_targets
  1028. )
  1029. return self.current_target
  1030. def _get_all_valid_targets(self) -> List[TrackingTarget]:
  1031. """
  1032. 获取所有有效的检测目标(用于多目标PTZ定位)
  1033. 返回按优先级排序的目标列表
  1034. """
  1035. with self.targets_lock:
  1036. if not self.tracking_targets:
  1037. self._set_state(TrackingState.IDLE)
  1038. self.current_target = None
  1039. return []
  1040. # 按得分排序所有目标
  1041. targets = list(self.tracking_targets.values())
  1042. targets.sort(key=lambda t: t.score, reverse=True)
  1043. if targets:
  1044. self._set_state(TrackingState.TRACKING)
  1045. self.current_target = targets[0] # 第一个作为当前目标
  1046. return targets
  1047. def _send_ptz_command(self, target: TrackingTarget, frame_size: Tuple[int, int]):
  1048. """将跟踪目标转化为PTZ命令放入队列"""
  1049. x_ratio, y_ratio = target.position
  1050. # 检查位置变化是否超过阈值
  1051. if self.last_ptz_position is not None:
  1052. last_x, last_y = self.last_ptz_position
  1053. if abs(x_ratio - last_x) < self.ptz_position_threshold and \
  1054. abs(y_ratio - last_y) < self.ptz_position_threshold:
  1055. return
  1056. # 冷却检查(线程安全)
  1057. current_time = time.time()
  1058. with self._last_ptz_time_lock:
  1059. if current_time - self._last_ptz_time < self.PTZ_COMMAND_COOLDOWN:
  1060. return
  1061. cmd = PTZCommand(
  1062. pan=0, tilt=0, zoom=0,
  1063. x_ratio=x_ratio, y_ratio=y_ratio,
  1064. use_calibration=self.enable_calibration
  1065. )
  1066. try:
  1067. self._ptz_queue.put_nowait(cmd)
  1068. self.last_ptz_position = (x_ratio, y_ratio)
  1069. except queue.Full:
  1070. pass # 丢弃命令,下一个检测周期会重发
  1071. def _send_ptz_command_with_log(self, target: TrackingTarget, frame_size: Tuple[int, int]):
  1072. """发送PTZ命令并打印日志"""
  1073. x_ratio, y_ratio = target.position
  1074. # 冷却检查(线程安全)
  1075. current_time = time.time()
  1076. with self._last_ptz_time_lock:
  1077. if current_time - self._last_ptz_time < self.PTZ_COMMAND_COOLDOWN:
  1078. return
  1079. # 位置变化阈值检查
  1080. if self.last_ptz_position is not None:
  1081. last_x, last_y = self.last_ptz_position
  1082. if abs(x_ratio - last_x) < self.ptz_position_threshold and \
  1083. abs(y_ratio - last_y) < self.ptz_position_threshold:
  1084. return
  1085. # 计算PTZ角度(用于日志)
  1086. if self.enable_calibration and self.calibrator and self.calibrator.is_calibrated():
  1087. pan, tilt = self.calibrator.transform(x_ratio, y_ratio)
  1088. zoom = self.ptz.ptz_config.get('default_zoom', 8)
  1089. coord_type = "校准坐标"
  1090. else:
  1091. pan, tilt, zoom = self.ptz.calculate_ptz_position(x_ratio, y_ratio)
  1092. coord_type = "估算坐标"
  1093. # 获取当前批次信息和人员序号
  1094. batch_id = self._current_batch_id if self._enable_paired_saving else None
  1095. person_index = self._person_ptz_index.get(target.track_id, -1) if self._enable_paired_saving else -1
  1096. cmd = PTZCommand(
  1097. pan=0, tilt=0, zoom=0,
  1098. x_ratio=x_ratio, y_ratio=y_ratio,
  1099. use_calibration=self.enable_calibration,
  1100. track_id=target.track_id, # 传递跟踪ID
  1101. batch_id=batch_id, # 传递批次ID
  1102. person_index=person_index # 传递人员序号
  1103. )
  1104. try:
  1105. self._ptz_queue.put_nowait(cmd)
  1106. self.last_ptz_position = (x_ratio, y_ratio) # 更新位置记录
  1107. self._update_stats('ptz_commands_sent' if 'ptz_commands_sent' in self.stats else 'persons_detected')
  1108. logger.info(
  1109. f"[PTZ] 命令已发送: 目标ID={target.track_id} "
  1110. f"全景位置=({x_ratio:.3f}, {y_ratio:.3f}) → "
  1111. f"PTZ角度=(pan={pan:.1f}°, tilt={tilt:.1f}°, zoom={zoom}) [{coord_type}]"
  1112. )
  1113. except queue.Full:
  1114. logger.warning("[PTZ] 命令队列满,丢弃本次命令")
  1115. def _execute_ptz_command(self, cmd: PTZCommand):
  1116. """
  1117. 执行PTZ命令(在PTZ线程中)
  1118. Args:
  1119. cmd: PTZ命令(包含 batch_id, person_index, track_id 用于配对保存)
  1120. """
  1121. # 更新最后执行时间(线程安全)
  1122. with self._last_ptz_time_lock:
  1123. self._last_ptz_time = time.time()
  1124. # 从命令中提取配对保存相关信息
  1125. track_id = cmd.track_id
  1126. batch_id = cmd.batch_id
  1127. person_index = cmd.person_index
  1128. if cmd.use_calibration and self.calibrator and self.calibrator.is_calibrated():
  1129. pan, tilt = self.calibrator.transform(cmd.x_ratio, cmd.y_ratio)
  1130. if self.ptz.ptz_config.get('pan_flip', False):
  1131. pan = (pan + 180) % 360
  1132. zoom = self.ptz.ptz_config.get('default_zoom', 8)
  1133. else:
  1134. pan, tilt, zoom = self.ptz.calculate_ptz_position(cmd.x_ratio, cmd.y_ratio)
  1135. self._set_state(TrackingState.TRACKING)
  1136. logger.info(
  1137. f"[PTZ] 执行: pan={pan:.1f}° tilt={tilt:.1f}° zoom={zoom} "
  1138. f"(全景位置=({cmd.x_ratio:.3f}, {cmd.y_ratio:.3f}), "
  1139. f"batch={batch_id}, person={person_index})"
  1140. )
  1141. success = self.ptz.goto_exact_position(pan, tilt, zoom)
  1142. if success:
  1143. # 等待球机物理移动到位(增加额外等待确保画面清晰)
  1144. time.sleep(self.PTZ_CONFIRM_WAIT)
  1145. # 球机端人体检测与自动对焦
  1146. final_pan, final_tilt, final_zoom = pan, tilt, zoom
  1147. if self.enable_ptz_detection and self.auto_zoom_config.get('enabled', False):
  1148. auto_zoom_result = self._auto_zoom_person(pan, tilt, zoom)
  1149. if auto_zoom_result != zoom:
  1150. final_zoom = auto_zoom_result
  1151. # 自动变焦后再次等待画面稳定
  1152. time.sleep(0.5)
  1153. # 获取清晰的球机画面(尝试多次获取最新帧)
  1154. ptz_frame = self._get_clear_ptz_frame()
  1155. # 保存球机图片到配对批次(使用命令中的 batch_id 和 person_index)
  1156. if self._enable_paired_saving and batch_id is not None and person_index >= 0 and ptz_frame is not None:
  1157. # 使用球机端检测器检测人体并标记
  1158. ptz_frame_marked = self._mark_ptz_frame_with_detection(ptz_frame, person_index=person_index)
  1159. self._save_ptz_image_for_person_batch(batch_id, person_index, ptz_frame_marked, (final_pan, final_tilt, final_zoom))
  1160. elif self._enable_paired_saving:
  1161. logger.warning(f"[配对保存] 跳过球机图保存: batch_id={batch_id}, person_index={person_index}, frame={ptz_frame is not None}")
  1162. logger.info(f"[PTZ] 到位确认完成: pan={final_pan:.1f}° tilt={final_tilt:.1f}° zoom={final_zoom}")
  1163. else:
  1164. logger.warning(f"[PTZ] 命令执行失败: pan={pan:.1f}° tilt={tilt:.1f}° zoom={zoom}")
  1165. def _auto_zoom_person(self, initial_pan: float, initial_tilt: float, initial_zoom: int) -> int:
  1166. """
  1167. 自动对焦人体
  1168. 在球机画面中检测人体,自动调整zoom使人体居中且大小合适
  1169. Returns:
  1170. 最终的 zoom 值
  1171. """
  1172. if self.auto_zoom_controller is None:
  1173. return initial_zoom
  1174. logger.info("[AutoZoom] 开始自动对焦...")
  1175. try:
  1176. success, final_zoom = self.auto_zoom_controller.auto_focus_loop(
  1177. get_frame_func=self.ptz.get_frame,
  1178. max_attempts=self.auto_zoom_config.get('max_adjust_attempts', 3)
  1179. )
  1180. if success:
  1181. logger.info(f"[AutoZoom] 自动对焦成功: zoom={final_zoom}")
  1182. return final_zoom
  1183. else:
  1184. logger.warning("[AutoZoom] 自动对焦未能定位人体")
  1185. return initial_zoom
  1186. except Exception as e:
  1187. logger.error(f"[AutoZoom] 自动对焦异常: {e}")
  1188. return initial_zoom
  1189. def _get_clear_ptz_frame(self, max_attempts: int = 5, wait_interval: float = 0.1) -> Optional[np.ndarray]:
  1190. """
  1191. 获取清晰的球机画面
  1192. 尝试多次获取,丢弃模糊/过渡帧
  1193. Args:
  1194. max_attempts: 最大尝试次数
  1195. wait_interval: 每次等待间隔
  1196. Returns:
  1197. 清晰的球机帧或 None
  1198. """
  1199. best_frame = None
  1200. best_score = -1
  1201. for i in range(max_attempts):
  1202. frame = self.ptz.get_frame()
  1203. if frame is not None:
  1204. # 使用拉普拉斯算子评估图像清晰度
  1205. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  1206. laplacian_var = cv2.Laplacian(gray, cv2.CV_64F).var()
  1207. if laplacian_var > best_score:
  1208. best_score = laplacian_var
  1209. best_frame = frame.copy()
  1210. # 如果清晰度足够高,直接返回
  1211. if laplacian_var > 100: # 清晰度阈值
  1212. return frame
  1213. time.sleep(wait_interval)
  1214. return best_frame
  1215. def _mark_ptz_frame_with_detection(self, frame: np.ndarray, person_index: int) -> np.ndarray:
  1216. """
  1217. 在球机帧上标记检测到的人体
  1218. Args:
  1219. frame: 球机帧
  1220. person_index: 人员序号
  1221. Returns:
  1222. 标记后的帧
  1223. """
  1224. marked_frame = frame.copy()
  1225. h, w = marked_frame.shape[:2]
  1226. # 重置保存的bbox
  1227. self._last_ptz_bbox = None
  1228. # 使用球机端检测器检测人体
  1229. if self.ptz_detector is not None:
  1230. try:
  1231. persons = self.ptz_detector.detect(frame)
  1232. if persons:
  1233. # 找到最大的人体(假设是目标)
  1234. largest_person = max(persons, key=lambda p: p.area)
  1235. x1, y1, x2, y2 = largest_person.bbox
  1236. # 保存bbox供后续使用
  1237. self._last_ptz_bbox = (x1, y1, x2, y2)
  1238. # 绘制边界框(红色,区别于全景的绿色)
  1239. cv2.rectangle(marked_frame, (x1, y1), (x2, y2), (0, 0, 255), 2)
  1240. # 绘制标签
  1241. label = f"person_{person_index} ({largest_person.confidence:.2f})"
  1242. (label_w, label_h), _ = cv2.getTextSize(
  1243. label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2
  1244. )
  1245. # 标签背景(红色)
  1246. cv2.rectangle(
  1247. marked_frame,
  1248. (x1, y1 - label_h - 8),
  1249. (x1 + label_w, y1),
  1250. (0, 0, 255),
  1251. -1
  1252. )
  1253. # 标签文字(白色)
  1254. cv2.putText(
  1255. marked_frame, label,
  1256. (x1, y1 - 4),
  1257. cv2.FONT_HERSHEY_SIMPLEX, 0.7,
  1258. (255, 255, 255), 2
  1259. )
  1260. logger.info(f"[配对保存] 球机图标记: person_{person_index}, "
  1261. f"位置=({x1},{y1},{x2},{y2}), 置信度={largest_person.confidence:.2f}")
  1262. else:
  1263. # 未检测到人体,在画面中心添加提示
  1264. cv2.putText(
  1265. marked_frame, f"person_{person_index} (no detection)",
  1266. (w // 2 - 100, h // 2),
  1267. cv2.FONT_HERSHEY_SIMPLEX, 0.8,
  1268. (0, 0, 255), 2
  1269. )
  1270. except Exception as e:
  1271. logger.error(f"[配对保存] 球机图检测标记失败: {e}")
  1272. return marked_frame
  1273. def _confirm_ptz_position(self, x_ratio: float, y_ratio: float):
  1274. """PTZ位置确认:读取球机帧验证目标是否可见"""
  1275. if not hasattr(self.ptz, 'get_frame') or self.ptz.get_frame() is None:
  1276. return
  1277. ptz_frame = self.ptz.get_frame()
  1278. if ptz_frame is None:
  1279. return
  1280. # 未来可以在这里添加球机帧目标验证逻辑
  1281. # 例如:在球机帧中检测目标是否在画面中心附近
  1282. def on_ptz_confirmed(self, callback: Callable):
  1283. """注册PTZ位置确认回调"""
  1284. self._on_ptz_confirmed = callback
  1285. class SequentialCoordinator(AsyncCoordinator):
  1286. """
  1287. 顺序联动控制器 — 全景检测→逐个PTZ抓拍→回到全景的循环模式
  1288. 工作流程:
  1289. 1. 全景摄像头检测人员
  1290. 2. 检测到人员后,暂停全景检测
  1291. 3. 球机依次对每个检测到的人员进行PTZ定位+变焦抓拍
  1292. 4. 所有人员抓拍完成后,球机回到默认位置
  1293. 5. 恢复全景检测,进入下一轮循环
  1294. 适用于需要高质量抓拍的场景,确保每个目标都能被球机清晰拍摄
  1295. """
  1296. def __init__(self, *args, **kwargs):
  1297. super().__init__(*args, **kwargs)
  1298. # 顺序抓拍状态
  1299. self._capture_state = 'idle' # 'idle', 'detecting', 'capturing', 'returning'
  1300. self._capture_state_lock = threading.Lock()
  1301. # 当前批次检测到的目标
  1302. self._batch_targets: List[TrackingTarget] = []
  1303. self._batch_targets_lock = threading.Lock()
  1304. self._current_capture_index = 0
  1305. # 抓拍完成事件(用于同步)
  1306. self._capture_done_event = threading.Event()
  1307. # 配置参数
  1308. self._capture_config = {
  1309. 'ptz_stabilize_time': 1.0, # PTZ到位后稳定等待时间
  1310. 'capture_wait_time': 0.5, # 抓拍等待时间
  1311. 'return_to_panorama': True, # 完成后是否回到全景默认位置
  1312. 'default_pan': 0.0, # 默认pan角度
  1313. 'default_tilt': 0.0, # 默认tilt角度
  1314. 'default_zoom': 1, # 默认zoom(广角)
  1315. }
  1316. # 覆盖父类的PTZ冷却时间(顺序模式下可以更短)
  1317. self.PTZ_COMMAND_COOLDOWN = 0.1
  1318. logger.info("[SequentialCoordinator] 顺序联动控制器初始化完成")
  1319. def _detection_worker(self):
  1320. """检测线程:顺序模式下的检测逻辑"""
  1321. # 从 DETECTION_CONFIG 获取检测帧率,默认每秒2帧
  1322. detection_fps = self.config.get('detection_fps', DETECTION_CONFIG.get('detection_fps', 2))
  1323. detection_interval = 1.0 / detection_fps
  1324. last_detection_time = 0
  1325. frame_count = 0
  1326. last_log_time = time.time()
  1327. log_interval = 5.0
  1328. detection_run_count = 0
  1329. detection_person_count = 0
  1330. last_no_detect_log_time = 0
  1331. no_detect_log_interval = 30.0
  1332. with self.stats_lock:
  1333. self.stats['start_time'] = time.time()
  1334. if self.detector is None:
  1335. logger.warning("[检测线程] ⚠️ 人体检测器未初始化!")
  1336. else:
  1337. logger.info(f"[检测线程] ✓ 顺序模式已就绪, 检测帧率={detection_fps}fps")
  1338. while self.running:
  1339. try:
  1340. current_time = time.time()
  1341. # 获取当前帧
  1342. frame = self.panorama.get_frame()
  1343. if frame is None:
  1344. time.sleep(0.01)
  1345. continue
  1346. frame_count += 1
  1347. self._update_stats('frames_processed')
  1348. frame_size = (frame.shape[1], frame.shape[0])
  1349. # 日志输出
  1350. if current_time - last_log_time >= log_interval:
  1351. elapsed = current_time - last_log_time
  1352. fps = frame_count / elapsed if elapsed > 0 else 0
  1353. state_str = self._get_capture_state()
  1354. logger.info(f"[检测线程] 帧率={fps:.1f}fps, 状态={state_str}, "
  1355. f"检测轮次={detection_run_count}(有人={detection_person_count})")
  1356. frame_count = 0
  1357. last_log_time = current_time
  1358. # 状态机处理
  1359. state = self._get_capture_state()
  1360. if state == 'idle':
  1361. # 【关键修复】每轮检测开始前清空跟踪目标,防止跨帧累积
  1362. with self.targets_lock:
  1363. if self.tracking_targets:
  1364. logger.debug(f"[顺序模式] 清空上一轮跟踪目标: {len(self.tracking_targets)} 个")
  1365. self.tracking_targets.clear()
  1366. # 空闲状态:周期性检测
  1367. if current_time - last_detection_time >= detection_interval:
  1368. last_detection_time = current_time
  1369. detection_run_count += 1
  1370. # 执行检测
  1371. detections = self._detect_persons(frame)
  1372. if detections:
  1373. self._update_stats('persons_detected', len(detections))
  1374. detection_person_count += 1
  1375. # 更新跟踪目标
  1376. self._update_tracking_targets(detections, frame_size)
  1377. # 获取有效目标列表
  1378. targets = self._get_all_valid_targets()
  1379. if targets:
  1380. logger.info(f"[顺序模式] 检测到 {len(targets)} 个目标,开始顺序抓拍")
  1381. # 创建配对保存批次
  1382. if self._enable_paired_saving and self._paired_saver is not None:
  1383. self._create_detection_batch(frame, detections, frame_size)
  1384. # 切换到抓拍状态
  1385. self._start_capture_sequence(targets)
  1386. else:
  1387. # 未检测到人员
  1388. if current_time - last_no_detect_log_time >= no_detect_log_interval:
  1389. logger.info(f"[检测] 本轮未检测到人员 (累计{detection_run_count}轮)")
  1390. last_no_detect_log_time = current_time
  1391. elif state == 'capturing':
  1392. # 抓拍状态中:检测线程等待,不执行新检测
  1393. # 等待PTZ线程完成当前批次
  1394. pass
  1395. elif state == 'returning':
  1396. # 球机回到默认位置中
  1397. pass
  1398. # 清理过期目标
  1399. self._cleanup_expired_targets()
  1400. time.sleep(0.01)
  1401. except Exception as e:
  1402. logger.error(f"[检测线程] 错误: {e}")
  1403. time.sleep(0.1)
  1404. def _ptz_worker(self):
  1405. """PTZ控制线程:顺序模式下的PTZ控制逻辑"""
  1406. logger.info("[PTZ线程] 顺序模式PTZ控制线程启动")
  1407. while self.running:
  1408. try:
  1409. state = self._get_capture_state()
  1410. if state == 'capturing':
  1411. # 执行顺序抓拍
  1412. self._execute_sequential_capture()
  1413. elif state == 'returning':
  1414. # 回到默认位置
  1415. self._return_to_default_position()
  1416. time.sleep(0.05)
  1417. except Exception as e:
  1418. logger.error(f"[PTZ线程] 错误: {e}")
  1419. time.sleep(0.1)
  1420. def _get_capture_state(self) -> str:
  1421. """获取当前抓拍状态"""
  1422. with self._capture_state_lock:
  1423. return self._capture_state
  1424. def _set_capture_state(self, state: str):
  1425. """设置抓拍状态"""
  1426. with self._capture_state_lock:
  1427. old_state = self._capture_state
  1428. self._capture_state = state
  1429. logger.info(f"[顺序模式] 状态切换: {old_state} -> {state}")
  1430. def _start_capture_sequence(self, targets: List[TrackingTarget]):
  1431. """开始顺序抓拍序列"""
  1432. with self._batch_targets_lock:
  1433. self._batch_targets = targets.copy()
  1434. self._current_capture_index = 0
  1435. self._set_capture_state('capturing')
  1436. def _execute_sequential_capture(self):
  1437. """执行顺序抓拍(依次对每个目标进行PTZ定位和抓拍)"""
  1438. with self._batch_targets_lock:
  1439. targets = self._batch_targets.copy()
  1440. current_idx = self._current_capture_index
  1441. if current_idx >= len(targets):
  1442. # 所有目标已抓拍完成
  1443. logger.info("[顺序模式] 所有目标抓拍完成")
  1444. self._set_capture_state('returning')
  1445. return
  1446. # 获取当前目标
  1447. target = targets[current_idx]
  1448. x_ratio, y_ratio = target.position
  1449. # 计算PTZ角度
  1450. if self.enable_calibration and self.calibrator and self.calibrator.is_calibrated():
  1451. pan, tilt = self.calibrator.transform(x_ratio, y_ratio)
  1452. if self.ptz.ptz_config.get('pan_flip', False):
  1453. pan = (pan + 180) % 360
  1454. zoom = self.ptz.ptz_config.get('default_zoom', 8)
  1455. coord_type = "校准坐标"
  1456. else:
  1457. pan, tilt, zoom = self.ptz.calculate_ptz_position(x_ratio, y_ratio)
  1458. coord_type = "估算坐标"
  1459. # 获取批次信息
  1460. batch_id = self._current_batch_id if self._enable_paired_saving else None
  1461. person_index = current_idx # 使用当前索引作为人员序号
  1462. logger.info(f"[顺序模式] 抓拍目标 {current_idx + 1}/{len(targets)}: "
  1463. f"位置=({x_ratio:.3f}, {y_ratio:.3f}) -> "
  1464. f"PTZ=({pan:.1f}°, {tilt:.1f}°, zoom={zoom}) [{coord_type}]")
  1465. # 执行PTZ移动
  1466. self._set_state(TrackingState.TRACKING)
  1467. success = self.ptz.goto_exact_position(pan, tilt, zoom)
  1468. if success:
  1469. # 等待球机稳定
  1470. stabilize_time = self._capture_config['ptz_stabilize_time']
  1471. logger.info(f"[顺序模式] 等待球机稳定 {stabilize_time}s...")
  1472. time.sleep(stabilize_time)
  1473. # 自动变焦(如果启用)
  1474. final_zoom = zoom
  1475. if self.enable_ptz_detection and self.auto_zoom_config.get('enabled', False):
  1476. auto_zoom_result = self._auto_zoom_person(pan, tilt, zoom)
  1477. if auto_zoom_result != zoom:
  1478. final_zoom = auto_zoom_result
  1479. time.sleep(0.5) # 变焦后再次等待
  1480. # 获取清晰的球机画面
  1481. ptz_frame = self._get_clear_ptz_frame()
  1482. if ptz_frame is not None:
  1483. # 保存球机图片
  1484. if self._enable_paired_saving and batch_id is not None:
  1485. ptz_frame_marked = self._mark_ptz_frame_with_detection(ptz_frame, person_index=person_index)
  1486. self._save_ptz_image_for_person_batch(
  1487. batch_id, person_index, ptz_frame_marked,
  1488. (pan, tilt, final_zoom)
  1489. )
  1490. # 保存到本地(无论是否启用配对保存)
  1491. self._save_local_snapshot(ptz_frame, current_idx, pan, tilt, final_zoom)
  1492. logger.info(f"[顺序模式] 目标 {current_idx + 1} 抓拍完成")
  1493. else:
  1494. logger.warning(f"[顺序模式] 获取球机画面失败")
  1495. else:
  1496. logger.warning(f"[顺序模式] PTZ移动失败")
  1497. # 移动到下一个目标
  1498. with self._batch_targets_lock:
  1499. self._current_capture_index += 1
  1500. # 抓拍间隔
  1501. time.sleep(self._capture_config['capture_wait_time'])
  1502. def _return_to_default_position(self):
  1503. """球机回到默认位置(广角全景)"""
  1504. if not self._capture_config['return_to_panorama']:
  1505. # 不回到默认位置,直接回到空闲状态
  1506. self._set_capture_state('idle')
  1507. return
  1508. default_pan = self._capture_config['default_pan']
  1509. default_tilt = self._capture_config['default_tilt']
  1510. default_zoom = self._capture_config['default_zoom']
  1511. logger.info(f"[顺序模式] 球机回到默认位置: ({default_pan}°, {default_tilt}°, zoom={default_zoom})")
  1512. success = self.ptz.goto_exact_position(default_pan, default_tilt, default_zoom)
  1513. if success:
  1514. # 等待到位
  1515. time.sleep(self._capture_config['ptz_stabilize_time'])
  1516. logger.info("[顺序模式] 球机已回到默认位置")
  1517. else:
  1518. logger.warning("[顺序模式] 球机回到默认位置失败")
  1519. # 回到空闲状态,恢复全景检测
  1520. self._set_capture_state('idle')
  1521. # 清空批次目标
  1522. with self._batch_targets_lock:
  1523. self._batch_targets = []
  1524. self._current_capture_index = 0
  1525. # 【关键修复】清空跟踪目标,防止跨帧累积
  1526. with self.targets_lock:
  1527. self.tracking_targets.clear()
  1528. logger.info("[顺序模式] 已清空跟踪目标列表")
  1529. def _save_local_snapshot(self, frame: np.ndarray, index: int,
  1530. pan: float, tilt: float, zoom: int):
  1531. """保存本地快照"""
  1532. try:
  1533. import os
  1534. from datetime import datetime
  1535. # 创建保存目录
  1536. save_dir = '/home/admin/dsh/captures'
  1537. os.makedirs(save_dir, exist_ok=True)
  1538. # 生成文件名
  1539. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
  1540. filename = f"capture_{timestamp}_person{index}_p{int(pan)}_t{int(tilt)}_z{zoom}.jpg"
  1541. filepath = os.path.join(save_dir, filename)
  1542. # 保存图片
  1543. cv2.imwrite(filepath, frame, [cv2.IMWRITE_JPEG_QUALITY, 90])
  1544. logger.info(f"[顺序模式] 快照已保存: {filepath}")
  1545. except Exception as e:
  1546. logger.error(f"[顺序模式] 保存快照失败: {e}")
  1547. def set_capture_config(self, **kwargs):
  1548. """设置抓拍配置"""
  1549. self._capture_config.update(kwargs)
  1550. logger.info(f"[顺序模式] 配置已更新: {kwargs}")
  1551. def get_capture_status(self) -> dict:
  1552. """获取当前抓拍状态"""
  1553. with self._batch_targets_lock:
  1554. total = len(self._batch_targets)
  1555. current = self._current_capture_index
  1556. return {
  1557. 'state': self._get_capture_state(),
  1558. 'total_targets': total,
  1559. 'current_index': current,
  1560. 'remaining': max(0, total - current)
  1561. }