-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
executable file
·232 lines (195 loc) · 13.2 KB
/
main.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# os.environ['CUDA_LAUNCH_BLOCKING']="1"
import shutil
# import warnings
from xml.etree.ElementTree import PI
from cv2 import log
import torch
from torch.utils.data import DataLoader
import yaml
import numpy as np
import sys
from dataset.kitti360.kitti360_dataset import Kitti360Dataset
from render.render_helper import *
# from torch.utils.tensorboard import SummaryWriter
import time
from utils.mesh_utils import extract_mesh_NFAtlas
from utils import qury_pose
import open3d as o3d
from dataset.kitti360.labels import labels, id2label
from train import Train, clean_cache
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Process some integers.')
# parser.add_argument('--mode', choices=['rgb', 'semantic', 'instance', 'confidence', 'bbox'], default='semantic',
# help='The modality to visualize')
parser.add_argument('--DATA_PATH', type=str, default="",
help='the path of the dataset path', required=True)
parser.add_argument('--config_file', type=str, default="",
help='the path of the configuration file', required=True)
parser.add_argument('--VOLUME_NUM', type=int, default=1,
help='reconstruct VOLUME_NUM volumes')
parser.add_argument('--VIS_FLAG', type=bool, default=False,
help='Generate the mesh per volume (after all epochs of one volume)')
parser.add_argument('--MESH_SIZE', nargs='+', default=[-1,1,-1,1,-0.1,0.2],
help='marchingcubes bbox size [x_min,x_max,y_min,y_max,z_min,z_max]')
parser.add_argument('--MESH_REVU', type=int, default=29,
help='2^MESH_REVU -> number of marchingcubes samples')
args = parser.parse_args()
# dataset
os.environ["KITTI360_DATASET"] = args.DATA_PATH
# warnings.filterwarnings("error")
torch.manual_seed(0)
np.random.seed(250)
torch.set_printoptions(precision=20)
np.set_printoptions(precision=20)
# get current time and create folder
current_time = time.localtime()
date = time.strftime('%Y-%m-%d', current_time)
hour_minute = time.strftime('%H:%M', current_time)
log_dir = os.path.join(os.getcwd(), 'logs', f"{date} {hour_minute}")
folder_name = os.path.join(log_dir, 'events')
if os.path.exists(folder_name):
shutil.rmtree(folder_name)
os.makedirs(folder_name, exist_ok=True)
# writer = SummaryWriter(folder_name)
writer = None
tensorboard_flag = False if writer == None else True
yaml_path = args.config_file #"config/kitti360.yaml"
config_file = yaml_path.split("/")[-1]
with open(yaml_path, "r") as f:
cfg = yaml.safe_load(f)
with open(os.path.join(log_dir, config_file), "w") as f:
yaml.dump(cfg, f, allow_unicode=True, indent=4, default_flow_style=None, sort_keys=False)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Get grid
grid_model_name = cfg['model']['model_name']
print(f"Grid Model = {grid_model_name}")
assert( grid_model_name in GRIDMODEL )
# train
batch_size = int(cfg['params']['ray_chunk_mode2'])
frame_step = cfg['frame']['step']
# read pose
all_pose_list = range(cfg['train']['all_pose'][0], cfg['train']['all_pose'][-1]) #cfg['train']['all_pose']
with torch.no_grad():
if cfg['path']['dataset_type'] == 'kitti-360':
from dataset.kitti360.init_kitti360_pose import init_all_poses
seq = int(cfg['path']['dataset_dir'].split("/")[-3][-6])
vec_es, vec_cam, vec_gt, traj_gt, traj_loam, odom, vec_loam = init_all_poses(cfg['path']['dataset_dir'], seq, all_pose_list, device)
frame_list = list(range(cfg['train']['all_pose'][0],cfg['train']['all_pose'][-1],frame_step))
vec_es_init = vec_loam
elif cfg['path']['dataset_type'] == 'maicity':
from dataset.maicity.init_maicity_pose import init_all_poses
vec_es, vec_gt, traj_gt, traj_loam, odom, vec_loam = init_all_poses(cfg, all_pose_list, device)
frame_list = list(range(cfg['train']['all_pose'][0],cfg['train']['all_pose'][-1],cfg['train']['step']))
else:
sys.exit("Wrong dataset type. Please use maicity or kitti-360")
vec_es_odom = qury_pose.PoseInit(odom, vec_es, vec_loam,frame_list)
logs = []
multi_cube = {"volumes":[], "span_idx":[-1]}
first_idx = frame_list[0]
cubes_num = cfg['start_block_idx']
frame_num = cfg['frame']['num']
frame_half = int(frame_num/2)
frame_start = cubes_num*frame_half
frame_end = frame_start + frame_num
#-------------STEP-------------
for si in range(args.VOLUME_NUM):
train_info = cfg['train']
step = 1
train_list = frame_list[frame_start:frame_end:step]
train_list_last = frame_list[frame_start-frame_half:frame_end-frame_half:1] if train_list[0]>first_idx else None
pose_t = vec_es[f"{train_list[0]}"][:3]
pose_t_last = vec_es[f"{train_list_last[0]}"][:3] if train_list[0]>first_idx else 0
print(f"====================No. {cubes_num} CUBE=====================")
Pipeline = Train(device, cfg, train_list, vec_es, vec_cam, cubes_num)
Pipeline.nef.optim_mode = 3
# iter num
its = 0
print(f"Train Step {si+1}")
key_start, key_num = 0, 1
#-------------optimer-------------
for k in range(key_start, key_num):
clean_cache()
# key frame
train_list_key_frame = train_list
#read data
if cfg['path']['dataset_type'] == 'kitti-360':
from dataset.kitti360.kitti360_dataset import Kitti360Dataset
dataset_train = Kitti360Dataset(cfg, train_list_key_frame, device, vec_gt, vec_es, vec_cam, "train", optim_flag=Pipeline.optim_flag) #0:2:中心点 3:5:方向 6:8:loss_rgb -1:depth_mask
elif cfg['path']['dataset_type'] == 'maicity':
# Pipeline.update_optimer()
from dataset.maicity.maicity_dataset import MaiCityDataset
dataset_train = MaiCityDataset(cfg, train_list_key_frame, device, vec_gt, vec_es, "train", cfg['path']['dataset_type'], normal_flag=Pipeline.normal_flag,semantic_flag=Pipeline.semantic_flag) #0:2:中心点 3:5:方向 6:8:loss_rgb -1:depth_mask
else:
sys.exit("Wrong dataset type. Please use maicity or kitti-360")
Pipeline.nef.TrCam0ToVelo = dataset_train.TrCam0ToVelo
Pipeline.set_frame_optimer(cfg['path']['proj_dir'], train_list_key_frame, vec_loam, vec_gt, vec_es_odom, k+1, traj_gt, traj_loam)
OCCExpLR = torch.optim.lr_scheduler.ExponentialLR(Pipeline.nef.optim_occ, gamma=train_info['occ_lr_decay'])
if train_info['pose_optim']:
pose_lr_optim = torch.optim.lr_scheduler.ExponentialLR(Pipeline.nef.pose_optimizer, gamma=train_info['occ_lr_decay'])
train_sampler = SimpleSampler(train_list_key_frame, dataset_train.camera, total=dataset_train.get_every_img_batch(), batch=batch_size)
#-------------batch-------------
epochs = train_info['epoch']
t1 = time.time()
e_start = 0
for e in range(e_start, epochs):
print(f"Start Epoch {e} : ")
depthloss_epoch = 0
with tqdm(total=train_sampler.epoch_iter) as t:
t.set_description('Optim: ')
Pipeline.init_loss()
for i in range(train_sampler.epoch_iter):
if Pipeline.nef.optim_mode != 3:
cos_anneal_ratio = min([1.0, its / (train_sampler.epoch_iter) ]) #cfg['train']['mode2']['epoch']*
else:
cos_anneal_ratio = 1.0
idx = train_sampler.nextids(len(dataset_train.imgs))
Pipeline.train(dataset_train[idx], train_list_key_frame, e, t, cos_anneal_ratio=cos_anneal_ratio)
# p.step()
t.update(1)
its += 1
Pipeline.mean_loss(e,show=tensorboard_flag)
if tensorboard_flag:
Pipeline.tensorboard_show(writer, its)
OCCExpLR.step()
if Pipeline.nef.epoch>=train_info['pose_epoch'] and train_info['pose_optim']:
pose_lr_optim.step()
Pipeline.nef.epoch += 1
# with torch.no_grad():
# test_list = list(range(train_list[0], train_list[0]+1,1))
# dataset_test = Kitti360Dataset(cfg, test_list, device, vec_gt, vec_es, Pipeline.nef.vec_cam, "test", optim_flag=Pipeline.optim_flag)
# dataloader_test = DataLoader(dataset = dataset_test, batch_size=1)
# _ = render_depth(dataloader_test, Pipeline.nef, cfg, Pipeline.get_sdf_reander)
t2 = time.time()
print(f"training time = {(t2-t1)} s")
with torch.no_grad():
if args.VIS_FLAG:
print("=====generate mesh=====")
extract_mesh_NFAtlas(Pipeline.nef,cubes_num,cfg['path']['proj_dir'], args.MESH_REVU, args.MESH_SIZE)
if Pipeline.semantic_flag:
print("=====generate semantic mesh=====")
mesh= o3d.io.read_triangle_mesh(cfg['path']['proj_dir']+f'/mesh/mesh_test{cubes_num}.stl')
vertices = np.asarray(mesh.vertices)
# vertices = (mesh.vertices-Pipeline.nef.origin.cpu().numpy())/Pipeline.nef.scale.cpu().numpy()
sem_batch = 65536
semantic = torch.zeros(vertices.shape[0])
for i in tqdm(range(0, vertices.shape[0], sem_batch), desc='get semantic labels'):
next_ind = min(i+sem_batch, vertices.shape[0])
out = Pipeline.nef.get_output(torch.from_numpy(vertices[i:next_ind]).float().cuda(), channels=Pipeline.nef.channels)
sem = torch.argmax(torch.nn.functional.softmax(out['semantic'].squeeze(), dim=-1), -1)
semantic[i:next_ind] = sem.cpu()
v_colors = np.vstack([id2label[semID].color for semID in semantic.tolist()])
mesh.vertex_colors = o3d.utility.Vector3dVector(v_colors/255.0)
save_file = cfg['path']['proj_dir']+f'/mesh/mesh_semantic{cubes_num}.ply'
o3d.io.write_triangle_mesh(save_file, mesh)
frame_start_last = frame_start
frame_start = frame_start + frame_half
frame_end = frame_start + frame_num
if train_info['save_grid']:
grid_save_path = os.path.join(cfg['path']['proj_dir'], f'grid/optimed_grid_{cubes_num}.pth')
Pipeline.nef.save_grid(grid_save_path)
print("Grid saved in : ", grid_save_path)
# # writer.close()
cubes_num = cubes_num + 1