-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgs_cpr_cam_rel.py
203 lines (177 loc) · 8.86 KB
/
gs_cpr_cam_rel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
from mast3r.model import AsymmetricMASt3R
import mast3r.utils.path_to_dust3r
from dust3r.inference import inference
from dust3r.utils.image import load_images
from argparse import ArgumentParser
from dust3r.cloud_opt import global_aligner, GlobalAlignerMode
from dust3r.image_pairs import make_pairs
from tqdm import tqdm
import numpy as np
import math
import cv2
import os
from utils.functions import *
import logging
_logger = logging.getLogger(__name__)
if __name__ == '__main__':
device = 'cuda'
batch_size = 1
schedule = 'cosine'
lr = 0.01
parser = ArgumentParser(description="GS-CPR_rel for pose estimators")
parser.add_argument("--pose_estimator", default="dfnet",choices=["ace","dfnet"], type=str)
parser.add_argument("--scene", default="ShopFacade", type=str)
parser.add_argument("--test_all", action='store_true', default=False)
args = parser.parse_args()
original_size = (1080, 1920)
pe = args.pose_estimator
if args.test_all:
SCENES = ['KingsCollege','ShopFacade','OldHospital','StMarysChurch']
else:
SCENES = [args.scene]
model_name = "naver/MASt3R_ViTLarge_BaseDecoder_512_catmlpdpt_metric"
# you can put the path to a local checkpoint in model_name if needed
model = AsymmetricMASt3R.from_pretrained(model_name).to(device).eval()
log_path = f"./outputs/cambridge/GS_CPR_rel_{pe}_results/"
if not os.path.exists(log_path):
os.makedirs(log_path)
print(f"Directory {log_path} created.")
else:
print(f"Directory {log_path} already exists.")
for SCENE in tqdm(SCENES):
logging.basicConfig(
level=logging.INFO, # 设置日志级别
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', # 日志格式
filename= log_path + f'logs_{SCENE}.log', # 日志文件名
filemode='w' # 写入模式,'w' 表示覆盖,'a' 表示追加
)
_logger = logging.getLogger(__name__)
# load_images can take a list of images or a directory
query_path = f'./datasets/Cambridge_{SCENE}/test/rgb/'
focal_length_path = f'./datasets/Cambridge_{SCENE}/test/calibration/'
raw_img_path = f'./datasets/Cambridge_{SCENE}/'
rendered_path = f'./ACT_Scaffold_GS/data/cambridge/scene_{SCENE}/test/evaluate_{pe}/train_output/render_single_view/'
predict_pose_w2c_path = f'./coarse_poses/{pe}/Cambridge/poses_Cambridge_{SCENE}_.txt'
gt_pose_c2w_path = f'./datasets/Cambridge_{SCENE}/test/poses/'
gs_depth_path = rendered_path
gt_pose_c2w_dict = {}
focal_length_dict = {}
predict_pose_w2c_dict = {}
images_list = []
for filename in os.listdir(query_path):
if filename.endswith('.png'):
images_list.append(filename.replace('_frame','/frame'))
images_list.sort()
for img_name in images_list:
pose_file_name = gt_pose_c2w_path + img_name.replace('.png','.txt').replace('/frame','_frame')
c2w_pose = np.loadtxt(pose_file_name)
focal_length = np.loadtxt(focal_length_path + img_name.replace('.png','.txt').replace('/frame','_frame'))
gt_pose_c2w_dict[img_name] = c2w_pose
focal_length_dict[img_name] = focal_length * 2.25
if pe == 'dfnet':
predict_w2c_ini= getPredictPos(img_name,predict_pose_w2c_path)
else:
predict_w2c_ini= getPredictPos(img_name.replace('/frame','_frame'),predict_pose_w2c_path)
predict_pose_w2c_dict[img_name] = predict_w2c_ini
results_ini = []
results_final = []
refine_results_path = log_path + "refine_predictions/"
if not os.path.exists(refine_results_path):
os.makedirs(refine_results_path)
print(f"Directory {refine_results_path} created.")
else:
print(f"Directory {refine_results_path} already exists.")
ransac_time = 0
with open(refine_results_path + f'{pe}_refinew2c_mast3r_{SCENE}.txt', 'w') as f:
for image in tqdm(images_list):
image1 = rendered_path + image
image2 = raw_img_path + image
images = load_images([image1, image2], size=512)
pairs = make_pairs(images, scene_graph='complete', prefilter=None, symmetrize=True)
output = inference(pairs, model, device, batch_size=batch_size)
scene = global_aligner(output, device=device, mode=GlobalAlignerMode.PairViewer)
poses = scene.get_im_poses()
P_rel = poses[1].detach().cpu().numpy()
T_rel = P_rel[:3,3]
R_rel = P_rel[:3,:3]
array_to_check = np.array([0, 0, 0])
P_ini = np.eye(4)
if np.array_equal(array_to_check, T_rel):
P_rel = np.linalg.inv(poses[0].detach().cpu().numpy())
depth_map = np.load(gs_depth_path+image.replace('png','npy').replace('_frame','/frame'))
depth_map_mast3r = scene.get_depthmaps()[0].cpu().numpy()
depth_map_resized = cv2.resize(depth_map, (512, 288), interpolation=cv2.INTER_LINEAR)
scale_factor = getScale(depth_map_mast3r,depth_map_resized)
predict_w2c_ini = predict_pose_w2c_dict[image]
gt_c2w_pose = gt_pose_c2w_dict[image]
predict_c2w_refine = P_rel.copy()
predict_c2w_refine[:3,3] = P_rel[:3,:3]@P_ini[:3,3] + scale_factor*P_rel[:3,3]
ini_rot_error,ini_translation_error=cal_campose_error(np.linalg.inv(predict_w2c_ini), gt_c2w_pose)
results_ini.append([ini_rot_error,ini_translation_error])
refine_rot_error,refine_translation_error=cal_campose_error(predict_c2w_refine, predict_w2c_ini@gt_c2w_pose)
results_final.append([refine_rot_error,refine_translation_error])
combined_list = [image.replace('_frame','/frame')] + rotmat2qvec(np.linalg.inv(predict_c2w_refine)[:3,:3]).tolist() + np.linalg.inv(predict_c2w_refine)[:3,3].tolist()
output_line = ' '.join(map(str, combined_list))
f.write(output_line + '\n')
median_result_ini = np.median(results_ini,axis=0)
mean_result_ini = np.mean(results_ini,axis=0)
median_result = np.median(results_final,axis=0)
mean_result = np.mean(results_final,axis=0)
pct10_5 = 0
pct5 = 0
pct2 = 0
pct1 = 0
for err in results_ini:
r_err = err[0]
t_err = err[1]
if r_err < 5 and t_err < 0.1: # 10cm/5deg
pct10_5 += 1
if r_err < 5 and t_err < 0.05: # 5cm/5deg
pct5 += 1
if r_err < 2 and t_err < 0.02: # 2cm/2deg
pct2 += 1
if r_err < 1 and t_err < 0.01: # 1cm/1deg
pct1 += 1
total_frames = len(results_ini)
pct10_5 = pct10_5 / total_frames * 100
pct5 = pct5 / total_frames * 100
pct2 = pct2 / total_frames * 100
pct1 = pct1 / total_frames * 100
_logger.info('Ini Accuracy:')
_logger.info(f'\t10cm/5deg: {pct10_5:.1f}%')
_logger.info(f'\t5cm/5deg: {pct5:.1f}%')
_logger.info(f'\t2cm/2deg: {pct2:.1f}%')
_logger.info(f'\t1cm/1deg: {pct1:.1f}%')
pct10_5 = 0
pct5 = 0
pct2 = 0
pct1 = 0
for err in results_final:
r_err = err[0]
t_err = err[1]
if r_err < 5 and t_err < 0.1: # 10cm/5deg
pct10_5 += 1
if r_err < 5 and t_err < 0.05: # 5cm/5deg
pct5 += 1
if r_err < 2 and t_err < 0.02: # 2cm/2deg
pct2 += 1
if r_err < 1 and t_err < 0.01: # 1cm/1deg
pct1 += 1
total_frames = len(results_final)
pct10_5 = pct10_5 / total_frames * 100
pct5 = pct5 / total_frames * 100
pct2 = pct2 / total_frames * 100
pct1 = pct1 / total_frames * 100
_logger.info('After refine Accuracy:')
_logger.info(f'\t10cm/5deg: {pct10_5:.1f}%')
_logger.info(f'\t5cm/5deg: {pct5:.1f}%')
_logger.info(f'\t2cm/2deg: {pct2:.1f}%')
_logger.info(f'\t1cm/1deg: {pct1:.1f}%')
# standard log
_logger.info(f"--------------GS-CPR_rel for {pe}:{SCENE}--------------")
_logger.info("Initial Precision:")
_logger.info('Median error {}m and {} degrees.'.format(median_result_ini[1], median_result_ini[0]))
_logger.info('Mean error {}m and {} degrees.'.format(mean_result_ini[1], mean_result_ini[0]))
_logger.info("After refine Precision:")
_logger.info('Median error {}m and {} degrees.'.format(median_result[1], median_result[0]))
_logger.info('Mean error {}m and {} degrees.'.format(mean_result[1], mean_result[0]))