File size: 7,518 Bytes
cde9b4e |
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 |
import os
import torch
from tqdm import tqdm
from argparse import ArgumentParser
import torchvision
from pathlib import Path
# 使用原代码中的模块
from scene import Scene
from gaussian_renderer import render, GaussianModel
from arguments import ModelParams, PipelineParams
def render_from_cameras(source_path, ply_path, output_dir, gpu_id=0,
white_background=False, sh_degree=3, resolution=1,
use_train_cameras=False):
"""
从指定的数据集和PLY文件渲染图像
Args:
source_path: 数据集路径(包含相机参数,如sparse/0/或transforms_train.json)
ply_path: 训练好的PLY模型文件路径(可选,如果不提供则使用Scene中的默认加载)
output_dir: 渲染结果保存路径
gpu_id: 使用的GPU ID
white_background: 是否使用白色背景
sh_degree: 球谐函数阶数
resolution: 分辨率缩放因子
use_train_cameras: 是否使用训练集相机(默认使用测试集)
"""
# 设置GPU
device = f'cuda:{gpu_id}'
torch.cuda.set_device(device)
# 创建输出目录
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
# 设置背景颜色
bg_color = [1, 1, 1] if white_background else [0, 0, 0]
background = torch.tensor(bg_color, dtype=torch.float32, device=device)
# 构造参数对象(模拟ModelParams)
class SimpleArgs:
def __init__(self):
self.source_path = source_path
self.model_path = source_path # 通常model_path和source_path相同
self.sh_degree = sh_degree
self.resolution = resolution
self.white_background = white_background
self.data_device = device
self.eval = True
self.images = "images" # 默认图像文件夹名
self.load_allres = False
args = SimpleArgs()
# 初始化高斯模型
print(f"初始化高斯模型 (SH degree: {sh_degree})")
gaussians = GaussianModel(sh_degree)
# 如果提供了外部PLY文件,先加载它
if ply_path and os.path.exists(ply_path):
print(f"从外部文件加载高斯模型: {ply_path}")
gaussians.load_ply(ply_path)
# 创建Scene但不让它加载PLY(通过设置load_iteration=None且不让Scene初始化gaussians)
scene = Scene(args, gaussians, load_iteration=None, shuffle=False)
else:
# 让Scene自动处理(会从point_cloud目录加载或从点云创建)
print(f"从数据集加载场景: {source_path}")
scene = Scene(args, gaussians, load_iteration=-1, shuffle=False)
# 获取相机
if use_train_cameras:
cameras = scene.getTrainCameras(scale=resolution)
camera_type = "训练集"
else:
cameras = scene.getTestCameras(scale=resolution)
camera_type = "测试集"
print(f"加载了 {len(cameras)} 个{camera_type}相机视角")
# 创建pipeline参数(如果需要)
class SimplePipeline:
def __init__(self):
self.convert_SHs_python = False
self.compute_cov3D_python = False
self.debug = False
pipeline = SimplePipeline()
# 渲染每个相机视角
for idx, camera in enumerate(tqdm(cameras, desc="渲染进度")):
with torch.no_grad():
rendering = render(camera, gaussians, pipeline, background)["render"]
# 保存图像
img_name = f"{camera.image_name}.png"
save_path = output_path / img_name
torchvision.utils.save_image(rendering, save_path)
print(f"\n渲染完成!图像保存至: {output_path}")
print(f"共渲染 {len(cameras)} 张图像")
def main():
parser = ArgumentParser(description="简化版3DGS渲染脚本")
# 核心参数
parser.add_argument("--source_path", type=str, required=True,
help="数据集路径(包含sparse/、transforms_train.json或metadata.json)")
parser.add_argument("--ply_file", type=str, default=None,
help="训练好的PLY模型文件路径(可选,不提供则从point_cloud/目录自动加载)")
parser.add_argument("--output_dir", type=str, required=True,
help="渲染结果保存路径")
parser.add_argument("--gpu_id", type=int, default=0,
help="使用的GPU ID,默认0")
# 可选参数
parser.add_argument("--sh_degree", type=int, default=3,
help="球谐函数阶数,默认3")
parser.add_argument("--resolution", type=int, default=1,
help="分辨率缩放因子,默认1(原分辨率)")
parser.add_argument("--white_background", action="store_true",
help="使用白色背景(默认黑色)")
parser.add_argument("--use_train_cameras", action="store_true",
help="使用训练集相机(默认使用测试集)")
args = parser.parse_args()
# 打印配置信息
print("=" * 60)
print("3D Gaussian Splatting 渲染工具")
print("=" * 60)
print(f"数据集路径: {args.source_path}")
print(f"PLY文件: {args.ply_file if args.ply_file else '自动加载'}")
print(f"输出目录: {args.output_dir}")
print(f"GPU ID: {args.gpu_id}")
print(f"SH阶数: {args.sh_degree}")
print(f"分辨率缩放: {args.resolution}")
print(f"背景颜色: {'白色' if args.white_background else '黑色'}")
print(f"相机类型: {'训练集' if args.use_train_cameras else '测试集'}")
print("=" * 60)
print()
render_from_cameras(
source_path=args.source_path,
ply_path=args.ply_file,
output_dir=args.output_dir,
gpu_id=args.gpu_id,
white_background=args.white_background,
sh_degree=args.sh_degree,
resolution=args.resolution,
use_train_cameras=args.use_train_cameras
)
if __name__ == "__main__":
main()
"""
使用说明:
=========
1. 使用COLMAP格式数据集:
python render_simple.py \
--source_path /path/to/dataset \
--ply_file /path/to/point_cloud.ply \
--output_dir ./output \
--gpu_id 0
2. 使用Blender格式数据集:
python render_simple.py \
--source_path /path/to/blender_dataset \
--ply_file /path/to/point_cloud.ply \
--output_dir ./output \
--white_background
3. 自动加载已训练模型(不指定ply_file):
python render_simple.py \
--source_path /path/to/dataset \
--output_dir ./output
需要的文件结构:
================
COLMAP格式:
dataset/
├── sparse/
│ └── 0/
│ ├── cameras.bin
│ ├── images.bin
│ └── points3D.bin
└── images/
├── img_001.jpg
└── ...
Blender格式:
dataset/
├── transforms_train.json
├── transforms_test.json
└── train/
├── r_0.png
└── ...
如果使用自动加载(不指定--ply_file):
dataset/
└── point_cloud/
└── iteration_30000/
└── point_cloud.ply
""" |