calibrate.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # -*- coding: utf-8 -*-
  2. """
  3. 带有RANSAC功能的摄像头自动标定工具 (v3.2 结构优化版)
  4. 功能:
  5. - RANSAC算法自动剔除“坏点”。
  6. - 新增 calculate_final_parameters 函数,使用所有“好点”进行最终的联合优化,计算出最精确结果。
  7. v3.2 更新日志:
  8. - 将最终优化步骤封装到独立的 calculate_final_parameters 函数中,使流程更清晰。
  9. """
  10. import numpy as np
  11. from scipy.optimize import minimize
  12. from scipy.spatial.transform import Rotation as R
  13. import random
  14. import warnings
  15. warnings.filterwarnings("ignore", category=RuntimeWarning)
  16. ## -------------------------------------------------------------------------- ##
  17. ## 1. 核心算法函数 (无变化)
  18. ## -------------------------------------------------------------------------- ##
  19. EARTH_RADIUS = 6378137.0
  20. def lonlat_to_enu(lon, lat, center_lon, center_lat):
  21. delta_lon = np.radians(lon - center_lon); delta_lat = np.radians(lat - center_lat)
  22. x = EARTH_RADIUS * delta_lon * np.cos(np.radians(center_lat)); y = EARTH_RADIUS * delta_lat
  23. return np.array([x, y, 0])
  24. def enu_to_lonlat(enu_point, center_lon, center_lat):
  25. x, y, _ = enu_point; delta_lat_rad = y / EARTH_RADIUS
  26. delta_lon_rad = x / (EARTH_RADIUS * np.cos(np.radians(center_lat)))
  27. lon = center_lon + np.degrees(delta_lon_rad); lat = center_lat + np.degrees(delta_lat_rad)
  28. return lon, lat
  29. def project_pixel_to_lonlat(u, v, resolution_w, resolution_h, cam_lon, cam_lat,
  30. cam_height, p, t, hfov, north_p_value=0.0, **kwargs):
  31. f_x = resolution_w / (2 * np.tan(np.radians(hfov) / 2)); f_y = f_x
  32. cx = resolution_w / 2; cy = resolution_h / 2
  33. vec_cam = np.array([(u - cx) / f_x, (v - cy) / f_y, 1.0]); vec_cam /= np.linalg.norm(vec_cam)
  34. r_base = R.from_euler('x', -90, degrees=True); p_corrected = p - north_p_value
  35. r_pan = R.from_euler('z', p_corrected, degrees=True); r_tilt = R.from_euler('x', -t, degrees=True)
  36. total_rotation = r_pan * r_tilt * r_base; vec_enu = total_rotation.apply(vec_cam)
  37. if vec_enu[2] >= -1e-9: return None, None
  38. cam_pos_enu = np.array([0, 0, cam_height]); s = -cam_height / vec_enu[2]
  39. intersection_enu = cam_pos_enu + s * vec_enu
  40. return enu_to_lonlat(intersection_enu, cam_lon, cam_lat)
  41. ## -------------------------------------------------------------------------- ##
  42. ## 2. RANSAC 及最终计算逻辑
  43. ## -------------------------------------------------------------------------- ##
  44. def solve_model_for_subset(subset_points, camera_params, initial_guesses):
  45. """(RANSAC内部使用) 使用一个小的点集来快速计算一个模型参数的估计值"""
  46. static_args = camera_params.copy()
  47. initial_values = [initial_guesses['height'], initial_guesses['hfov']]
  48. def objective(params):
  49. total_error = 0.0
  50. for point in subset_points:
  51. pred_lon, pred_lat = project_pixel_to_lonlat(point[0], point[1], cam_height=params[0], hfov=params[1], **static_args)
  52. if pred_lon is None: return 1e12
  53. true_enu = lonlat_to_enu(point[2], point[3], camera_params['cam_lon'], camera_params['cam_lat']); pred_enu = lonlat_to_enu(pred_lon, pred_lat, camera_params['cam_lon'], camera_params['cam_lat'])
  54. total_error += np.sum((pred_enu - true_enu)**2)
  55. return total_error
  56. result = minimize(objective, initial_values, method='Nelder-Mead', options={'xatol': 1e-2, 'fatol': 1e-2})
  57. if result.success: return result.x[0], result.x[1]
  58. return None, None
  59. def calculate_final_parameters(inliers, camera_params, initial_guesses):
  60. """
  61. [新增方法] 使用所有“好点”(inliers)进行最终的联合优化,计算最精确的平均高度和HFOV。
  62. """
  63. print("\n--- 使用所有内点进行最终优化 ---")
  64. static_args = camera_params.copy()
  65. initial_values = [initial_guesses['height'], initial_guesses['hfov']]
  66. def objective(params):
  67. total_error = 0.0
  68. for point in inliers:
  69. pred_lon, pred_lat = project_pixel_to_lonlat(point[0], point[1], cam_height=params[0], hfov=params[1], **static_args)
  70. if pred_lon is None: return 1e12
  71. true_enu = lonlat_to_enu(point[2], point[3], camera_params['cam_lon'], camera_params['cam_lat']); pred_enu = lonlat_to_enu(pred_lon, pred_lat, camera_params['cam_lon'], camera_params['cam_lat'])
  72. error = np.sum((pred_enu - true_enu)**2); total_error += error
  73. return total_error
  74. result = minimize(objective, initial_values, method='Nelder-Mead', options={'disp': True, 'xatol': 1e-6, 'fatol': 1e-6})
  75. if result.success and result.fun < 1e11:
  76. return result.x[0], result.x[1], result.fun
  77. else:
  78. return (result.x[0], result.x[1], result.fun)
  79. def run_ransac_calibration(all_points, camera_params, initial_guesses,
  80. ransac_iterations=100, subset_size=3, error_threshold=3.0):
  81. """执行RANSAC算法来寻找最佳的内点集。"""
  82. print("--- 开始执行RANSAC自动标定 ---")
  83. print(f"总点数: {len(all_points)}, RANSAC迭代次数: {ransac_iterations}, 误差阈值: {error_threshold}米")
  84. best_inliers, best_model_params = [], (0, 0)
  85. for i in range(ransac_iterations):
  86. if len(all_points) < subset_size: print("错误:总点数小于子集大小。"); return None, None, []
  87. subset = random.sample(all_points, subset_size)
  88. height_hyp, hfov_hyp = solve_model_for_subset(subset, camera_params, initial_guesses)
  89. if height_hyp is None: continue
  90. current_inliers = []
  91. for point in all_points:
  92. pred_lon, pred_lat = project_pixel_to_lonlat(point[0], point[1], cam_height=height_hyp, hfov=hfov_hyp, **camera_params)
  93. if pred_lon is not None:
  94. true_enu = lonlat_to_enu(point[2], point[3], camera_params['cam_lon'], camera_params['cam_lat']); pred_enu = lonlat_to_enu(pred_lon, pred_lat, camera_params['cam_lon'], camera_params['cam_lat'])
  95. error = np.linalg.norm(true_enu - pred_enu)
  96. if error < error_threshold: current_inliers.append(point)
  97. if len(current_inliers) > len(best_inliers):
  98. best_inliers = current_inliers
  99. best_model_params = (height_hyp, hfov_hyp)
  100. print(f" 迭代 {i+1}/{ransac_iterations}: 发现更好的模型,内点数量 = {len(best_inliers)}")
  101. if not best_inliers:
  102. print("\nRANSAC失败:未找到一致的点集。"); return None, None, []
  103. print(f"\nRANSAC完成:找到的最佳模型有 {len(best_inliers)} 个内点。")
  104. # [结构调整] 调用新增的函数进行最终计算
  105. final_height, final_hfov, _ = calculate_final_parameters(best_inliers, camera_params,
  106. {"height": best_model_params[0], "hfov": best_model_params[1]})
  107. return final_height, final_hfov, best_inliers
  108. ## -------------------------------------------------------------------------- ##
  109. ## 3. 数据输入与执行
  110. ## -------------------------------------------------------------------------- ##
  111. if __name__ == '__main__':
  112. all_calibration_data = [
  113. (548, 196, 112.894553, 28.221280), (91, 276, 112.894612, 28.221594), (216, 189, 112.894757, 28.221469),
  114. (850, 250, 112.89487, 28.22086), (450, 450, 112.89389, 28.22137), (1100, 500, 112.89468, 28.22050),
  115. (610, 415, 112.8955, 28.2220), (362, 527, 112.8930, 28.2210),
  116. ]
  117. camera_params = {
  118. "resolution_w": 1280, "resolution_h": 720, "cam_lon": 112.893799, "cam_lat": 28.221701,
  119. "north_p_value": 39.0, "p": 271.9, "t": 26.2
  120. }
  121. initial_guesses = {"height": 0, "hfov": 0}
  122. final_height, final_hfov, inliers = run_ransac_calibration(
  123. all_points=all_calibration_data, camera_params=camera_params, initial_guesses=initial_guesses,
  124. ransac_iterations=100, subset_size=3, error_threshold=3.0)
  125. if final_height is not None:
  126. print("\n" + "#"*50); print("#" + " "*12 + "RANSAC 自动标定成功完成" + " "*13 + "#"); print("#"*50)
  127. print(f"# >>> 最终标定结果 (Final Calibrated Results):")
  128. print(f"# - 摄像头高度 (Height): {final_height:.4f} 米")
  129. print(f"# - 水平视场角 (HFOV): {final_hfov:.4f} 度")
  130. print("#" + "-"*48 + "#")
  131. print(f"# 共找到 {len(inliers)} 个一致的“好点”(Inliers):")
  132. inlier_pixels = {(p[0], p[1]) for p in inliers}
  133. for point in all_calibration_data:
  134. if (point[0], point[1]) in inlier_pixels: print(f"# - 像素点 ({point[0]}, {point[1]},{point[2]}, {point[3]}) [内点]")
  135. outliers = [p for p in all_calibration_data if (p[0], p[1]) not in inlier_pixels]
  136. if outliers:
  137. print(f"# 共剔除 {len(outliers)} 个“坏点”(Outliers):")
  138. for point in outliers: print(f"# - 像素点 ({point[0]}, {point[1]},{point[2]}, {point[3]}) [外点]")
  139. print("#"*50)