calibration.py 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  1. """
  2. 相机校准模块
  3. 实现全景相机与球机的自动校准
  4. 建立画面坐标到PTZ角度的映射关系
  5. 核心改进:先发现视野重叠区域,再在重叠区内校准,
  6. 避免球机指向与全景画面无重叠的方向导致校准失败。
  7. """
  8. import time
  9. import math
  10. import threading
  11. import logging
  12. import numpy as np
  13. import cv2
  14. from typing import List, Tuple, Dict, Optional, Callable
  15. from dataclasses import dataclass, field
  16. from enum import Enum
  17. from ptz_camera import PTZCamera
  18. logger = logging.getLogger(__name__)
  19. # 加载PTZ配置
  20. def _get_ptz_config():
  21. try:
  22. from config import PTZ_CONFIG
  23. return PTZ_CONFIG
  24. except ImportError:
  25. return {
  26. 'mount_type': 'wall',
  27. 'tilt_flip': False,
  28. 'pan_flip': False
  29. }
  30. class CalibrationState(Enum):
  31. IDLE = 0
  32. RUNNING = 1
  33. SUCCESS = 2
  34. FAILED = 3
  35. @dataclass
  36. class CalibrationPoint:
  37. pan: float
  38. tilt: float
  39. zoom: float = 1.0
  40. x_ratio: float = 0.0
  41. y_ratio: float = 0.0
  42. detected: bool = False
  43. match_count: int = 0
  44. @dataclass
  45. class CalibrationResult:
  46. success: bool
  47. points: List[CalibrationPoint]
  48. transform_matrix: Optional[np.ndarray] = None
  49. error_message: str = ""
  50. rms_error: float = 0.0
  51. @dataclass
  52. class OverlapRange:
  53. pan_start: float
  54. pan_end: float
  55. tilt_start: float
  56. tilt_end: float
  57. match_count: int
  58. panorama_center_x: float
  59. panorama_center_y: float
  60. MIN_MATCH_THRESHOLD = 8
  61. class OverlapDiscovery:
  62. """
  63. 视野重叠发现器
  64. 扫描球机视野范围,找出与全景画面有视觉重叠的角度区间
  65. """
  66. def __init__(self, feature_type: str = 'SIFT'):
  67. try:
  68. self.feature_detector = cv2.SIFT_create()
  69. self.feature_type = 'SIFT'
  70. except AttributeError:
  71. self.feature_detector = cv2.ORB_create(nfeatures=500)
  72. self.feature_type = 'ORB'
  73. norm_type = cv2.NORM_L2 if self.feature_type == 'SIFT' else cv2.NORM_HAMMING
  74. self.matcher = cv2.BFMatcher(norm_type)
  75. def match_frames(self, ptz_frame: np.ndarray, panorama_frame: np.ndarray
  76. ) -> Tuple[bool, int, float, float]:
  77. """
  78. 特征匹配球机画面与全景画面
  79. Returns: (是否匹配成功, 匹配点数, 全景画面中心x, 全景画面中心y)
  80. """
  81. if ptz_frame is None or panorama_frame is None:
  82. return (False, 0, 0.0, 0.0)
  83. try:
  84. ptz_gray = cv2.cvtColor(ptz_frame, cv2.COLOR_BGR2GRAY) if len(ptz_frame.shape) == 3 else ptz_frame
  85. pan_gray = cv2.cvtColor(panorama_frame, cv2.COLOR_BGR2GRAY) if len(panorama_frame.shape) == 3 else panorama_frame
  86. # 缩小图像加速特征提取(匹配坐标按比例还原)
  87. ptz_scale = 1.0
  88. pan_scale = 1.0
  89. max_dim = 960
  90. if ptz_gray.shape[1] > max_dim:
  91. ptz_scale = max_dim / ptz_gray.shape[1]
  92. ptz_gray = cv2.resize(ptz_gray, None, fx=ptz_scale, fy=ptz_scale,
  93. interpolation=cv2.INTER_AREA)
  94. if pan_gray.shape[1] > max_dim:
  95. pan_scale = max_dim / pan_gray.shape[1]
  96. pan_gray = cv2.resize(pan_gray, None, fx=pan_scale, fy=pan_scale,
  97. interpolation=cv2.INTER_AREA)
  98. kp1, des1 = self.feature_detector.detectAndCompute(ptz_gray, None)
  99. kp2, des2 = self.feature_detector.detectAndCompute(pan_gray, None)
  100. if des1 is None or des2 is None or len(kp1) < 4 or len(kp2) < 4:
  101. return (False, 0, 0.0, 0.0)
  102. matches = self.matcher.knnMatch(des1, des2, k=2)
  103. good_matches = []
  104. for match_pair in matches:
  105. if len(match_pair) == 2:
  106. m, n = match_pair
  107. if m.distance < 0.75 * n.distance:
  108. good_matches.append(m)
  109. if len(good_matches) < MIN_MATCH_THRESHOLD:
  110. return (False, len(good_matches), 0.0, 0.0)
  111. pan_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches])
  112. # 还原到原始图像坐标系
  113. center_x = np.mean(pan_pts[:, 0]) / pan_scale
  114. center_y = np.mean(pan_pts[:, 1]) / pan_scale
  115. return (True, len(good_matches), center_x, center_y)
  116. except Exception as e:
  117. logger.error(f"特征匹配异常: {e}")
  118. return (False, 0, 0.0, 0.0)
  119. def discover_overlap_ranges(
  120. self,
  121. ptz: PTZCamera,
  122. get_panorama_frame: Callable[[], np.ndarray],
  123. ptz_capture: Callable[[], Optional[np.ndarray]],
  124. pan_range: Tuple[float, float] = (0, 360),
  125. tilt_range: Tuple[float, float] = (-20, 40),
  126. pan_step: float = 20,
  127. tilt_step: float = 15,
  128. stabilize_time: float = 2.0,
  129. on_progress: Callable[[int, int, str], None] = None,
  130. max_ranges: int = 3,
  131. min_positions_per_range: int = 3
  132. ) -> List[OverlapRange]:
  133. """
  134. 扫描球机视野范围,发现与全景画面有重叠的角度区间
  135. 1. 先拍一张全景参考帧
  136. 2. 逐步移动球机到各个角度
  137. 3. 在每个位置抓拍球机画面,与全景做特征匹配
  138. 4. 记录有足够匹配点的角度
  139. 5. 合并相邻的有重叠的角度形成区间
  140. """
  141. logger.info(f"阶段1: 视野重叠发现, 扫描范围: pan={pan_range}, tilt={tilt_range}, 步进: pan={pan_step}°, tilt={tilt_step}°")
  142. # 1. 拍全景参考帧
  143. logger.info("获取全景参考帧...")
  144. ref_frames = []
  145. for _ in range(3):
  146. frame = get_panorama_frame()
  147. if frame is not None:
  148. ref_frames.append(frame)
  149. time.sleep(0.1)
  150. if not ref_frames:
  151. logger.error("无法获取全景参考帧!")
  152. return []
  153. panorama_ref = ref_frames[0]
  154. logger.info(f"全景参考帧: {panorama_ref.shape}")
  155. # 2. 扫描各个角度
  156. scan_results: List[Tuple[float, float, int, float, float]] = []
  157. pan_values = np.arange(pan_range[0], pan_range[1] + pan_step, pan_step)
  158. tilt_values = np.arange(tilt_range[0], tilt_range[1] + tilt_step, tilt_step)
  159. total_positions = len(pan_values) * len(tilt_values)
  160. current_idx = 0
  161. for pan in pan_values:
  162. for tilt in tilt_values:
  163. current_idx += 1
  164. pos_desc = f"pan={pan:.0f}°, tilt={tilt:.0f}°"
  165. if on_progress:
  166. on_progress(current_idx, total_positions, f"扫描 {pos_desc}")
  167. logger.info(f"[{current_idx}/{total_positions}] {pos_desc}")
  168. # 移动球机
  169. if not ptz.goto_exact_position(float(pan), float(tilt), 1):
  170. logger.warning(f"移动球机失败, 跳过")
  171. continue
  172. time.sleep(stabilize_time)
  173. # 抓拍球机画面
  174. ptz_frame = ptz_capture() if ptz_capture else None
  175. if ptz_frame is None:
  176. logger.warning(f"球机抓拍失败, 跳过")
  177. continue
  178. # 获取当前全景帧并匹配
  179. cur_panorama = get_panorama_frame()
  180. if cur_panorama is None:
  181. continue
  182. success, match_count, cx, cy = self.match_frames(ptz_frame, cur_panorama)
  183. if success:
  184. h, w = cur_panorama.shape[:2]
  185. x_ratio = cx / w
  186. y_ratio = cy / h
  187. logger.info(f"匹配成功: {match_count}个特征点, 全景位置=({x_ratio:.3f}, {y_ratio:.3f})")
  188. scan_results.append((float(pan), float(tilt), match_count, x_ratio, y_ratio))
  189. else:
  190. logger.debug(f"匹配不足: {match_count}个特征点")
  191. if not scan_results:
  192. logger.warning("未发现任何视野重叠位置!")
  193. return []
  194. logger.info(f"发现 {len(scan_results)} 个有重叠的扫描位置")
  195. # 保存原始扫描结果供后续校准使用
  196. self.scan_results = scan_results
  197. # 3. 合并相邻位置为重叠区间
  198. overlap_ranges = self._merge_scan_results(
  199. scan_results,
  200. max_ranges=max_ranges,
  201. min_positions=min_positions_per_range
  202. )
  203. for i, r in enumerate(overlap_ranges):
  204. logger.info(f"重叠区间 {i+1}: pan=[{r.pan_start:.0f}°, {r.pan_end:.0f}°], "
  205. f"tilt=[{r.tilt_start:.0f}°, {r.tilt_end:.0f}°], "
  206. f"匹配点={r.match_count}")
  207. return overlap_ranges
  208. def _merge_scan_results(
  209. self,
  210. results: List[Tuple[float, float, int, float, float]],
  211. pan_tolerance: float = 20,
  212. tilt_tolerance: float = 35,
  213. max_ranges: int = 3,
  214. min_positions: int = 2
  215. ) -> List[OverlapRange]:
  216. """
  217. 使用union-find连通分量聚类合并相邻扫描结果
  218. 只保留最大的 max_ranges 个区间
  219. """
  220. if not results:
  221. return []
  222. n = len(results)
  223. # union-find
  224. parent = list(range(n))
  225. def find(x):
  226. while parent[x] != x:
  227. parent[x] = parent[parent[x]]
  228. x = parent[x]
  229. return x
  230. def union(a, b):
  231. ra, rb = find(a), find(b)
  232. if ra != rb:
  233. parent[ra] = rb
  234. # 判断两点是否相邻
  235. for i in range(n):
  236. for j in range(i + 1, n):
  237. pi, ti = results[i][0], results[i][1]
  238. pj, tj = results[j][0], results[j][1]
  239. if abs(pi - pj) <= pan_tolerance and abs(ti - tj) <= tilt_tolerance:
  240. union(i, j)
  241. # 按连通分量分组
  242. groups: Dict[int, List[int]] = {}
  243. for i in range(n):
  244. root = find(i)
  245. if root not in groups:
  246. groups[root] = []
  247. groups[root].append(i)
  248. # 转换为OverlapRange,过滤太小的组
  249. ranges = []
  250. for indices in groups.values():
  251. if len(indices) < min_positions:
  252. continue
  253. group_data = [results[i] for i in indices]
  254. ranges.append(self._group_to_range(group_data))
  255. # 按match_count降序排序,只保留最大的 max_ranges 个
  256. ranges.sort(key=lambda r: r.match_count, reverse=True)
  257. ranges = ranges[:max_ranges]
  258. # 按pan_start排序输出
  259. ranges.sort(key=lambda r: r.pan_start)
  260. return ranges
  261. def _group_to_range(self, group: List[Tuple[float, float, int, float, float]]) -> OverlapRange:
  262. """将一组扫描结果转换为一个OverlapRange"""
  263. pans = [r[0] for r in group]
  264. tilts = [r[1] for r in group]
  265. match_counts = [r[2] for r in group]
  266. x_ratios = [r[3] for r in group]
  267. y_ratios = [r[4] for r in group]
  268. step = 5 # 在边缘各扩展5度
  269. return OverlapRange(
  270. pan_start=min(pans) - step,
  271. pan_end=max(pans) + step,
  272. tilt_start=min(tilts) - step,
  273. tilt_end=max(tilts) + step,
  274. match_count=max(match_counts),
  275. panorama_center_x=float(np.mean(x_ratios)),
  276. panorama_center_y=float(np.mean(y_ratios))
  277. )
  278. class VisualCalibrationDetector:
  279. """
  280. 视觉校准检测器
  281. 通过运动检测和特征匹配定位球机在全景画面中的位置
  282. """
  283. def __init__(self):
  284. try:
  285. self.feature_detector = cv2.SIFT_create()
  286. self.feature_type = 'SIFT'
  287. except AttributeError:
  288. self.feature_detector = cv2.ORB_create(nfeatures=500)
  289. self.feature_type = 'ORB'
  290. self.matcher = cv2.BFMatcher(
  291. cv2.NORM_L2 if self.feature_type == 'SIFT' else cv2.NORM_HAMMING
  292. )
  293. self.use_motion_detection = True
  294. self.use_feature_matching = True
  295. def detect_by_motion(self, frames_before: np.ndarray,
  296. frames_after: np.ndarray) -> Optional[Tuple[float, float]]:
  297. """通过运动检测定位球机指向位置"""
  298. if frames_before is None or frames_after is None:
  299. return None
  300. before_gray = cv2.cvtColor(frames_before, cv2.COLOR_BGR2GRAY) \
  301. if len(frames_before.shape) == 3 else frames_before
  302. after_gray = cv2.cvtColor(frames_after, cv2.COLOR_BGR2GRAY) \
  303. if len(frames_after.shape) == 3 else frames_after
  304. diff = cv2.absdiff(before_gray, after_gray)
  305. _, thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)
  306. kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))
  307. thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
  308. thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
  309. contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  310. if not contours:
  311. return None
  312. max_contour = max(contours, key=cv2.contourArea)
  313. area = cv2.contourArea(max_contour)
  314. if area < 500:
  315. return None
  316. M = cv2.moments(max_contour)
  317. if M["m00"] == 0:
  318. return None
  319. cx = M["m10"] / M["m00"]
  320. cy = M["m01"] / M["m00"]
  321. h, w = before_gray.shape
  322. logger.debug(f"运动检测: 中心=({cx:.1f}, {cy:.1f}), 面积={area:.0f})")
  323. return (cx / w, cy / h)
  324. def detect_by_feature_match(self, panorama_frame: np.ndarray,
  325. ptz_frame: np.ndarray) -> Optional[Tuple[float, float]]:
  326. """通过特征匹配定位"""
  327. if panorama_frame is None or ptz_frame is None:
  328. return None
  329. try:
  330. pan_gray = cv2.cvtColor(panorama_frame, cv2.COLOR_BGR2GRAY) \
  331. if len(panorama_frame.shape) == 3 else panorama_frame
  332. ptz_gray = cv2.cvtColor(ptz_frame, cv2.COLOR_BGR2GRAY) \
  333. if len(ptz_frame.shape) == 3 else ptz_frame
  334. # 缩小图像加速
  335. max_dim = 960
  336. ptz_scale = 1.0
  337. pan_scale = 1.0
  338. if ptz_gray.shape[1] > max_dim:
  339. ptz_scale = max_dim / ptz_gray.shape[1]
  340. ptz_gray = cv2.resize(ptz_gray, None, fx=ptz_scale, fy=ptz_scale,
  341. interpolation=cv2.INTER_AREA)
  342. if pan_gray.shape[1] > max_dim:
  343. pan_scale = max_dim / pan_gray.shape[1]
  344. pan_gray = cv2.resize(pan_gray, None, fx=pan_scale, fy=pan_scale,
  345. interpolation=cv2.INTER_AREA)
  346. kp1, des1 = self.feature_detector.detectAndCompute(ptz_gray, None)
  347. kp2, des2 = self.feature_detector.detectAndCompute(pan_gray, None)
  348. if des1 is None or des2 is None or len(kp1) < 4 or len(kp2) < 4:
  349. return None
  350. matches = self.matcher.knnMatch(des1, des2, k=2)
  351. good_matches = []
  352. for match_pair in matches:
  353. if len(match_pair) == 2:
  354. m, n = match_pair
  355. if m.distance < 0.75 * n.distance:
  356. good_matches.append(m)
  357. if len(good_matches) < 4:
  358. return None
  359. pan_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches])
  360. center_x = np.mean(pan_pts[:, 0])
  361. center_y = np.mean(pan_pts[:, 1])
  362. h, w = pan_gray.shape
  363. logger.debug(f"特征匹配: 匹配点={len(good_matches)}, 中心=({center_x:.1f}, {center_y:.1f})")
  364. return (center_x / w, center_y / h)
  365. except Exception as e:
  366. logger.error(f"特征匹配错误: {e}")
  367. return None
  368. def detect_position(self, panorama_frame: np.ndarray,
  369. frames_before: np.ndarray = None,
  370. frames_after: np.ndarray = None,
  371. ptz_frame: np.ndarray = None) -> Tuple[bool, float, float]:
  372. """综合检测球机在全景画面中的位置"""
  373. results = []
  374. if self.use_motion_detection and frames_before is not None and frames_after is not None:
  375. motion_result = self.detect_by_motion(frames_before, frames_after)
  376. if motion_result:
  377. results.append(('motion', motion_result, 0.4))
  378. if self.use_feature_matching and ptz_frame is not None:
  379. feature_result = self.detect_by_feature_match(panorama_frame, ptz_frame)
  380. if feature_result:
  381. results.append(('feature', feature_result, 0.6))
  382. if not results:
  383. return (False, 0.0, 0.0)
  384. total_weight = sum(r[2] for r in results)
  385. x_ratio = sum(r[1][0] * r[2] for r in results) / total_weight
  386. y_ratio = sum(r[1][1] * r[2] for r in results) / total_weight
  387. logger.debug(f"融合结果: ({x_ratio:.3f}, {y_ratio:.3f})")
  388. return (True, x_ratio, y_ratio)
  389. class CameraCalibrator:
  390. """
  391. 相机校准器
  392. 两阶段校准:先发现视野重叠区域,再在重叠区内校准
  393. """
  394. def __init__(self, ptz_camera: PTZCamera,
  395. get_frame_func: Callable[[], np.ndarray],
  396. detect_marker_func: Callable[[np.ndarray], Optional[Tuple[float, float]]] = None,
  397. ptz_capture_func: Callable[[], Optional[np.ndarray]] = None):
  398. self.ptz = ptz_camera
  399. self.get_frame = get_frame_func
  400. self.detect_marker = detect_marker_func
  401. self.ptz_capture = ptz_capture_func
  402. self.visual_detector = VisualCalibrationDetector()
  403. self.overlap_discovery = OverlapDiscovery()
  404. self.state = CalibrationState.IDLE
  405. self.result: Optional[CalibrationResult] = None
  406. # 变换参数 (线性模型 - 作为后备)
  407. self.pan_offset = 0.0
  408. self.pan_scale_x = 1.0
  409. self.pan_scale_y = 0.0
  410. self.tilt_offset = 0.0
  411. self.tilt_scale_x = 0.0
  412. self.tilt_scale_y = 1.0
  413. # 分段线性查找表 (主变换方法)
  414. # 存储 x_ratio → pan 和 y_ratio → tilt 的映射
  415. self.pan_lookup: List[Tuple[float, float]] = [] # [(x_ratio, pan), ...] sorted by x_ratio
  416. self.tilt_lookup: List[Tuple[float, float]] = [] # [(y_ratio, tilt), ...] sorted by y_ratio
  417. # tilt偏移补偿(度),正值=向下补偿,从PTZ_CONFIG读取
  418. from config import PTZ_CONFIG
  419. self.tilt_offset_deg = PTZ_CONFIG.get('tilt_offset', 0)
  420. self.pan_offset_deg = PTZ_CONFIG.get('pan_offset', 0)
  421. self.pan_edge_offset = PTZ_CONFIG.get('pan_edge_offset', 0)
  422. self.pan_curve_power = PTZ_CONFIG.get('pan_curve_power', 1.0)
  423. # tilt线性映射(替代不稳定的查找表)
  424. self.tilt_linear_enabled = PTZ_CONFIG.get('tilt_linear_enabled', False)
  425. self.tilt_y0 = PTZ_CONFIG.get('tilt_y0', 0)
  426. self.tilt_y1 = PTZ_CONFIG.get('tilt_y1', 45)
  427. self.tilt_curve_power = PTZ_CONFIG.get('tilt_curve_power', 1.0)
  428. # 校准配置
  429. self.stabilize_time = 1.0
  430. self.use_motion_detection = True
  431. self.use_feature_matching = True
  432. # 重叠发现配置
  433. self.overlap_pan_range = (0, 360)
  434. self.overlap_tilt_range = (-20, 50)
  435. self.overlap_pan_step = 20
  436. self.overlap_tilt_step = 15
  437. self.max_overlap_ranges = 3
  438. self.min_positions_per_range = 3
  439. # 回调
  440. self.on_progress: Optional[Callable[[int, int, str], None]] = None
  441. self.on_complete: Optional[Callable[[CalibrationResult], None]] = None
  442. # 发现的重叠区间
  443. self.overlap_ranges: List[OverlapRange] = []
  444. def _angular_diff(self, a: float, b: float) -> float:
  445. """计算两个角度之间的最小差值,考虑360°环绕"""
  446. diff = a - b
  447. while diff > 180:
  448. diff -= 360
  449. while diff < -180:
  450. diff += 360
  451. return diff
  452. def _unwrap_pan_angles(self, pan_values: np.ndarray) -> np.ndarray:
  453. """
  454. 将pan角度展开为连续值,避免0°/360°边界的不连续性
  455. 使用中位数作为参考点,将所有角度调整到参考点的±180°范围内。
  456. 这样即使校准点跨越0°/360°边界,也能正确拟合线性变换。
  457. 例如: [350, 355, 5, 10] → [-10, -5, 5, 10] (ref=5)
  458. """
  459. if len(pan_values) == 0:
  460. return pan_values
  461. ref = float(np.median(pan_values))
  462. unwrapped = pan_values.astype(float).copy()
  463. for i in range(len(unwrapped)):
  464. diff = unwrapped[i] - ref
  465. while diff > 180:
  466. unwrapped[i] -= 360
  467. diff = unwrapped[i] - ref
  468. while diff < -180:
  469. unwrapped[i] += 360
  470. diff = unwrapped[i] - ref
  471. return unwrapped
  472. def calibrate(self, quick_mode: bool = True) -> CalibrationResult:
  473. """
  474. 执行校准 - 两阶段流程
  475. 阶段1: 视野重叠发现 - 扫描球机范围,找出与全景有重叠的角度区间
  476. 阶段2: 精确校准 - 仅在重叠区间内生成校准点,逐一验证后拟合变换
  477. """
  478. self.state = CalibrationState.RUNNING
  479. # ===================== 阶段1: 视野重叠发现 =====================
  480. logger.info("阶段1: 视野重叠发现 - 确定球机与全景的重叠区域")
  481. self.overlap_ranges = self.overlap_discovery.discover_overlap_ranges(
  482. ptz=self.ptz,
  483. get_panorama_frame=self.get_frame,
  484. ptz_capture=self.ptz_capture,
  485. pan_range=self.overlap_pan_range,
  486. tilt_range=self.overlap_tilt_range,
  487. pan_step=self.overlap_pan_step,
  488. tilt_step=self.overlap_tilt_step,
  489. stabilize_time=self.stabilize_time,
  490. on_progress=self.on_progress,
  491. max_ranges=self.max_overlap_ranges,
  492. min_positions_per_range=self.min_positions_per_range
  493. )
  494. if not self.overlap_ranges:
  495. self.state = CalibrationState.FAILED
  496. self.result = CalibrationResult(
  497. success=False,
  498. points=[],
  499. error_message="未发现球机与全景的视野重叠区域,无法校准。请检查两台摄像头的安装位置和朝向。"
  500. )
  501. logger.error(f"校准失败: {self.result.error_message}")
  502. if self.on_complete:
  503. self.on_complete(self.result)
  504. return self.result
  505. logger.info(f"发现 {len(self.overlap_ranges)} 个重叠区间")
  506. # 保留所有重叠区间用于校准(覆盖更广的视野范围)
  507. logger.info(f"使用全部 {len(self.overlap_ranges)} 个重叠区间进行校准(覆盖更广视野)")
  508. for i, r in enumerate(self.overlap_ranges):
  509. logger.info(f" 区间{i+1}: pan=[{r.pan_start:.0f}°, {r.pan_end:.0f}°], "
  510. f"tilt=[{r.tilt_start:.0f}°, {r.tilt_end:.0f}°], 匹配点={r.match_count}")
  511. # ===================== 阶段2: 使用阶段1扫描数据 + 补充校准 =====================
  512. # 阶段1已对整个视野扫描并记录了(pan, tilt) → (x_ratio, y_ratio)对应关系
  513. # 直接使用这些数据比阶段2重新在单个区间内采集更全面、更高效
  514. valid_points = []
  515. # 直接从阶段1扫描结果构建校准点
  516. scan_results = getattr(self.overlap_discovery, 'scan_results', [])
  517. if scan_results:
  518. logger.info(f"使用阶段1扫描数据: {len(scan_results)}个有效匹配位置")
  519. for pan, tilt, match_count, x_ratio, y_ratio in scan_results:
  520. valid_points.append(CalibrationPoint(
  521. pan=pan, tilt=tilt, zoom=1.0,
  522. x_ratio=x_ratio, y_ratio=y_ratio,
  523. detected=True, match_count=match_count
  524. ))
  525. else:
  526. logger.warning("阶段1无扫描数据,回退到阶段2逐点校准")
  527. # 如果扫描数据不足,补充在重叠区内采集更多点
  528. min_scan_points = 8
  529. if len(valid_points) < min_scan_points:
  530. logger.info(f"扫描数据不足({len(valid_points)}<{min_scan_points}),在重叠区间内补充采集")
  531. supplement_points = self._generate_points_in_overlaps(quick_mode)
  532. total_supplement = len(supplement_points)
  533. supplement_valid = 0
  534. for idx, point in enumerate(supplement_points):
  535. if self.on_progress:
  536. self.on_progress(idx + 1, total_supplement,
  537. f"补充校准点 {idx + 1}/{total_supplement}: pan={point.pan:.1f}°, tilt={point.tilt:.1f}°")
  538. logger.info(f"补充校准点 {idx + 1}/{total_supplement}: pan={point.pan:.1f}°, tilt={point.tilt:.1f}°")
  539. # 获取移动前全景帧
  540. frames_before_list = []
  541. for _ in range(3):
  542. frame = self.get_frame()
  543. if frame is not None:
  544. frames_before_list.append(frame)
  545. time.sleep(0.1)
  546. if not frames_before_list:
  547. continue
  548. frames_before = np.mean(frames_before_list, axis=0).astype(np.uint8)
  549. # 移动球机
  550. if not self.ptz.goto_exact_position(point.pan, point.tilt, 1):
  551. continue
  552. time.sleep(self.stabilize_time)
  553. # 获取移动后帧
  554. frames_after_list = []
  555. for _ in range(3):
  556. frame = self.get_frame()
  557. if frame is not None:
  558. frames_after_list.append(frame)
  559. time.sleep(0.1)
  560. if not frames_after_list:
  561. continue
  562. panorama_frame = np.mean(frames_after_list, axis=0).astype(np.uint8)
  563. # 球机抓拍
  564. ptz_frame = None
  565. if self.ptz_capture:
  566. try:
  567. ptz_frame = self.ptz_capture()
  568. except Exception:
  569. pass
  570. # 特征匹配验证
  571. if ptz_frame is not None and panorama_frame is not None:
  572. success, match_count, cx, cy = self.overlap_discovery.match_frames(ptz_frame, panorama_frame)
  573. if success:
  574. h, w = panorama_frame.shape[:2]
  575. point.x_ratio = cx / w
  576. point.y_ratio = cy / h
  577. point.detected = True
  578. valid_points.append(point)
  579. supplement_valid += 1
  580. logger.info(f"补充点验证通过: {match_count}个匹配点, "
  581. f"全景位置=({point.x_ratio:.3f}, {point.y_ratio:.3f})")
  582. continue
  583. # 运动检测备选
  584. if self.use_motion_detection and frames_before is not None and panorama_frame is not None:
  585. motion_result = self.visual_detector.detect_by_motion(frames_before, panorama_frame)
  586. if motion_result:
  587. point.x_ratio, point.y_ratio = motion_result
  588. point.detected = True
  589. valid_points.append(point)
  590. supplement_valid += 1
  591. logger.info(f"运动检测定位: ({point.x_ratio:.3f}, {point.y_ratio:.3f})")
  592. logger.info(f"补充采集: {supplement_valid}/{total_supplement} 个点验证通过")
  593. # ===================== 检查有效校准点 =====================
  594. min_valid = 4
  595. if len(valid_points) < min_valid:
  596. self.state = CalibrationState.FAILED
  597. self.result = CalibrationResult(
  598. success=False,
  599. points=valid_points,
  600. error_message=f"有效校准点不足 (需要至少{min_valid}个, 实际{len(valid_points)}个)。"
  601. f"请检查球机与全景的视野重叠是否足够。"
  602. )
  603. logger.error(f"校准失败: {self.result.error_message}")
  604. if self.on_complete:
  605. self.on_complete(self.result)
  606. return self.result
  607. # ===================== 计算变换参数 =====================
  608. success = self._calculate_transform(valid_points)
  609. if success:
  610. # 构建分段线性查找表(主变换方法,处理pan环绕)
  611. lookup_ok = self._build_lookup_tables(valid_points)
  612. self.state = CalibrationState.SUCCESS
  613. rms_error = self._calculate_rms_error(valid_points)
  614. self.result = CalibrationResult(
  615. success=True,
  616. points=valid_points,
  617. rms_error=rms_error
  618. )
  619. logger.info(f"校准成功! 有效校准点: {len(valid_points)}, "
  620. f"重叠区间数: {len(self.overlap_ranges)}, RMS误差: {rms_error:.4f}°")
  621. # 校准验证:将球机移到全景画面中心,检查是否指向正确位置
  622. verify_ok = self._verify_calibration()
  623. if not verify_ok:
  624. logger.warning("校准验证未通过,校准结果可能不准确")
  625. # 自动保存校准结果
  626. try:
  627. from config import CALIBRATION_CONFIG
  628. if CALIBRATION_CONFIG.get('auto_save', True):
  629. filepath = CALIBRATION_CONFIG.get('calibration_file', 'calibration.json')
  630. self.save_calibration(filepath)
  631. except Exception:
  632. pass
  633. # 校准完成后,将球机复位到初始位置
  634. self._reset_ptz_position()
  635. else:
  636. self.state = CalibrationState.FAILED
  637. self.result = CalibrationResult(
  638. success=False,
  639. points=valid_points,
  640. error_message="变换参数计算失败"
  641. )
  642. logger.error(f"校准失败: {self.result.error_message}")
  643. if self.on_complete:
  644. self.on_complete(self.result)
  645. return self.result
  646. def _reset_ptz_position(self):
  647. """校准完成后将球机复位到初始位置"""
  648. if self.ptz is None:
  649. return
  650. try:
  651. # 获取默认位置配置
  652. from config import PTZ_CONFIG
  653. default_pan = PTZ_CONFIG.get('default_pan', 0)
  654. default_tilt = PTZ_CONFIG.get('default_tilt', 0)
  655. default_zoom = PTZ_CONFIG.get('default_zoom', 1)
  656. logger.info(f"球机复位到位置: pan={default_pan}, tilt={default_tilt}, zoom={default_zoom}")
  657. self.ptz.goto_exact_position(default_pan, default_tilt, default_zoom)
  658. time.sleep(0.5)
  659. except Exception as e:
  660. logger.warning(f"球机复位失败: {e}")
  661. def _verify_calibration(self) -> bool:
  662. """
  663. 校准验证:将球机移到全景画面中心对应的PTZ角度,
  664. 通过特征匹配验证球机是否指向了全景画面中心区域。
  665. 同时验证全景画面中的多个关键位置(左、中、右),
  666. 确保变换在整个视野范围内基本正确。
  667. Returns:
  668. 验证是否通过
  669. """
  670. logger.info("=" * 50)
  671. logger.info("校准验证: 将球机移到全景画面中心位置")
  672. logger.info("=" * 50)
  673. if self.ptz is None or self.get_frame is None:
  674. logger.warning("无法执行校准验证: PTZ或全景帧获取函数不可用")
  675. return False
  676. # 验证位置列表:全景画面中的关键位置
  677. verify_positions = [
  678. ("全景中心", 0.5, 0.5),
  679. ("全景左侧", 0.25, 0.5),
  680. ("全景右侧", 0.75, 0.5),
  681. ]
  682. passed = 0
  683. total = len(verify_positions)
  684. for name, x_ratio, y_ratio in verify_positions:
  685. pan, tilt = self.transform(x_ratio, y_ratio)
  686. logger.info(f"验证 {name} ({x_ratio:.2f}, {y_ratio:.2f}) → "
  687. f"PTZ角度: pan={pan:.1f}°, tilt={tilt:.1f}°")
  688. # 检查角度是否在合理范围
  689. if pan < -10 or pan > 370 or tilt < -95 or tilt > 95:
  690. logger.warning(f" 变换结果异常: pan={pan:.1f}°, tilt={tilt:.1f}° 超出合理范围")
  691. continue
  692. # 移动球机到计算出的位置
  693. if not self.ptz.goto_exact_position(pan, tilt, 1):
  694. logger.warning(f" 移动球机失败")
  695. continue
  696. time.sleep(self.stabilize_time)
  697. # 获取全景帧和球机帧
  698. panorama_frame = self.get_frame()
  699. ptz_frame = self.ptz_capture() if self.ptz_capture else None
  700. if panorama_frame is None or ptz_frame is None:
  701. logger.warning(f" 获取帧失败: 全景={'OK' if panorama_frame is not None else '失败'}, "
  702. f"球机={'OK' if ptz_frame is not None else '失败'}")
  703. continue
  704. # 特征匹配验证
  705. success, match_count, cx, cy = self.overlap_discovery.match_frames(
  706. ptz_frame, panorama_frame
  707. )
  708. h, w = panorama_frame.shape[:2]
  709. match_x_ratio = cx / w
  710. match_y_ratio = cy / h
  711. # 计算期望位置与实际匹配位置的偏差
  712. position_error = math.sqrt(
  713. (match_x_ratio - x_ratio) ** 2 + (match_y_ratio - y_ratio) ** 2
  714. )
  715. if success:
  716. logger.info(f" 匹配成功: {match_count}个特征点, "
  717. f"匹配位置=({match_x_ratio:.3f}, {match_y_ratio:.3f}), "
  718. f"期望位置=({x_ratio:.3f}, {y_ratio:.3f}), "
  719. f"位置偏差={position_error:.3f}")
  720. if position_error < 0.15:
  721. passed += 1
  722. logger.info(f" 验证通过 (偏差 < 15%)")
  723. else:
  724. logger.warning(f" 验证偏差较大 ({position_error:.1%}),校准精度可能不足")
  725. else:
  726. logger.warning(f" 特征匹配不足({match_count}点), "
  727. f"球机可能未指向全景画面中期望的位置")
  728. logger.info(f"校准验证结果: {passed}/{total} 个位置验证通过")
  729. if passed == 0:
  730. logger.error("所有验证位置均未通过,校准结果可能完全错误!请检查:")
  731. logger.error(" 1. 球机安装方向配置是否正确 (mount_type, pan_flip, tilt_flip)")
  732. logger.error(" 2. 两台摄像头的相对位置是否合理")
  733. logger.error(" 3. 球机PTZ角度范围是否配置正确")
  734. return False
  735. if passed < total:
  736. logger.warning(f"部分验证未通过,校准精度可能有限")
  737. return True
  738. return True
  739. def _generate_points_in_overlaps(self, quick_mode: bool = True) -> List[CalibrationPoint]:
  740. """
  741. 在发现的重叠区间内生成校准点
  742. 只在球机和全景有视觉重叠的区域生成点
  743. """
  744. points = []
  745. if quick_mode:
  746. # 快速模式: 每个重叠区间内生成9个点(3x3网格)
  747. for overlap in self.overlap_ranges:
  748. # 在区间中心生成点
  749. pan_center = (overlap.pan_start + overlap.pan_end) / 2
  750. tilt_center = (overlap.tilt_start + overlap.tilt_end) / 2
  751. pan_span = overlap.pan_end - overlap.pan_start
  752. tilt_span = overlap.tilt_end - overlap.tilt_start
  753. # 3x3网格分布
  754. pan_positions = [0.25, 0.5, 0.75] if pan_span > 10 else [0.5]
  755. tilt_positions = [0.25, 0.5, 0.75] if tilt_span > 10 else [0.5]
  756. for pf in pan_positions:
  757. for tf in tilt_positions:
  758. points.append(CalibrationPoint(
  759. pan=overlap.pan_start + pan_span * pf,
  760. tilt=overlap.tilt_start + tilt_span * tf,
  761. zoom=1.0))
  762. else:
  763. # 完整模式: 在每个重叠区间内均匀分布
  764. grid_size = 5
  765. for overlap in self.overlap_ranges:
  766. for i in range(grid_size):
  767. for j in range(grid_size):
  768. pan = overlap.pan_start + (overlap.pan_end - overlap.pan_start) * i / (grid_size - 1)
  769. tilt = overlap.tilt_start + (overlap.tilt_end - overlap.tilt_start) * j / (grid_size - 1)
  770. points.append(CalibrationPoint(pan=pan, tilt=tilt, zoom=1.0))
  771. return points
  772. def _calculate_transform(self, points: List[CalibrationPoint]) -> bool:
  773. """使用RANSAC + 最小二乘法拟合变换参数,剔除异常值"""
  774. try:
  775. if len(points) < 4:
  776. logger.error(f"计算变换参数错误: 有效点不足({len(points)}个)")
  777. return False
  778. pan_values = np.array([p.pan for p in points])
  779. tilt_values = np.array([p.tilt for p in points])
  780. x_ratios = np.array([p.x_ratio for p in points])
  781. y_ratios = np.array([p.y_ratio for p in points])
  782. # 记录原始校准数据便于调试
  783. logger.info("校准点原始数据:")
  784. for i, p in enumerate(points):
  785. logger.info(f" 点{i+1}: pan={p.pan:.1f}°, tilt={p.tilt:.1f}° → "
  786. f"全景位置=({p.x_ratio:.3f}, {p.y_ratio:.3f})")
  787. # 展开pan角度避免0°/360°边界不连续性
  788. pan_unwrapped = self._unwrap_pan_angles(pan_values)
  789. if not np.allclose(pan_values, pan_unwrapped, atol=0.1):
  790. logger.info(f"Pan角度展开: 原始={pan_values.tolist()} → 展开后={pan_unwrapped.tolist()}")
  791. else:
  792. logger.info("Pan角度无需展开(无0°/360°边界跨越)")
  793. # RANSAC剔除异常值 (使用展开后的pan)
  794. inlier_mask = self._ransac_filter(x_ratios, y_ratios, pan_unwrapped, tilt_values)
  795. inlier_count = np.sum(inlier_mask)
  796. if inlier_count < 4:
  797. logger.warning(f"RANSAC后有效点不足({inlier_count}个),使用全部点")
  798. inlier_mask = np.ones(len(points), dtype=bool)
  799. inlier_count = np.sum(inlier_mask)
  800. else:
  801. logger.info(f"RANSAC: {len(points)}个点中{inlier_count}个内点,"
  802. f"剔除{len(points) - inlier_count}个异常值")
  803. # 记录内点数据
  804. logger.info("RANSAC内点数据:")
  805. for i, p in enumerate(points):
  806. if inlier_mask[i]:
  807. logger.info(f" 点{i+1}: pan={pan_unwrapped[i]:.1f}°(原始={p.pan:.1f}°), "
  808. f"tilt={p.tilt:.1f}° → ({p.x_ratio:.3f}, {p.y_ratio:.3f})")
  809. # 用内点拟合完整模型
  810. A = np.ones((inlier_count, 3))
  811. A[:, 1] = x_ratios[inlier_mask]
  812. A[:, 2] = y_ratios[inlier_mask]
  813. pan_params, _, _, _ = np.linalg.lstsq(A, pan_unwrapped[inlier_mask], rcond=None)
  814. tilt_params, _, _, _ = np.linalg.lstsq(A, tilt_values[inlier_mask], rcond=None)
  815. self.pan_offset = pan_params[0]
  816. self.pan_scale_x = pan_params[1]
  817. self.pan_scale_y = pan_params[2]
  818. self.tilt_offset = tilt_params[0]
  819. self.tilt_scale_x = tilt_params[1]
  820. self.tilt_scale_y = tilt_params[2]
  821. # 系数合理性检查
  822. pan_coeffs_ok = (abs(self.pan_scale_x) < 500 and abs(self.pan_scale_y) < 500)
  823. tilt_coeffs_ok = (abs(self.tilt_scale_x) < 300 and abs(self.tilt_scale_y) < 300)
  824. if not (pan_coeffs_ok and tilt_coeffs_ok):
  825. logger.warning(f"完整模型系数异常: pan_scale_x={self.pan_scale_x:.1f}, "
  826. f"pan_scale_y={self.pan_scale_y:.1f}, "
  827. f"tilt_scale_x={self.tilt_scale_x:.1f}, "
  828. f"tilt_scale_y={self.tilt_scale_y:.1f}")
  829. logger.info("尝试简化模型: pan仅依赖x, tilt仅依赖y")
  830. # 简化模型: pan = offset + scale_x * x
  831. # tilt = offset + scale_y * y
  832. A_pan = np.ones((inlier_count, 2))
  833. A_pan[:, 1] = x_ratios[inlier_mask]
  834. pan_params_s, _, _, _ = np.linalg.lstsq(A_pan, pan_unwrapped[inlier_mask], rcond=None)
  835. A_tilt = np.ones((inlier_count, 2))
  836. A_tilt[:, 1] = y_ratios[inlier_mask]
  837. tilt_params_s, _, _, _ = np.linalg.lstsq(A_tilt, tilt_values[inlier_mask], rcond=None)
  838. self.pan_offset = pan_params_s[0]
  839. self.pan_scale_x = pan_params_s[1]
  840. self.pan_scale_y = 0.0
  841. self.tilt_offset = tilt_params_s[0]
  842. self.tilt_scale_x = 0.0
  843. self.tilt_scale_y = tilt_params_s[1]
  844. logger.info(f"简化模型: pan={self.pan_offset:.2f} + {self.pan_scale_x:.2f}*x, "
  845. f"tilt={self.tilt_offset:.2f} + {self.tilt_scale_y:.2f}*y")
  846. # 验证变换对全景中心的预测是否合理
  847. center_pan, center_tilt = self.transform(0.5, 0.5)
  848. logger.info(f"全景中心(0.5,0.5)预测: pan={center_pan:.1f}°, tilt={center_tilt:.1f}°")
  849. logger.info(f"最终变换参数: pan = {self.pan_offset:.2f} + {self.pan_scale_x:.2f}*x + {self.pan_scale_y:.2f}*y, "
  850. f"tilt = {self.tilt_offset:.2f} + {self.tilt_scale_x:.2f}*x + {self.tilt_scale_y:.2f}*y")
  851. return True
  852. except Exception as e:
  853. logger.error(f"计算变换参数错误: {e}")
  854. import traceback
  855. logger.error(traceback.format_exc())
  856. return False
  857. def _ransac_filter(self, x: np.ndarray, y: np.ndarray,
  858. pan: np.ndarray, tilt: np.ndarray,
  859. max_iterations: int = 200, threshold: float = 15.0,
  860. min_samples: int = 4) -> np.ndarray:
  861. """RANSAC剔除变换拟合中的异常值(pan应已展开为连续值)"""
  862. n = len(x)
  863. best_inliers = np.zeros(n, dtype=bool)
  864. best_inlier_count = 0
  865. rng = np.random.RandomState(42)
  866. for _ in range(max_iterations):
  867. # 随机选min_samples个点
  868. indices = rng.choice(n, min_samples, replace=False)
  869. # 用这些点拟合
  870. A = np.ones((min_samples, 3))
  871. A[:, 1] = x[indices]
  872. A[:, 2] = y[indices]
  873. try:
  874. pan_params, _, _, _ = np.linalg.lstsq(A, pan[indices], rcond=None)
  875. tilt_params, _, _, _ = np.linalg.lstsq(A, tilt[indices], rcond=None)
  876. except np.linalg.LinAlgError:
  877. continue
  878. # 计算所有点的误差
  879. pred_pan = pan_params[0] + pan_params[1] * x + pan_params[2] * y
  880. pred_tilt = tilt_params[0] + tilt_params[1] * x + tilt_params[2] * y
  881. # 使用角度差计算pan误差(即使已展开,仍用角度差以防边界情况)
  882. pan_errors = np.array([self._angular_diff(float(pred_pan[i]), float(pan[i]))
  883. for i in range(n)])
  884. tilt_errors = pred_tilt - tilt
  885. errors = np.sqrt(pan_errors ** 2 + tilt_errors ** 2)
  886. inliers = errors < threshold
  887. inlier_count = np.sum(inliers)
  888. if inlier_count > best_inlier_count:
  889. best_inlier_count = inlier_count
  890. best_inliers = inliers
  891. if best_inlier_count == 0:
  892. return np.ones(n, dtype=bool)
  893. return best_inliers
  894. def _calculate_rms_error(self, points: List[CalibrationPoint]) -> float:
  895. """计算均方根误差(使用角度差处理pan环绕)"""
  896. total_error = 0.0
  897. for p in points:
  898. pred_pan, pred_tilt = self.transform(p.x_ratio, p.y_ratio)
  899. # 使用角度差计算pan误差,处理0°/360°环绕
  900. pan_error = self._angular_diff(pred_pan, p.pan)
  901. tilt_error = pred_tilt - p.tilt
  902. error = math.sqrt(pan_error ** 2 + tilt_error ** 2)
  903. total_error += error ** 2
  904. return math.sqrt(total_error / len(points))
  905. def transform(self, x_ratio: float, y_ratio: float) -> Tuple[float, float]:
  906. """将全景坐标转换为PTZ角度 - 梯形透视补偿"""
  907. # 优先使用分段线性查找表(pan)
  908. if self.pan_lookup:
  909. pan = self._interp_lookup(self.pan_lookup, x_ratio)
  910. else:
  911. pan = self.pan_offset + self.pan_scale_x * x_ratio + self.pan_scale_y * y_ratio
  912. # pan边缘曲线补偿:越靠近边缘补偿越大,中心不补偿
  913. # 梯形透视:底部(y大)更宽,边缘补偿更大;顶部(y小)更窄,补偿更小
  914. if self.pan_edge_offset != 0:
  915. dx = 2 * x_ratio - 1 # -1(左) ~ 0(中) ~ +1(右)
  916. y_scale = 0.3 + 0.7 * y_ratio # 顶部0.3倍,底部1.0倍
  917. pan_correction = self.pan_edge_offset * y_scale * math.copysign(abs(dx) ** self.pan_curve_power, dx)
  918. pan += pan_correction
  919. # tilt:优先使用曲线映射(查找表tilt数据不稳定),后备查找表
  920. if self.tilt_linear_enabled:
  921. tilt = self.tilt_y0 + (self.tilt_y1 - self.tilt_y0) * (y_ratio ** self.tilt_curve_power)
  922. elif self.tilt_lookup:
  923. tilt = self._interp_lookup(self.tilt_lookup, y_ratio)
  924. else:
  925. tilt = self.tilt_offset + self.tilt_scale_x * x_ratio + self.tilt_scale_y * y_ratio
  926. return (pan % 360, tilt)
  927. def _interp_lookup(self, lookup: List[Tuple[float, float]], ratio: float) -> float:
  928. """分段线性插值"""
  929. if not lookup:
  930. return 0.0
  931. if len(lookup) == 1:
  932. return lookup[0][1]
  933. if ratio <= lookup[0][0]:
  934. return lookup[0][1]
  935. if ratio >= lookup[-1][0]:
  936. return lookup[-1][1]
  937. # 二分查找插入位置
  938. lo, hi = 0, len(lookup) - 1
  939. while lo < hi - 1:
  940. mid = (lo + hi) // 2
  941. if lookup[mid][0] <= ratio:
  942. lo = mid
  943. else:
  944. hi = mid
  945. # 线性插值
  946. x0, v0 = lookup[lo]
  947. x1, v1 = lookup[hi]
  948. if abs(x1 - x0) < 1e-10:
  949. return v0
  950. t = (ratio - x0) / (x1 - x0)
  951. return v0 + t * (v1 - v0)
  952. def _build_lookup_tables(self, points: List[CalibrationPoint]) -> bool:
  953. """
  954. 从校准点构建分段线性查找表
  955. 核心策略:
  956. 1. 将所有校准点按x_ratio分桶,取匹配点数加权的pan值
  957. 2. 用最长连续单调子序列(LCMA)过滤假阳性:x_ratio→pan应近似单调
  958. 3. 处理pan角度环绕
  959. """
  960. if len(points) < 3:
  961. return False
  962. sorted_by_x = sorted(points, key=lambda p: p.x_ratio)
  963. # ===== 构建 x_ratio → pan 映射 =====
  964. grid_size = 0.05
  965. x_buckets: Dict[float, List[Tuple[float, int]]] = {}
  966. for p in sorted_by_x:
  967. x_key = round(p.x_ratio / grid_size) * grid_size
  968. if x_key not in x_buckets:
  969. x_buckets[x_key] = []
  970. match_count = getattr(p, 'match_count', 10)
  971. x_buckets[x_key].append((p.pan, match_count))
  972. # 加权中位数
  973. raw_entries = []
  974. for x_key in sorted(x_buckets.keys()):
  975. entries = x_buckets[x_key]
  976. total_weight = sum(mc for _, mc in entries)
  977. weighted_pans = []
  978. for pan, mc in entries:
  979. weighted_pans.extend([pan] * max(1, mc // 5))
  980. weighted_pan = float(np.median(weighted_pans))
  981. raw_entries.append((x_key, weighted_pan, total_weight))
  982. logger.info(f"Pan原始映射 ({len(raw_entries)} 个x_key):")
  983. for x, pan, w in raw_entries:
  984. logger.info(f" x={x:.3f} → pan={pan:.1f}° (weight={w})")
  985. # 用LCMA过滤:找到最长的近似连续单调子序列
  986. # pan随x_ratio应该是近似单调递减或递增的
  987. if len(raw_entries) >= 3:
  988. filtered = self._filter_continuous_monotonic(raw_entries)
  989. self.pan_lookup = [(x, pan) for x, pan, w in filtered]
  990. else:
  991. self.pan_lookup = [(x, pan % 360) for x, pan, w in raw_entries]
  992. # ===== 构建 y_ratio → tilt 映射 =====
  993. # 只使用通过pan过滤的点(x_ratio对应的pan与查找表一致)
  994. pan_valid_x = set(x for x, _ in self.pan_lookup)
  995. pan_tolerance = grid_size * 1.5 # 允许在pan有效区域附近的点
  996. valid_points_for_tilt = []
  997. for p in sorted_by_x:
  998. for vx in pan_valid_x:
  999. if abs(p.x_ratio - vx) <= pan_tolerance:
  1000. valid_points_for_tilt.append(p)
  1001. break
  1002. logger.info(f"Tilt映射使用 {len(valid_points_for_tilt)}/{len(sorted_by_x)} 个经过pan验证的点")
  1003. y_buckets: Dict[float, List[Tuple[float, int]]] = {}
  1004. for p in valid_points_for_tilt:
  1005. y_key = round(p.y_ratio / grid_size) * grid_size
  1006. if y_key not in y_buckets:
  1007. y_buckets[y_key] = []
  1008. match_count = getattr(p, 'match_count', 10)
  1009. y_buckets[y_key].append((p.tilt, match_count))
  1010. tilt_entries = []
  1011. for y_key in sorted(y_buckets.keys()):
  1012. entries = y_buckets[y_key]
  1013. weighted_tilts = []
  1014. for tilt, mc in entries:
  1015. weighted_tilts.extend([tilt] * max(1, mc // 5))
  1016. tilt_median = float(np.median(weighted_tilts))
  1017. tilt_entries.append((y_key, tilt_median))
  1018. self.tilt_lookup = tilt_entries
  1019. # 记录查找表内容
  1020. logger.info(f"Pan查找表 ({len(self.pan_lookup)} 项):")
  1021. for x, pan in self.pan_lookup:
  1022. logger.info(f" x={x:.3f} → pan={pan:.1f}°")
  1023. logger.info(f"Tilt查找表 ({len(self.tilt_lookup)} 项):")
  1024. for y, tilt in self.tilt_lookup:
  1025. logger.info(f" y={y:.3f} → tilt={tilt:.1f}°")
  1026. return True
  1027. def _filter_continuous_monotonic(
  1028. self, entries: List[Tuple[float, float, int]],
  1029. max_step: float = 60.0
  1030. ) -> List[Tuple[float, float, int]]:
  1031. """
  1032. 过滤出最长的连续单调子序列
  1033. x_ratio→pan应该是近似单调的(递增或递减,可能环绕一次)。
  1034. 假阳性匹配会导致pan突然跳变到完全不相关的角度,
  1035. 这个方法通过寻找最长的"步长<max_step"的子序列来过滤。
  1036. Args:
  1037. entries: [(x_key, pan, weight), ...] 已按x_key排序
  1038. max_step: 相邻两个点允许的最大pan差(度)
  1039. Returns:
  1040. 过滤后的entries子集
  1041. """
  1042. n = len(entries)
  1043. if n <= 2:
  1044. return [(x, pan % 360, w) for x, pan, w in entries]
  1045. # 尝试两种方向:pan递减和pan递增
  1046. # 对于递减方向:每个点的pan应比前一个小(允许环绕)
  1047. best_result = []
  1048. for direction in ['decreasing', 'increasing']:
  1049. # 动态规划找最长连续子序列
  1050. # dp[i] = 以entries[i]结尾的最长连续子序列长度
  1051. # parent[i] = 前驱索引
  1052. dp = [1] * n
  1053. parent = [-1] * n
  1054. for i in range(1, n):
  1055. for j in range(i):
  1056. # 检查j→i的pan变化是否合理
  1057. pan_j = entries[j][1]
  1058. pan_i = entries[i][1]
  1059. # 计算角度差(考虑环绕)
  1060. diff = pan_i - pan_j
  1061. while diff > 180:
  1062. diff -= 360
  1063. while diff < -180:
  1064. diff += 360
  1065. # 检查方向
  1066. if direction == 'decreasing':
  1067. ok = diff <= 0 and abs(diff) <= max_step
  1068. else:
  1069. ok = diff >= 0 and abs(diff) <= max_step
  1070. if ok and dp[j] + 1 > dp[i]:
  1071. dp[i] = dp[j] + 1
  1072. parent[i] = j
  1073. # 找最长子序列的终点
  1074. end = max(range(n), key=lambda i: dp[i])
  1075. # 回溯构建子序列
  1076. seq = []
  1077. idx = end
  1078. while idx >= 0:
  1079. seq.append(idx)
  1080. idx = parent[idx]
  1081. seq.reverse()
  1082. # 展开pan角度
  1083. result = self._unwrap_sequence(entries, seq)
  1084. if len(result) > len(best_result):
  1085. best_result = result
  1086. logger.info(f"LCMA过滤: {n}个点 → {len(best_result)}个点 (方向: "
  1087. f"{'递减' if len(best_result) > 0 else '无'})")
  1088. # 如果过滤后太少,放宽条件重试
  1089. if len(best_result) < 3 and n >= 3:
  1090. logger.info("LCMA结果太少,放宽步长限制重试")
  1091. for wider_step in [90, 120, 180]:
  1092. for direction in ['decreasing', 'increasing']:
  1093. dp = [1] * n
  1094. parent = [-1] * n
  1095. for i in range(1, n):
  1096. for j in range(i):
  1097. diff = entries[i][1] - entries[j][1]
  1098. while diff > 180:
  1099. diff -= 360
  1100. while diff < -180:
  1101. diff += 360
  1102. if direction == 'decreasing':
  1103. ok = diff <= 0 and abs(diff) <= wider_step
  1104. else:
  1105. ok = diff >= 0 and abs(diff) <= wider_step
  1106. if ok and dp[j] + 1 > dp[i]:
  1107. dp[i] = dp[j] + 1
  1108. parent[i] = j
  1109. end = max(range(n), key=lambda i: dp[i])
  1110. seq = []
  1111. idx = end
  1112. while idx >= 0:
  1113. seq.append(idx)
  1114. idx = parent[idx]
  1115. seq.reverse()
  1116. result = self._unwrap_sequence(entries, seq)
  1117. if len(result) > len(best_result):
  1118. best_result = result
  1119. if len(best_result) >= 3:
  1120. break
  1121. if not best_result:
  1122. # 全部过滤后为空,使用原始数据
  1123. logger.warning("LCMA过滤后为空,使用原始数据")
  1124. return [(x, pan % 360, w) for x, pan, w in entries]
  1125. return best_result
  1126. def _unwrap_sequence(
  1127. self, entries: List[Tuple[float, float, int]],
  1128. indices: List[int]
  1129. ) -> List[Tuple[float, float, int]]:
  1130. """将子序列的pan角度展开并归一化到[0, 360)"""
  1131. result = []
  1132. prev_unwrapped = None
  1133. for idx in indices:
  1134. x, pan, w = entries[idx]
  1135. if prev_unwrapped is None:
  1136. unwrapped = pan
  1137. else:
  1138. diff = pan - prev_unwrapped
  1139. while diff > 180:
  1140. pan -= 360
  1141. diff = pan - prev_unwrapped
  1142. while diff < -180:
  1143. pan += 360
  1144. diff = pan - prev_unwrapped
  1145. unwrapped = pan
  1146. prev_unwrapped = unwrapped
  1147. result.append((x, unwrapped % 360, w))
  1148. return result
  1149. def inverse_transform(self, pan: float, tilt: float) -> Tuple[float, float]:
  1150. """将PTZ角度转换为全景坐标"""
  1151. # 优先使用查找表的反向查找
  1152. if self.pan_lookup and self.tilt_lookup:
  1153. # 反向查找: pan → x_ratio
  1154. x_ratio = self._reverse_lookup(self.pan_lookup, pan % 360)
  1155. y_ratio = self._reverse_lookup(self.tilt_lookup, tilt)
  1156. return (max(0, min(1, x_ratio)), max(0, min(1, y_ratio)))
  1157. # 后备:线性模型逆变换
  1158. M = np.array([
  1159. [self.pan_scale_x, self.pan_scale_y],
  1160. [self.tilt_scale_x, self.tilt_scale_y]
  1161. ])
  1162. det = np.linalg.det(M)
  1163. if abs(det) < 1e-10:
  1164. x_ratio = (pan - self.pan_offset) / self.pan_scale_x if abs(self.pan_scale_x) > 1e-10 else 0.5
  1165. y_ratio = (tilt - self.tilt_offset) / self.tilt_scale_y if abs(self.tilt_scale_y) > 1e-10 else 0.5
  1166. else:
  1167. M_inv = np.linalg.inv(M)
  1168. offset = np.array([pan - self.pan_offset, tilt - self.tilt_offset])
  1169. result = M_inv @ offset
  1170. x_ratio, y_ratio = result[0], result[1]
  1171. return (max(0, min(1, x_ratio)), max(0, min(1, y_ratio)))
  1172. def _reverse_lookup(self, lookup: List[Tuple[float, float]], value: float) -> float:
  1173. """查找表反向查找:从value找ratio"""
  1174. if not lookup:
  1175. return 0.5
  1176. # 处理pan环绕:找到最接近的段
  1177. best_idx = 0
  1178. best_diff = float('inf')
  1179. for i, (ratio, v) in enumerate(lookup):
  1180. diff = self._angular_diff(value, v)
  1181. if abs(diff) < abs(best_diff):
  1182. best_diff = diff
  1183. best_idx = i
  1184. # 精确定位到最近的两个点之间
  1185. if best_idx == 0:
  1186. return lookup[0][0]
  1187. if best_idx == len(lookup) - 1:
  1188. return lookup[-1][0]
  1189. # 检查前一个和后一个点,选择更近的段
  1190. prev_v = lookup[best_idx - 1][1]
  1191. curr_v = lookup[best_idx][1]
  1192. next_v = lookup[best_idx + 1][1] if best_idx + 1 < len(lookup) else curr_v
  1193. # 在 (best_idx-1, best_idx) 和 (best_idx, best_idx+1) 之间选择
  1194. if abs(self._angular_diff(value, prev_v)) < abs(self._angular_diff(value, next_v)):
  1195. lo, hi = best_idx - 1, best_idx
  1196. else:
  1197. lo, hi = best_idx, best_idx + 1
  1198. x0, v0 = lookup[lo]
  1199. x1, v1 = lookup[hi]
  1200. # 考虑角度环绕
  1201. diff_v = self._angular_diff(v1, v0)
  1202. if abs(diff_v) < 1e-10:
  1203. return (x0 + x1) / 2
  1204. t = self._angular_diff(value, v0) / diff_v
  1205. t = max(0, min(1, t))
  1206. return x0 + t * (x1 - x0)
  1207. def is_calibrated(self) -> bool:
  1208. return self.state == CalibrationState.SUCCESS
  1209. def get_state(self) -> CalibrationState:
  1210. return self.state
  1211. def get_result(self) -> Optional[CalibrationResult]:
  1212. return self.result
  1213. def get_overlap_ranges(self) -> List[OverlapRange]:
  1214. """返回发现的重叠区间"""
  1215. return self.overlap_ranges
  1216. def save_calibration(self, filepath: str) -> bool:
  1217. """保存校准结果"""
  1218. if not self.is_calibrated():
  1219. return False
  1220. try:
  1221. import json
  1222. ptz_config = _get_ptz_config()
  1223. data = {
  1224. 'pan_offset': self.pan_offset,
  1225. 'pan_scale_x': self.pan_scale_x,
  1226. 'pan_scale_y': self.pan_scale_y,
  1227. 'tilt_offset': self.tilt_offset,
  1228. 'tilt_scale_x': self.tilt_scale_x,
  1229. 'tilt_scale_y': self.tilt_scale_y,
  1230. 'rms_error': self.result.rms_error if self.result else 0,
  1231. 'overlap_ranges': [
  1232. {
  1233. 'pan_start': r.pan_start,
  1234. 'pan_end': r.pan_end,
  1235. 'tilt_start': r.tilt_start,
  1236. 'tilt_end': r.tilt_end,
  1237. 'match_count': r.match_count
  1238. }
  1239. for r in self.overlap_ranges
  1240. ],
  1241. # 分段线性查找表
  1242. 'pan_lookup': self.pan_lookup,
  1243. 'tilt_lookup': self.tilt_lookup,
  1244. # 保存安装方向配置
  1245. 'mount_type': ptz_config.get('mount_type', 'wall'),
  1246. 'tilt_flip': ptz_config.get('tilt_flip', False),
  1247. 'pan_flip': ptz_config.get('pan_flip', False),
  1248. }
  1249. with open(filepath, 'w') as f:
  1250. json.dump(data, f, indent=2)
  1251. logger.info(f"校准结果已保存: {filepath}")
  1252. return True
  1253. except Exception as e:
  1254. logger.error(f"保存校准结果失败: {e}")
  1255. return False
  1256. def load_calibration(self, filepath: str) -> bool:
  1257. """加载校准结果"""
  1258. try:
  1259. import json
  1260. with open(filepath, 'r') as f:
  1261. data = json.load(f)
  1262. self.pan_offset = data['pan_offset']
  1263. self.pan_scale_x = data['pan_scale_x']
  1264. self.pan_scale_y = data['pan_scale_y']
  1265. self.tilt_offset = data['tilt_offset']
  1266. self.tilt_scale_x = data['tilt_scale_x']
  1267. self.tilt_scale_y = data['tilt_scale_y']
  1268. # 加载分段线性查找表
  1269. self.pan_lookup = [tuple(p) for p in data.get('pan_lookup', [])]
  1270. self.tilt_lookup = [tuple(t) for t in data.get('tilt_lookup', [])]
  1271. # 加载重叠区间(如果有)
  1272. if 'overlap_ranges' in data:
  1273. self.overlap_ranges = [
  1274. OverlapRange(
  1275. pan_start=r['pan_start'],
  1276. pan_end=r['pan_end'],
  1277. tilt_start=r['tilt_start'],
  1278. tilt_end=r['tilt_end'],
  1279. match_count=r['match_count'],
  1280. panorama_center_x=0,
  1281. panorama_center_y=0
  1282. )
  1283. for r in data['overlap_ranges']
  1284. ]
  1285. self.state = CalibrationState.SUCCESS
  1286. self.result = CalibrationResult(
  1287. success=True,
  1288. points=[],
  1289. rms_error=data.get('rms_error', 0)
  1290. )
  1291. # 检查安装方向配置是否匹配
  1292. ptz_config = _get_ptz_config()
  1293. current_mount = ptz_config.get('mount_type', 'wall')
  1294. saved_mount = data.get('mount_type', 'wall')
  1295. if current_mount != saved_mount:
  1296. logger.warning(f"当前安装类型({current_mount})与校准时的({saved_mount})不同,建议重新校准!")
  1297. logger.info(f"校准结果已加载: {filepath}")
  1298. return True
  1299. except FileNotFoundError:
  1300. logger.warning(f"校准文件不存在: {filepath}")
  1301. return False
  1302. except Exception as e:
  1303. logger.error(f"加载校准结果失败: {e}")
  1304. return False
  1305. class CalibrationManager:
  1306. """校准管理器"""
  1307. def __init__(self, calibrator: CameraCalibrator, calibration_file: str = None):
  1308. self.calibrator = calibrator
  1309. # 优先使用传入的路径,否则从配置读取,最后使用默认值
  1310. if calibration_file:
  1311. self.calibration_file = calibration_file
  1312. else:
  1313. try:
  1314. from config import CALIBRATION_CONFIG
  1315. self.calibration_file = CALIBRATION_CONFIG.get(
  1316. 'calibration_file', 'calibration.json'
  1317. )
  1318. except ImportError:
  1319. self.calibration_file = 'calibration.json'
  1320. def auto_calibrate(self, force: bool = False, fallback_on_failure: bool = True) -> CalibrationResult:
  1321. """
  1322. 自动校准
  1323. Args:
  1324. force: 是否强制重新校准(不加载已有数据)
  1325. fallback_on_failure: 校准失败时是否回退使用已有数据
  1326. Returns:
  1327. 校准结果
  1328. """
  1329. # 检查是否启用加载上次校准数据
  1330. load_on_startup = True # 默认启用
  1331. try:
  1332. from config import CALIBRATION_CONFIG
  1333. load_on_startup = CALIBRATION_CONFIG.get('load_on_startup', True)
  1334. except:
  1335. pass
  1336. # 如果不是强制校准,尝试加载已有数据
  1337. if not force and load_on_startup:
  1338. if self.calibrator.load_calibration(self.calibration_file):
  1339. logger.info("使用已有校准结果")
  1340. return self.calibrator.get_result()
  1341. # 执行新校准
  1342. if force:
  1343. logger.info("强制重新校准(不使用已有数据)...")
  1344. elif not load_on_startup:
  1345. logger.info("已禁用加载校准数据,开始新校准...")
  1346. else:
  1347. logger.info("开始自动校准...")
  1348. result = self.calibrator.calibrate(quick_mode=True)
  1349. if result.success:
  1350. self.calibrator.save_calibration(self.calibration_file)
  1351. elif fallback_on_failure:
  1352. # 校准失败,尝试回退使用已有数据
  1353. logger.warning("校准失败,尝试回退使用已有校准数据...")
  1354. if self.calibrator.load_calibration(self.calibration_file):
  1355. logger.info("已回退到已有校准数据")
  1356. result = self.calibrator.get_result()
  1357. return result
  1358. def check_calibration(self) -> Tuple[bool, str]:
  1359. """检查校准状态"""
  1360. state = self.calibrator.get_state()
  1361. if state == CalibrationState.SUCCESS:
  1362. result = self.calibrator.get_result()
  1363. overlaps = self.calibrator.get_overlap_ranges()
  1364. overlap_info = f", {len(overlaps)}个重叠区间" if overlaps else ""
  1365. return (True, f"校准有效, RMS误差: {result.rms_error:.4f}°{overlap_info}")
  1366. elif state == CalibrationState.FAILED:
  1367. return (False, "校准失败")
  1368. elif state == CalibrationState.RUNNING:
  1369. return (False, "校准进行中")
  1370. else:
  1371. return (False, "未校准")