forked from mikeqzy/3dgs-avatar-release
-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.py
201 lines (164 loc) · 6.92 KB
/
render.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
#
# Copyright (C) 2023, Inria
# GRAPHDECO research group, https://team.inria.fr/graphdeco
# All rights reserved.
#
# This software is free for non-commercial, research and evaluation use
# under the terms of the LICENSE.md file.
#
# For inquiries contact george.drettakis@inria.fr
#
import torch
import numpy as np
from scene import Scene
import os
from tqdm import tqdm, trange
from os import makedirs
from gaussian_renderer import render
import torchvision
from utils.general_utils import fix_random
from scene import GaussianModel
from utils.general_utils import Evaluator, PSEvaluator
import hydra
from omegaconf import OmegaConf
import wandb
def predict(config):
with torch.set_grad_enabled(False):
gaussians = GaussianModel(config.model.gaussian)
scene = Scene(config, gaussians, config.exp_dir)
scene.eval()
load_ckpt = config.get('load_ckpt', None)
if load_ckpt is None:
load_ckpt = os.path.join(scene.save_dir, "ckpt" + str(config.opt.iterations) + ".pth")
scene.load_checkpoint(load_ckpt)
bg_color = [1, 1, 1] if config.dataset.white_background else [0, 0, 0]
background = torch.tensor(bg_color, dtype=torch.float32, device="cuda")
render_path = os.path.join(config.exp_dir, config.suffix, 'renders')
makedirs(render_path, exist_ok=True)
iter_start = torch.cuda.Event(enable_timing=True)
iter_end = torch.cuda.Event(enable_timing=True)
times = []
for idx in trange(len(scene.test_dataset), desc="Rendering progress"):
view = scene.test_dataset[idx]
iter_start.record()
render_pkg = render(view, config.opt.iterations, scene, config.pipeline, background,
compute_loss=False, return_opacity=False)
iter_end.record()
torch.cuda.synchronize()
elapsed = iter_start.elapsed_time(iter_end)
rendering = render_pkg["render"]
wandb_img = [wandb.Image(rendering[None], caption='render_{}'.format(view.image_name)),]
wandb.log({'test_images': wandb_img})
torchvision.utils.save_image(rendering, os.path.join(render_path, f"render_{view.image_name}.png"))
# evaluate
times.append(elapsed)
_time = np.mean(times[1:])
wandb.log({'metrics/time': _time})
np.savez(os.path.join(config.exp_dir, config.suffix, 'results.npz'),
time=_time)
def test(config):
with torch.no_grad():
gaussians = GaussianModel(config.model.gaussian)
scene = Scene(config, gaussians, config.exp_dir)
scene.eval()
load_ckpt = config.get('load_ckpt', None)
if load_ckpt is None:
load_ckpt = os.path.join(scene.save_dir, "ckpt" + str(config.opt.iterations) + ".pth")
scene.load_checkpoint(load_ckpt)
bg_color = [1, 1, 1] if config.dataset.white_background else [0, 0, 0]
background = torch.tensor(bg_color, dtype=torch.float32, device="cuda")
render_path = os.path.join(config.exp_dir, config.suffix, 'renders')
makedirs(render_path, exist_ok=True)
iter_start = torch.cuda.Event(enable_timing=True)
iter_end = torch.cuda.Event(enable_timing=True)
evaluator = PSEvaluator() if config.dataset.name == 'people_snapshot' else Evaluator()
psnrs = []
ssims = []
lpipss = []
times = []
for idx in trange(len(scene.test_dataset), desc="Rendering progress"):
view = scene.test_dataset[idx]
iter_start.record()
render_pkg = render(view, config.opt.iterations, scene, config.pipeline, background,
compute_loss=False, return_opacity=False)
iter_end.record()
torch.cuda.synchronize()
elapsed = iter_start.elapsed_time(iter_end)
rendering = render_pkg["render"]
gt = view.original_image[:3, :, :]
wandb_img = [wandb.Image(rendering[None], caption='render_{}'.format(view.image_name)),
wandb.Image(gt[None], caption='gt_{}'.format(view.image_name))]
wandb.log({'test_images': wandb_img})
torchvision.utils.save_image(rendering, os.path.join(render_path, f"render_{view.image_name}.png"))
# evaluate
if config.evaluate:
metrics = evaluator(rendering, gt)
psnrs.append(metrics['psnr'])
ssims.append(metrics['ssim'])
lpipss.append(metrics['lpips'])
else:
psnrs.append(torch.tensor([0.], device='cuda'))
ssims.append(torch.tensor([0.], device='cuda'))
lpipss.append(torch.tensor([0.], device='cuda'))
times.append(elapsed)
_psnr = torch.mean(torch.stack(psnrs))
_ssim = torch.mean(torch.stack(ssims))
_lpips = torch.mean(torch.stack(lpipss))
_time = np.mean(times[1:])
wandb.log({'metrics/psnr': _psnr,
'metrics/ssim': _ssim,
'metrics/lpips': _lpips,
'metrics/time': _time})
np.savez(os.path.join(config.exp_dir, config.suffix, 'results.npz'),
psnr=_psnr.cpu().numpy(),
ssim=_ssim.cpu().numpy(),
lpips=_lpips.cpu().numpy(),
time=_time)
@hydra.main(version_base=None, config_path="configs", config_name="config")
def main(config):
OmegaConf.set_struct(config, False)
config.dataset.preload = False
config.exp_dir = config.get('exp_dir') or os.path.join('./exp', config.name)
os.makedirs(config.exp_dir, exist_ok=True)
# set wandb logger
if config.mode == 'test':
config.suffix = config.mode + '-' + config.dataset.test_mode
elif config.mode == 'predict':
predict_seq = config.dataset.predict_seq
if config.dataset.name == 'zjumocap':
predict_dict = {
0: 'dance0',
1: 'dance1',
2: 'flipping',
3: 'canonical'
}
else:
predict_dict = {
0: 'rotation',
1: 'dance2',
}
predict_mode = predict_dict[predict_seq]
config.suffix = config.mode + '-' + predict_mode
else:
raise ValueError
if config.dataset.freeview:
config.suffix = config.suffix + '-freeview'
wandb_name = config.name + '-' + config.suffix
wandb.init(
mode="disabled" if config.wandb_disable else None,
name=wandb_name,
project='gaussian-splatting-avatar-test',
entity='fast-avatar',
dir=config.exp_dir,
config=OmegaConf.to_container(config, resolve=True),
settings=wandb.Settings(start_method='fork'),
)
fix_random(config.seed)
if config.mode == 'test':
test(config)
elif config.mode == 'predict':
predict(config)
else:
raise ValueError
if __name__ == "__main__":
main()