Download render_ortho.py from happyPHD/DiffusionUavLoc: direct link, hf CLI and curl.
- Browser
- Download file 25 kB
-
https://huggingface.co/datasets/happyPHD/DiffusionUavLoc/resolve/main/render_ortho.py
- Command line
-
hf download hf://datasets/happyPHD/DiffusionUavLoc/render_ortho.py
-
curl -L -o render_ortho.py https://huggingface.co/datasets/happyPHD/DiffusionUavLoc/resolve/main/render_ortho.py
25 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
3DGS 自动垂直俯视与中心区域正交投影渲染
功能:
1. 自动寻找 cameras.json
2. 自动估计场景竖直方向
3. 加载并过滤 3DGS 高斯模型
4. 自动构建垂直俯视相机
5. 自动裁剪中心正方形区域
6. GPU 正交高斯光栅化渲染
7. 保存 RGB、Alpha 和 JSON
默认输出:
中心短边 60% 的正方形区域
2048 × 2048 像素
"""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from plyfile import PlyData
from gsplat import rasterization
# ==========================================================
# 1. 自动寻找 cameras.json
# ==========================================================
def find_cameras(ply_path):
for parent in ply_path.resolve().parents:
path = parent / "cameras.json"
if path.is_file():
return path
raise FileNotFoundError(
"未找到 cameras.json,请通过 --cameras 指定路径"
)
# ==========================================================
# 2. 自动估计场景竖直方向
# ==========================================================
def estimate_up(cameras_path):
print(f"读取相机参数:{cameras_path}")
with open(cameras_path, "r", encoding="utf-8") as f:
cameras = json.load(f)
rotations = np.asarray(
[cam["rotation"] for cam in cameras],
dtype=np.float64
)
if (
len(cameras) < 3
or rotations.shape != (len(cameras), 3, 3)
or not np.isfinite(rotations).all()
):
raise ValueError("相机姿态数据无效")
# 相机坐标系:
# X:右方向
# Y:下方向
# Z:前方向
right_vectors = rotations[:, :, 0]
forward_vectors = rotations[:, :, 2]
# SVD 求解场景竖直方向
_, singular_values, vh = np.linalg.svd(
right_vectors,
full_matrices=False
)
if (
singular_values[0] <= 0
or singular_values[1] < 1e-3 * singular_values[0]
):
raise ValueError(
"相机观测方向不足,无法可靠估计竖直方向"
)
up = vh[-1]
up /= np.linalg.norm(up)
# 根据相机光轴确定竖直方向正负
if np.mean(forward_vectors @ up) > 0:
up = -up
# 计算水平约束误差
residual = np.degrees(
np.arcsin(
np.clip(
np.abs(right_vectors @ up),
0,
1
)
)
)
# 计算相机俯角
pitch = np.degrees(
np.arcsin(
np.clip(
-(forward_vectors @ up),
-1,
1
)
)
)
print(f"相机数量:{len(cameras)}")
print(f"奇异值:{singular_values}")
print(f"场景竖直方向:{up}")
print(f"平均水平约束误差:{residual.mean():.4f}°")
print(f"最大水平约束误差:{residual.max():.4f}°")
print(f"平均相机俯角:{pitch.mean():.4f}°")
if (
singular_values[2] / singular_values[1] > 0.2
or residual.mean() > 5
or pitch.mean() < 5
):
print("警告:自动估计方向可能不准确")
info = {
"camera_count": len(cameras),
"singular_values": singular_values.tolist(),
"mean_residual_deg": float(residual.mean()),
"max_residual_deg": float(residual.max()),
"mean_pitch_deg": float(pitch.mean())
}
return up, info
# ==========================================================
# 3. 读取标准 3DGS 高斯模型
# ==========================================================
def load_gaussians(
ply_path,
min_opacity=0.01,
max_scale_quantile=1.0
):
vertex = PlyData.read(str(ply_path))["vertex"].data
names = (
"x", "y", "z",
"opacity",
"f_dc_0", "f_dc_1", "f_dc_2",
"scale_0", "scale_1", "scale_2",
"rot_0", "rot_1", "rot_2", "rot_3"
)
missing = set(names) - set(vertex.dtype.names)
if missing:
raise ValueError(
f"PLY 缺少高斯属性:{sorted(missing)}"
)
values = np.column_stack(
[vertex[name] for name in names]
).astype(np.float32)
original_count = len(values)
# 过滤非法数值
values = values[
np.isfinite(values).all(axis=1)
]
# Sigmoid 激活透明度
opacity = 1.0 / (
1.0 + np.exp(
-np.clip(values[:, 3], -80, 80)
)
)
# 过滤低透明度高斯
keep = opacity >= min_opacity
values = values[keep]
opacity = opacity[keep]
if len(values) == 0:
raise ValueError("透明度过滤后没有有效高斯")
means = values[:, :3]
# 指数激活高斯尺度
with np.errstate(over="ignore", under="ignore"):
scales = np.exp(values[:, 7:10])
# 高斯旋转四元数
quats = values[:, 10:14]
norms = np.linalg.norm(
quats,
axis=1,
keepdims=True
)
# 过滤无效尺度和旋转
valid = (
np.isfinite(scales).all(axis=1)
& (scales > 0).all(axis=1)
& np.isfinite(norms[:, 0])
& (norms[:, 0] > 0)
)
means = means[valid]
scales = scales[valid]
opacity = opacity[valid]
quats = quats[valid] / norms[valid]
# SH DC 系数转换为 RGB
SH_C0 = 0.28209479177387814
colors = np.clip(
0.5 + SH_C0 * values[valid, 4:7],
0,
1
)
if len(means) == 0:
raise ValueError("没有有效高斯")
# 可选:过滤异常大尺度高斯
if max_scale_quantile < 1.0:
scale_max = scales.max(axis=1)
threshold = np.quantile(
scale_max,
max_scale_quantile
)
keep = scale_max <= threshold
means = means[keep]
scales = scales[keep]
opacity = opacity[keep]
quats = quats[keep]
colors = colors[keep]
print(f"高斯尺度过滤阈值:{threshold:.6f}")
if len(means) == 0:
raise ValueError("尺度过滤后没有有效高斯")
print(f"原始高斯数量:{original_count:,}")
print(f"有效高斯数量:{len(means):,}")
print(f"移除高斯数量:{original_count - len(means):,}")
return means, quats, scales, opacity, colors
# ==========================================================
# 4. 构建垂直俯视正交相机
# ==========================================================
def camera_geometry(
means,
scales,
up,
resolution=None,
size=2048,
bounds=None,
crop_percent=0.5,
padding=0.03,
center_ratio=0.6,
center_offset=(0.0, 0.0)
):
up = np.asarray(
up,
dtype=np.float64
)
norm = np.linalg.norm(up)
if not np.isfinite(norm) or norm == 0:
raise ValueError("竖直方向无效")
up /= norm
# 选取辅助参考轴
reference = np.array([0., 1., 0.])
if abs(reference @ up) > 0.99:
reference = np.array([0., 0., 1.])
# 构建水平坐标基底
right = np.cross(reference, up)
right /= np.linalg.norm(right)
image_up = np.cross(up, right)
image_up /= np.linalg.norm(image_up)
# 相机坐标轴:右、下、前
rotation = np.stack([
right,
-image_up,
-up
])
# 高斯中心投影到水平坐标系
x = means @ right
y = means @ image_up
z = means @ up
# ------------------------------------------------------
# 4.1 自动确定初始场景范围
# ------------------------------------------------------
if bounds is None:
xmin, xmax = np.percentile(
x,
[crop_percent, 100 - crop_percent]
)
ymin, ymax = np.percentile(
y,
[crop_percent, 100 - crop_percent]
)
span = max(
xmax - xmin,
ymax - ymin
)
if span <= 0:
raise ValueError("场景投影范围无效")
margin = span * padding
xmin -= margin
xmax += margin
ymin -= margin
ymax += margin
else:
xmin, ymin, xmax, ymax = bounds
if (
not np.isfinite([xmin, ymin, xmax, ymax]).all()
or xmax <= xmin
or ymax <= ymin
):
raise ValueError("投影范围无效")
original_bounds = [
float(xmin),
float(ymin),
float(xmax),
float(ymax)
]
original_width = xmax - xmin
original_height = ymax - ymin
print(f"初始场景范围:{original_bounds}")
print(f"初始场景宽度:{original_width:.6f}")
print(f"初始场景高度:{original_height:.6f}")
# ------------------------------------------------------
# 4.2 中心正方形区域裁剪
# ------------------------------------------------------
# 如果手动指定 bounds,则使用手动范围
# 否则自动裁剪中心正方形
if bounds is None:
cx = (xmin + xmax) / 2
cy = (ymin + ymax) / 2
# 中心位置微调
# 正 X:向右
# 正 Y:向上
cx += center_offset[0] * original_width
cy += center_offset[1] * original_height
# 以场景短边为基准
# 默认保留中心 60%
side = min(
original_width,
original_height
) * center_ratio
if not np.isfinite(side) or side <= 0:
raise ValueError("中心裁剪尺寸无效")
xmin = cx - side / 2
xmax = cx + side / 2
ymin = cy - side / 2
ymax = cy + side / 2
print(f"中心裁剪比例:{center_ratio:.1%}")
print(f"中心裁剪边长:{side:.6f}")
print(f"中心偏移:{center_offset}")
print(f"中心位置:{cx:.6f}, {cy:.6f}")
else:
print("使用手动投影范围,跳过自动中心裁剪")
# ------------------------------------------------------
# 4.3 计算正交投影分辨率
# ------------------------------------------------------
span_x = xmax - xmin
span_y = ymax - ymin
cx = (xmin + xmax) / 2
cy = (ymin + ymax) / 2
if resolution is None:
resolution = max(
span_x,
span_y
) / size
if bounds is None:
# 自动中心裁剪时保证输出为正方形
# 避免浮点误差产生 2049 像素
width = size
height = size
else:
width = max(
1,
int(np.ceil(span_x / resolution - 1e-9))
)
height = max(
1,
int(np.ceil(span_y / resolution - 1e-9))
)
else:
if bounds is None:
width = max(
1,
int(np.ceil(span_x / resolution))
)
height = width
else:
width = max(
1,
int(np.ceil(span_x / resolution))
)
height = max(
1,
int(np.ceil(span_y / resolution))
)
if width * height > 100_000_000:
raise ValueError("输出尺寸过大,请降低分辨率")
# 根据最终像素尺寸更新投影边界
# 保证中心位置不变
xmin = cx - width * resolution / 2
xmax = cx + width * resolution / 2
ymin = cy - height * resolution / 2
ymax = cy + height * resolution / 2
# ------------------------------------------------------
# 4.4 设置垂直俯视相机位置
# ------------------------------------------------------
scene_span = max(
xmax - xmin,
ymax - ymin
)
scale_margin = float(
3 * np.quantile(
scales.max(axis=1),
0.99
)
)
elevation = float(
z.max()
+ max(scene_span, scale_margin, 1.0)
)
center = (
right * cx
+ image_up * cy
+ up * elevation
)
# ------------------------------------------------------
# 4.5 构建相机外参矩阵
# ------------------------------------------------------
view = np.eye(4)
view[:3, :3] = rotation
view[:3, 3] = -rotation @ center
# ------------------------------------------------------
# 4.6 构建正交相机内参
# ------------------------------------------------------
intrinsics = np.array([
[1.0 / resolution, 0, width / 2],
[0, 1.0 / resolution, height / 2],
[0, 0, 1]
])
far_plane = max(
1.0,
elevation - float(z.min())
+ scale_margin + 1.0
)
# ------------------------------------------------------
# 4.7 保存投影参数
# ------------------------------------------------------
metadata = {
"width": width,
"height": height,
"units_per_pixel": float(resolution),
"original_bounds": original_bounds,
"bounds": [
float(xmin),
float(ymin),
float(xmax),
float(ymax)
],
"center_crop_enabled": bounds is None,
"center_ratio": (
float(center_ratio)
if bounds is None
else None
),
"center_offset": (
list(center_offset)
if bounds is None
else None
),
"crop_center": [
float(cx),
float(cy)
],
"world_up": up.tolist(),
"camera_forward": (-up).tolist(),
"camera_position": center.tolist(),
"right": right.tolist(),
"image_up": image_up.tolist(),
"pixel_center_00_world": (
right * (xmin + resolution / 2)
+ image_up * (ymax - resolution / 2)
).tolist(),
"pixel_column_step_world": (
right * resolution
).tolist(),
"pixel_row_step_world": (
-image_up * resolution
).tolist(),
"view_matrix": view.tolist(),
"intrinsics": intrinsics.tolist(),
"projection": "orthographic",
"georeferenced": False
}
return view, intrinsics, far_plane, metadata
# ==========================================================
# 5. gsplat 正交投影渲染
# ==========================================================
def render_gaussians(
means,
quats,
scales,
opacity,
colors,
view,
intrinsics,
far_plane,
metadata,
background,
device
):
device = torch.device(device)
if (
device.type != "cuda"
or not torch.cuda.is_available()
):
raise RuntimeError("需要可用的 CUDA GPU")
print(f"渲染设备:{device}")
print(f"GPU 型号:{torch.cuda.get_device_name(device)}")
def tensor(value):
return torch.as_tensor(
np.ascontiguousarray(value),
dtype=torch.float32,
device=device
)
with torch.no_grad():
rgb, alpha, _ = rasterization(
means=tensor(means),
quats=tensor(quats),
scales=tensor(scales),
opacities=tensor(opacity),
colors=tensor(colors),
viewmats=tensor(view[None]),
Ks=tensor(intrinsics[None]),
width=metadata["width"],
height=metadata["height"],
near_plane=0.01,
far_plane=far_plane,
camera_model="ortho",
backgrounds=tensor([background]),
render_mode="RGB",
# 保留之前的背景色维度异常修复
packed=False
)
rgb = rgb[0].cpu().numpy()
alpha = alpha[0, ..., 0].cpu().numpy()
if (
not np.isfinite(rgb).all()
or not np.isfinite(alpha).all()
):
raise RuntimeError("渲染结果包含非法数值")
return rgb, alpha
# ==========================================================
# 6. 保存渲染结果
# ==========================================================
def save_results(
rgb,
alpha,
metadata,
output
):
output.parent.mkdir(
parents=True,
exist_ok=True
)
rgb_image = np.uint8(
np.clip(rgb, 0, 1) * 255 + 0.5
)
alpha_image = np.uint8(
np.clip(alpha, 0, 1) * 255 + 0.5
)
# 保存 RGB 正交影像
Image.fromarray(
rgb_image
).save(output)
# 保存 Alpha 透明度掩膜
alpha_path = output.with_suffix(
".alpha.png"
)
Image.fromarray(
alpha_image
).save(alpha_path)
# 保存投影参数
json_path = output.with_suffix(
".json"
)
json_path.write_text(
json.dumps(
metadata,
indent=2,
ensure_ascii=False
),
encoding="utf-8"
)
print(f"RGB 影像:{output.resolve()}")
print(f"Alpha 掩膜:{alpha_path.resolve()}")
print(f"投影参数:{json_path.resolve()}")
# ==========================================================
# 7. 主函数
# ==========================================================
def main():
parser = argparse.ArgumentParser(
description="3DGS 自动俯视与中心区域正交渲染"
)
parser.add_argument(
"--ply",
type=Path,
required=True,
help="3DGS 高斯模型路径"
)
parser.add_argument(
"--output",
type=Path,
required=True,
help="输出 PNG 路径"
)
parser.add_argument(
"--cameras",
type=Path,
default=None,
help="cameras.json 路径,默认自动查找"
)
parser.add_argument(
"--up",
type=float,
nargs=3,
default=None,
help="手动指定场景竖直方向,默认自动估计"
)
parser.add_argument(
"--size",
type=int,
default=2048,
help="输出影像最长边尺寸"
)
parser.add_argument(
"--resolution",
type=float,
default=None,
help="场景坐标单位/像素"
)
parser.add_argument(
"--bounds",
type=float,
nargs=4,
default=None,
help="手动指定投影范围,覆盖自动中心裁剪"
)
parser.add_argument(
"--min-opacity",
type=float,
default=0.01,
help="最小高斯透明度"
)
parser.add_argument(
"--max-scale-quantile",
type=float,
default=1.0,
help="高斯尺度过滤分位数"
)
parser.add_argument(
"--crop-percent",
type=float,
default=0.5,
help="初始投影范围两侧裁剪百分比"
)
parser.add_argument(
"--padding",
type=float,
default=0.03,
help="初始场景边缘留白比例"
)
# 新增:中心裁剪比例
parser.add_argument(
"--center-ratio",
type=float,
default=0.6,
help="中心正方形裁剪比例,默认0.6"
)
# 新增:中心位置微调
parser.add_argument(
"--center-offset",
type=float,
nargs=2,
default=[0.0, 0.0],
help="中心相对偏移,正X向右,正Y向上"
)
parser.add_argument(
"--background",
type=float,
nargs=3,
default=[1, 1, 1],
help="背景颜色,默认白色"
)
parser.add_argument(
"--device",
default="cuda:0",
help="CUDA 设备"
)
args = parser.parse_args()
# ------------------------------------------------------
# 参数检查
# ------------------------------------------------------
if not args.ply.is_file():
parser.error("PLY 文件不存在")
if args.output.suffix.lower() != ".png":
parser.error("输出必须为 PNG 文件")
if args.size <= 0:
parser.error("--size 必须大于 0")
if args.resolution is not None:
if (
not np.isfinite(args.resolution)
or args.resolution <= 0
):
parser.error("--resolution 必须大于 0")
if not 0 <= args.min_opacity < 1:
parser.error("--min-opacity 必须位于 [0,1)")
if not 0 < args.max_scale_quantile <= 1:
parser.error("--max-scale-quantile 必须位于 (0,1]")
if not 0 <= args.crop_percent < 50:
parser.error("--crop-percent 必须位于 [0,50)")
if not np.isfinite(args.padding) or args.padding < 0:
parser.error("--padding 必须为非负数")
if not 0 < args.center_ratio <= 1:
parser.error("--center-ratio 必须位于 (0,1]")
if not all(
np.isfinite(v)
for v in args.center_offset
):
parser.error("--center-offset 必须为有限数值")
if not all(
np.isfinite(v) and 0 <= v <= 1
for v in args.background
):
parser.error("--background 必须位于 [0,1]")
print("=" * 60)
print("3DGS 自动垂直俯视与中心区域正交渲染")
print("=" * 60)
# ------------------------------------------------------
# 第一步:自动估计竖直方向
# ------------------------------------------------------
print("\n[1/5] 估计场景竖直方向")
cameras_path = None
direction_info = {}
if args.up is not None:
up = np.asarray(
args.up,
dtype=np.float64
)
print(f"使用手动指定方向:{up}")
direction_method = "manual"
else:
cameras_path = args.cameras
if cameras_path is None:
cameras_path = find_cameras(args.ply)
up, direction_info = estimate_up(
cameras_path
)
direction_method = "camera_pose_svd"
# ------------------------------------------------------
# 第二步:读取高斯模型
# ------------------------------------------------------
print("\n[2/5] 加载并过滤高斯模型")
means, quats, scales, opacity, colors = load_gaussians(
args.ply,
min_opacity=args.min_opacity,
max_scale_quantile=args.max_scale_quantile
)
# ------------------------------------------------------
# 第三步:构建垂直俯视相机并进行中心裁剪
# ------------------------------------------------------
print("\n[3/5] 构建垂直俯视相机与中心裁剪")
view, intrinsics, far_plane, metadata = camera_geometry(
means=means,
scales=scales,
up=up,
resolution=args.resolution,
size=args.size,
bounds=args.bounds,
crop_percent=args.crop_percent,
padding=args.padding,
center_ratio=args.center_ratio,
center_offset=args.center_offset
)
print(f"竖直方向:{metadata['world_up']}")
print(f"相机光轴:{metadata['camera_forward']}")
print(
f"输出尺寸:"
f"{metadata['width']} × "
f"{metadata['height']}"
)
print(
f"空间分辨率:"
f"{metadata['units_per_pixel']:.8f}"
f" 单位/像素"
)
print(f"最终投影范围:{metadata['bounds']}")
# ------------------------------------------------------
# 第四步:GPU 正交投影渲染
# ------------------------------------------------------
print("\n[4/5] 执行 GPU 正交高斯渲染")
rgb, alpha = render_gaussians(
means=means,
quats=quats,
scales=scales,
opacity=opacity,
colors=colors,
view=view,
intrinsics=intrinsics,
far_plane=far_plane,
metadata=metadata,
background=args.background,
device=args.device
)
# ------------------------------------------------------
# 第五步:保存结果
# ------------------------------------------------------
print("\n[5/5] 保存中心区域正交投影结果")
metadata.update({
"source_ply": str(args.ply.resolve()),
"source_cameras": (
str(cameras_path.resolve())
if cameras_path is not None
else None
),
"gaussian_count": len(means),
"direction_method": direction_method,
"direction_estimation": direction_info,
"min_opacity": args.min_opacity,
"max_scale_quantile": args.max_scale_quantile,
"crop_percent": args.crop_percent,
"padding": args.padding,
"color_mode": "SH DC only",
"background": args.background
})
save_results(
rgb,
alpha,
metadata,
args.output
)
print("\n" + "=" * 60)
print("3DGS 中心区域垂直俯视正交投影完成!")
print(
f"最终输出尺寸:"
f"{metadata['width']} × "
f"{metadata['height']}"
)
print("=" * 60)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
3DGS 自动垂直俯视与中心区域正交投影渲染
功能:
1. 自动寻找 cameras.json
2. 自动估计场景竖直方向
3. 加载并过滤 3DGS 高斯模型
4. 自动构建垂直俯视相机
5. 自动裁剪中心正方形区域
6. GPU 正交高斯光栅化渲染
7. 保存 RGB、Alpha 和 JSON
默认输出:
中心短边 60% 的正方形区域
2048 × 2048 像素
"""
import argparse
import json
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from plyfile import PlyData
from gsplat import rasterization
# ==========================================================
# 1. 自动寻找 cameras.json
# ==========================================================
def find_cameras(ply_path):
for parent in ply_path.resolve().parents:
path = parent / "cameras.json"
if path.is_file():
return path
raise FileNotFoundError(
"未找到 cameras.json,请通过 --cameras 指定路径"
)
# ==========================================================
# 2. 自动估计场景竖直方向
# ==========================================================
def estimate_up(cameras_path):
print(f"读取相机参数:{cameras_path}")
with open(cameras_path, "r", encoding="utf-8") as f:
cameras = json.load(f)
rotations = np.asarray(
[cam["rotation"] for cam in cameras],
dtype=np.float64
)
if (
len(cameras) < 3
or rotations.shape != (len(cameras), 3, 3)
or not np.isfinite(rotations).all()
):
raise ValueError("相机姿态数据无效")
# 相机坐标系:
# X:右方向
# Y:下方向
# Z:前方向
right_vectors = rotations[:, :, 0]
forward_vectors = rotations[:, :, 2]
# SVD 求解场景竖直方向
_, singular_values, vh = np.linalg.svd(
right_vectors,
full_matrices=False
)
if (
singular_values[0] <= 0
or singular_values[1] < 1e-3 * singular_values[0]
):
raise ValueError(
"相机观测方向不足,无法可靠估计竖直方向"
)
up = vh[-1]
up /= np.linalg.norm(up)