-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender.py
More file actions
208 lines (170 loc) · 8.58 KB
/
render.py
File metadata and controls
208 lines (170 loc) · 8.58 KB
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
#
# 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
from scene import Scene
import os
from tqdm import tqdm
from os import makedirs
from gaussian_renderer import render
import torchvision
from utils.general_utils import safe_state
from argparse import ArgumentParser
from arguments import ModelParams, PipelineParams, get_combined_args
from gaussian_renderer import GaussianModel
import numpy as np
import cv2
from scene.cameras import Camera
from utils.graphics_utils import getWorld2View2, getProjectionMatrix
try:
from diff_gaussian_rasterization import SparseGaussianAdam
SPARSE_ADAM_AVAILABLE = True
except:
SPARSE_ADAM_AVAILABLE = False
def render_set(model_path, name, iteration, views, gaussians, pipeline, background, train_test_exp, separate_sh):
render_path = os.path.join(model_path, name, "ours_{}".format(iteration), "renders")
gts_path = os.path.join(model_path, name, "ours_{}".format(iteration), "gt")
makedirs(render_path, exist_ok=True)
makedirs(gts_path, exist_ok=True)
for idx, view in enumerate(tqdm(views, desc="Rendering progress")):
rendering = render(view, gaussians, pipeline, background, use_trained_exp=train_test_exp, separate_sh=separate_sh)["render"]
gt = view.original_image[0:3, :, :]
if args.train_test_exp:
rendering = rendering[..., rendering.shape[-1] // 2:]
gt = gt[..., gt.shape[-1] // 2:]
torchvision.utils.save_image(rendering, os.path.join(render_path, '{0:05d}'.format(idx) + ".png"))
torchvision.utils.save_image(gt, os.path.join(gts_path, '{0:05d}'.format(idx) + ".png"))
def create_rotation_views(camera_pos, avg_up, num_frames=120):
"""固定位置,围绕up轴360度旋转朝向"""
angles = np.linspace(0, 2 * np.pi, num_frames, endpoint=False)
# 创建一个垂直于up向量的基准方向
# 找一个不平行于up的向量
if abs(np.dot(avg_up, [1, 0, 0])) < 0.9:
base_dir = np.array([1, 0, 0])
else:
base_dir = np.array([0, 1, 0])
# 计算垂直于up的两个正交向量
right = np.cross(avg_up, base_dir)
right = right / np.linalg.norm(right)
forward_base = np.cross(right, avg_up)
forward_base = forward_base / np.linalg.norm(forward_base)
look_at_directions = []
for angle in angles:
# 围绕up轴旋转
cos_a, sin_a = np.cos(angle), np.sin(angle)
forward = cos_a * forward_base + sin_a * right
look_at_directions.append(forward)
return look_at_directions
def render_rotation_video(model_path, iteration, gaussians, pipeline, background, camera_pos, avg_up, train_cameras, num_frames=480, fps=30):
"""生成旋转视频"""
video_path = os.path.join(model_path, "rotation_video")
makedirs(video_path, exist_ok=True)
# 创建旋转朝向
look_at_directions = create_rotation_views(camera_pos, avg_up, num_frames)
# 从训练相机获取真实参数
ref_cam = train_cameras[0]
width = ref_cam.image_width
height_cam = ref_cam.image_height
fovx = ref_cam.FoVx
fovy = ref_cam.FoVy
znear = 0.01
zfar = 100.0
frames = []
for i, look_direction in enumerate(tqdm(look_at_directions, desc="Rendering rotation video")):
# 相机位置固定,只改变朝向
pos = camera_pos
forward = look_direction
forward = forward / np.linalg.norm(forward)
# 使用从训练相机提取的平均up向量
up = avg_up
right = np.cross(forward, up)
right = right / np.linalg.norm(right)
up = np.cross(right, forward) # 重新计算up保证正交
# 使用getWorld2View2构建变换矩阵
R = np.array([right, up, -forward]).T
t = -R @ pos
world_view_transform = torch.tensor(getWorld2View2(R, t)).transpose(0, 1).cuda()
projection_matrix = getProjectionMatrix(znear, zfar, fovx, fovy).transpose(0, 1).cuda()
full_proj_transform = world_view_transform.unsqueeze(0).bmm(projection_matrix.unsqueeze(0)).squeeze(0)
camera_center = world_view_transform.inverse()[3, :3]
# 创建虚拟相机
class VirtualCamera:
def __init__(self):
self.world_view_transform = world_view_transform
self.projection_matrix = projection_matrix
self.full_proj_transform = full_proj_transform
self.camera_center = camera_center
self.image_width = width
self.image_height = height_cam
self.FoVx = fovx
self.FoVy = fovy
virtual_cam = VirtualCamera()
# 渲染
rendering = render(virtual_cam, gaussians, pipeline, background)["render"]
# 转换为numpy数组并保存帧
frame = rendering.detach().cpu().numpy().transpose(1, 2, 0)
frame = (frame * 255).astype(np.uint8)
frames.append(frame)
# 保存单帧图像
torchvision.utils.save_image(rendering, os.path.join(video_path, f'{i:05d}.png'))
# 生成视频
video_file = os.path.join(video_path, 'circular_video.mp4')
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(video_file, fourcc, fps, (frames[0].shape[1], frames[0].shape[0]))
for frame in frames:
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
out.write(frame_bgr)
out.release()
print(f"旋转视频已保存到: {video_file}")
def render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool, separate_sh: bool, render_video: bool = False):
with torch.no_grad():
gaussians = GaussianModel(dataset.sh_degree)
scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)
bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]
background = torch.tensor(bg_color, dtype=torch.float32, device="cuda")
if not skip_train:
render_set(dataset.model_path, "train", scene.loaded_iter, scene.getTrainCameras(), gaussians, pipeline, background, dataset.train_test_exp, separate_sh)
if not skip_test:
render_set(dataset.model_path, "test", scene.loaded_iter, scene.getTestCameras(), gaussians, pipeline, background, dataset.train_test_exp, separate_sh)
if render_video:
# 计算场景中心和合适的相机参数
train_cameras = scene.getTrainCameras()
if train_cameras:
# 从训练相机估算场景中心
positions = [cam.camera_center.cpu().numpy() for cam in train_cameras]
center = np.mean(positions, axis=0)
# 使用第104个相机(索引103)的Y轴作为up向量
if len(train_cameras) > 110:
ref_cam_for_up = train_cameras[103]
R = ref_cam_for_up.world_view_transform[:3, :3].cpu().numpy()
avg_up = R[0, :] # 第104个相机的X轴(向上方向)
avg_up = avg_up / np.linalg.norm(avg_up) # 归一化
else:
# 如果相机数量不够,使用第一个相机的up向量
R = train_cameras[0].world_view_transform[:3, :3].cpu().numpy()
avg_up = R[0, :]
avg_up = avg_up / np.linalg.norm(avg_up)
render_rotation_video(dataset.model_path, scene.loaded_iter, gaussians, pipeline, background,
center, avg_up, train_cameras)
if __name__ == "__main__":
# Set up command line argument parser
parser = ArgumentParser(description="Testing script parameters")
model = ModelParams(parser, sentinel=True)
pipeline = PipelineParams(parser)
parser.add_argument("--iteration", default=-1, type=int)
parser.add_argument("--skip_train", action="store_true")
parser.add_argument("--skip_test", action="store_true")
parser.add_argument("--quiet", action="store_true")
parser.add_argument("--render_video", action="store_true", help="生成环形视频")
args = get_combined_args(parser)
print("Rendering " + args.model_path)
# Initialize system state (RNG)
safe_state(args.quiet)
render_sets(model.extract(args), args.iteration, pipeline.extract(args), args.skip_train, args.skip_test, SPARSE_ADAM_AVAILABLE, args.render_video)