calibration.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. """
  2. 相机校准模块
  3. 实现全景相机与球机的自动校准
  4. 建立画面坐标到PTZ角度的映射关系
  5. 核心改进:先发现视野重叠区域,再在重叠区内校准,
  6. 避免球机指向与全景画面无重叠的方向导致校准失败。
  7. """
  8. import time
  9. import math
  10. import threading
  11. import numpy as np
  12. import cv2
  13. from typing import List, Tuple, Dict, Optional, Callable
  14. from dataclasses import dataclass, field
  15. from enum import Enum
  16. from ptz_camera import PTZCamera
  17. class CalibrationState(Enum):
  18. IDLE = 0
  19. RUNNING = 1
  20. SUCCESS = 2
  21. FAILED = 3
  22. @dataclass
  23. class CalibrationPoint:
  24. pan: float
  25. tilt: float
  26. zoom: float = 1.0
  27. x_ratio: float = 0.0
  28. y_ratio: float = 0.0
  29. detected: bool = False
  30. @dataclass
  31. class CalibrationResult:
  32. success: bool
  33. points: List[CalibrationPoint]
  34. transform_matrix: Optional[np.ndarray] = None
  35. error_message: str = ""
  36. rms_error: float = 0.0
  37. @dataclass
  38. class OverlapRange:
  39. pan_start: float
  40. pan_end: float
  41. tilt_start: float
  42. tilt_end: float
  43. match_count: int
  44. panorama_center_x: float
  45. panorama_center_y: float
  46. MIN_MATCH_THRESHOLD = 8
  47. class OverlapDiscovery:
  48. """
  49. 视野重叠发现器
  50. 扫描球机视野范围,找出与全景画面有视觉重叠的角度区间
  51. """
  52. def __init__(self, feature_type: str = 'SIFT'):
  53. try:
  54. self.feature_detector = cv2.SIFT_create()
  55. self.feature_type = 'SIFT'
  56. except AttributeError:
  57. self.feature_detector = cv2.ORB_create(nfeatures=500)
  58. self.feature_type = 'ORB'
  59. norm_type = cv2.NORM_L2 if self.feature_type == 'SIFT' else cv2.NORM_HAMMING
  60. self.matcher = cv2.BFMatcher(norm_type)
  61. def match_frames(self, ptz_frame: np.ndarray, panorama_frame: np.ndarray
  62. ) -> Tuple[bool, int, float, float]:
  63. """
  64. 特征匹配球机画面与全景画面
  65. Returns: (是否匹配成功, 匹配点数, 全景画面中心x, 全景画面中心y)
  66. """
  67. if ptz_frame is None or panorama_frame is None:
  68. return (False, 0, 0.0, 0.0)
  69. try:
  70. ptz_gray = cv2.cvtColor(ptz_frame, cv2.COLOR_BGR2GRAY) if len(ptz_frame.shape) == 3 else ptz_frame
  71. pan_gray = cv2.cvtColor(panorama_frame, cv2.COLOR_BGR2GRAY) if len(panorama_frame.shape) == 3 else panorama_frame
  72. kp1, des1 = self.feature_detector.detectAndCompute(ptz_gray, None)
  73. kp2, des2 = self.feature_detector.detectAndCompute(pan_gray, None)
  74. if des1 is None or des2 is None or len(kp1) < 4 or len(kp2) < 4:
  75. return (False, 0, 0.0, 0.0)
  76. matches = self.matcher.knnMatch(des1, des2, k=2)
  77. good_matches = []
  78. for match_pair in matches:
  79. if len(match_pair) == 2:
  80. m, n = match_pair
  81. if m.distance < 0.75 * n.distance:
  82. good_matches.append(m)
  83. if len(good_matches) < MIN_MATCH_THRESHOLD:
  84. return (False, len(good_matches), 0.0, 0.0)
  85. pan_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches])
  86. center_x = np.mean(pan_pts[:, 0])
  87. center_y = np.mean(pan_pts[:, 1])
  88. return (True, len(good_matches), center_x, center_y)
  89. except Exception as e:
  90. print(f" 特征匹配异常: {e}")
  91. return (False, 0, 0.0, 0.0)
  92. def discover_overlap_ranges(
  93. self,
  94. ptz: PTZCamera,
  95. get_panorama_frame: Callable[[], np.ndarray],
  96. ptz_capture: Callable[[], Optional[np.ndarray]],
  97. pan_range: Tuple[float, float] = (0, 360),
  98. tilt_range: Tuple[float, float] = (-30, 30),
  99. pan_step: float = 20,
  100. tilt_step: float = 15,
  101. stabilize_time: float = 2.0,
  102. on_progress: Callable[[int, int, str], None] = None,
  103. max_ranges: int = 3,
  104. min_positions_per_range: int = 3
  105. ) -> List[OverlapRange]:
  106. """
  107. 扫描球机视野范围,发现与全景画面有重叠的角度区间
  108. 1. 先拍一张全景参考帧
  109. 2. 逐步移动球机到各个角度
  110. 3. 在每个位置抓拍球机画面,与全景做特征匹配
  111. 4. 记录有足够匹配点的角度
  112. 5. 合并相邻的有重叠的角度形成区间
  113. """
  114. print(f"\n{'='*50}")
  115. print(f"阶段1: 视野重叠发现")
  116. print(f"扫描范围: pan={pan_range}, tilt={tilt_range}")
  117. print(f"步进: pan={pan_step}°, tilt={tilt_step}°")
  118. print(f"{'='*50}")
  119. # 1. 拍全景参考帧
  120. print(" 获取全景参考帧...")
  121. ref_frames = []
  122. for _ in range(3):
  123. frame = get_panorama_frame()
  124. if frame is not None:
  125. ref_frames.append(frame)
  126. time.sleep(0.1)
  127. if not ref_frames:
  128. print(" 错误: 无法获取全景参考帧!")
  129. return []
  130. panorama_ref = ref_frames[0]
  131. print(f" 全景参考帧: {panorama_ref.shape}")
  132. # 2. 扫描各个角度
  133. scan_results: List[Tuple[float, float, int, float, float]] = []
  134. pan_values = np.arange(pan_range[0], pan_range[1] + pan_step, pan_step)
  135. tilt_values = np.arange(tilt_range[0], tilt_range[1] + tilt_step, tilt_step)
  136. total_positions = len(pan_values) * len(tilt_values)
  137. current_idx = 0
  138. for pan in pan_values:
  139. for tilt in tilt_values:
  140. current_idx += 1
  141. pos_desc = f"pan={pan:.0f}°, tilt={tilt:.0f}°"
  142. if on_progress:
  143. on_progress(current_idx, total_positions, f"扫描 {pos_desc}")
  144. print(f" [{current_idx}/{total_positions}] {pos_desc}")
  145. # 移动球机
  146. if not ptz.goto_exact_position(float(pan), float(tilt), 1):
  147. print(f" 移动球机失败, 跳过")
  148. continue
  149. time.sleep(stabilize_time)
  150. # 抓拍球机画面
  151. ptz_frame = ptz_capture() if ptz_capture else None
  152. if ptz_frame is None:
  153. print(f" 球机抓拍失败, 跳过")
  154. continue
  155. # 获取当前全景帧并匹配
  156. cur_panorama = get_panorama_frame()
  157. if cur_panorama is None:
  158. continue
  159. success, match_count, cx, cy = self.match_frames(ptz_frame, cur_panorama)
  160. if success:
  161. h, w = cur_panorama.shape[:2]
  162. x_ratio = cx / w
  163. y_ratio = cy / h
  164. print(f" ✓ 匹配成功: {match_count}个特征点, 全景位置=({x_ratio:.3f}, {y_ratio:.3f})")
  165. scan_results.append((float(pan), float(tilt), match_count, x_ratio, y_ratio))
  166. else:
  167. print(f" ✗ 匹配不足: {match_count}个特征点")
  168. if not scan_results:
  169. print("\n 未发现任何视野重叠位置!")
  170. return []
  171. print(f"\n 发现 {len(scan_results)} 个有重叠的扫描位置")
  172. # 3. 合并相邻位置为重叠区间
  173. overlap_ranges = self._merge_scan_results(
  174. scan_results,
  175. max_ranges=max_ranges,
  176. min_positions=min_positions_per_range
  177. )
  178. for i, r in enumerate(overlap_ranges):
  179. print(f" 重叠区间 {i+1}: pan=[{r.pan_start:.0f}°, {r.pan_end:.0f}°], "
  180. f"tilt=[{r.tilt_start:.0f}°, {r.tilt_end:.0f}°], "
  181. f"匹配点={r.match_count}")
  182. return overlap_ranges
  183. def _merge_scan_results(
  184. self,
  185. results: List[Tuple[float, float, int, float, float]],
  186. pan_tolerance: float = 25,
  187. tilt_tolerance: float = 20,
  188. max_ranges: int = 3,
  189. min_positions: int = 3
  190. ) -> List[OverlapRange]:
  191. """
  192. 使用union-find连通分量聚类合并相邻扫描结果
  193. 只保留最大的 max_ranges 个区间
  194. """
  195. if not results:
  196. return []
  197. n = len(results)
  198. # union-find
  199. parent = list(range(n))
  200. def find(x):
  201. while parent[x] != x:
  202. parent[x] = parent[parent[x]]
  203. x = parent[x]
  204. return x
  205. def union(a, b):
  206. ra, rb = find(a), find(b)
  207. if ra != rb:
  208. parent[ra] = rb
  209. # 判断两点是否相邻
  210. for i in range(n):
  211. for j in range(i + 1, n):
  212. pi, ti = results[i][0], results[i][1]
  213. pj, tj = results[j][0], results[j][1]
  214. if abs(pi - pj) <= pan_tolerance and abs(ti - tj) <= tilt_tolerance:
  215. union(i, j)
  216. # 按连通分量分组
  217. groups: Dict[int, List[int]] = {}
  218. for i in range(n):
  219. root = find(i)
  220. if root not in groups:
  221. groups[root] = []
  222. groups[root].append(i)
  223. # 转换为OverlapRange,过滤太小的组
  224. ranges = []
  225. for indices in groups.values():
  226. if len(indices) < min_positions:
  227. continue
  228. group_data = [results[i] for i in indices]
  229. ranges.append(self._group_to_range(group_data))
  230. # 按match_count降序排序,只保留最大的 max_ranges 个
  231. ranges.sort(key=lambda r: r.match_count, reverse=True)
  232. ranges = ranges[:max_ranges]
  233. # 按pan_start排序输出
  234. ranges.sort(key=lambda r: r.pan_start)
  235. return ranges
  236. def _group_to_range(self, group: List[Tuple[float, float, int, float, float]]) -> OverlapRange:
  237. """将一组扫描结果转换为一个OverlapRange"""
  238. pans = [r[0] for r in group]
  239. tilts = [r[1] for r in group]
  240. match_counts = [r[2] for r in group]
  241. x_ratios = [r[3] for r in group]
  242. y_ratios = [r[4] for r in group]
  243. step = 5 # 在边缘各扩展5度
  244. return OverlapRange(
  245. pan_start=min(pans) - step,
  246. pan_end=max(pans) + step,
  247. tilt_start=min(tilts) - step,
  248. tilt_end=max(tilts) + step,
  249. match_count=max(match_counts),
  250. panorama_center_x=float(np.mean(x_ratios)),
  251. panorama_center_y=float(np.mean(y_ratios))
  252. )
  253. class VisualCalibrationDetector:
  254. """
  255. 视觉校准检测器
  256. 通过运动检测和特征匹配定位球机在全景画面中的位置
  257. """
  258. def __init__(self):
  259. try:
  260. self.feature_detector = cv2.SIFT_create()
  261. self.feature_type = 'SIFT'
  262. except AttributeError:
  263. self.feature_detector = cv2.ORB_create(nfeatures=500)
  264. self.feature_type = 'ORB'
  265. self.matcher = cv2.BFMatcher(
  266. cv2.NORM_L2 if self.feature_type == 'SIFT' else cv2.NORM_HAMMING
  267. )
  268. self.use_motion_detection = True
  269. self.use_feature_matching = True
  270. def detect_by_motion(self, frames_before: np.ndarray,
  271. frames_after: np.ndarray) -> Optional[Tuple[float, float]]:
  272. """通过运动检测定位球机指向位置"""
  273. if frames_before is None or frames_after is None:
  274. return None
  275. before_gray = cv2.cvtColor(frames_before, cv2.COLOR_BGR2GRAY) \
  276. if len(frames_before.shape) == 3 else frames_before
  277. after_gray = cv2.cvtColor(frames_after, cv2.COLOR_BGR2GRAY) \
  278. if len(frames_after.shape) == 3 else frames_after
  279. diff = cv2.absdiff(before_gray, after_gray)
  280. _, thresh = cv2.threshold(diff, 25, 255, cv2.THRESH_BINARY)
  281. kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))
  282. thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
  283. thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
  284. contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  285. if not contours:
  286. return None
  287. max_contour = max(contours, key=cv2.contourArea)
  288. area = cv2.contourArea(max_contour)
  289. if area < 500:
  290. return None
  291. M = cv2.moments(max_contour)
  292. if M["m00"] == 0:
  293. return None
  294. cx = M["m10"] / M["m00"]
  295. cy = M["m01"] / M["m00"]
  296. h, w = before_gray.shape
  297. print(f" 运动检测: 中心=({cx:.1f}, {cy:.1f}), 面积={area:.0f})")
  298. return (cx / w, cy / h)
  299. def detect_by_feature_match(self, panorama_frame: np.ndarray,
  300. ptz_frame: np.ndarray) -> Optional[Tuple[float, float]]:
  301. """通过特征匹配定位"""
  302. if panorama_frame is None or ptz_frame is None:
  303. return None
  304. try:
  305. pan_gray = cv2.cvtColor(panorama_frame, cv2.COLOR_BGR2GRAY) \
  306. if len(panorama_frame.shape) == 3 else panorama_frame
  307. ptz_gray = cv2.cvtColor(ptz_frame, cv2.COLOR_BGR2GRAY) \
  308. if len(ptz_frame.shape) == 3 else ptz_frame
  309. kp1, des1 = self.feature_detector.detectAndCompute(ptz_gray, None)
  310. kp2, des2 = self.feature_detector.detectAndCompute(pan_gray, None)
  311. if des1 is None or des2 is None or len(kp1) < 4 or len(kp2) < 4:
  312. return None
  313. matches = self.matcher.knnMatch(des1, des2, k=2)
  314. good_matches = []
  315. for match_pair in matches:
  316. if len(match_pair) == 2:
  317. m, n = match_pair
  318. if m.distance < 0.75 * n.distance:
  319. good_matches.append(m)
  320. if len(good_matches) < 4:
  321. return None
  322. pan_pts = np.float32([kp2[m.trainIdx].pt for m in good_matches])
  323. center_x = np.mean(pan_pts[:, 0])
  324. center_y = np.mean(pan_pts[:, 1])
  325. h, w = pan_gray.shape
  326. print(f" 特征匹配: 匹配点={len(good_matches)}, 中心=({center_x:.1f}, {center_y:.1f})")
  327. return (center_x / w, center_y / h)
  328. except Exception as e:
  329. print(f" 特征匹配错误: {e}")
  330. return None
  331. def detect_position(self, panorama_frame: np.ndarray,
  332. frames_before: np.ndarray = None,
  333. frames_after: np.ndarray = None,
  334. ptz_frame: np.ndarray = None) -> Tuple[bool, float, float]:
  335. """综合检测球机在全景画面中的位置"""
  336. results = []
  337. if self.use_motion_detection and frames_before is not None and frames_after is not None:
  338. motion_result = self.detect_by_motion(frames_before, frames_after)
  339. if motion_result:
  340. results.append(('motion', motion_result, 0.4))
  341. if self.use_feature_matching and ptz_frame is not None:
  342. feature_result = self.detect_by_feature_match(panorama_frame, ptz_frame)
  343. if feature_result:
  344. results.append(('feature', feature_result, 0.6))
  345. if not results:
  346. return (False, 0.0, 0.0)
  347. total_weight = sum(r[2] for r in results)
  348. x_ratio = sum(r[1][0] * r[2] for r in results) / total_weight
  349. y_ratio = sum(r[1][1] * r[2] for r in results) / total_weight
  350. print(f" 融合结果: ({x_ratio:.3f}, {y_ratio:.3f})")
  351. return (True, x_ratio, y_ratio)
  352. class CameraCalibrator:
  353. """
  354. 相机校准器
  355. 两阶段校准:先发现视野重叠区域,再在重叠区内校准
  356. """
  357. def __init__(self, ptz_camera: PTZCamera,
  358. get_frame_func: Callable[[], np.ndarray],
  359. detect_marker_func: Callable[[np.ndarray], Optional[Tuple[float, float]]] = None,
  360. ptz_capture_func: Callable[[], Optional[np.ndarray]] = None):
  361. self.ptz = ptz_camera
  362. self.get_frame = get_frame_func
  363. self.detect_marker = detect_marker_func
  364. self.ptz_capture = ptz_capture_func
  365. self.visual_detector = VisualCalibrationDetector()
  366. self.overlap_discovery = OverlapDiscovery()
  367. self.state = CalibrationState.IDLE
  368. self.result: Optional[CalibrationResult] = None
  369. # 变换参数
  370. self.pan_offset = 0.0
  371. self.pan_scale_x = 1.0
  372. self.pan_scale_y = 0.0
  373. self.tilt_offset = 0.0
  374. self.tilt_scale_x = 0.0
  375. self.tilt_scale_y = 1.0
  376. # 校准配置
  377. self.stabilize_time = 2.0
  378. self.use_motion_detection = True
  379. self.use_feature_matching = True
  380. # 重叠发现配置
  381. self.overlap_pan_range = (0, 360)
  382. self.overlap_tilt_range = (-30, 30)
  383. self.overlap_pan_step = 20
  384. self.overlap_tilt_step = 15
  385. self.max_overlap_ranges = 3
  386. self.min_positions_per_range = 3
  387. # 回调
  388. self.on_progress: Optional[Callable[[int, int, str], None]] = None
  389. self.on_complete: Optional[Callable[[CalibrationResult], None]] = None
  390. # 发现的重叠区间
  391. self.overlap_ranges: List[OverlapRange] = []
  392. def calibrate(self, quick_mode: bool = True) -> CalibrationResult:
  393. """
  394. 执行校准 - 两阶段流程
  395. 阶段1: 视野重叠发现 - 扫描球机范围,找出与全景有重叠的角度区间
  396. 阶段2: 精确校准 - 仅在重叠区间内生成校准点,逐一验证后拟合变换
  397. """
  398. self.state = CalibrationState.RUNNING
  399. # ===================== 阶段1: 视野重叠发现 =====================
  400. print(f"\n{'='*60}")
  401. print(f"阶段1: 视野重叠发现 - 确定球机与全景的重叠区域")
  402. print(f"{'='*60}")
  403. self.overlap_ranges = self.overlap_discovery.discover_overlap_ranges(
  404. ptz=self.ptz,
  405. get_panorama_frame=self.get_frame,
  406. ptz_capture=self.ptz_capture,
  407. pan_range=self.overlap_pan_range,
  408. tilt_range=self.overlap_tilt_range,
  409. pan_step=self.overlap_pan_step,
  410. tilt_step=self.overlap_tilt_step,
  411. stabilize_time=self.stabilize_time,
  412. on_progress=self.on_progress,
  413. max_ranges=self.max_overlap_ranges,
  414. min_positions_per_range=self.min_positions_per_range
  415. )
  416. if not self.overlap_ranges:
  417. self.state = CalibrationState.FAILED
  418. self.result = CalibrationResult(
  419. success=False,
  420. points=[],
  421. error_message="未发现球机与全景的视野重叠区域,无法校准。请检查两台摄像头的安装位置和朝向。"
  422. )
  423. print(f"\n校准失败: {self.result.error_message}")
  424. if self.on_complete:
  425. self.on_complete(self.result)
  426. return self.result
  427. print(f"\n发现 {len(self.overlap_ranges)} 个重叠区间")
  428. # 选择匹配点最多的区间用于校准
  429. best_range = max(self.overlap_ranges, key=lambda r: r.match_count)
  430. self.overlap_ranges = [best_range]
  431. print(f"选择最佳重叠区间: pan=[{best_range.pan_start:.0f}°, {best_range.pan_end:.0f}°], "
  432. f"tilt=[{best_range.tilt_start:.0f}°, {best_range.tilt_end:.0f}°], "
  433. f"匹配点={best_range.match_count}")
  434. print(f"进入阶段2校准")
  435. # ===================== 阶段2: 在重叠区内精确校准 =====================
  436. print(f"\n{'='*60}")
  437. print(f"阶段2: 精确校准 - 在重叠区间内采集校准点")
  438. print(f"{'='*60}")
  439. calib_points = self._generate_points_in_overlaps(quick_mode)
  440. valid_points = []
  441. total_points = len(calib_points)
  442. print(f"生成 {total_points} 个校准点(仅位于重叠区域内)")
  443. for idx, point in enumerate(calib_points):
  444. if self.on_progress:
  445. self.on_progress(idx + 1, total_points,
  446. f"校准点 {idx + 1}/{total_points}: pan={point.pan:.1f}°, tilt={point.tilt:.1f}°")
  447. print(f"\n 校准点 {idx + 1}/{total_points}: pan={point.pan:.1f}°, tilt={point.tilt:.1f}°")
  448. # 步骤1: 获取移动前全景帧(用于运动检测)
  449. frames_before_list = []
  450. for _ in range(3):
  451. frame = self.get_frame()
  452. if frame is not None:
  453. frames_before_list.append(frame)
  454. time.sleep(0.1)
  455. if not frames_before_list:
  456. print(f" 警告: 无法获取移动前的全景画面")
  457. continue
  458. frames_before = np.mean(frames_before_list, axis=0).astype(np.uint8)
  459. # 步骤2: 移动球机到目标位置
  460. print(f" [2/4] 移动球机到目标位置...")
  461. if not self.ptz.goto_exact_position(point.pan, point.tilt, 1):
  462. print(f" 警告: 移动球机失败")
  463. continue
  464. time.sleep(self.stabilize_time)
  465. # 步骤3: 获取移动后全景帧和球机抓拍
  466. print(f" [3/4] 获取移动后的帧...")
  467. frames_after_list = []
  468. for _ in range(3):
  469. frame = self.get_frame()
  470. if frame is not None:
  471. frames_after_list.append(frame)
  472. time.sleep(0.1)
  473. if not frames_after_list:
  474. print(f" 警告: 无法获取移动后的全景画面")
  475. continue
  476. frames_after = np.mean(frames_after_list, axis=0).astype(np.uint8)
  477. panorama_frame = frames_after
  478. # 球机抓拍(关键:特征匹配需要球机画面)
  479. ptz_frame = None
  480. if self.use_feature_matching and self.ptz_capture:
  481. try:
  482. ptz_frame = self.ptz_capture()
  483. if ptz_frame is not None:
  484. print(f" 球机抓拍成功: {ptz_frame.shape}")
  485. except Exception as e:
  486. print(f" 球机抓拍失败: {e}")
  487. # 步骤4: 视觉检测 + 重叠验证
  488. print(f" [4/4] 视觉检测与重叠验证...")
  489. # 优先使用特征匹配(最可靠的方法)
  490. if ptz_frame is not None and panorama_frame is not None:
  491. success, match_count, cx, cy = self.overlap_discovery.match_frames(ptz_frame, panorama_frame)
  492. if success:
  493. h, w = panorama_frame.shape[:2]
  494. point.x_ratio = cx / w
  495. point.y_ratio = cy / h
  496. point.detected = True
  497. valid_points.append(point)
  498. print(f" ✓ 特征匹配验证通过: {match_count}个匹配点, "
  499. f"全景位置=({point.x_ratio:.3f}, {point.y_ratio:.3f})")
  500. continue
  501. else:
  502. print(f" ✗ 特征匹配不足({match_count}点), 尝试运动检测...")
  503. # 备选: 运动检测
  504. if self.use_motion_detection and frames_before is not None and frames_after is not None:
  505. motion_result = self.visual_detector.detect_by_motion(frames_before, frames_after)
  506. if motion_result:
  507. point.x_ratio, point.y_ratio = motion_result
  508. point.detected = True
  509. valid_points.append(point)
  510. print(f" ✓ 运动检测定位: ({point.x_ratio:.3f}, {point.y_ratio:.3f})")
  511. continue
  512. # 自定义标记检测
  513. if self.detect_marker:
  514. marker_pos = self.detect_marker(panorama_frame)
  515. if marker_pos:
  516. point.x_ratio, point.y_ratio = marker_pos
  517. point.detected = True
  518. valid_points.append(point)
  519. print(f" ✓ 标记检测成功: ({point.x_ratio:.3f}, {point.y_ratio:.3f})")
  520. continue
  521. # 所有方法均失败 - 跳过此点(不使用估算!)
  522. print(f" ✗ 此校准点无法验证,跳过(不使用估算)")
  523. # ===================== 检查有效校准点 =====================
  524. min_valid = 4
  525. if len(valid_points) < min_valid:
  526. self.state = CalibrationState.FAILED
  527. self.result = CalibrationResult(
  528. success=False,
  529. points=valid_points,
  530. error_message=f"有效校准点不足 (需要至少{min_valid}个, 实际{len(valid_points)}个)。"
  531. f"请检查球机与全景的视野重叠是否足够。"
  532. )
  533. print(f"\n校准失败: {self.result.error_message}")
  534. if self.on_complete:
  535. self.on_complete(self.result)
  536. return self.result
  537. # ===================== 计算变换参数 =====================
  538. success = self._calculate_transform(valid_points)
  539. if success:
  540. self.state = CalibrationState.SUCCESS
  541. rms_error = self._calculate_rms_error(valid_points)
  542. self.result = CalibrationResult(
  543. success=True,
  544. points=valid_points,
  545. rms_error=rms_error
  546. )
  547. print(f"\n{'='*60}")
  548. print(f"校准成功!")
  549. print(f"有效校准点: {len(valid_points)}")
  550. print(f"重叠区间数: {len(self.overlap_ranges)}")
  551. print(f"RMS误差: {rms_error:.4f}°")
  552. print(f"{'='*60}")
  553. else:
  554. self.state = CalibrationState.FAILED
  555. self.result = CalibrationResult(
  556. success=False,
  557. points=valid_points,
  558. error_message="变换参数计算失败"
  559. )
  560. print(f"校准失败: {self.result.error_message}")
  561. if self.on_complete:
  562. self.on_complete(self.result)
  563. return self.result
  564. def _generate_points_in_overlaps(self, quick_mode: bool = True) -> List[CalibrationPoint]:
  565. """
  566. 在发现的重叠区间内生成校准点
  567. 只在球机和全景有视觉重叠的区域生成点
  568. """
  569. points = []
  570. if quick_mode:
  571. # 快速模式: 每个重叠区间内生成3-5个点
  572. for overlap in self.overlap_ranges:
  573. # 在区间中心生成点
  574. pan_center = (overlap.pan_start + overlap.pan_end) / 2
  575. tilt_center = (overlap.tilt_start + overlap.tilt_end) / 2
  576. pan_span = overlap.pan_end - overlap.pan_start
  577. tilt_span = overlap.tilt_end - overlap.tilt_start
  578. # 中心点
  579. points.append(CalibrationPoint(pan=pan_center, tilt=tilt_center, zoom=1.0))
  580. # 四角点(如果区间足够宽)
  581. if pan_span > 10:
  582. points.append(CalibrationPoint(
  583. pan=overlap.pan_start + pan_span * 0.25,
  584. tilt=tilt_center, zoom=1.0))
  585. points.append(CalibrationPoint(
  586. pan=overlap.pan_start + pan_span * 0.75,
  587. tilt=tilt_center, zoom=1.0))
  588. if tilt_span > 10:
  589. points.append(CalibrationPoint(
  590. pan=pan_center,
  591. tilt=overlap.tilt_start + tilt_span * 0.3, zoom=1.0))
  592. points.append(CalibrationPoint(
  593. pan=pan_center,
  594. tilt=overlap.tilt_start + tilt_span * 0.7, zoom=1.0))
  595. else:
  596. # 完整模式: 在每个重叠区间内均匀分布
  597. grid_size = 5
  598. for overlap in self.overlap_ranges:
  599. for i in range(grid_size):
  600. for j in range(grid_size):
  601. pan = overlap.pan_start + (overlap.pan_end - overlap.pan_start) * i / (grid_size - 1)
  602. tilt = overlap.tilt_start + (overlap.tilt_end - overlap.tilt_start) * j / (grid_size - 1)
  603. points.append(CalibrationPoint(pan=pan, tilt=tilt, zoom=1.0))
  604. return points
  605. def _calculate_transform(self, points: List[CalibrationPoint]) -> bool:
  606. """使用RANSAC + 最小二乘法拟合变换参数,剔除异常值"""
  607. try:
  608. if len(points) < 4:
  609. print(f"计算变换参数错误: 有效点不足({len(points)}个)")
  610. return False
  611. pan_values = np.array([p.pan for p in points])
  612. tilt_values = np.array([p.tilt for p in points])
  613. x_ratios = np.array([p.x_ratio for p in points])
  614. y_ratios = np.array([p.y_ratio for p in points])
  615. # RANSAC剔除异常值
  616. inlier_mask = self._ransac_filter(x_ratios, y_ratios, pan_values, tilt_values)
  617. inlier_count = np.sum(inlier_mask)
  618. if inlier_count < 4:
  619. print(f"RANSAC后有效点不足({inlier_count}个),使用全部点")
  620. inlier_mask = np.ones(len(points), dtype=bool)
  621. else:
  622. print(f"RANSAC: {len(points)}个点中{inlier_count}个内点,剔除{len(points) - inlier_count}个异常值")
  623. # 用内点拟合
  624. A = np.ones((inlier_count, 3))
  625. A[:, 1] = x_ratios[inlier_mask]
  626. A[:, 2] = y_ratios[inlier_mask]
  627. pan_params, _, _, _ = np.linalg.lstsq(A, pan_values[inlier_mask], rcond=None)
  628. tilt_params, _, _, _ = np.linalg.lstsq(A, tilt_values[inlier_mask], rcond=None)
  629. self.pan_offset = pan_params[0]
  630. self.pan_scale_x = pan_params[1]
  631. self.pan_scale_y = pan_params[2]
  632. self.tilt_offset = tilt_params[0]
  633. self.tilt_scale_x = tilt_params[1]
  634. self.tilt_scale_y = tilt_params[2]
  635. print(f"变换参数:")
  636. print(f" pan = {self.pan_offset:.2f} + {self.pan_scale_x:.2f}*x + {self.pan_scale_y:.2f}*y")
  637. print(f" tilt = {self.tilt_offset:.2f} + {self.tilt_scale_x:.2f}*x + {self.tilt_scale_y:.2f}*y")
  638. return True
  639. except Exception as e:
  640. print(f"计算变换参数错误: {e}")
  641. return False
  642. def _ransac_filter(self, x: np.ndarray, y: np.ndarray,
  643. pan: np.ndarray, tilt: np.ndarray,
  644. max_iterations: int = 200, threshold: float = 15.0,
  645. min_samples: int = 4) -> np.ndarray:
  646. """RANSAC剔除变换拟合中的异常值"""
  647. n = len(x)
  648. best_inliers = np.zeros(n, dtype=bool)
  649. best_inlier_count = 0
  650. rng = np.random.RandomState(42)
  651. for _ in range(max_iterations):
  652. # 随机选min_samples个点
  653. indices = rng.choice(n, min_samples, replace=False)
  654. # 用这些点拟合
  655. A = np.ones((min_samples, 3))
  656. A[:, 1] = x[indices]
  657. A[:, 2] = y[indices]
  658. try:
  659. pan_params, _, _, _ = np.linalg.lstsq(A, pan[indices], rcond=None)
  660. tilt_params, _, _, _ = np.linalg.lstsq(A, tilt[indices], rcond=None)
  661. except np.linalg.LinAlgError:
  662. continue
  663. # 计算所有点的误差
  664. pred_pan = pan_params[0] + pan_params[1] * x + pan_params[2] * y
  665. pred_tilt = tilt_params[0] + tilt_params[1] * x + tilt_params[2] * y
  666. errors = np.sqrt((pred_pan - pan) ** 2 + (pred_tilt - tilt) ** 2)
  667. inliers = errors < threshold
  668. inlier_count = np.sum(inliers)
  669. if inlier_count > best_inlier_count:
  670. best_inlier_count = inlier_count
  671. best_inliers = inliers
  672. if best_inlier_count == 0:
  673. return np.ones(n, dtype=bool)
  674. return best_inliers
  675. def _calculate_rms_error(self, points: List[CalibrationPoint]) -> float:
  676. """计算均方根误差"""
  677. total_error = 0.0
  678. for p in points:
  679. pred_pan, pred_tilt = self.transform(p.x_ratio, p.y_ratio)
  680. error = math.sqrt((pred_pan - p.pan) ** 2 + (pred_tilt - p.tilt) ** 2)
  681. total_error += error ** 2
  682. return math.sqrt(total_error / len(points))
  683. def transform(self, x_ratio: float, y_ratio: float) -> Tuple[float, float]:
  684. """将全景坐标转换为PTZ角度"""
  685. pan = self.pan_offset + self.pan_scale_x * x_ratio + self.pan_scale_y * y_ratio
  686. tilt = self.tilt_offset + self.tilt_scale_x * x_ratio + self.tilt_scale_y * y_ratio
  687. return (pan, tilt)
  688. def inverse_transform(self, pan: float, tilt: float) -> Tuple[float, float]:
  689. """将PTZ角度转换为全景坐标(近似)"""
  690. x_ratio = (pan - self.pan_offset) / self.pan_scale_x if self.pan_scale_x != 0 else 0.5
  691. y_ratio = (tilt - self.tilt_offset) / self.tilt_scale_y if self.tilt_scale_y != 0 else 0.5
  692. return (max(0, min(1, x_ratio)), max(0, min(1, y_ratio)))
  693. def is_calibrated(self) -> bool:
  694. return self.state == CalibrationState.SUCCESS
  695. def get_state(self) -> CalibrationState:
  696. return self.state
  697. def get_result(self) -> Optional[CalibrationResult]:
  698. return self.result
  699. def get_overlap_ranges(self) -> List[OverlapRange]:
  700. """返回发现的重叠区间"""
  701. return self.overlap_ranges
  702. def save_calibration(self, filepath: str) -> bool:
  703. """保存校准结果"""
  704. if not self.is_calibrated():
  705. return False
  706. try:
  707. import json
  708. data = {
  709. 'pan_offset': self.pan_offset,
  710. 'pan_scale_x': self.pan_scale_x,
  711. 'pan_scale_y': self.pan_scale_y,
  712. 'tilt_offset': self.tilt_offset,
  713. 'tilt_scale_x': self.tilt_scale_x,
  714. 'tilt_scale_y': self.tilt_scale_y,
  715. 'rms_error': self.result.rms_error if self.result else 0,
  716. 'overlap_ranges': [
  717. {
  718. 'pan_start': r.pan_start,
  719. 'pan_end': r.pan_end,
  720. 'tilt_start': r.tilt_start,
  721. 'tilt_end': r.tilt_end,
  722. 'match_count': r.match_count
  723. }
  724. for r in self.overlap_ranges
  725. ]
  726. }
  727. with open(filepath, 'w') as f:
  728. json.dump(data, f, indent=2)
  729. print(f"校准结果已保存: {filepath}")
  730. return True
  731. except Exception as e:
  732. print(f"保存校准结果失败: {e}")
  733. return False
  734. def load_calibration(self, filepath: str) -> bool:
  735. """加载校准结果"""
  736. try:
  737. import json
  738. with open(filepath, 'r') as f:
  739. data = json.load(f)
  740. self.pan_offset = data['pan_offset']
  741. self.pan_scale_x = data['pan_scale_x']
  742. self.pan_scale_y = data['pan_scale_y']
  743. self.tilt_offset = data['tilt_offset']
  744. self.tilt_scale_x = data['tilt_scale_x']
  745. self.tilt_scale_y = data['tilt_scale_y']
  746. # 加载重叠区间(如果有)
  747. if 'overlap_ranges' in data:
  748. self.overlap_ranges = [
  749. OverlapRange(
  750. pan_start=r['pan_start'],
  751. pan_end=r['pan_end'],
  752. tilt_start=r['tilt_start'],
  753. tilt_end=r['tilt_end'],
  754. match_count=r['match_count'],
  755. panorama_center_x=0,
  756. panorama_center_y=0
  757. )
  758. for r in data['overlap_ranges']
  759. ]
  760. self.state = CalibrationState.SUCCESS
  761. self.result = CalibrationResult(
  762. success=True,
  763. points=[],
  764. rms_error=data.get('rms_error', 0)
  765. )
  766. print(f"校准结果已加载: {filepath}")
  767. return True
  768. except FileNotFoundError:
  769. print(f"校准文件不存在: {filepath}")
  770. return False
  771. except Exception as e:
  772. print(f"加载校准结果失败: {e}")
  773. return False
  774. class CalibrationManager:
  775. """校准管理器"""
  776. def __init__(self, calibrator: CameraCalibrator):
  777. self.calibrator = calibrator
  778. self.calibration_file = "calibration.json"
  779. def auto_calibrate(self, force: bool = False) -> CalibrationResult:
  780. """自动校准"""
  781. if not force:
  782. if self.calibrator.load_calibration(self.calibration_file):
  783. print("使用已有校准结果")
  784. return self.calibrator.get_result()
  785. print("开始自动校准...")
  786. result = self.calibrator.calibrate(quick_mode=True)
  787. if result.success:
  788. self.calibrator.save_calibration(self.calibration_file)
  789. return result
  790. def check_calibration(self) -> Tuple[bool, str]:
  791. """检查校准状态"""
  792. state = self.calibrator.get_state()
  793. if state == CalibrationState.SUCCESS:
  794. result = self.calibrator.get_result()
  795. overlaps = self.calibrator.get_overlap_ranges()
  796. overlap_info = f", {len(overlaps)}个重叠区间" if overlaps else ""
  797. return (True, f"校准有效, RMS误差: {result.rms_error:.4f}°{overlap_info}")
  798. elif state == CalibrationState.FAILED:
  799. return (False, "校准失败")
  800. elif state == CalibrationState.RUNNING:
  801. return (False, "校准进行中")
  802. else:
  803. return (False, "未校准")