megadepth_pose_estimation_benchmark_poselib.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import numpy as np
  2. import torch
  3. from romatch.utils import *
  4. from PIL import Image
  5. from tqdm import tqdm
  6. # wrap cause pyposelib is still in dev
  7. # will add in deps later
  8. import poselib
  9. class Mega1500PoseLibBenchmark:
  10. def __init__(self, data_root="data/megadepth", scene_names = None, num_ransac_iter = 5, test_every = 1) -> None:
  11. if scene_names is None:
  12. self.scene_names = [
  13. "0015_0.1_0.3.npz",
  14. "0015_0.3_0.5.npz",
  15. "0022_0.1_0.3.npz",
  16. "0022_0.3_0.5.npz",
  17. "0022_0.5_0.7.npz",
  18. ]
  19. else:
  20. self.scene_names = scene_names
  21. self.scenes = [
  22. np.load(f"{data_root}/{scene}", allow_pickle=True)
  23. for scene in self.scene_names
  24. ]
  25. self.data_root = data_root
  26. self.num_ransac_iter = num_ransac_iter
  27. self.test_every = test_every
  28. def benchmark(self, model, model_name = None):
  29. with torch.no_grad():
  30. data_root = self.data_root
  31. tot_e_t, tot_e_R, tot_e_pose = [], [], []
  32. thresholds = [5, 10, 20]
  33. for scene_ind in range(len(self.scenes)):
  34. import os
  35. scene_name = os.path.splitext(self.scene_names[scene_ind])[0]
  36. scene = self.scenes[scene_ind]
  37. pairs = scene["pair_infos"]
  38. intrinsics = scene["intrinsics"]
  39. poses = scene["poses"]
  40. im_paths = scene["image_paths"]
  41. pair_inds = range(len(pairs))[::self.test_every]
  42. for pairind in (pbar := tqdm(pair_inds, desc = "Current AUC: ?")):
  43. idx1, idx2 = pairs[pairind][0]
  44. K1 = intrinsics[idx1].copy()
  45. T1 = poses[idx1].copy()
  46. R1, t1 = T1[:3, :3], T1[:3, 3]
  47. K2 = intrinsics[idx2].copy()
  48. T2 = poses[idx2].copy()
  49. R2, t2 = T2[:3, :3], T2[:3, 3]
  50. R, t = compute_relative_pose(R1, t1, R2, t2)
  51. T1_to_2 = np.concatenate((R,t[:,None]), axis=-1)
  52. im_A_path = f"{data_root}/{im_paths[idx1]}"
  53. im_B_path = f"{data_root}/{im_paths[idx2]}"
  54. dense_matches, dense_certainty = model.match(
  55. im_A_path, im_B_path, K1.copy(), K2.copy(), T1_to_2.copy()
  56. )
  57. sparse_matches,_ = model.sample(
  58. dense_matches, dense_certainty, 5_000
  59. )
  60. im_A = Image.open(im_A_path)
  61. w1, h1 = im_A.size
  62. im_B = Image.open(im_B_path)
  63. w2, h2 = im_B.size
  64. kpts1, kpts2 = model.to_pixel_coordinates(sparse_matches, h1, w1, h2, w2)
  65. kpts1, kpts2 = kpts1.cpu().numpy(), kpts2.cpu().numpy()
  66. for _ in range(self.num_ransac_iter):
  67. shuffling = np.random.permutation(np.arange(len(kpts1)))
  68. kpts1 = kpts1[shuffling]
  69. kpts2 = kpts2[shuffling]
  70. try:
  71. threshold = 1
  72. camera1 = {'model': 'PINHOLE', 'width': w1, 'height': h1, 'params': K1[[0,1,0,1], [0,1,2,2]]}
  73. camera2 = {'model': 'PINHOLE', 'width': w2, 'height': h2, 'params': K2[[0,1,0,1], [0,1,2,2]]}
  74. relpose, res = poselib.estimate_relative_pose(
  75. kpts1,
  76. kpts2,
  77. camera1,
  78. camera2,
  79. ransac_opt = {"max_reproj_error": 2*threshold, "max_epipolar_error": threshold, "min_inliers": 8, "max_iterations": 10_000},
  80. )
  81. Rt_est = relpose.Rt
  82. R_est, t_est = Rt_est[:3,:3], Rt_est[:3,3:]
  83. mask = np.array(res['inliers']).astype(np.float32)
  84. T1_to_2_est = np.concatenate((R_est, t_est), axis=-1) #
  85. e_t, e_R = compute_pose_error(T1_to_2_est, R, t)
  86. e_pose = max(e_t, e_R)
  87. except Exception as e:
  88. print(repr(e))
  89. e_t, e_R = 90, 90
  90. e_pose = max(e_t, e_R)
  91. tot_e_t.append(e_t)
  92. tot_e_R.append(e_R)
  93. tot_e_pose.append(e_pose)
  94. pbar.set_description(f"Current AUC: {pose_auc(tot_e_pose, thresholds)}")
  95. tot_e_pose = np.array(tot_e_pose)
  96. auc = pose_auc(tot_e_pose, thresholds)
  97. acc_5 = (tot_e_pose < 5).mean()
  98. acc_10 = (tot_e_pose < 10).mean()
  99. acc_15 = (tot_e_pose < 15).mean()
  100. acc_20 = (tot_e_pose < 20).mean()
  101. map_5 = acc_5
  102. map_10 = np.mean([acc_5, acc_10])
  103. map_20 = np.mean([acc_5, acc_10, acc_15, acc_20])
  104. print(f"{model_name} auc: {auc}")
  105. return {
  106. "auc_5": auc[0],
  107. "auc_10": auc[1],
  108. "auc_20": auc[2],
  109. "map_5": map_5,
  110. "map_10": map_10,
  111. "map_20": map_20,
  112. }