coordinator.py 83 KB

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