From 81590b1f57fe1ec7d2a553b83eb44928b5165d6b Mon Sep 17 00:00:00 2001 From: Xun2001 Date: Mon, 19 May 2025 09:10:15 +0800 Subject: [PATCH] created sky and groud box --- arguments/__init__.py | 10 +- scene/__init__.py | 8 +- scene/dataset_readers.py | 5 +- scene/gaussian_model.py | 133 +++++++++-- scene/xy_utils.py | 21 ++ submodules/diff-gaussian-rasterization | 2 +- train-sky.py | 307 +++++++++++++++++++++++++ utils/points_utils.py | 31 +++ xy_utils/learning.ipynb | 93 ++++++-- xy_utils/sky_groud.py | 19 ++ xy_utils/tools/points_utils.py | 27 ++- 11 files changed, 619 insertions(+), 37 deletions(-) create mode 100644 scene/xy_utils.py create mode 100644 train-sky.py create mode 100644 utils/points_utils.py create mode 100644 xy_utils/sky_groud.py diff --git a/arguments/__init__.py b/arguments/__init__.py index 0b2f448..98a177c 100644 --- a/arguments/__init__.py +++ b/arguments/__init__.py @@ -40,8 +40,8 @@ class ParamGroup: def extract(self, args): group = GroupParams() for arg in vars(args).items(): - if arg[0] in vars(self) or ("_" + arg[0]) in vars(self): - setattr(group, arg[0], arg[1]) + if arg[0] in vars(self) or ("_" + arg[0]) in vars(self): # 将args中的参数进行分流,分给不同的Params;所以Param初始化中没有的不能额外加入 + setattr(group, arg[0], arg[1]) # 内置函数,将属性 arg[0] 和对应的值 arg[1] 赋给group return group class ModelParams(ParamGroup): @@ -56,7 +56,11 @@ class ModelParams(ParamGroup): self.train_test_exp = False self.data_device = "cuda" self.eval = False - super().__init__(parser, "Loading Parameters", sentinel) + self.skybox_locked = False + self.skybox_num = 0 + self.scaffold_file = "" + self.bounds_file = "" + super().__init__(parser, "Loading Parameters", sentinel) # add parameters into parser def extract(self, args): g = super().extract(args) diff --git a/scene/__init__.py b/scene/__init__.py index 8091614..a1d77c8 100644 --- a/scene/__init__.py +++ b/scene/__init__.py @@ -80,7 +80,13 @@ class Scene: "iteration_" + str(self.loaded_iter), "point_cloud.ply"), args.train_test_exp) else: - self.gaussians.create_from_pcd(scene_info.point_cloud, scene_info.train_cameras, self.cameras_extent) + self.gaussians.create_from_pcd(scene_info.point_cloud, + scene_info.train_cameras, + self.cameras_extent, + args.skybox_num, + args.scaffold_file, + args.bounds_file, + args.skybox_locked) def save(self, iteration): point_cloud_path = os.path.join(self.model_path, "point_cloud/iteration_{}".format(iteration)) diff --git a/scene/dataset_readers.py b/scene/dataset_readers.py index 493d98d..2803961 100644 --- a/scene/dataset_readers.py +++ b/scene/dataset_readers.py @@ -122,7 +122,10 @@ def fetchPly(path): vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 - normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T + if 'nx' in vertices and 'ny' in vertices and 'nz' in vertices: + normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T + else: + normals = None return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): diff --git a/scene/gaussian_model.py b/scene/gaussian_model.py index 473887d..271d778 100644 --- a/scene/gaussian_model.py +++ b/scene/gaussian_model.py @@ -21,6 +21,7 @@ from utils.sh_utils import RGB2SH from simple_knn._C import distCUDA2 from utils.graphics_utils import BasicPointCloud from utils.general_utils import strip_symmetric, build_scaling_rotation +from scene.xy_utils import storePly try: from diff_gaussian_rasterization import SparseGaussianAdam @@ -64,6 +65,9 @@ class GaussianModel: self.percent_dense = 0 self.spatial_lr_scale = 0 self.setup_functions() + + self.skybox_points = 0 + self.skybox_locked = True def capture(self): return ( @@ -146,34 +150,137 @@ class GaussianModel: if self.active_sh_degree < self.max_sh_degree: self.active_sh_degree += 1 - def create_from_pcd(self, pcd : BasicPointCloud, cam_infos : int, spatial_lr_scale : float): + def create_from_pcd(self, + pcd : BasicPointCloud, + cam_infos : int, + spatial_lr_scale : float, + addition_points: int, + scaffold_file: str, + bounds_file: str, + skybox_locked: bool): + + # if addition_points > 0: + # self.skybox_points = addition_points # 原主代码中控制 skybox_points 更新的逻辑 + # groundbox_points = addition_points // 2 + # skybox_points = addition_points - groundbox_points + + self.skybox_points = addition_points + skybox_points = addition_points + self.skybox_locked = skybox_locked self.spatial_lr_scale = spatial_lr_scale - fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda() - fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda()) + + xyz_np = np.asarray(pcd.points) + xyz = torch.tensor(xyz_np).float().cuda() # [N,3] use xyz replace fused_point_cloud + fused_color = torch.tensor(np.asarray(pcd.colors)).float().cuda() # [N,3] from 0 to 1 + + # segment ground plane + from utils.points_utils import fit_ground_plane + plane_model, inliers = fit_ground_plane(xyz_np, threshold=0.001) + inliers = np.array(inliers) + ground_points = xyz_np[inliers] + ground_center = ground_points.mean(axis=0) + ground_radius = np.linalg.norm(ground_points - ground_center, axis=1).max() # need-check + + if scaffold_file != "" and skybox_points > 0: # TODO: load scaffold_file + print(f"Overriding skybox_points: loading skybox from scaffold_file: {scaffold_file}") + skybox_points = 0 + + if skybox_points > 0: + radius = ground_radius + mean = torch.tensor(ground_center).float().cuda() + theta = (2.0 * torch.pi * torch.rand(skybox_points, device="cuda")).float() # torch.rand generate [0,1) + phi = (torch.arccos(1.0 - 1.4 * torch.rand(skybox_points, device="cuda"))).float() # arc cos [-0.4,1] --> 角度 [0,110] + skybox_xyz = torch.zeros((skybox_points, 3)) + skybox_xyz[:, 0] = radius * 5 * torch.cos(theta)*torch.sin(phi) # 5 * radius + skybox_xyz[:, 1] = radius * 5 * torch.sin(theta)*torch.sin(phi) + skybox_xyz[:, 2] = radius * 5 * torch.cos(phi) + + normal = torch.tensor(plane_model[:3], dtype=torch.float32) + up = torch.tensor([0.0, 0.0, 1.0]) + + from utils.points_utils import create_rotation_matrix + R = create_rotation_matrix(up, normal) + R = torch.from_numpy(R).float() + skybox_xyz = (R@skybox_xyz.T).T + + skybox_xyz += mean.cpu() # put points in the center of the scene + xyz = torch.concat((skybox_xyz.cuda(), xyz)) + fused_color = torch.concat((torch.ones((skybox_points, 3)).cuda(), fused_color)) + fused_color[:skybox_points,0] *= 0.7 + fused_color[:skybox_points,1] *= 0.8 + fused_color[:skybox_points,2] *= 0.95 + + groundbox_points = 0 + if groundbox_points > 0: + radius = ground_radius + mean = torch.tensor(ground_center).float().cuda() + + a, b, c, d = plane_model + theta = 2.0 * torch.pi * torch.rand(groundbox_points, device="cuda") # 角度 [0, 2pi) + r = radius * torch.sqrt(torch.rand(groundbox_points, device="cuda")) # 半径范围 [0, 2*radius] + + groundbox_xyz = torch.zeros((groundbox_points, 3)) + groundbox_xyz[:, 0] = r * torch.cos(theta) + groundbox_xyz[:, 1] = r * torch.sin(theta) + groundbox_xyz[:, 2] = (-a * groundbox_xyz[:, 0] - b * groundbox_xyz[:, 1] - d) / c + groundbox_xyz += mean.cpu() + groundbox_color = torch.ones((groundbox_points, 3), device="cuda") * torch.tensor([0.5, 0.5, 0.5], device="cuda") + + xyz = torch.concat((groundbox_xyz.cuda(), xyz), dim=0) + fused_color = torch.concat((groundbox_color.cuda(), fused_color), dim=0) + + debug_xy = True + if debug_xy: + folder = "/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_debug/mini3/outputs_debug" + sky_ply_path = os.path.join(folder, "skybox_scene_init.ply") + storePly(sky_ply_path, xyz.cpu(), fused_color.cpu()*255) + print("save sky and groud init ply in: ", sky_ply_path) + + + # fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda() + + # fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda()) features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda() - features[:, :3, 0 ] = fused_color + features[:, :3, 0 ] = RGB2SH(fused_color) features[:, 3:, 1:] = 0.0 - print("Number of points at initialisation : ", fused_point_cloud.shape[0]) - - dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001) + # dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001) + dist2 = torch.clamp_min(distCUDA2(xyz), 0.0000001) # shape [],to caculate the + if scaffold_file == "" and skybox_points > 0: + dist2[:skybox_points] *= 10 # sky points * 10 扩大每个高斯最近 + dist2[skybox_points:] = torch.clamp_max(dist2[skybox_points:], 10) # 使得场景内高斯点的距离小于10 + scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3) - rots = torch.zeros((fused_point_cloud.shape[0], 4), device="cuda") + rots = torch.zeros((xyz.shape[0], 4), device="cuda") rots[:, 0] = 1 - opacities = self.inverse_opacity_activation(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda")) - - self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True)) - self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True)) - self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True)) + # opacities = self.inverse_opacity_activation(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda")) + if scaffold_file == "" and skybox_points > 0: + opacities = self.inverse_opacity_activation(0.02 * torch.ones((xyz.shape[0], 1), dtype=torch.float, device="cuda")) + opacities[:skybox_points] = 0.7 # sky 0.02 other 0.7 + else: + opacities = self.inverse_opacity_activation(0.01 * torch.ones((xyz.shape[0], 1), dtype=torch.float, device="cuda")) + + features_dc = features[:,:,0:1].transpose(1, 2).contiguous() + features_rest = features[:,:,1:].transpose(1, 2).contiguous() + self.scaffold_points = None + if scaffold_file != "": + print("TODO:load scaffold_file") + + self._xyz = nn.Parameter(xyz.requires_grad_(True)) + self._features_dc = nn.Parameter(features_dc.requires_grad_(True)) + self._features_rest = nn.Parameter(features_rest.requires_grad_(True)) self._scaling = nn.Parameter(scales.requires_grad_(True)) self._rotation = nn.Parameter(rots.requires_grad_(True)) self._opacity = nn.Parameter(opacities.requires_grad_(True)) self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda") + self.exposure_mapping = {cam_info.image_name: idx for idx, cam_info in enumerate(cam_infos)} + self.pretrained_exposures = None exposure = torch.eye(3, 4, device="cuda")[None].repeat(len(cam_infos), 1, 1) self._exposure = nn.Parameter(exposure.requires_grad_(True)) + print("Number of points at initialisation : ", self._xyz.shape[0]) def training_setup(self, training_args): self.percent_dense = training_args.percent_dense diff --git a/scene/xy_utils.py b/scene/xy_utils.py new file mode 100644 index 0000000..a907285 --- /dev/null +++ b/scene/xy_utils.py @@ -0,0 +1,21 @@ +from plyfile import PlyData, PlyElement +import numpy as np + + +def storePly(path, xyz, rgb): + # Define the dtype for the structured array + # RGB should be 0-255 + dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), + ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), + ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] + + normals = np.zeros_like(xyz) + + elements = np.empty(xyz.shape[0], dtype=dtype) + attributes = np.concatenate((xyz, normals, rgb), axis=1) + elements[:] = list(map(tuple, attributes)) + + # Create the PlyData object and write to file + vertex_element = PlyElement.describe(elements, 'vertex') + ply_data = PlyData([vertex_element]) + ply_data.write(path) \ No newline at end of file diff --git a/submodules/diff-gaussian-rasterization b/submodules/diff-gaussian-rasterization index 9c5c202..26ce026 160000 --- a/submodules/diff-gaussian-rasterization +++ b/submodules/diff-gaussian-rasterization @@ -1 +1 @@ -Subproject commit 9c5c2028f6fbee2be239bc4c9421ff894fe4fbe0 +Subproject commit 26ce026ae9d3cfa56a103279b863a9f320c3e555 diff --git a/train-sky.py b/train-sky.py new file mode 100644 index 0000000..e8cd446 --- /dev/null +++ b/train-sky.py @@ -0,0 +1,307 @@ +# +# 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 +# + +# edit like train_coarse.py + +import os +import torch +from random import randint +from utils.loss_utils import l1_loss, ssim +from gaussian_renderer import render, network_gui +import sys +from scene import Scene, GaussianModel +from utils.general_utils import safe_state, get_expon_lr_func +import uuid +from tqdm import tqdm +from utils.image_utils import psnr +from argparse import ArgumentParser, Namespace +from arguments import ModelParams, PipelineParams, OptimizationParams +try: + from torch.utils.tensorboard import SummaryWriter + TENSORBOARD_FOUND = True +except ImportError: + TENSORBOARD_FOUND = False + +try: + from fused_ssim import fused_ssim + FUSED_SSIM_AVAILABLE = True +except: + FUSED_SSIM_AVAILABLE = False + +try: + from diff_gaussian_rasterization import SparseGaussianAdam + SPARSE_ADAM_AVAILABLE = True +except: + SPARSE_ADAM_AVAILABLE = False + +def training(dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from): + # dataset = args + if not SPARSE_ADAM_AVAILABLE and opt.optimizer_type == "sparse_adam": + sys.exit(f"Trying to use sparse adam but it is not installed, please install the correct rasterizer using pip install [3dgs_accel].") + + first_iter = 0 + tb_writer = prepare_output_and_logger(dataset) + gaussians = GaussianModel(dataset.sh_degree, opt.optimizer_type) + print(f"dataset.sh_degree: {dataset.sh_degree}") + scene = Scene(dataset, gaussians) + debug_xy = True + if debug_xy: + scene.save(0) + gaussians.training_setup(opt) + if checkpoint: + (model_params, first_iter) = torch.load(checkpoint) + gaussians.restore(model_params, opt) + + bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0] + background = torch.tensor(bg_color, dtype=torch.float32, device="cuda") + + iter_start = torch.cuda.Event(enable_timing = True) + iter_end = torch.cuda.Event(enable_timing = True) + + use_sparse_adam = opt.optimizer_type == "sparse_adam" and SPARSE_ADAM_AVAILABLE + depth_l1_weight = get_expon_lr_func(opt.depth_l1_weight_init, opt.depth_l1_weight_final, max_steps=opt.iterations) + + viewpoint_stack = scene.getTrainCameras().copy() + viewpoint_indices = list(range(len(viewpoint_stack))) + ema_loss_for_log = 0.0 + ema_Ll1depth_for_log = 0.0 + + progress_bar = tqdm(range(first_iter, opt.iterations), desc="Training progress") + first_iter += 1 + + # freeze xyz + for param_group in gaussians.optimizer.param_groups: # xyz,f_dc,f_rest,opacity,scaling,rotation + if param_group["name"] == "xyz": + param_group['lr'] = 0.0 + + for iteration in range(first_iter, opt.iterations + 1): + if network_gui.conn == None: + network_gui.try_connect() + while network_gui.conn != None: + try: + net_image_bytes = None + custom_cam, do_training, pipe.convert_SHs_python, pipe.compute_cov3D_python, keep_alive, scaling_modifer = network_gui.receive() + if custom_cam != None: + net_image = render(custom_cam, gaussians, pipe, background, scaling_modifier=scaling_modifer, use_trained_exp=dataset.train_test_exp, separate_sh=SPARSE_ADAM_AVAILABLE)["render"] + net_image_bytes = memoryview((torch.clamp(net_image, min=0, max=1.0) * 255).byte().permute(1, 2, 0).contiguous().cpu().numpy()) + network_gui.send(net_image_bytes, dataset.source_path) + if do_training and ((iteration < int(opt.iterations)) or not keep_alive): + break + except Exception as e: + network_gui.conn = None + + iter_start.record() + + gaussians.update_learning_rate(iteration) + + # Every 1000 its we increase the levels of SH up to a maximum degree + if iteration % 1000 == 0: + gaussians.oneupSHdegree() + + # Pick a random Camera + if not viewpoint_stack: + viewpoint_stack = scene.getTrainCameras().copy() + viewpoint_indices = list(range(len(viewpoint_stack))) + rand_idx = randint(0, len(viewpoint_indices) - 1) + viewpoint_cam = viewpoint_stack.pop(rand_idx) + vind = viewpoint_indices.pop(rand_idx) + + # Render + if (iteration - 1) == debug_from: + pipe.debug = True + + bg = torch.rand((3), device="cuda") if opt.random_background else background + + render_pkg = render(viewpoint_cam, gaussians, pipe, bg, use_trained_exp=dataset.train_test_exp, separate_sh=SPARSE_ADAM_AVAILABLE) + image, viewspace_point_tensor, visibility_filter, radii = render_pkg["render"], render_pkg["viewspace_points"], render_pkg["visibility_filter"], render_pkg["radii"] + + if viewpoint_cam.alpha_mask is not None: + alpha_mask = viewpoint_cam.alpha_mask.cuda()# can set to sky mask + image *= alpha_mask + + # Loss + gt_image = viewpoint_cam.original_image.cuda() + Ll1 = l1_loss(image, gt_image) + if FUSED_SSIM_AVAILABLE: + ssim_value = fused_ssim(image.unsqueeze(0), gt_image.unsqueeze(0)) + else: + ssim_value = ssim(image, gt_image) + + loss = (1.0 - opt.lambda_dssim) * Ll1 + opt.lambda_dssim * (1.0 - ssim_value) + + # Depth regularization + Ll1depth_pure = 0.0 + if depth_l1_weight(iteration) > 0 and viewpoint_cam.depth_reliable: + invDepth = render_pkg["depth"] + mono_invdepth = viewpoint_cam.invdepthmap.cuda() + depth_mask = viewpoint_cam.depth_mask.cuda() + + Ll1depth_pure = torch.abs((invDepth - mono_invdepth) * depth_mask).mean() + Ll1depth = depth_l1_weight(iteration) * Ll1depth_pure + loss += Ll1depth + Ll1depth = Ll1depth.item() + else: + Ll1depth = 0 + + loss.backward() + + iter_end.record() + + with torch.no_grad(): + # Progress bar + ema_loss_for_log = 0.4 * loss.item() + 0.6 * ema_loss_for_log + ema_Ll1depth_for_log = 0.4 * Ll1depth + 0.6 * ema_Ll1depth_for_log + + if iteration % 10 == 0: + progress_bar.set_postfix({"Loss": f"{ema_loss_for_log:.{7}f}", "Depth Loss": f"{ema_Ll1depth_for_log:.{7}f}"}) + progress_bar.update(10) + if iteration == opt.iterations: + progress_bar.close() + + # Log and save + training_report(tb_writer, iteration, Ll1, loss, l1_loss, iter_start.elapsed_time(iter_end), testing_iterations, scene, render, (pipe, background, 1., SPARSE_ADAM_AVAILABLE, None, dataset.train_test_exp), dataset.train_test_exp) + if (iteration in saving_iterations): + print("\n[ITER {}] Saving Gaussians".format(iteration)) + scene.save(iteration) + + # # Densification + # if iteration < opt.densify_until_iter: + # # Keep track of max radii in image-space for pruning + # gaussians.max_radii2D[visibility_filter] = torch.max(gaussians.max_radii2D[visibility_filter], radii[visibility_filter]) + # gaussians.add_densification_stats(viewspace_point_tensor, visibility_filter) + + # if iteration > opt.densify_from_iter and iteration % opt.densification_interval == 0: + # size_threshold = 20 if iteration > opt.opacity_reset_interval else None + # gaussians.densify_and_prune(opt.densify_grad_threshold, 0.005, scene.cameras_extent, size_threshold, radii) + + # if iteration % opt.opacity_reset_interval == 0 or (dataset.white_background and iteration == opt.densify_from_iter): + # gaussians.reset_opacity() + + # Optimizer step + if iteration < opt.iterations: + gaussians.exposure_optimizer.step() # + gaussians.exposure_optimizer.zero_grad(set_to_none = True) + if use_sparse_adam: + # # raw 3dgs with sparse adam + # visible = radii > 0 + # gaussians.optimizer.step(visible, radii.shape[0]) + # gaussians.optimizer.zero_grad(set_to_none = True) + gaussians._scaling.grad[:gaussians.skybox_points,:] = 0 # sky points' gradients set to zero + relevant = (gaussians._opacity.grad != 0).squeeze() # points - opacity gradients != 0 + gaussians.optimizer.step(relevant, gaussians.get_xyz.shape[0]) # no densification so need step relevant points + gaussians.optimizer.zero_grad(set_to_none = True) + + if (iteration in checkpoint_iterations): + print("\n[ITER {}] Saving Checkpoint".format(iteration)) + torch.save((gaussians.capture(), iteration), scene.model_path + "/chkpnt" + str(iteration) + ".pth") + + with torch.no_grad(): + vals, _ = gaussians.get_scaling.max(dim=1) # max scaling for each point + violators = vals > scene.cameras_extent * 0.1 # 违反者(过大的点) + violators[:gaussians.skybox_points] = False # sky points not considered + gaussians._scaling[violators] = gaussians.scaling_inverse_activation(gaussians.get_scaling[violators] * 0.8) # scale down violators + +def prepare_output_and_logger(args): + if not args.model_path: + if os.getenv('OAR_JOB_ID'): + unique_str=os.getenv('OAR_JOB_ID') + else: + unique_str = str(uuid.uuid4()) + args.model_path = os.path.join("./output/", unique_str[0:10]) + + # Set up output folder + print("Output folder: {}".format(args.model_path)) + os.makedirs(args.model_path, exist_ok = True) + with open(os.path.join(args.model_path, "cfg_args"), 'w') as cfg_log_f: + cfg_log_f.write(str(Namespace(**vars(args)))) + + # Create Tensorboard writer + tb_writer = None + if TENSORBOARD_FOUND: + tb_writer = SummaryWriter(args.model_path) + else: + print("Tensorboard not available: not logging progress") + return tb_writer + +def training_report(tb_writer, iteration, Ll1, loss, l1_loss, elapsed, testing_iterations, scene : Scene, renderFunc, renderArgs, train_test_exp): + if tb_writer: + tb_writer.add_scalar('train_loss_patches/l1_loss', Ll1.item(), iteration) + tb_writer.add_scalar('train_loss_patches/total_loss', loss.item(), iteration) + tb_writer.add_scalar('iter_time', elapsed, iteration) + + # Report test and samples of training set + if iteration in testing_iterations: + torch.cuda.empty_cache() + validation_configs = ({'name': 'test', 'cameras' : scene.getTestCameras()}, + {'name': 'train', 'cameras' : [scene.getTrainCameras()[idx % len(scene.getTrainCameras())] for idx in range(5, 30, 5)]}) + + for config in validation_configs: + if config['cameras'] and len(config['cameras']) > 0: + l1_test = 0.0 + psnr_test = 0.0 + for idx, viewpoint in enumerate(config['cameras']): + image = torch.clamp(renderFunc(viewpoint, scene.gaussians, *renderArgs)["render"], 0.0, 1.0) + gt_image = torch.clamp(viewpoint.original_image.to("cuda"), 0.0, 1.0) + if train_test_exp: + image = image[..., image.shape[-1] // 2:] + gt_image = gt_image[..., gt_image.shape[-1] // 2:] + if tb_writer and (idx < 5): + tb_writer.add_images(config['name'] + "_view_{}/render".format(viewpoint.image_name), image[None], global_step=iteration) + if iteration == testing_iterations[0]: + tb_writer.add_images(config['name'] + "_view_{}/ground_truth".format(viewpoint.image_name), gt_image[None], global_step=iteration) + l1_test += l1_loss(image, gt_image).mean().double() + psnr_test += psnr(image, gt_image).mean().double() + psnr_test /= len(config['cameras']) + l1_test /= len(config['cameras']) + print("\n[ITER {}] Evaluating {}: L1 {} PSNR {}".format(iteration, config['name'], l1_test, psnr_test)) + if tb_writer: + tb_writer.add_scalar(config['name'] + '/loss_viewpoint - l1_loss', l1_test, iteration) + tb_writer.add_scalar(config['name'] + '/loss_viewpoint - psnr', psnr_test, iteration) + + if tb_writer: + tb_writer.add_histogram("scene/opacity_histogram", scene.gaussians.get_opacity, iteration) + tb_writer.add_scalar('total_points', scene.gaussians.get_xyz.shape[0], iteration) + torch.cuda.empty_cache() + +if __name__ == "__main__": + # Set up command line argument parser + parser = ArgumentParser(description="Training script parameters") + lp = ModelParams(parser) + op = OptimizationParams(parser) + pp = PipelineParams(parser) + parser.add_argument('--ip', type=str, default="127.0.0.1") + parser.add_argument('--port', type=int, default=6009) + parser.add_argument('--debug_from', type=int, default=-1) + parser.add_argument('--detect_anomaly', action='store_true', default=False) + parser.add_argument("--test_iterations", nargs="+", type=int, default=[7_000, 10_000, 15_000, 20_000, 25_000, 30_000, 50_000]) + parser.add_argument("--save_iterations", nargs="+", type=int, default=[7_000, 10_000, 15_000, 20_000, 25_000, 30_000, 50_000]) + parser.add_argument("--quiet", action="store_true") + parser.add_argument('--disable_viewer', action='store_true', default=False) + parser.add_argument("--checkpoint_iterations", nargs="+", type=int, default=[]) + parser.add_argument("--start_checkpoint", type=str, default = None) + + args = parser.parse_args(sys.argv[1:]) + + args.save_iterations.append(args.iterations) + + print("Optimizing " + args.model_path) + + # Initialize system state (RNG) + safe_state(args.quiet) + + # Start GUI server, configure and run training + if not args.disable_viewer: + network_gui.init(args.ip, args.port) + torch.autograd.set_detect_anomaly(args.detect_anomaly) + training(lp.extract(args), op.extract(args), pp.extract(args), args.test_iterations, args.save_iterations, args.checkpoint_iterations, args.start_checkpoint, args.debug_from) + + # All done + print("\nTraining complete.") diff --git a/utils/points_utils.py b/utils/points_utils.py new file mode 100644 index 0000000..4f53110 --- /dev/null +++ b/utils/points_utils.py @@ -0,0 +1,31 @@ +import open3d as o3d +import torch +def fit_ground_plane(xyz, threshold=0.02): + pcd = o3d.geometry.PointCloud() + pcd.points = o3d.utility.Vector3dVector(xyz) + plane_model, inliers = pcd.segment_plane(distance_threshold=threshold, + ransac_n=3, + num_iterations=10000) + return plane_model, inliers + +def create_rotation_matrix(source_dir, target_dir): + + source_dir = source_dir / torch.norm(source_dir) + target_dir = target_dir / torch.norm(target_dir) + + axis = torch.cross(source_dir, target_dir) + cos_angle = torch.dot(source_dir, target_dir) + + if torch.norm(axis) < 1e-6: + return torch.eye(3, device=source_dir.device) + + axis = axis / torch.norm(axis) + # k = axis.unsqueeze(-1) + # K = torch.zeros((3, 3), device=source_dir.device) + # K[0, 1] = -k[2] + # K[0, 2] = k[1] + # K[1, 2] = -k[0] + # K = K - K.T + # R = torch.eye(3, device=source_dir.device) + K + K @ K * (1 - cos_angle) / (1 + cos_angle) + R_align = o3d.geometry.get_rotation_matrix_from_axis_angle(axis * torch.acos(cos_angle)) + return R_align \ No newline at end of file diff --git a/xy_utils/learning.ipynb b/xy_utils/learning.ipynb index 9180fbe..434e30e 100644 --- a/xy_utils/learning.ipynb +++ b/xy_utils/learning.ipynb @@ -207,7 +207,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "id": "56f5cba7", "metadata": {}, "outputs": [ @@ -215,9 +215,9 @@ "name": "stdout", "output_type": "stream", "text": [ - "raw points len : 15254842\n", - "downsample points len : 201667\n", - "降采样后的点云已保存到 /home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_livo2/sparse/0/points3D_filter_0.2.ply,体素大小:0.2\n" + "raw points len : 16404321\n", + "downsample points len : 4671298\n", + "降采样后的点云已保存到 /home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_debug/mini3/sparse/0/raw/all_raw_points_0.05.ply,体素大小:0.05\n" ] } ], @@ -225,12 +225,12 @@ "import os\n", "from tools.points_utils import voxel_downsample_and_save\n", "\n", - "voxel_size = 0.2\n", + "voxel_size = 0.05\n", "folder_path = '/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_livo2/livo2_results'\n", "input_ply_path = os.path.join(folder_path,'pcd/points3D.ply')\n", "output_ply_path = os.path.join(folder_path,f'pcd/points3D_{voxel_size}.ply')\n", - "input_ply_path = '/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_livo2/sparse/0/points3D_filter.ply'\n", - "output_ply_path = f'/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_livo2/sparse/0/points3D_filter_{voxel_size}.ply'\n", + "input_ply_path = '/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_debug/mini3/sparse/0/raw/all_raw_points.ply'\n", + "output_ply_path = f'/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_debug/mini3/sparse/0/raw/all_raw_points_{voxel_size}.ply'\n", "\n", "voxel_downsample_and_save(voxel_size, input_ply_path, output_ply_path) # ply downsample to ply\n" ] @@ -238,26 +238,34 @@ { "cell_type": "code", "execution_count": null, + "id": "d1df326d", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 1, "id": "8544bb3e", "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "True" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "Jupyter environment detected. Enabling Open3D WebVisualizer.\n", + "[Open3D INFO] WebRTC GUI backend enabled.\n", + "[Open3D INFO] WebRTCWindowSystem: HTTP handshake server disabled.\n", + "Converted /home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_debug/mini3/sparse/0/raw/all_raw_points.pcd to /home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_debug/mini3/sparse/0/raw/all_raw_points.ply\n" + ] } ], "source": [ "# pcd 2 ply\n", "# 将原pcd点云,转换为ply点云\n", "from tools.points_utils import pcd_2_ply\n", - "pcd_file = '/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_livo2/livo2_results/pcd/all_raw_points.pcd'\n", - "ply_file = '/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_livo2/livo2_results/pcd/all_raw_points.ply'\n", + "pcd_file = '/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_debug/mini3/sparse/0/raw/all_raw_points.pcd'\n", + "ply_file = '/home/qinllgroup/hongxiangyu/git_project/gaussian-splatting-xy/data/tree_01_debug/mini3/sparse/0/raw/all_raw_points.ply'\n", "\n", "pcd_2_ply(pcd_file,ply_file)\n" ] @@ -515,6 +523,57 @@ " -s data/tree_01_colmap \\\n", " -m data/tree_01_colmap/outputs/3dgs_baseline " ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0156e92d", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[[2, 4, 5], [1, 5, 4]]" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\n", + "iss = [[1,5,4],[2,4,5]]\n", + "iss.sort(key=lambda x: [x[1],x[0]], reverse=True)\n", + "iss" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bf857aee", + "metadata": {}, + "outputs": [], + "source": [ + "class Solution(object):\n", + " def merge(self, intervals):\n", + " \"\"\"\n", + " :type intervals: List[List[int]]\n", + " :rtype: List[List[int]]\n", + " \"\"\"\n", + " if not intervals:\n", + " return []\n", + " # 先按区间的起始位置排序\n", + " intervals.sort(key=lambda x: x[0])\n", + " merged = [intervals[0]]\n", + " for i in range(1, len(intervals)):\n", + " # 如果当前区间与上一个区间重叠,则合并\n", + " if intervals[i][0] <= merged[-1][1]:\n", + " merged[-1][1] = max(merged[-1][1], intervals[i][1])\n", + " else:\n", + " merged.append(intervals[i])\n", + " return merged" + ] } ], "metadata": { diff --git a/xy_utils/sky_groud.py b/xy_utils/sky_groud.py new file mode 100644 index 0000000..55c69c1 --- /dev/null +++ b/xy_utils/sky_groud.py @@ -0,0 +1,19 @@ +from tools.points_utils import * +import numpy as np +import math +import open3d as o3d + + +def fit_ground_plane(xyz, threshold=0.02): + """ + 使用 RANSAC 拟合地面平面模型。 + 返回:平面模型 [a, b, c, d] 和内点索引。 + """ + pcd = o3d.geometry.PointCloud() + pcd.points = o3d.utility.Vector3dVector(xyz) + plane_model, inliers = pcd.segment_plane(distance_threshold=threshold, + ransac_n=3, + num_iterations=1000) + [a, b, c, d] = plane_model + print(f"拟合的地面平面方程: {a:.4f}x + {b:.4f}y + {c:.4f}z + {d:.4f} = 0") + return plane_model, inliers \ No newline at end of file diff --git a/xy_utils/tools/points_utils.py b/xy_utils/tools/points_utils.py index 33ae19b..41ef062 100644 --- a/xy_utils/tools/points_utils.py +++ b/xy_utils/tools/points_utils.py @@ -55,4 +55,29 @@ def voxel_downsample_and_save(voxel_size, input_ply_path, output_ply_path): # 保存降采样后的点云 o3d.io.write_point_cloud(output_ply_path, pcd_downsampled) - print(f"降采样后的点云已保存到 {output_ply_path},体素大小:{voxel_size}") \ No newline at end of file + print(f"降采样后的点云已保存到 {output_ply_path},体素大小:{voxel_size}") + +def load_pcd(pcd_file_path): + pcd = o3d.io.read_point_cloud(pcd_file_path) + xyz = np.asarray(pcd.points) + rgb = np.asarray(pcd.colors) + if np.max(rgb) <= 1.0: + rgb = (rgb * 255).astype(np.uint8) + return xyz, rgb + +def load_ply(ply_file_path): + pcd = o3d.io.read_point_cloud(ply_file_path) + xyz = np.asarray(pcd.points) + rgb = np.asarray(pcd.colors) + if np.max(rgb) <= 1.0: + rgb = (rgb * 255).astype(np.uint8) + return xyz, rgb + +def save_ply(xyz, colors, file_path): + + pcd = o3d.geometry.PointCloud() + pcd.points = o3d.utility.Vector3dVector(xyz) + pcd.colors = o3d.utility.Vector3dVector(colors) + o3d.io.write_point_cloud(file_path, pcd) + + print(f"保存点云到 {file_path}") \ No newline at end of file