calibration.py 68 KB

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