diff --git a/.gitmodules b/.gitmodules index 2a78943..d20bef2 100644 --- a/.gitmodules +++ b/.gitmodules @@ -6,4 +6,4 @@ url = https://github.com/graphdeco-inria/diff-gaussian-rasterization [submodule "SIBR_viewers"] path = SIBR_viewers - url = https://gitlab.inria.fr/sibr/sibr_core + url = https://gitlab.inria.fr/sibr/sibr_core.git diff --git a/README.md b/README.md index 9aa5bd8..a0e39a3 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,7 @@ # 3D Gaussian Splatting for Real-Time Radiance Field Rendering Bernhard Kerbl*, Georgios Kopanas*, Thomas Leimkühler, George Drettakis (* indicates equal contribution)
-| [Webpage](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/) | [Full Paper](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/3d_gaussian_splatting_high.pdf) | -[Video](https://youtu.be/T_kXY43VZnk) | [Other GRAPHDECO Publications](http://www-sop.inria.fr/reves/publis/gdindex.php) | [FUNGRAPH project page](https://fungraph.inria.fr) | - -| [T&T+DB COLMAP (650MB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/input/tandt_db.zip) | [Pre-trained Models (14 GB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/pretrained/models.zip) | [Viewers for Windows (60MB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/binaries/viewers.zip) | [Evaluation Images (7 GB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/evaluation/images.zip) |
+| [Webpage](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/) | [Full Paper](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/3d_gaussian_splatting_high.pdf) | [Video](https://youtu.be/T_kXY43VZnk) | [Other GRAPHDECO Publications](http://www-sop.inria.fr/reves/publis/gdindex.php) | [FUNGRAPH project page](https://fungraph.inria.fr) |
+| [T&T+DB COLMAP (650MB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/input/tandt_db.zip) | [Pre-trained Models (14 GB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/pretrained/models.zip) | [Viewers for Windows (60MB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/binaries/viewers.zip) | [Evaluation Images (7 GB)](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/evaluation/images.zip) |
![Teaser image](assets/teaser.png) This repository contains the official authors implementation associated with the paper "3D Gaussian Splatting for Real-Time Radiance Field Rendering", which can be found [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/). We further provide the reference images used to create the error metrics reported in the paper, as well as recently created, pre-trained models. @@ -36,6 +34,14 @@ Abstract: *Radiance Field methods have recently revolutionized novel-view synthe This research was funded by the ERC Advanced grant FUNGRAPH No 788065. The authors are grateful to Adobe for generous donations, the OPAL infrastructure from Université Côte d’Azur and for the HPC resources from GENCI–IDRIS (Grant 2022-AD011013409). The authors thank the anonymous reviewers for their valuable feedback, P. Hedman and A. Tewari for proofreading earlier drafts also T. Müller, A. Yu and S. Fridovich-Keil for helping with the comparisons. +## Step-by-step Tutorial + +Jonathan Stephens made a fantastic step-by-step tutorial for setting up Gaussian Splatting on your machine, along with instructions for creating usable datasets from videos. If the instructions below are too dry for you, go ahead and check it out [here](https://www.youtube.com/watch?v=UXtuigy_wYc). + +## Colab + +User [camenduru](https://github.com/camenduru) was kind enough to provide a Colab template that uses this repo's source (status: August 2023!) for quick and easy access to the method. Please check it out [here](https://github.com/camenduru/gaussian-splatting-colab). + ## Cloning the Repository The repository contains submodules, thus please check it out with @@ -72,17 +78,20 @@ The optimizer uses PyTorch and CUDA extensions in a Python environment to produc ### Software Requirements - Conda (recommended for easy setup) - C++ Compiler for PyTorch extensions (we used Visual Studio 2019 for Windows) -- CUDA SDK 11.7+ for PyTorch extensions (we used 11.8, **known issues with 11.6**) +- CUDA SDK 11 for PyTorch extensions, install *after* Visual Studio (we used 11.8, **known issues with 11.6**) - C++ Compiler and CUDA SDK must be compatible ### Setup -Our provided install method is based on Conda package and environment management: +#### Local Setup + +Our default, provided install method is based on Conda package and environment management: ```shell SET DISTUTILS_USE_SDK=1 # Windows only conda env create --file environment.yml conda activate gaussian_splatting ``` +Please note that this process assumes that you have CUDA SDK **11** installed, not **12**. For modifications, see below. Tip: Downloading packages and creating a new environment with Conda can require a significant amount of disk space. By default, Conda will use the main system hard drive. You can avoid this by specifying a different package download location and an environment on a different drive: @@ -92,7 +101,13 @@ conda env create --file environment.yml --prefix //gaussian_spl conda activate //gaussian_splatting ``` -If you can afford the disk space, we recommend using our environment files for setting up a training environment identical to ours. If you want to make modifications, please note that major version changes might affect the results of our method. However, our (limited) experiments suggest that the codebase works just fine inside a more up-to-date environment (Python 3.8, PyTorch 2.0.0, CUDA 11.8). +#### Modifications + +If you can afford the disk space, we recommend using our environment files for setting up a training environment identical to ours. If you want to make modifications, please note that major version changes might affect the results of our method. However, our (limited) experiments suggest that the codebase works just fine inside a more up-to-date environment (Python 3.8, PyTorch 2.0.0, CUDA 12). Make sure to create an environment where PyTorch and its CUDA runtime version match and the installed CUDA SDK has no major version difference with PyTorch's CUDA version. + +#### Known Issues + +Some users experience problems building the submodules on Windows (```cl.exe: File not found``` or similar). Please consider the workaround for this problem from the FAQ. ### Running @@ -116,7 +131,7 @@ python train.py -s #### --resolution / -r Specifies resolution of the loaded images before training. If provided ```1, 2, 4``` or ```8```, uses original, 1/2, 1/4 or 1/8 resolution, respectively. For all other values, rescales the width to the given number while maintaining image aspect. **If not set and input image width exceeds 1.6K pixels, inputs are automatically rescaled to this target.** #### --data_device - Specifies where to put the source image data, ```cuda``` by default, recommended to use ```cpu``` if training on large/high-resolution dataset, will reduce VRAM consumption, but slightly slow down training. + Specifies where to put the source image data, ```cuda``` by default, recommended to use ```cpu``` if training on large/high-resolution dataset, will reduce VRAM consumption, but slightly slow down training. Thanks to [HrsPythonix](https://github.com/HrsPythonix). #### --white_background / -w Add this flag to use white background instead of black (default), e.g., for evaluation of NeRF Synthetic dataset. #### --sh_degree @@ -125,14 +140,32 @@ python train.py -s Flag to make pipeline compute forward and backward of SHs with PyTorch instead of ours. #### --convert_cov3D_python Flag to make pipeline compute forward and backward of the 3D covariance with PyTorch instead of ours. + #### --debug + Enables debug mode if you experience erros. If the rasterizer fails, a ```dump``` file is created that you may forward to us in an issue so we can take a look. + #### --debug_from + Debugging is **slow**. You may specify an iteration (starting from 0) after which the above debugging becomes active. #### --iterations Number of total iterations to train for, ```30_000``` by default. + #### --ip + IP to start GUI server on, ```127.0.0.1``` by default. + #### --port + Port to use for GUI server, ```6009``` by default. + #### --test_iterations + Space-separated iterations at which the training script computes L1 and PSNR over test set, ```7000 30000``` by default. + #### --save_iterations + Space-separated iterations at which the training script saves the Gaussian model, ```7000 30000 ``` by default. + #### --checkpoint_iterations + Space-separated iterations at which to store a checkpoint for continuing later, saved in the model directory. + #### --start_checkpoint + Path to a saved checkpoint to continue training from. + #### --quiet + Flag to omit any text written to standard out pipe. #### --feature_lr Spherical harmonics features learning rate, ```0.0025``` by default. #### --opacity_lr Opacity learning rate, ```0.05``` by default. #### --scaling_lr - Scaling learning rate, ```0.001``` by default. + Scaling learning rate, ```0.005``` by default. #### --rotation_lr Rotation learning rate, ```0.001``` by default. #### --position_lr_max_steps @@ -149,31 +182,21 @@ python train.py -s Iteration where densification stops, ```15_000``` by default. #### --densify_grad_threshold Limit that decides if points should be densified based on 2D position gradient, ```0.0002``` by default. - #### --densification_interal + #### --densification_interval How frequently to densify, ```100``` (every 100 iterations) by default. #### --opacity_reset_interval How frequently to reset opacity, ```3_000``` by default. #### --lambda_dssim Influence of SSIM on total loss from 0 to 1, ```0.2``` by default. #### --percent_dense - Percentage of scene extent (0--1) a point must exceed to be forcibly densified, ```0.1``` by default. - #### --ip - IP to start GUI server on, ```127.0.0.1``` by default. - #### --port - Port to use for GUI server, ```6009``` by default. - #### --test_iterations - Space-separated iterations at which the training script computes L1 and PSNR over test set, ```7000 30000``` by default. - #### --save_iterations - Space-separated iterations at which the training script saves the Gaussian model, ```7000 30000 ``` by default. - #### --quiet - Flag to omit any text written to standard out pipe. + Percentage of scene extent (0--1) a point must exceed to be forcibly densified, ```0.01``` by default.
Note that similar to MipNeRF360, we target images at resolutions in the 1-1.6K pixel range. For convenience, arbitrary-size inputs can be passed and will be automatically resized if their width exceeds 1600 pixels. We recommend to keep this behavior, but you may force training to use your higher-resolution images by setting ```-r 1```. -The MipNeRF360 scenes are hosted by the paper authors [here](https://jonbarron.info/mipnerf360/). You can find our SfM data sets for Tanks&Temples and Deep Blending [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/input/tandt+db.zip). If you do not provide an output model directory (```-m```), trained models are written to folders with randomized unique names inside the ```output``` directory. At this point, the trained models may be viewed with the real-time viewer (see further below). +The MipNeRF360 scenes are hosted by the paper authors [here](https://jonbarron.info/mipnerf360/). You can find our SfM data sets for Tanks&Temples and Deep Blending [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/input/tandt_db.zip). If you do not provide an output model directory (```-m```), trained models are written to folders with randomized unique names inside the ```output``` directory. At this point, the trained models may be viewed with the real-time viewer (see further below). ### Evaluation By default, the trained models use all available images in the dataset. To train them while withholding a test set for evaluation, use the ```--eval``` flag. This way, you can render training/test sets and produce error metrics as follows: @@ -263,16 +286,16 @@ python full_eval.py -m /garden ... --skip_trai
## Interactive Viewers -We provide two interactive iewers for our method: remote and real-time. Our viewing solutions are based on the [SIBR](https://sibr.gitlabpages.inria.fr/) framework, developed by the GRAPHDECO group for several novel-view synthesis projects. +We provide two interactive viewers for our method: remote and real-time. Our viewing solutions are based on the [SIBR](https://sibr.gitlabpages.inria.fr/) framework, developed by the GRAPHDECO group for several novel-view synthesis projects. ### Hardware Requirements -- OpenGL 4.5-ready GPU +- OpenGL 4.5-ready GPU and drivers (or latest MESA software) - 4 GB VRAM recommended - CUDA-ready GPU with Compute Capability 7.0+ (only for Real-Time Viewer) ### Software Requirements - Visual Studio or g++, **not Clang** (we used Visual Studio 2019 for Windows) -- CUDA SDK 11 (we used 11.8) +- CUDA SDK 11, install *after* Visual Studio (we used 11.8) - CMake (recent version, we used 3.24) - 7zip (only on Windows) @@ -298,7 +321,6 @@ You will need to install a few dependencies before running the project setup. sudo apt install -y libglew-dev libassimp-dev libboost-all-dev libgtk-3-dev libopencv-dev libglfw3-dev libavdevice-dev libavcodec-dev libeigen3-dev libxxf86vm-dev libembree-dev # Project setup cd SIBR_viewers -# Default cmake -Bbuild . -DCMAKE_BUILD_TYPE=Release # add -G Ninja to build faster cmake --build build -j24 --target install ``` @@ -364,7 +386,7 @@ It should suffice to provide the ```-m``` parameter pointing to a trained model ![Teaser image](assets/select.png) -In addition to the intial point cloud and the splats, you also have the option to visualize the Gaussians by rendering them as ellipsoids from the floating menu. +In addition to the initial point cloud and the splats, you also have the option to visualize the Gaussians by rendering them as ellipsoids from the floating menu. SIBR has many other functionalities, please see the [documentation](https://sibr.gitlabpages.inria.fr/) for more details on the viewer, navigation options etc. There is also a Top View (available from the menu) that shows the placement of the input cameras and the original SfM point cloud; please note that Top View slows rendering when enabled. The real-time viewer also uses slightly more aggressive, fast culling, which can be toggled in the floating menu. If you ever encounter an issue that can be solved by turning fast culling off, please let us know.
@@ -382,6 +404,8 @@ SIBR has many other functionalities, please see the [documentation](https://sibr Flag to load source dataset images to be displayed in the top view for each camera. #### --device Index of CUDA device to use for rasterization if multiple are available, ```0``` by default. + #### --no_interop + Disables CUDA/GL interop forcibly. Use on systems that may not behave according to spec (e.g., WSL2 with MESA GL 4.5 software rendering).

@@ -455,13 +479,32 @@ python convert.py -s --skip_matching [--resize] #If not resizing, Ima
## FAQ -- *Where do I get data sets, e.g., those referenced in ```full_eval.py```?* The MipNeRF360 data set is provided by the authors of the original paper on the project site. Note that two of the data sets cannot be openly shared and require you to consult the authors directly. For Tanks&Temples and Deep Blending, please use the download links provided at the top of the page. +- *Where do I get data sets, e.g., those referenced in ```full_eval.py```?* The MipNeRF360 data set is provided by the authors of the original paper on the project site. Note that two of the data sets cannot be openly shared and require you to consult the authors directly. For Tanks&Temples and Deep Blending, please use the download links provided at the top of the page. Alternatively, you may access the cloned data (status: August 2023!) from [HuggingFace](https://huggingface.co/camenduru/gaussian-splatting) + + +- *How can I use this for a much larger dataset, like a city district?* The current method was not designed for these, but given enough memory, it should work out. However, the approach can struggle in multi-scale detail scenes (extreme close-ups, mixed with far-away shots). This is usually the case in, e.g., driving data sets (cars close up, buildings far away). For such scenes, you can lower the ```--position_lr_init```, ```--position_lr_final``` and ```--scaling_lr``` (x0.3, x0.1, ...). The more extensive the scene, the lower these values should be. Below, we use default learning rates (left) and ```--position_lr_init 0.000016 --scaling_lr 0.001"``` (right). + +| ![Default learning rate result](assets/worse.png "title-1") | ![Reduced learning rate result](assets/better.png "title-2") | +| --- | --- | + +- *I'm on Windows and I can't manage to build the submodules, what do I do?* Consider following the steps in the excellent video tutorial [here](https://www.youtube.com/watch?v=UXtuigy_wYc), hopefully they should help. The order in which the steps are done is important! Alternatively, consider using the linked Colab template. + +- *It still doesn't work. It says something about ```cl.exe```. What do I do?* User Henry Pearce found a workaround. You can you try adding the visual studio path to your environment variables (your version number might differ); +```C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64``` +Then make sure you start a new conda prompt and cd to your repo location and try this; +``` +conda activate gaussian_splatting +cd /gaussian-splatting +pip install submodules\diff-gaussian-rasterization +pip install submodules\simple-knn +``` + +- *I'm on macOS/Puppy Linux/Greenhat and I can't manage to build, what do I do?* Sorry, we can't provide support for platforms outside of the ones we list in this README. Consider using the linked Colab template. - *I don't have 24 GB of VRAM for training, what do I do?* The VRAM consumption is determined by the number of points that are being optimized, which increases over time. If you only want to train to 7k iterations, you will need significantly less. To do the full training routine and avoid running out of memory, you can increase the ```--densify_grad_threshold```, ```--densification_interval``` or reduce the value of ```--densify_until_iter```. Note however that this will affect the quality of the result. Also try setting ```--test_iterations``` to ```-1``` to avoid memory spikes during testing. If ```--densify_grad_threshold``` is very high, no densification should occur and training should complete if the scene itself loads successfully. - *24 GB of VRAM for reference quality training is still a lot! Can't we do it with less?* Yes, most likely. By our calculations it should be possible with **way** less memory (~8GB). If we can find the time we will try to achieve this. If some PyTorch veteran out there wants to tackle this, we look forward to your pull request! -- *How can I use this for a much larger dataset, like a city district?* Given enough memory, this should work out fine, but it will require to adapt the ```--scaling_lr``` and ```--position_lr_init/final```. To avoid manual tuning, a suggestion is to check the loss: if it diverges early on, reset and use a lower scaling / position learning rate. - *How can I use the differentiable Gaussian rasterizer for my own project?* Easy, it is included in this repo as a submodule ```diff-gaussian-rasterization```. Feel free to check out and install the package. It's not really documented, but using it from the Python side is very straightforward (cf. ```gaussian_renderer/__init__.py```). diff --git a/SIBR_viewers b/SIBR_viewers index 440bd4c..1419988 160000 --- a/SIBR_viewers +++ b/SIBR_viewers @@ -1 +1 @@ -Subproject commit 440bd4c75b2029d0d5f60f6c5859a273e7ae651b +Subproject commit 14199886ae3f42358092c16ada909c1e0b1cba20 diff --git a/arguments/__init__.py b/arguments/__init__.py index eba1dba..1793b47 100644 --- a/arguments/__init__.py +++ b/arguments/__init__.py @@ -65,6 +65,7 @@ class PipelineParams(ParamGroup): def __init__(self, parser): self.convert_SHs_python = False self.compute_cov3D_python = False + self.debug = False super().__init__(parser, "Pipeline Parameters") class OptimizationParams(ParamGroup): @@ -76,7 +77,7 @@ class OptimizationParams(ParamGroup): self.position_lr_max_steps = 30_000 self.feature_lr = 0.0025 self.opacity_lr = 0.05 - self.scaling_lr = 0.001 + self.scaling_lr = 0.005 self.rotation_lr = 0.001 self.percent_dense = 0.01 self.lambda_dssim = 0.2 diff --git a/assets/better.png b/assets/better.png new file mode 100644 index 0000000..019c143 Binary files /dev/null and b/assets/better.png differ diff --git a/assets/worse.png b/assets/worse.png new file mode 100644 index 0000000..b384897 Binary files /dev/null and b/assets/worse.png differ diff --git a/convert.py b/convert.py index 333f875..7894884 100644 --- a/convert.py +++ b/convert.py @@ -3,13 +3,14 @@ # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # -# This software is free for non-commercial, research and evaluation use +# 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 os +import logging from argparse import ArgumentParser import shutil @@ -31,34 +32,50 @@ if not args.skip_matching: os.makedirs(args.source_path + "/distorted/sparse", exist_ok=True) ## Feature extraction - os.system(colmap_command + " feature_extractor "\ + feat_extracton_cmd = colmap_command + " feature_extractor "\ "--database_path " + args.source_path + "/distorted/database.db \ --image_path " + args.source_path + "/input \ --ImageReader.single_camera 1 \ --ImageReader.camera_model " + args.camera + " \ - --SiftExtraction.use_gpu " + str(use_gpu)) + --SiftExtraction.use_gpu " + str(use_gpu) + exit_code = os.system(feat_extracton_cmd) + if exit_code != 0: + logging.error(f"Feature extraction failed with code {exit_code}. Exiting.") + exit(exit_code) ## Feature matching - os.system(colmap_command + " exhaustive_matcher \ + feat_matching_cmd = colmap_command + " exhaustive_matcher \ --database_path " + args.source_path + "/distorted/database.db \ - --SiftMatching.use_gpu " + str(use_gpu)) + --SiftMatching.use_gpu " + str(use_gpu) + exit_code = os.system(feat_matching_cmd) + if exit_code != 0: + logging.error(f"Feature matching failed with code {exit_code}. Exiting.") + exit(exit_code) ### Bundle adjustment # The default Mapper tolerance is unnecessarily large, # decreasing it speeds up bundle adjustment steps. - os.system(colmap_command + " mapper \ + mapper_cmd = (colmap_command + " mapper \ --database_path " + args.source_path + "/distorted/database.db \ --image_path " + args.source_path + "/input \ --output_path " + args.source_path + "/distorted/sparse \ --Mapper.ba_global_function_tolerance=0.000001") + exit_code = os.system(mapper_cmd) + if exit_code != 0: + logging.error(f"Mapper failed with code {exit_code}. Exiting.") + exit(exit_code) ### Image undistortion ## We need to undistort our images into ideal pinhole intrinsics. -os.system(colmap_command + " image_undistorter \ +img_undist_cmd = (colmap_command + " image_undistorter \ --image_path " + args.source_path + "/input \ --input_path " + args.source_path + "/distorted/sparse/0 \ --output_path " + args.source_path + "\ --output_type COLMAP") +exit_code = os.system(img_undist_cmd) +if exit_code != 0: + logging.error(f"Mapper failed with code {exit_code}. Exiting.") + exit(exit_code) files = os.listdir(args.source_path + "/sparse") os.makedirs(args.source_path + "/sparse/0", exist_ok=True) @@ -85,14 +102,23 @@ if(args.resize): destination_file = os.path.join(args.source_path, "images_2", file) shutil.copy2(source_file, destination_file) - os.system(magick_command + " mogrify -resize 50% " + destination_file) + exit_code = os.system(magick_command + " mogrify -resize 50% " + destination_file) + if exit_code != 0: + logging.error(f"50% resize failed with code {exit_code}. Exiting.") + exit(exit_code) destination_file = os.path.join(args.source_path, "images_4", file) shutil.copy2(source_file, destination_file) - os.system(magick_command + " mogrify -resize 25% " + destination_file) + exit_code = os.system(magick_command + " mogrify -resize 25% " + destination_file) + if exit_code != 0: + logging.error(f"25% resize failed with code {exit_code}. Exiting.") + exit(exit_code) destination_file = os.path.join(args.source_path, "images_8", file) shutil.copy2(source_file, destination_file) - os.system(magick_command + " mogrify -resize 12.5% " + destination_file) + exit_code = os.system(magick_command + " mogrify -resize 12.5% " + destination_file) + if exit_code != 0: + logging.error(f"12.5% resize failed with code {exit_code}. Exiting.") + exit(exit_code) -print("Done.") \ No newline at end of file +print("Done.") diff --git a/gaussian_renderer/__init__.py b/gaussian_renderer/__init__.py index 34e3e95..db7ef7d 100644 --- a/gaussian_renderer/__init__.py +++ b/gaussian_renderer/__init__.py @@ -44,7 +44,8 @@ def render(viewpoint_camera, pc : GaussianModel, pipe, bg_color : torch.Tensor, projmatrix=viewpoint_camera.full_proj_transform, sh_degree=pc.active_sh_degree, campos=viewpoint_camera.camera_center, - prefiltered=False + prefiltered=False, + debug=pipe.debug ) rasterizer = GaussianRasterizer(raster_settings=raster_settings) @@ -68,7 +69,7 @@ def render(viewpoint_camera, pc : GaussianModel, pipe, bg_color : torch.Tensor, # from SHs in Python, do it. If not, then SH -> RGB conversion will be done by rasterizer. shs = None colors_precomp = None - if colors_precomp is None: + if override_color is None: if pipe.convert_SHs_python: shs_view = pc.get_features.transpose(1, 2).view(-1, 3, (pc.max_sh_degree+1)**2) dir_pp = (pc.get_xyz - viewpoint_camera.camera_center.repeat(pc.get_features.shape[0], 1)) diff --git a/scene/__init__.py b/scene/__init__.py index c1799f2..2b31398 100644 --- a/scene/__init__.py +++ b/scene/__init__.py @@ -78,8 +78,7 @@ class Scene: self.gaussians.load_ply(os.path.join(self.model_path, "point_cloud", "iteration_" + str(self.loaded_iter), - "point_cloud.ply"), - og_number_points=len(scene_info.point_cloud.points)) + "point_cloud.ply")) else: self.gaussians.create_from_pcd(scene_info.point_cloud, self.cameras_extent) diff --git a/scene/colmap_loader.py b/scene/colmap_loader.py index 0f32d23..8f6fba6 100644 --- a/scene/colmap_loader.py +++ b/scene/colmap_loader.py @@ -89,6 +89,21 @@ def read_points3D_text(path): xyzs = None rgbs = None errors = None + num_points = 0 + with open(path, "r") as fid: + while True: + line = fid.readline() + if not line: + break + line = line.strip() + if len(line) > 0 and line[0] != "#": + num_points += 1 + + + xyzs = np.empty((num_points, 3)) + rgbs = np.empty((num_points, 3)) + errors = np.empty((num_points, 1)) + count = 0 with open(path, "r") as fid: while True: line = fid.readline() @@ -100,14 +115,11 @@ def read_points3D_text(path): xyz = np.array(tuple(map(float, elems[1:4]))) rgb = np.array(tuple(map(int, elems[4:7]))) error = np.array(float(elems[7])) - if xyzs is None: - xyzs = xyz[None, ...] - rgbs = rgb[None, ...] - errors = error[None, ...] - else: - xyzs = np.append(xyzs, xyz[None, ...], axis=0) - rgbs = np.append(rgbs, rgb[None, ...], axis=0) - errors = np.append(errors, error[None, ...], axis=0) + xyzs[count] = xyz + rgbs[count] = rgb + errors[count] = error + count += 1 + return xyzs, rgbs, errors def read_points3D_binary(path_to_model_file): diff --git a/scene/dataset_readers.py b/scene/dataset_readers.py index 31b4bba..2a6f904 100644 --- a/scene/dataset_readers.py +++ b/scene/dataset_readers.py @@ -187,10 +187,15 @@ def readCamerasFromTransforms(path, transformsfile, white_background, extension= for idx, frame in enumerate(frames): cam_name = os.path.join(path, frame["file_path"] + extension) - matrix = np.linalg.inv(np.array(frame["transform_matrix"])) - R = -np.transpose(matrix[:3,:3]) - R[:,0] = -R[:,0] - T = -matrix[:3, 3] + # NeRF 'transform_matrix' is a camera-to-world transform + c2w = np.array(frame["transform_matrix"]) + # change from OpenGL/Blender camera axes (Y up, Z back) to COLMAP (Y down, Z forward) + c2w[:3, 1:3] *= -1 + + # get the world-to-camera transform and set R, T + w2c = np.linalg.inv(c2w) + R = np.transpose(w2c[:3,:3]) # R is stored transposed due to 'glm' in CUDA code + T = w2c[:3, 3] image_path = os.path.join(path, cam_name) image_name = Path(cam_name).stem @@ -205,8 +210,8 @@ def readCamerasFromTransforms(path, transformsfile, white_background, extension= image = Image.fromarray(np.array(arr*255.0, dtype=np.byte), "RGB") fovy = focal2fov(fov2focal(fovx, image.size[0]), image.size[1]) - FovY = fovx - FovX = fovy + FovY = fovy + FovX = fovx cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=image.size[0], height=image.size[1])) diff --git a/scene/gaussian_model.py b/scene/gaussian_model.py index cd8c2ce..632a1e8 100644 --- a/scene/gaussian_model.py +++ b/scene/gaussian_model.py @@ -22,28 +22,14 @@ from utils.graphics_utils import BasicPointCloud from utils.general_utils import strip_symmetric, build_scaling_rotation class GaussianModel: - def __init__(self, sh_degree : int): + def setup_functions(self): def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation): L = build_scaling_rotation(scaling_modifier * scaling, rotation) actual_covariance = L @ L.transpose(1, 2) symm = strip_symmetric(actual_covariance) return symm - - self.active_sh_degree = 0 - self.max_sh_degree = sh_degree - - self._xyz = torch.empty(0) - self._features_dc = torch.empty(0) - self._features_rest = torch.empty(0) - self._scaling = torch.empty(0) - self._rotation = torch.empty(0) - self._opacity = torch.empty(0) - self.max_radii2D = torch.empty(0) - self.xyz_gradient_accum = torch.empty(0) - - self.optimizer = None - + self.scaling_activation = torch.exp self.scaling_inverse_activation = torch.log @@ -54,6 +40,58 @@ class GaussianModel: self.rotation_activation = torch.nn.functional.normalize + + def __init__(self, sh_degree : int): + self.active_sh_degree = 0 + self.max_sh_degree = sh_degree + self._xyz = torch.empty(0) + self._features_dc = torch.empty(0) + self._features_rest = torch.empty(0) + self._scaling = torch.empty(0) + self._rotation = torch.empty(0) + self._opacity = torch.empty(0) + self.max_radii2D = torch.empty(0) + self.xyz_gradient_accum = torch.empty(0) + self.denom = torch.empty(0) + self.optimizer = None + self.percent_dense = 0 + self.spatial_lr_scale = 0 + self.setup_functions() + + def capture(self): + return ( + self.active_sh_degree, + self._xyz, + self._features_dc, + self._features_rest, + self._scaling, + self._rotation, + self._opacity, + self.max_radii2D, + self.xyz_gradient_accum, + self.denom, + self.optimizer.state_dict(), + self.spatial_lr_scale, + ) + + def restore(self, model_args, training_args): + (self.active_sh_degree, + self._xyz, + self._features_dc, + self._features_rest, + self._scaling, + self._rotation, + self._opacity, + self.max_radii2D, + xyz_gradient_accum, + denom, + opt_dict, + self.spatial_lr_scale) = model_args + self.training_setup(training_args) + self.xyz_gradient_accum = xyz_gradient_accum + self.denom = denom + self.optimizer.load_state_dict(opt_dict) + @property def get_scaling(self): return self.scaling_activation(self._scaling) @@ -84,7 +122,7 @@ class GaussianModel: self.active_sh_degree += 1 def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float): - self.spatial_lr_scale = 5 + 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()) features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda() @@ -114,11 +152,11 @@ class GaussianModel: self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") l = [ - {'params': [self._xyz], 'lr': training_args.position_lr_init*self.spatial_lr_scale, "name": "xyz"}, + {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"}, {'params': [self._features_dc], 'lr': training_args.feature_lr, "name": "f_dc"}, {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, "name": "f_rest"}, {'params': [self._opacity], 'lr': training_args.opacity_lr, "name": "opacity"}, - {'params': [self._scaling], 'lr': training_args.scaling_lr*self.spatial_lr_scale, "name": "scaling"}, + {'params': [self._scaling], 'lr': training_args.scaling_lr, "name": "scaling"}, {'params': [self._rotation], 'lr': training_args.rotation_lr, "name": "rotation"} ] @@ -174,8 +212,7 @@ class GaussianModel: optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, "opacity") self._opacity = optimizable_tensors["opacity"] - def load_ply(self, path, og_number_points=-1): - self.og_number_points = og_number_points + def load_ply(self, path): plydata = PlyData.read(path) xyz = np.stack((np.asarray(plydata.elements[0]["x"]), @@ -189,6 +226,7 @@ class GaussianModel: features_dc[:, 2, 0] = np.asarray(plydata.elements[0]["f_dc_2"]) extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("f_rest_")] + extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1])) assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3 features_extra = np.zeros((xyz.shape[0], len(extra_f_names))) for idx, attr_name in enumerate(extra_f_names): @@ -197,11 +235,13 @@ class GaussianModel: features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1)) scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("scale_")] + scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1])) scales = np.zeros((xyz.shape[0], len(scale_names))) for idx, attr_name in enumerate(scale_names): scales[:, idx] = np.asarray(plydata.elements[0][attr_name]) rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot")] + rot_names = sorted(rot_names, key = lambda x: int(x.split('_')[-1])) rots = np.zeros((xyz.shape[0], len(rot_names))) for idx, attr_name in enumerate(rot_names): rots[:, idx] = np.asarray(plydata.elements[0][attr_name]) diff --git a/submodules/diff-gaussian-rasterization b/submodules/diff-gaussian-rasterization index fc0cfe9..59f5f77 160000 --- a/submodules/diff-gaussian-rasterization +++ b/submodules/diff-gaussian-rasterization @@ -1 +1 @@ -Subproject commit fc0cfe904a7870245437d9bfe17f819d9260281d +Subproject commit 59f5f77e3ddbac3ed9db93ec2cfe99ed6c5d121d diff --git a/train.py b/train.py index f919db2..36faf0d 100644 --- a/train.py +++ b/train.py @@ -28,12 +28,15 @@ try: except ImportError: TENSORBOARD_FOUND = False -def training(dataset, opt, pipe, testing_iterations, saving_iterations): +def training(dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from): + first_iter = 0 tb_writer = prepare_output_and_logger(dataset) gaussians = GaussianModel(dataset.sh_degree) - scene = Scene(dataset, gaussians) 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") @@ -43,14 +46,15 @@ def training(dataset, opt, pipe, testing_iterations, saving_iterations): viewpoint_stack = None ema_loss_for_log = 0.0 - progress_bar = tqdm(range(opt.iterations), desc="Training progress") - for iteration in range(1, opt.iterations + 1): + progress_bar = tqdm(range(first_iter, opt.iterations), desc="Training progress") + first_iter += 1 + 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.do_shs_python, pipe.do_cov_python, keep_alive, scaling_modifer = network_gui.receive() + 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_modifer)["render"] net_image_bytes = memoryview((torch.clamp(net_image, min=0, max=1.0) * 255).byte().permute(1, 2, 0).contiguous().cpu().numpy()) @@ -62,6 +66,8 @@ def training(dataset, opt, pipe, testing_iterations, saving_iterations): 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() @@ -72,6 +78,8 @@ def training(dataset, opt, pipe, testing_iterations, saving_iterations): viewpoint_cam = viewpoint_stack.pop(randint(0, len(viewpoint_stack)-1)) # Render + if (iteration - 1) == debug_from: + pipe.debug = True render_pkg = render(viewpoint_cam, gaussians, pipe, background) image, viewspace_point_tensor, visibility_filter, radii = render_pkg["render"], render_pkg["viewspace_points"], render_pkg["visibility_filter"], render_pkg["radii"] @@ -92,9 +100,6 @@ def training(dataset, opt, pipe, testing_iterations, saving_iterations): if iteration == opt.iterations: progress_bar.close() - # 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]) - # Log and save training_report(tb_writer, iteration, Ll1, loss, l1_loss, iter_start.elapsed_time(iter_end), testing_iterations, scene, render, (pipe, background)) if (iteration in saving_iterations): @@ -103,6 +108,8 @@ def training(dataset, opt, pipe, testing_iterations, saving_iterations): # 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: @@ -116,7 +123,10 @@ def training(dataset, opt, pipe, testing_iterations, saving_iterations): if iteration < opt.iterations: gaussians.optimizer.step() gaussians.optimizer.zero_grad(set_to_none = True) - gaussians.update_learning_rate(iteration) + + if (iteration in checkpoint_iterations): + print("\n[ITER {}] Saving Checkpoint".format(iteration)) + torch.save((gaussians.capture(), iteration), scene.model_path + "/chkpnt" + str(iteration) + ".pth") def prepare_output_and_logger(args): if not args.model_path: @@ -154,20 +164,19 @@ def training_report(tb_writer, iteration, Ll1, loss, l1_loss, elapsed, testing_i for config in validation_configs: if config['cameras'] and len(config['cameras']) > 0: - images = torch.tensor([], device="cuda") - gts = torch.tensor([], device="cuda") + 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) - images = torch.cat((images, image.unsqueeze(0)), dim=0) - gts = torch.cat((gts, gt_image.unsqueeze(0)), dim=0) 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(images, gts) - psnr_test = psnr(images, gts).mean() + 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) @@ -186,10 +195,13 @@ if __name__ == "__main__": 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, 30_000]) parser.add_argument("--save_iterations", nargs="+", type=int, default=[7_000, 30_000]) parser.add_argument("--quiet", action="store_true") + 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) @@ -201,7 +213,7 @@ if __name__ == "__main__": # Start GUI server, configure and run training 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) + 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.")