[
  {
    "path": ".gitignore",
    "content": "*.pyc\n.vscode\noutput\nbuild\ndiff_rasterization/diff_rast.egg-info\ndiff_rasterization/dist\ntensorboard_3d\nscreenshots"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"submodules/simple-knn\"]\n\tpath = submodules/simple-knn\n\turl = https://gitlab.inria.fr/bkerbl/simple-knn.git\n[submodule \"submodules/diff-gaussian-rasterization\"]\n\tpath = submodules/diff-gaussian-rasterization\n\turl = https://github.com/graphdeco-inria/diff-gaussian-rasterization.git\n\tbranch = dr_aa\n[submodule \"SIBR_viewers\"]\n\tpath = SIBR_viewers\n\turl = https://gitlab.inria.fr/sibr/sibr_core.git\n[submodule \"submodules/fused-ssim\"]\n\tpath = submodules/fused-ssim\n\turl = https://github.com/rahul-goel/fused-ssim.git\n"
  },
  {
    "path": "LICENSE.md",
    "content": "Gaussian-Splatting License  \n===========================  \n\n**Inria** and **the Max Planck Institut for Informatik (MPII)** hold all the ownership rights on the *Software* named **gaussian-splatting**.  \nThe *Software* is in the process of being registered with the Agence pour la Protection des  \nProgrammes (APP).  \n\nThe *Software* is still being developed by the *Licensor*.  \n\n*Licensor*'s goal is to allow the research community to use, test and evaluate  \nthe *Software*.  \n\n## 1.  Definitions  \n\n*Licensee* means any person or entity that uses the *Software* and distributes  \nits *Work*.  \n\n*Licensor* means the owners of the *Software*, i.e Inria and MPII  \n\n*Software* means the original work of authorship made available under this  \nLicense ie gaussian-splatting.  \n\n*Work* means the *Software* and any additions to or derivative works of the  \n*Software* that are made available under this License.  \n\n\n## 2.  Purpose  \nThis license is intended to define the rights granted to the *Licensee* by  \nLicensors under the *Software*.  \n\n## 3.  Rights granted  \n\nFor the above reasons Licensors have decided to distribute the *Software*.  \nLicensors grant non-exclusive rights to use the *Software* for research purposes  \nto research users (both academic and industrial), free of charge, without right  \nto sublicense.. The *Software* may be used \"non-commercially\", i.e., for research  \nand/or evaluation purposes only.  \n\nSubject to the terms and conditions of this License, you are granted a  \nnon-exclusive, royalty-free, license to reproduce, prepare derivative works of,  \npublicly display, publicly perform and distribute its *Work* and any resulting  \nderivative works in any form.  \n\n## 4.  Limitations  \n\n**4.1 Redistribution.** You may reproduce or distribute the *Work* only if (a) you do  \nso under this License, (b) you include a complete copy of this License with  \nyour distribution, and (c) you retain without modification any copyright,  \npatent, trademark, or attribution notices that are present in the *Work*.  \n\n**4.2 Derivative Works.** You may specify that additional or different terms apply  \nto the use, reproduction, and distribution of your derivative works of the *Work*  \n(\"Your Terms\") only if (a) Your Terms provide that the use limitation in  \nSection 2 applies to your derivative works, and (b) you identify the specific  \nderivative works that are subject to Your Terms. Notwithstanding Your Terms,  \nthis License (including the redistribution requirements in Section 3.1) will  \ncontinue to apply to the *Work* itself.  \n\n**4.3** Any other use without of prior consent of Licensors is prohibited. Research  \nusers explicitly acknowledge having received from Licensors all information  \nallowing to appreciate the adequacy between of the *Software* and their needs and  \nto undertake all necessary precautions for its execution and use.  \n\n**4.4** The *Software* is provided both as a compiled library file and as source  \ncode. In case of using the *Software* for a publication or other results obtained  \nthrough the use of the *Software*, users are strongly encouraged to cite the  \ncorresponding publications as explained in the documentation of the *Software*.  \n\n## 5.  Disclaimer  \n\nTHE USER CANNOT USE, EXPLOIT OR DISTRIBUTE THE *SOFTWARE* FOR COMMERCIAL PURPOSES  \nWITHOUT PRIOR AND EXPLICIT CONSENT OF LICENSORS. YOU MUST CONTACT INRIA FOR ANY  \nUNAUTHORIZED USE: stip-sophia.transfert@inria.fr . ANY SUCH ACTION WILL  \nCONSTITUTE A FORGERY. THIS *SOFTWARE* IS PROVIDED \"AS IS\" WITHOUT ANY WARRANTIES  \nOF ANY NATURE AND ANY EXPRESS OR IMPLIED WARRANTIES, WITH REGARDS TO COMMERCIAL  \nUSE, PROFESSIONNAL USE, LEGAL OR NOT, OR OTHER, OR COMMERCIALISATION OR  \nADAPTATION. UNLESS EXPLICITLY PROVIDED BY LAW, IN NO EVENT, SHALL INRIA OR THE  \nAUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR  \nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE  \nGOODS OR SERVICES, LOSS OF USE, DATA, OR PROFITS OR BUSINESS INTERRUPTION)  \nHOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT  \nLIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING FROM, OUT OF OR  \nIN CONNECTION WITH THE *SOFTWARE* OR THE USE OR OTHER DEALINGS IN THE *SOFTWARE*.  \n\n## 6.  Files subject to permissive licenses\nThe contents of the file ```utils/loss_utils.py``` are based on publicly available code authored by Evan Su, which falls under the permissive MIT license. \n\nTitle: pytorch-ssim\\\nProject code: https://github.com/Po-Hsun-Su/pytorch-ssim\\\nCopyright Evan Su, 2017\\\nLicense: https://github.com/Po-Hsun-Su/pytorch-ssim/blob/master/LICENSE.txt (MIT)"
  },
  {
    "path": "README.md",
    "content": "# 3D Gaussian Splatting for Real-Time Radiance Field Rendering\nBernhard Kerbl*, Georgios Kopanas*, Thomas Leimkühler, George Drettakis (* indicates equal contribution)<br>\n| [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) |<br>\n| [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) |<br>\n![Teaser image](assets/teaser.png)\n\nThis 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. \n\n<a href=\"https://www.inria.fr/\"><img height=\"100\" src=\"assets/logo_inria.png\"> </a>\n<a href=\"https://univ-cotedazur.eu/\"><img height=\"100\" src=\"assets/logo_uca.png\"> </a>\n<a href=\"https://www.mpi-inf.mpg.de\"><img height=\"100\" src=\"assets/logo_mpi.png\"> </a> \n<a href=\"https://team.inria.fr/graphdeco/\"> <img style=\"width:100%;\" src=\"assets/logo_graphdeco.png\"></a>\n\nAbstract: *Radiance Field methods have recently revolutionized novel-view synthesis of scenes captured with multiple photos or videos. However, achieving high visual quality still requires neural networks that are costly to train and render, while recent faster methods inevitably trade off speed for quality. For unbounded and complete scenes (rather than isolated objects) and 1080p resolution rendering, no current method can achieve real-time display rates. We introduce three key elements that allow us to achieve state-of-the-art visual quality while maintaining competitive training times and importantly allow high-quality real-time (≥ 30 fps) novel-view synthesis at 1080p resolution. First, starting from sparse points produced during camera calibration, we represent the scene with 3D Gaussians that preserve desirable properties of continuous volumetric radiance fields for scene optimization while avoiding unnecessary computation in empty space; Second, we perform interleaved optimization/density control of the 3D Gaussians, notably optimizing anisotropic covariance to achieve an accurate representation of the scene; Third, we develop a fast visibility-aware rendering algorithm that supports anisotropic splatting and both accelerates training and allows realtime rendering. We demonstrate state-of-the-art visual quality and real-time rendering on several established datasets.*\n\n<section class=\"section\" id=\"BibTeX\">\n  <div class=\"container is-max-desktop content\">\n    <h2 class=\"title\">BibTeX</h2>\n    <pre><code>@Article{kerbl3Dgaussians,\n      author       = {Kerbl, Bernhard and Kopanas, Georgios and Leimk{\\\"u}hler, Thomas and Drettakis, George},\n      title        = {3D Gaussian Splatting for Real-Time Radiance Field Rendering},\n      journal      = {ACM Transactions on Graphics},\n      number       = {4},\n      volume       = {42},\n      month        = {July},\n      year         = {2023},\n      url          = {https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/}\n}</code></pre>\n  </div>\n</section>\n\n\n\n## Funding and Acknowledgments\n\nThis 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.\n\n## NEW FEATURES !\n\nWe have limited resources for maintaining and updating the code. However, we have added a few new features since the original release that are inspired by some of the excellent work many other researchers have been doing on 3DGS. We will be adding other features within the ability of our resources.\n\n**Update of October 2024**: We integrated [training speed acceleration](#training-speed-acceleration) and made it compatible with [depth regularization](#depth-regularization), [anti-aliasing](#anti-aliasing) and [exposure compensation](#exposure-compensation). We have enhanced the SIBR real time viewer by correcting bugs and adding features in the [Top View](#sibr-top-view) that allows visualization of input and user cameras.\n\n**Update of Spring 2024**:\nOrange Labs has kindly added [OpenXR support](#openxr-support) for VR viewing. \n\n## Step-by-step Tutorial\n\nJonathan 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).\n\n## Colab\n\nUser [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).\n\n## Cloning the Repository\n\nThe repository contains submodules, thus please check it out with \n```shell\n# SSH\ngit clone git@github.com:graphdeco-inria/gaussian-splatting.git --recursive\n```\nor\n```shell\n# HTTPS\ngit clone https://github.com/graphdeco-inria/gaussian-splatting --recursive\n```\n\n## Overview\n\nThe codebase has 4 main components:\n- A PyTorch-based optimizer to produce a 3D Gaussian model from SfM inputs\n- A network viewer that allows to connect to and visualize the optimization process\n- An OpenGL-based real-time viewer to render trained models in real-time.\n- A script to help you turn your own images into optimization-ready SfM data sets\n\nThe components have different requirements w.r.t. both hardware and software. They have been tested on Windows 10 and Ubuntu Linux 22.04. Instructions for setting up and running each of them are found in the sections below.\n\n\n\n\n## Optimizer\n\nThe optimizer uses PyTorch and CUDA extensions in a Python environment to produce trained models. \n\n### Hardware Requirements\n\n- CUDA-ready GPU with Compute Capability 7.0+\n- 24 GB VRAM (to train to paper evaluation quality)\n- Please see FAQ for smaller VRAM configurations\n\n### Software Requirements\n- Conda (recommended for easy setup)\n- C++ Compiler for PyTorch extensions (we used Visual Studio 2019 for Windows)\n- CUDA SDK 11 for PyTorch extensions, install *after* Visual Studio (we used 11.8, **known issues with 11.6**)\n- C++ Compiler and CUDA SDK must be compatible\n\n### Setup\n\n#### Local Setup\n\nOur default, provided install method is based on Conda package and environment management:\n```shell\nSET DISTUTILS_USE_SDK=1 # Windows only\nconda env create --file environment.yml\nconda activate gaussian_splatting\n```\nPlease note that this process assumes that you have CUDA SDK **11** installed, not **12**. For modifications, see below.\n\nTip: 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:\n\n```shell\nconda config --add pkgs_dirs <Drive>/<pkg_path>\nconda env create --file environment.yml --prefix <Drive>/<env_path>/gaussian_splatting\nconda activate <Drive>/<env_path>/gaussian_splatting\n```\n\n#### Modifications\n\nIf 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.\n\n#### Known Issues\n\nSome 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.\n\n### Running\n\nTo run the optimizer, simply use\n\n```shell\npython train.py -s <path to COLMAP or NeRF Synthetic dataset>\n```\n\n<details>\n<summary><span style=\"font-weight: bold;\">Command Line Arguments for train.py</span></summary>\n\n  #### --source_path / -s\n  Path to the source directory containing a COLMAP or Synthetic NeRF data set.\n  #### --model_path / -m \n  Path where the trained model should be stored (```output/<random>``` by default).\n  #### --images / -i\n  Alternative subdirectory for COLMAP images (```images``` by default).\n  #### --eval\n  Add this flag to use a MipNeRF360-style training/test split for evaluation.\n  #### --resolution / -r\n  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.**\n  #### --data_device\n  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).\n  #### --white_background / -w\n  Add this flag to use white background instead of black (default), e.g., for evaluation of NeRF Synthetic dataset.\n  #### --sh_degree\n  Order of spherical harmonics to be used (no larger than 3). ```3``` by default.\n  #### --convert_SHs_python\n  Flag to make pipeline compute forward and backward of SHs with PyTorch instead of ours.\n  #### --convert_cov3D_python\n  Flag to make pipeline compute forward and backward of the 3D covariance with PyTorch instead of ours.\n  #### --debug\n  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.\n  #### --debug_from\n  Debugging is **slow**. You may specify an iteration (starting from 0) after which the above debugging becomes active.\n  #### --iterations\n  Number of total iterations to train for, ```30_000``` by default.\n  #### --ip\n  IP to start GUI server on, ```127.0.0.1``` by default.\n  #### --port \n  Port to use for GUI server, ```6009``` by default.\n  #### --test_iterations\n  Space-separated iterations at which the training script computes L1 and PSNR over test set, ```7000 30000``` by default.\n  #### --save_iterations\n  Space-separated iterations at which the training script saves the Gaussian model, ```7000 30000 <iterations>``` by default.\n  #### --checkpoint_iterations\n  Space-separated iterations at which to store a checkpoint for continuing later, saved in the model directory.\n  #### --start_checkpoint\n  Path to a saved checkpoint to continue training from.\n  #### --quiet \n  Flag to omit any text written to standard out pipe. \n  #### --feature_lr\n  Spherical harmonics features learning rate, ```0.0025``` by default.\n  #### --opacity_lr\n  Opacity learning rate, ```0.05``` by default.\n  #### --scaling_lr\n  Scaling learning rate, ```0.005``` by default.\n  #### --rotation_lr\n  Rotation learning rate, ```0.001``` by default.\n  #### --position_lr_max_steps\n  Number of steps (from 0) where position learning rate goes from ```initial``` to ```final```. ```30_000``` by default.\n  #### --position_lr_init\n  Initial 3D position learning rate, ```0.00016``` by default.\n  #### --position_lr_final\n  Final 3D position learning rate, ```0.0000016``` by default.\n  #### --position_lr_delay_mult\n  Position learning rate multiplier (cf. Plenoxels), ```0.01``` by default. \n  #### --densify_from_iter\n  Iteration where densification starts, ```500``` by default. \n  #### --densify_until_iter\n  Iteration where densification stops, ```15_000``` by default.\n  #### --densify_grad_threshold\n  Limit that decides if points should be densified based on 2D position gradient, ```0.0002``` by default.\n  #### --densification_interval\n  How frequently to densify, ```100``` (every 100 iterations) by default.\n  #### --opacity_reset_interval\n  How frequently to reset opacity, ```3_000``` by default. \n  #### --lambda_dssim\n  Influence of SSIM on total loss from 0 to 1, ```0.2``` by default. \n  #### --percent_dense\n  Percentage of scene extent (0--1) a point must exceed to be forcibly densified, ```0.01``` by default.\n\n</details>\n<br>\n\nNote 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```.\n\nThe 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).\n\n### Evaluation\nBy 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:\n```shell\npython train.py -s <path to COLMAP or NeRF Synthetic dataset> --eval # Train with train/test split\npython render.py -m <path to trained model> # Generate renderings\npython metrics.py -m <path to trained model> # Compute error metrics on renderings\n```\n\nIf you want to evaluate our [pre-trained models](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/datasets/pretrained/models.zip), you will have to download the corresponding source data sets and indicate their location to ```render.py``` with an additional ```--source_path/-s``` flag. Note: The pre-trained models were created with the release codebase. This code base has been cleaned up and includes bugfixes, hence the metrics you get from evaluating them will differ from those in the paper.\n```shell\npython render.py -m <path to pre-trained model> -s <path to COLMAP dataset>\npython metrics.py -m <path to pre-trained model>\n```\n\n<details>\n<summary><span style=\"font-weight: bold;\">Command Line Arguments for render.py</span></summary>\n\n  #### --model_path / -m \n  Path to the trained model directory you want to create renderings for.\n  #### --skip_train\n  Flag to skip rendering the training set.\n  #### --skip_test\n  Flag to skip rendering the test set.\n  #### --quiet \n  Flag to omit any text written to standard out pipe. \n\n  **The below parameters will be read automatically from the model path, based on what was used for training. However, you may override them by providing them explicitly on the command line.** \n\n  #### --source_path / -s\n  Path to the source directory containing a COLMAP or Synthetic NeRF data set.\n  #### --images / -i\n  Alternative subdirectory for COLMAP images (```images``` by default).\n  #### --eval\n  Add this flag to use a MipNeRF360-style training/test split for evaluation.\n  #### --resolution / -r\n  Changes the 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. ```1``` by default.\n  #### --white_background / -w\n  Add this flag to use white background instead of black (default), e.g., for evaluation of NeRF Synthetic dataset.\n  #### --convert_SHs_python\n  Flag to make pipeline render with computed SHs from PyTorch instead of ours.\n  #### --convert_cov3D_python\n  Flag to make pipeline render with computed 3D covariance from PyTorch instead of ours.\n\n</details>\n\n<details>\n<summary><span style=\"font-weight: bold;\">Command Line Arguments for metrics.py</span></summary>\n\n  #### --model_paths / -m \n  Space-separated list of model paths for which metrics should be computed.\n</details>\n<br>\n\nWe further provide the ```full_eval.py``` script. This script specifies the routine used in our evaluation and demonstrates the use of some additional parameters, e.g., ```--images (-i)``` to define alternative image directories within COLMAP data sets. If you have downloaded and extracted all the training data, you can run it like this:\n```shell\npython full_eval.py -m360 <mipnerf360 folder> -tat <tanks and temples folder> -db <deep blending folder>\n```\nIn the current version, this process takes about 7h on our reference machine containing an A6000. If you want to do the full evaluation on our pre-trained models, you can specify their download location and skip training. \n```shell\npython full_eval.py -o <directory with pretrained models> --skip_training -m360 <mipnerf360 folder> -tat <tanks and temples folder> -db <deep blending folder>\n```\n\nIf you want to compute the metrics on our paper's [evaluation images](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/evaluation/images.zip), you can also skip rendering. In this case it is not necessary to provide the source datasets. You can compute metrics for multiple image sets at a time. \n```shell\npython full_eval.py -m <directory with evaluation images>/garden ... --skip_training --skip_rendering\n```\n\n<details>\n<summary><span style=\"font-weight: bold;\">Command Line Arguments for full_eval.py</span></summary>\n  \n  #### --skip_training\n  Flag to skip training stage.\n  #### --skip_rendering\n  Flag to skip rendering stage.\n  #### --skip_metrics\n  Flag to skip metrics calculation stage.\n  #### --output_path\n  Directory to put renderings and results in, ```./eval``` by default, set to pre-trained model location if evaluating them.\n  #### --mipnerf360 / -m360\n  Path to MipNeRF360 source datasets, required if training or rendering.\n  #### --tanksandtemples / -tat\n  Path to Tanks&Temples source datasets, required if training or rendering.\n  #### --deepblending / -db\n  Path to Deep Blending source datasets, required if training or rendering.\n</details>\n<br>\n\n## Interactive Viewers\nWe 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.\n\n### Hardware Requirements\n- OpenGL 4.5-ready GPU and drivers (or latest MESA software)\n- 4 GB VRAM recommended\n- CUDA-ready GPU with Compute Capability 7.0+ (only for Real-Time Viewer)\n\n### Software Requirements\n- Visual Studio or g++, **not Clang** (we used Visual Studio 2019 for Windows)\n- CUDA SDK 11, install *after* Visual Studio (we used 11.8)\n- CMake (recent version, we used 3.24)\n- 7zip (only on Windows)\n\n### Pre-built Windows Binaries\nWe provide pre-built binaries for Windows [here](https://repo-sam.inria.fr/fungraph/3d-gaussian-splatting/binaries/viewers.zip). We recommend using them on Windows for an efficient setup, since the building of SIBR involves several external dependencies that must be downloaded and compiled on-the-fly.\n\n### Installation from Source\nIf you cloned with submodules (e.g., using ```--recursive```), the source code for the viewers is found in ```SIBR_viewers```. The network viewer runs within the SIBR framework for Image-based Rendering applications.\n\n#### Windows\nCMake should take care of your dependencies.\n```shell\ncd SIBR_viewers\ncmake -Bbuild .\ncmake --build build --target install --config RelWithDebInfo\n```\nYou may specify a different configuration, e.g. ```Debug``` if you need more control during development.\n\n#### Ubuntu 22.04\nYou will need to install a few dependencies before running the project setup.\n```shell\n# Dependencies\nsudo 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\n# Project setup\ncd SIBR_viewers\ncmake -Bbuild . -DCMAKE_BUILD_TYPE=Release # add -G Ninja to build faster\ncmake --build build -j24 --target install\n``` \n\n#### Ubuntu 20.04\nBackwards compatibility with Focal Fossa is not fully tested, but building SIBR with CMake should still work after invoking\n```shell\ngit checkout fossa_compatibility\n```\n\n### Navigation in SIBR Viewers\nThe SIBR interface provides several methods of navigating the scene. By default, you will be started with an FPS navigator, which you can control with ```W, A, S, D, Q, E``` for camera translation and ```I, K, J, L, U, O``` for rotation. Alternatively, you may want to use a Trackball-style navigator (select from the floating menu). You can also snap to a camera from the data set with the ```Snap to``` button or find the closest camera with ```Snap to closest```. The floating menues also allow you to change the navigation speed. You can use the ```Scaling Modifier``` to control the size of the displayed Gaussians, or show the initial point cloud.\n\n### Running the Network Viewer\n\n\n\nhttps://github.com/graphdeco-inria/gaussian-splatting/assets/40643808/90a2e4d3-cf2e-4633-b35f-bfe284e28ff7\n\n\n\nAfter extracting or installing the viewers, you may run the compiled ```SIBR_remoteGaussian_app[_config]``` app in ```<SIBR install dir>/bin```, e.g.: \n```shell\n./<SIBR install dir>/bin/SIBR_remoteGaussian_app\n```\nThe network viewer allows you to connect to a running training process on the same or a different machine. If you are training on the same machine and OS, no command line parameters should be required: the optimizer communicates the location of the training data to the network viewer. By default, optimizer and network viewer will try to establish a connection on **localhost** on port **6009**. You can change this behavior by providing matching ```--ip``` and ```--port``` parameters to both the optimizer and the network viewer. If for some reason the path used by the optimizer to find the training data is not reachable by the network viewer (e.g., due to them running on different (virtual) machines), you may specify an override location to the viewer by using ```-s <source path>```. \n\n<details>\n<summary><span style=\"font-weight: bold;\">Primary Command Line Arguments for Network Viewer</span></summary>\n\n  #### --path / -s\n  Argument to override model's path to source dataset.\n  #### --ip\n  IP to use for connection to a running training script.\n  #### --port\n  Port to use for connection to a running training script. \n  #### --rendering-size \n  Takes two space separated numbers to define the resolution at which network rendering occurs, ```1200``` width by default.\n  Note that to enforce an aspect that differs from the input images, you need ```--force-aspect-ratio``` too.\n  #### --load_images\n  Flag to load source dataset images to be displayed in the top view for each camera.\n</details>\n<br>\n\n### Running the Real-Time Viewer\n\n\n\n\nhttps://github.com/graphdeco-inria/gaussian-splatting/assets/40643808/0940547f-1d82-4c2f-a616-44eabbf0f816\n\n\n\n\nAfter extracting or installing the viewers, you may run the compiled ```SIBR_gaussianViewer_app[_config]``` app in ```<SIBR install dir>/bin```, e.g.: \n```shell\n./<SIBR install dir>/bin/SIBR_gaussianViewer_app -m <path to trained model>\n```\n\nIt should suffice to provide the ```-m``` parameter pointing to a trained model directory. Alternatively, you can specify an override location for training input data using ```-s```. To use a specific resolution other than the auto-chosen one, specify ```--rendering-size <width> <height>```. Combine it with ```--force-aspect-ratio``` if you want the exact resolution and don't mind image distortion. \n\n**To unlock the full frame rate, please disable V-Sync on your machine and also in the application (Menu &rarr; Display). In a multi-GPU system (e.g., laptop) your OpenGL/Display GPU should be the same as your CUDA GPU (e.g., by setting the application's GPU preference on Windows, see below) for maximum performance.**\n\n![Teaser image](assets/select.png)\n\nIn 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.\nSIBR 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.\n\n<details>\n<summary><span style=\"font-weight: bold;\">Primary Command Line Arguments for Real-Time Viewer</span></summary>\n\n  #### --model-path / -m\n  Path to trained model.\n  #### --iteration\n  Specifies which of state to load if multiple are available. Defaults to latest available iteration.\n  #### --path / -s\n  Argument to override model's path to source dataset.\n  #### --rendering-size \n  Takes two space separated numbers to define the resolution at which real-time rendering occurs, ```1200``` width by default. Note that to enforce an aspect that differs from the input images, you need ```--force-aspect-ratio``` too.\n  #### --load_images\n  Flag to load source dataset images to be displayed in the top view for each camera.\n  #### --device\n  Index of CUDA device to use for rasterization if multiple are available, ```0``` by default.\n  #### --no_interop\n  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).\n</details>\n<br>\n\n## Processing your own Scenes\n\nOur COLMAP loaders expect the following dataset structure in the source path location:\n\n```\n<location>\n|---images\n|   |---<image 0>\n|   |---<image 1>\n|   |---...\n|---sparse\n    |---0\n        |---cameras.bin\n        |---images.bin\n        |---points3D.bin\n```\n\nFor rasterization, the camera models must be either a SIMPLE_PINHOLE or PINHOLE camera. We provide a converter script ```convert.py```, to extract undistorted images and SfM information from input images. Optionally, you can use ImageMagick to resize the undistorted images. This rescaling is similar to MipNeRF360, i.e., it creates images with 1/2, 1/4 and 1/8 the original resolution in corresponding folders. To use them, please first install a recent version of COLMAP (ideally CUDA-powered) and ImageMagick. Put the images you want to use in a directory ```<location>/input```.\n```\n<location>\n|---input\n    |---<image 0>\n    |---<image 1>\n    |---...\n```\n If you have COLMAP and ImageMagick on your system path, you can simply run \n```shell\npython convert.py -s <location> [--resize] #If not resizing, ImageMagick is not needed\n```\nAlternatively, you can use the optional parameters ```--colmap_executable``` and ```--magick_executable``` to point to the respective paths. Please note that on Windows, the executable should point to the COLMAP ```.bat``` file that takes care of setting the execution environment. Once done, ```<location>``` will contain the expected COLMAP data set structure with undistorted, resized input images, in addition to your original images and some temporary (distorted) data in the directory ```distorted```.\n\nIf you have your own COLMAP dataset without undistortion (e.g., using ```OPENCV``` camera), you can try to just run the last part of the script: Put the images in ```input``` and the COLMAP info in a subdirectory ```distorted```:\n```\n<location>\n|---input\n|   |---<image 0>\n|   |---<image 1>\n|   |---...\n|---distorted\n    |---database.db\n    |---sparse\n        |---0\n            |---...\n```\nThen run \n```shell\npython convert.py -s <location> --skip_matching [--resize] #If not resizing, ImageMagick is not needed\n```\n\n<details>\n<summary><span style=\"font-weight: bold;\">Command Line Arguments for convert.py</span></summary>\n\n  #### --no_gpu\n  Flag to avoid using GPU in COLMAP.\n  #### --skip_matching\n  Flag to indicate that COLMAP info is available for images.\n  #### --source_path / -s\n  Location of the inputs.\n  #### --camera \n  Which camera model to use for the early matching steps, ```OPENCV``` by default.\n  #### --resize\n  Flag for creating resized versions of input images.\n  #### --colmap_executable\n  Path to the COLMAP executable (```.bat``` on Windows).\n  #### --magick_executable\n  Path to the ImageMagick executable.\n</details>\n<br>\n\n### Training speed acceleration\n\nWe integrated the drop-in replacements from [Taming-3dgs](https://humansensinglab.github.io/taming-3dgs/)<sup>1</sup> with [fused ssim](https://github.com/rahul-goel/fused-ssim/tree/main) into the original codebase to speed up training times. Once installed, the accelerated rasterizer delivers a **$\\times$ 1.6 training time speedup** using `--optimizer_type default` and a **$\\times$ 2.7 training time speedup** using `--optimizer_type sparse_adam`.\n\nTo get faster training times you must first install the accelerated rasterizer to your environment:\n\n```bash\npip uninstall diff-gaussian-rasterization -y\ncd submodules/diff-gaussian-rasterization\nrm -r build\ngit checkout 3dgs_accel\npip install .\n```\n\nThen you can add the following parameter to use the sparse adam optimizer when running `train.py`:\n\n```bash\n--optimizer_type sparse_adam\n```\n\n*Note that this custom rasterizer has a different behaviour than the original version, for more details on training times please see [stats for training times](results.md/#training-times-comparisons)*.\n\n*1. Mallick and Goel, et al. ‘Taming 3DGS: High-Quality Radiance Fields with Limited Resources’. SIGGRAPH Asia 2024 Conference Papers, 2024, https://doi.org/10.1145/3680528.3687694, [github](https://github.com/humansensinglab/taming-3dgs)*\n\n\n### Depth regularization\n\nTo have better reconstructed scenes we use depth maps as priors during optimization with each input images. It works best on untextured parts ex: roads and can remove floaters. Several papers have used similar ideas to improve various aspects of 3DGS; (e.g. [DepthRegularizedGS](https://robot0321.github.io/DepthRegGS/index.html), [SparseGS](https://formycat.github.io/SparseGS-Real-Time-360-Sparse-View-Synthesis-using-Gaussian-Splatting/), [DNGaussian](https://fictionarry.github.io/DNGaussian/)). The depth regularization we integrated is that used in our [Hierarchical 3DGS](https://repo-sam.inria.fr/fungraph/hierarchical-3d-gaussians/) paper, but applied to the original 3DGS; for some scenes (e.g., the DeepBlending scenes) it improves quality significantly; for others it either makes a small difference or can even be worse. For example results showing the potential benefit and statistics on quality please see here: [Stats for depth regularization](results.md).\n\nWhen training on a synthetic dataset, depth maps can be produced and they do not require further processing to be used in our method.\n\nFor real world datasets depth maps should be generated for each input images, to generate them please do the following:\n1. Clone [Depth Anything v2](https://github.com/DepthAnything/Depth-Anything-V2?tab=readme-ov-file#usage):\n    ```\n    git clone https://github.com/DepthAnything/Depth-Anything-V2.git\n    ```\n2. Download weights from [Depth-Anything-V2-Large](https://huggingface.co/depth-anything/Depth-Anything-V2-Large/resolve/main/depth_anything_v2_vitl.pth?download=true) and place it under `Depth-Anything-V2/checkpoints/`\n3. Generate depth maps:\n   ```\n   python Depth-Anything-V2/run.py --encoder vitl --pred-only --grayscale --img-path <path to input images> --outdir <output path>\n   ```\n5. Generate a `depth_params.json` file using:\n    ```\n    python utils/make_depth_scale.py --base_dir <path to colmap> --depths_dir <path to generated depths>\n    ```\n\nA new parameter should be set when training if you want to use depth regularization `-d <path to depth maps>`.\n\n### Exposure compensation\nTo compensate for exposure changes in the different input images we optimize an affine transformation for each image just as in [Hierarchical 3dgs](https://repo-sam.inria.fr/fungraph/hierarchical-3d-gaussians/).  \n\nThis can greatly improve reconstruction results for \"in the wild\" captures, e.g., with a smartphone when the exposure setting of the camera is not fixed. For example results showing the potential benefit and statistics on quality please see here: [Stats for exposure compensation](results.md).\n\nAdd the following parameters to enable it:\n```\n--exposure_lr_init 0.001 --exposure_lr_final 0.0001 --exposure_lr_delay_steps 5000 --exposure_lr_delay_mult 0.001 --train_test_exp\n```\nAgain, other excellent papers have used similar ideas e.g. [NeRF-W](https://nerf-w.github.io/), [URF](https://urban-radiance-fields.github.io/).\n\n### Anti-aliasing\nWe added the EWA Filter from [Mip Splatting](https://niujinshuchong.github.io/mip-splatting/) in our codebase to remove aliasing. It is disabled by default but you can enable it by adding `--antialiasing` when training on a scene using `train.py` or rendering using `render.py`. Antialiasing can be toggled in the SIBR viewer, it is disabled by default but you should enable it when viewing a scene trained using `--antialiasing`.\n![aa](/assets/aa_onoff.gif)\n*this scene was trained using `--antialiasing`*.\n\n### SIBR: Top view\n> `Views > Top view`\n\nThe `Top view` renders the SfM point cloud in another view with the corresponding input cameras and the `Point view` user camera. This allows visualization of how far the viewer is from the input cameras for example.\n\nIt is a 3D view so the user can navigate through it just as in the `Point view` (modes available: FPS, trackball, orbit).\n<!-- _gif showing the top view, showing it is realtime_ -->\n<!-- ![topViewOpen_1.gif](../assets/topViewOpen_1_1709560483017_0.gif) -->\n![top view open](assets/top_view_open.gif)\n\nOptions are available to customize this view, meshes can be disabled/enabled and their scales can be modified. \n<!-- _gif showing different options_ -->\n<!-- ![topViewOptions.gif](../assets/topViewOptions_1709560615266_0.gif) -->\n![top view options](assets/top_view_options.gif)\nA useful additional functionality is to move to the position of an input image, and progressively fade out to the SfM point view in that position (e.g., to verify camera alignment). Views from input cameras can be displayed in the `Top view` (*note that `--images-path` must be set in the command line*). One can snap the `Top view` camera to the closest input camera from the user camera in the `Point view` by clicking `Top view settings > Cameras > Snap to closest`. \n<!-- _gif showing for a snapped camera the ground truth image with alpha_ -->\n<!-- ![topViewImageAlpha.gif](../assets/topViewImageAlpha_1709560852268_0.gif) -->\n![top view image alpha](assets/top_view_image_alpha.gif)\n\n### OpenXR support\n\nOpenXR is supported in the branch `gaussian_code_release_openxr` \nWithin that branch, you can find documentation for VR support [here](https://gitlab.inria.fr/sibr/sibr_core/-/tree/gaussian_code_release_openxr?ref_type=heads).\n\n\n## FAQ\n- *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)\n\n\n- *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).\n\n| ![Default learning rate result](assets/worse.png \"title-1\") <!-- --> | <!-- --> ![Reduced learning rate result](assets/better.png \"title-2\") |\n| --- | --- |\n\n- *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.\n\n- *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);\n```C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.29.30133\\bin\\Hostx64\\x64```\nThen make sure you start a new conda prompt and cd to your repo location and try this;\n```\nconda activate gaussian_splatting\ncd <dir_to_repo>/gaussian-splatting\npip install submodules\\diff-gaussian-rasterization\npip install submodules\\simple-knn\n```\n\n- *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.\n\n- *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.\n\n- *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!\n\n\n- *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```).\n\n- *Wait, but ```<insert feature>``` isn't optimized and could be much better?* There are several parts we didn't even have time to think about improving (yet). The performance you get with this prototype is probably a rather slow baseline for what is physically possible.\n\n- *Something is broken, how did this happen?* We tried hard to provide a solid and comprehensible basis to make use of the paper's method. We have refactored the code quite a bit, but we have limited capacity to test all possible usage scenarios. Thus, if part of the website, the code or the performance is lacking, please create an issue. If we find the time, we will do our best to address it.\n"
  },
  {
    "path": "arguments/__init__.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nfrom argparse import ArgumentParser, Namespace\nimport sys\nimport os\n\nclass GroupParams:\n    pass\n\nclass ParamGroup:\n    def __init__(self, parser: ArgumentParser, name : str, fill_none = False):\n        group = parser.add_argument_group(name)\n        for key, value in vars(self).items():\n            shorthand = False\n            if key.startswith(\"_\"):\n                shorthand = True\n                key = key[1:]\n            t = type(value)\n            value = value if not fill_none else None \n            if shorthand:\n                if t == bool:\n                    group.add_argument(\"--\" + key, (\"-\" + key[0:1]), default=value, action=\"store_true\")\n                else:\n                    group.add_argument(\"--\" + key, (\"-\" + key[0:1]), default=value, type=t)\n            else:\n                if t == bool:\n                    group.add_argument(\"--\" + key, default=value, action=\"store_true\")\n                else:\n                    group.add_argument(\"--\" + key, default=value, type=t)\n\n    def extract(self, args):\n        group = GroupParams()\n        for arg in vars(args).items():\n            if arg[0] in vars(self) or (\"_\" + arg[0]) in vars(self):\n                setattr(group, arg[0], arg[1])\n        return group\n\nclass ModelParams(ParamGroup): \n    def __init__(self, parser, sentinel=False):\n        self.sh_degree = 3\n        self._source_path = \"\"\n        self._model_path = \"\"\n        self._images = \"images\"\n        self._depths = \"\"\n        self._resolution = -1\n        self._white_background = False\n        self.train_test_exp = False\n        self.data_device = \"cuda\"\n        self.eval = False\n        super().__init__(parser, \"Loading Parameters\", sentinel)\n\n    def extract(self, args):\n        g = super().extract(args)\n        g.source_path = os.path.abspath(g.source_path)\n        return g\n\nclass PipelineParams(ParamGroup):\n    def __init__(self, parser):\n        self.convert_SHs_python = False\n        self.compute_cov3D_python = False\n        self.debug = False\n        self.antialiasing = False\n        super().__init__(parser, \"Pipeline Parameters\")\n\nclass OptimizationParams(ParamGroup):\n    def __init__(self, parser):\n        self.iterations = 30_000\n        self.position_lr_init = 0.00016\n        self.position_lr_final = 0.0000016\n        self.position_lr_delay_mult = 0.01\n        self.position_lr_max_steps = 30_000\n        self.feature_lr = 0.0025\n        self.opacity_lr = 0.025\n        self.scaling_lr = 0.005\n        self.rotation_lr = 0.001\n        self.exposure_lr_init = 0.01\n        self.exposure_lr_final = 0.001\n        self.exposure_lr_delay_steps = 0\n        self.exposure_lr_delay_mult = 0.0\n        self.percent_dense = 0.01\n        self.lambda_dssim = 0.2\n        self.densification_interval = 100\n        self.opacity_reset_interval = 3000\n        self.densify_from_iter = 500\n        self.densify_until_iter = 15_000\n        self.densify_grad_threshold = 0.0002\n        self.depth_l1_weight_init = 1.0\n        self.depth_l1_weight_final = 0.01\n        self.random_background = False\n        self.optimizer_type = \"default\"\n        super().__init__(parser, \"Optimization Parameters\")\n\ndef get_combined_args(parser : ArgumentParser):\n    cmdlne_string = sys.argv[1:]\n    cfgfile_string = \"Namespace()\"\n    args_cmdline = parser.parse_args(cmdlne_string)\n\n    try:\n        cfgfilepath = os.path.join(args_cmdline.model_path, \"cfg_args\")\n        print(\"Looking for config file in\", cfgfilepath)\n        with open(cfgfilepath) as cfg_file:\n            print(\"Config file found: {}\".format(cfgfilepath))\n            cfgfile_string = cfg_file.read()\n    except TypeError:\n        print(\"Config file not found at\")\n        pass\n    args_cfgfile = eval(cfgfile_string)\n\n    merged_dict = vars(args_cfgfile).copy()\n    for k,v in vars(args_cmdline).items():\n        if v != None:\n            merged_dict[k] = v\n    return Namespace(**merged_dict)\n"
  },
  {
    "path": "convert.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use\n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport os\nimport logging\nfrom argparse import ArgumentParser\nimport shutil\n\n# This Python script is based on the shell converter script provided in the MipNerF 360 repository.\nparser = ArgumentParser(\"Colmap converter\")\nparser.add_argument(\"--no_gpu\", action='store_true')\nparser.add_argument(\"--skip_matching\", action='store_true')\nparser.add_argument(\"--source_path\", \"-s\", required=True, type=str)\nparser.add_argument(\"--camera\", default=\"OPENCV\", type=str)\nparser.add_argument(\"--colmap_executable\", default=\"\", type=str)\nparser.add_argument(\"--resize\", action=\"store_true\")\nparser.add_argument(\"--magick_executable\", default=\"\", type=str)\nargs = parser.parse_args()\ncolmap_command = '\"{}\"'.format(args.colmap_executable) if len(args.colmap_executable) > 0 else \"colmap\"\nmagick_command = '\"{}\"'.format(args.magick_executable) if len(args.magick_executable) > 0 else \"magick\"\nuse_gpu = 1 if not args.no_gpu else 0\n\nif not args.skip_matching:\n    os.makedirs(args.source_path + \"/distorted/sparse\", exist_ok=True)\n\n    ## Feature extraction\n    feat_extracton_cmd = colmap_command + \" feature_extractor \"\\\n        \"--database_path \" + args.source_path + \"/distorted/database.db \\\n        --image_path \" + args.source_path + \"/input \\\n        --ImageReader.single_camera 1 \\\n        --ImageReader.camera_model \" + args.camera + \" \\\n        --SiftExtraction.use_gpu \" + str(use_gpu)\n    exit_code = os.system(feat_extracton_cmd)\n    if exit_code != 0:\n        logging.error(f\"Feature extraction failed with code {exit_code}. Exiting.\")\n        exit(exit_code)\n\n    ## Feature matching\n    feat_matching_cmd = colmap_command + \" exhaustive_matcher \\\n        --database_path \" + args.source_path + \"/distorted/database.db \\\n        --SiftMatching.use_gpu \" + str(use_gpu)\n    exit_code = os.system(feat_matching_cmd)\n    if exit_code != 0:\n        logging.error(f\"Feature matching failed with code {exit_code}. Exiting.\")\n        exit(exit_code)\n\n    ### Bundle adjustment\n    # The default Mapper tolerance is unnecessarily large,\n    # decreasing it speeds up bundle adjustment steps.\n    mapper_cmd = (colmap_command + \" mapper \\\n        --database_path \" + args.source_path + \"/distorted/database.db \\\n        --image_path \"  + args.source_path + \"/input \\\n        --output_path \"  + args.source_path + \"/distorted/sparse \\\n        --Mapper.ba_global_function_tolerance=0.000001\")\n    exit_code = os.system(mapper_cmd)\n    if exit_code != 0:\n        logging.error(f\"Mapper failed with code {exit_code}. Exiting.\")\n        exit(exit_code)\n\n### Image undistortion\n## We need to undistort our images into ideal pinhole intrinsics.\nimg_undist_cmd = (colmap_command + \" image_undistorter \\\n    --image_path \" + args.source_path + \"/input \\\n    --input_path \" + args.source_path + \"/distorted/sparse/0 \\\n    --output_path \" + args.source_path + \"\\\n    --output_type COLMAP\")\nexit_code = os.system(img_undist_cmd)\nif exit_code != 0:\n    logging.error(f\"Mapper failed with code {exit_code}. Exiting.\")\n    exit(exit_code)\n\nfiles = os.listdir(args.source_path + \"/sparse\")\nos.makedirs(args.source_path + \"/sparse/0\", exist_ok=True)\n# Copy each file from the source directory to the destination directory\nfor file in files:\n    if file == '0':\n        continue\n    source_file = os.path.join(args.source_path, \"sparse\", file)\n    destination_file = os.path.join(args.source_path, \"sparse\", \"0\", file)\n    shutil.move(source_file, destination_file)\n\nif(args.resize):\n    print(\"Copying and resizing...\")\n\n    # Resize images.\n    os.makedirs(args.source_path + \"/images_2\", exist_ok=True)\n    os.makedirs(args.source_path + \"/images_4\", exist_ok=True)\n    os.makedirs(args.source_path + \"/images_8\", exist_ok=True)\n    # Get the list of files in the source directory\n    files = os.listdir(args.source_path + \"/images\")\n    # Copy each file from the source directory to the destination directory\n    for file in files:\n        source_file = os.path.join(args.source_path, \"images\", file)\n\n        destination_file = os.path.join(args.source_path, \"images_2\", file)\n        shutil.copy2(source_file, destination_file)\n        exit_code = os.system(magick_command + \" mogrify -resize 50% \" + destination_file)\n        if exit_code != 0:\n            logging.error(f\"50% resize failed with code {exit_code}. Exiting.\")\n            exit(exit_code)\n\n        destination_file = os.path.join(args.source_path, \"images_4\", file)\n        shutil.copy2(source_file, destination_file)\n        exit_code = os.system(magick_command + \" mogrify -resize 25% \" + destination_file)\n        if exit_code != 0:\n            logging.error(f\"25% resize failed with code {exit_code}. Exiting.\")\n            exit(exit_code)\n\n        destination_file = os.path.join(args.source_path, \"images_8\", file)\n        shutil.copy2(source_file, destination_file)\n        exit_code = os.system(magick_command + \" mogrify -resize 12.5% \" + destination_file)\n        if exit_code != 0:\n            logging.error(f\"12.5% resize failed with code {exit_code}. Exiting.\")\n            exit(exit_code)\n\nprint(\"Done.\")\n"
  },
  {
    "path": "environment.yml",
    "content": "name: gaussian_splatting\nchannels:\n  - pytorch\n  - conda-forge\n  - defaults\ndependencies:\n  - cudatoolkit=11.6\n  - plyfile\n  - python=3.7.13\n  - pip=22.3.1\n  - pytorch=1.12.1\n  - torchaudio=0.12.1\n  - torchvision=0.13.1\n  - tqdm\n  - pip:\n    - submodules/diff-gaussian-rasterization\n    - submodules/simple-knn\n    - submodules/fused-ssim\n    - opencv-python\n    - joblib\n"
  },
  {
    "path": "full_eval.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport os\nfrom argparse import ArgumentParser\nimport time\n\nmipnerf360_outdoor_scenes = [\"bicycle\", \"flowers\", \"garden\", \"stump\", \"treehill\"]\nmipnerf360_indoor_scenes = [\"room\", \"counter\", \"kitchen\", \"bonsai\"]\ntanks_and_temples_scenes = [\"truck\", \"train\"]\ndeep_blending_scenes = [\"drjohnson\", \"playroom\"]\n\nparser = ArgumentParser(description=\"Full evaluation script parameters\")\nparser.add_argument(\"--skip_training\", action=\"store_true\")\nparser.add_argument(\"--skip_rendering\", action=\"store_true\")\nparser.add_argument(\"--skip_metrics\", action=\"store_true\")\nparser.add_argument(\"--output_path\", default=\"./eval\")\nparser.add_argument(\"--use_depth\", action=\"store_true\")\nparser.add_argument(\"--use_expcomp\", action=\"store_true\")\nparser.add_argument(\"--fast\", action=\"store_true\")\nparser.add_argument(\"--aa\", action=\"store_true\")\n\n\n\n\nargs, _ = parser.parse_known_args()\n\nall_scenes = []\nall_scenes.extend(mipnerf360_outdoor_scenes)\nall_scenes.extend(mipnerf360_indoor_scenes)\nall_scenes.extend(tanks_and_temples_scenes)\nall_scenes.extend(deep_blending_scenes)\n\nif not args.skip_training or not args.skip_rendering:\n    parser.add_argument('--mipnerf360', \"-m360\", required=True, type=str)\n    parser.add_argument(\"--tanksandtemples\", \"-tat\", required=True, type=str)\n    parser.add_argument(\"--deepblending\", \"-db\", required=True, type=str)\n    args = parser.parse_args()\nif not args.skip_training:\n    common_args = \" --disable_viewer --quiet --eval --test_iterations -1 \"\n    \n    if args.aa:\n        common_args += \" --antialiasing \"\n    if args.use_depth:\n        common_args += \" -d depths2/ \"\n\n    if args.use_expcomp:\n        common_args += \" --exposure_lr_init 0.001 --exposure_lr_final 0.0001 --exposure_lr_delay_steps 5000 --exposure_lr_delay_mult 0.001 --train_test_exp \"\n\n    if args.fast:\n        common_args += \" --optimizer_type sparse_adam \"\n\n    start_time = time.time()\n    for scene in mipnerf360_outdoor_scenes:\n        source = args.mipnerf360 + \"/\" + scene\n        os.system(\"python train.py -s \" + source + \" -i images_4 -m \" + args.output_path + \"/\" + scene + common_args)\n    for scene in mipnerf360_indoor_scenes:\n        source = args.mipnerf360 + \"/\" + scene\n        os.system(\"python train.py -s \" + source + \" -i images_2 -m \" + args.output_path + \"/\" + scene + common_args)\n    m360_timing = (time.time() - start_time)/60.0\n\n    start_time = time.time()\n    for scene in tanks_and_temples_scenes:\n        source = args.tanksandtemples + \"/\" + scene\n        os.system(\"python train.py -s \" + source + \" -m \" + args.output_path + \"/\" + scene + common_args)\n    tandt_timing = (time.time() - start_time)/60.0\n\n    start_time = time.time()\n    for scene in deep_blending_scenes:\n        source = args.deepblending + \"/\" + scene\n        os.system(\"python train.py -s \" + source + \" -m \" + args.output_path + \"/\" + scene + common_args)\n    db_timing = (time.time() - start_time)/60.0\n\nwith open(os.path.join(args.output_path,\"timing.txt\"), 'w') as file:\n    file.write(f\"m360: {m360_timing} minutes \\n tandt: {tandt_timing} minutes \\n db: {db_timing} minutes\\n\")\n\nif not args.skip_rendering:\n    all_sources = []\n    for scene in mipnerf360_outdoor_scenes:\n        all_sources.append(args.mipnerf360 + \"/\" + scene)\n    for scene in mipnerf360_indoor_scenes:\n        all_sources.append(args.mipnerf360 + \"/\" + scene)\n    for scene in tanks_and_temples_scenes:\n        all_sources.append(args.tanksandtemples + \"/\" + scene)\n    for scene in deep_blending_scenes:\n        all_sources.append(args.deepblending + \"/\" + scene)\n    \n    common_args = \" --quiet --eval --skip_train\"\n    \n    if args.aa:\n        common_args += \" --antialiasing \"\n    if args.use_expcomp:\n        common_args += \" --train_test_exp \"\n\n    for scene, source in zip(all_scenes, all_sources):\n        os.system(\"python render.py --iteration 7000 -s \" + source + \" -m \" + args.output_path + \"/\" + scene + common_args)\n        os.system(\"python render.py --iteration 30000 -s \" + source + \" -m \" + args.output_path + \"/\" + scene + common_args)\n\nif not args.skip_metrics:\n    scenes_string = \"\"\n    for scene in all_scenes:\n        scenes_string += \"\\\"\" + args.output_path + \"/\" + scene + \"\\\" \"\n\n    os.system(\"python metrics.py -m \" + scenes_string)\n"
  },
  {
    "path": "gaussian_renderer/__init__.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport torch\nimport math\nfrom diff_gaussian_rasterization import GaussianRasterizationSettings, GaussianRasterizer\nfrom scene.gaussian_model import GaussianModel\nfrom utils.sh_utils import eval_sh\n\ndef render(viewpoint_camera, pc : GaussianModel, pipe, bg_color : torch.Tensor, scaling_modifier = 1.0, separate_sh = False, override_color = None, use_trained_exp=False):\n    \"\"\"\n    Render the scene. \n    \n    Background tensor (bg_color) must be on GPU!\n    \"\"\"\n \n    # Create zero tensor. We will use it to make pytorch return gradients of the 2D (screen-space) means\n    screenspace_points = torch.zeros_like(pc.get_xyz, dtype=pc.get_xyz.dtype, requires_grad=True, device=\"cuda\") + 0\n    try:\n        screenspace_points.retain_grad()\n    except:\n        pass\n\n    # Set up rasterization configuration\n    tanfovx = math.tan(viewpoint_camera.FoVx * 0.5)\n    tanfovy = math.tan(viewpoint_camera.FoVy * 0.5)\n\n    raster_settings = GaussianRasterizationSettings(\n        image_height=int(viewpoint_camera.image_height),\n        image_width=int(viewpoint_camera.image_width),\n        tanfovx=tanfovx,\n        tanfovy=tanfovy,\n        bg=bg_color,\n        scale_modifier=scaling_modifier,\n        viewmatrix=viewpoint_camera.world_view_transform,\n        projmatrix=viewpoint_camera.full_proj_transform,\n        sh_degree=pc.active_sh_degree,\n        campos=viewpoint_camera.camera_center,\n        prefiltered=False,\n        debug=pipe.debug,\n        antialiasing=pipe.antialiasing\n    )\n\n    rasterizer = GaussianRasterizer(raster_settings=raster_settings)\n\n    means3D = pc.get_xyz\n    means2D = screenspace_points\n    opacity = pc.get_opacity\n\n    # If precomputed 3d covariance is provided, use it. If not, then it will be computed from\n    # scaling / rotation by the rasterizer.\n    scales = None\n    rotations = None\n    cov3D_precomp = None\n\n    if pipe.compute_cov3D_python:\n        cov3D_precomp = pc.get_covariance(scaling_modifier)\n    else:\n        scales = pc.get_scaling\n        rotations = pc.get_rotation\n\n    # If precomputed colors are provided, use them. Otherwise, if it is desired to precompute colors\n    # from SHs in Python, do it. If not, then SH -> RGB conversion will be done by rasterizer.\n    shs = None\n    colors_precomp = None\n    if override_color is None:\n        if pipe.convert_SHs_python:\n            shs_view = pc.get_features.transpose(1, 2).view(-1, 3, (pc.max_sh_degree+1)**2)\n            dir_pp = (pc.get_xyz - viewpoint_camera.camera_center.repeat(pc.get_features.shape[0], 1))\n            dir_pp_normalized = dir_pp/dir_pp.norm(dim=1, keepdim=True)\n            sh2rgb = eval_sh(pc.active_sh_degree, shs_view, dir_pp_normalized)\n            colors_precomp = torch.clamp_min(sh2rgb + 0.5, 0.0)\n        else:\n            if separate_sh:\n                dc, shs = pc.get_features_dc, pc.get_features_rest\n            else:\n                shs = pc.get_features\n    else:\n        colors_precomp = override_color\n\n    # Rasterize visible Gaussians to image, obtain their radii (on screen). \n    if separate_sh:\n        rendered_image, radii, depth_image = rasterizer(\n            means3D = means3D,\n            means2D = means2D,\n            dc = dc,\n            shs = shs,\n            colors_precomp = colors_precomp,\n            opacities = opacity,\n            scales = scales,\n            rotations = rotations,\n            cov3D_precomp = cov3D_precomp)\n    else:\n        rendered_image, radii, depth_image = rasterizer(\n            means3D = means3D,\n            means2D = means2D,\n            shs = shs,\n            colors_precomp = colors_precomp,\n            opacities = opacity,\n            scales = scales,\n            rotations = rotations,\n            cov3D_precomp = cov3D_precomp)\n        \n    # Apply exposure to rendered image (training only)\n    if use_trained_exp:\n        exposure = pc.get_exposure_from_name(viewpoint_camera.image_name)\n        rendered_image = torch.matmul(rendered_image.permute(1, 2, 0), exposure[:3, :3]).permute(2, 0, 1) + exposure[:3, 3,   None, None]\n\n    # Those Gaussians that were frustum culled or had a radius of 0 were not visible.\n    # They will be excluded from value updates used in the splitting criteria.\n    rendered_image = rendered_image.clamp(0, 1)\n    out = {\n        \"render\": rendered_image,\n        \"viewspace_points\": screenspace_points,\n        \"visibility_filter\" : (radii > 0).nonzero(),\n        \"radii\": radii,\n        \"depth\" : depth_image\n        }\n    \n    return out\n"
  },
  {
    "path": "gaussian_renderer/network_gui.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport torch\nimport traceback\nimport socket\nimport json\nfrom scene.cameras import MiniCam\n\nhost = \"127.0.0.1\"\nport = 6009\n\nconn = None\naddr = None\n\nlistener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ndef init(wish_host, wish_port):\n    global host, port, listener\n    host = wish_host\n    port = wish_port\n    listener.bind((host, port))\n    listener.listen()\n    listener.settimeout(0)\n\ndef try_connect():\n    global conn, addr, listener\n    try:\n        conn, addr = listener.accept()\n        print(f\"\\nConnected by {addr}\")\n        conn.settimeout(None)\n    except Exception as inst:\n        pass\n            \ndef read():\n    global conn\n    messageLength = conn.recv(4)\n    messageLength = int.from_bytes(messageLength, 'little')\n    message = conn.recv(messageLength)\n    return json.loads(message.decode(\"utf-8\"))\n\ndef send(message_bytes, verify):\n    global conn\n    if message_bytes != None:\n        conn.sendall(message_bytes)\n    conn.sendall(len(verify).to_bytes(4, 'little'))\n    conn.sendall(bytes(verify, 'ascii'))\n\ndef receive():\n    message = read()\n\n    width = message[\"resolution_x\"]\n    height = message[\"resolution_y\"]\n\n    if width != 0 and height != 0:\n        try:\n            do_training = bool(message[\"train\"])\n            fovy = message[\"fov_y\"]\n            fovx = message[\"fov_x\"]\n            znear = message[\"z_near\"]\n            zfar = message[\"z_far\"]\n            do_shs_python = bool(message[\"shs_python\"])\n            do_rot_scale_python = bool(message[\"rot_scale_python\"])\n            keep_alive = bool(message[\"keep_alive\"])\n            scaling_modifier = message[\"scaling_modifier\"]\n            world_view_transform = torch.reshape(torch.tensor(message[\"view_matrix\"]), (4, 4)).cuda()\n            world_view_transform[:,1] = -world_view_transform[:,1]\n            world_view_transform[:,2] = -world_view_transform[:,2]\n            full_proj_transform = torch.reshape(torch.tensor(message[\"view_projection_matrix\"]), (4, 4)).cuda()\n            full_proj_transform[:,1] = -full_proj_transform[:,1]\n            custom_cam = MiniCam(width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform)\n        except Exception as e:\n            print(\"\")\n            traceback.print_exc()\n            raise e\n        return custom_cam, do_training, do_shs_python, do_rot_scale_python, keep_alive, scaling_modifier\n    else:\n        return None, None, None, None, None, None"
  },
  {
    "path": "lpipsPyTorch/__init__.py",
    "content": "import torch\n\nfrom .modules.lpips import LPIPS\n\n\ndef lpips(x: torch.Tensor,\n          y: torch.Tensor,\n          net_type: str = 'alex',\n          version: str = '0.1'):\n    r\"\"\"Function that measures\n    Learned Perceptual Image Patch Similarity (LPIPS).\n\n    Arguments:\n        x, y (torch.Tensor): the input tensors to compare.\n        net_type (str): the network type to compare the features: \n                        'alex' | 'squeeze' | 'vgg'. Default: 'alex'.\n        version (str): the version of LPIPS. Default: 0.1.\n    \"\"\"\n    device = x.device\n    criterion = LPIPS(net_type, version).to(device)\n    return criterion(x, y)\n"
  },
  {
    "path": "lpipsPyTorch/modules/lpips.py",
    "content": "import torch\nimport torch.nn as nn\n\nfrom .networks import get_network, LinLayers\nfrom .utils import get_state_dict\n\n\nclass LPIPS(nn.Module):\n    r\"\"\"Creates a criterion that measures\n    Learned Perceptual Image Patch Similarity (LPIPS).\n\n    Arguments:\n        net_type (str): the network type to compare the features: \n                        'alex' | 'squeeze' | 'vgg'. Default: 'alex'.\n        version (str): the version of LPIPS. Default: 0.1.\n    \"\"\"\n    def __init__(self, net_type: str = 'alex', version: str = '0.1'):\n\n        assert version in ['0.1'], 'v0.1 is only supported now'\n\n        super(LPIPS, self).__init__()\n\n        # pretrained network\n        self.net = get_network(net_type)\n\n        # linear layers\n        self.lin = LinLayers(self.net.n_channels_list)\n        self.lin.load_state_dict(get_state_dict(net_type, version))\n\n    def forward(self, x: torch.Tensor, y: torch.Tensor):\n        feat_x, feat_y = self.net(x), self.net(y)\n\n        diff = [(fx - fy) ** 2 for fx, fy in zip(feat_x, feat_y)]\n        res = [l(d).mean((2, 3), True) for d, l in zip(diff, self.lin)]\n\n        return torch.sum(torch.cat(res, 0), 0, True)\n"
  },
  {
    "path": "lpipsPyTorch/modules/networks.py",
    "content": "from typing import Sequence\n\nfrom itertools import chain\n\nimport torch\nimport torch.nn as nn\nfrom torchvision import models\n\nfrom .utils import normalize_activation\n\n\ndef get_network(net_type: str):\n    if net_type == 'alex':\n        return AlexNet()\n    elif net_type == 'squeeze':\n        return SqueezeNet()\n    elif net_type == 'vgg':\n        return VGG16()\n    else:\n        raise NotImplementedError('choose net_type from [alex, squeeze, vgg].')\n\n\nclass LinLayers(nn.ModuleList):\n    def __init__(self, n_channels_list: Sequence[int]):\n        super(LinLayers, self).__init__([\n            nn.Sequential(\n                nn.Identity(),\n                nn.Conv2d(nc, 1, 1, 1, 0, bias=False)\n            ) for nc in n_channels_list\n        ])\n\n        for param in self.parameters():\n            param.requires_grad = False\n\n\nclass BaseNet(nn.Module):\n    def __init__(self):\n        super(BaseNet, self).__init__()\n\n        # register buffer\n        self.register_buffer(\n            'mean', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])\n        self.register_buffer(\n            'std', torch.Tensor([.458, .448, .450])[None, :, None, None])\n\n    def set_requires_grad(self, state: bool):\n        for param in chain(self.parameters(), self.buffers()):\n            param.requires_grad = state\n\n    def z_score(self, x: torch.Tensor):\n        return (x - self.mean) / self.std\n\n    def forward(self, x: torch.Tensor):\n        x = self.z_score(x)\n\n        output = []\n        for i, (_, layer) in enumerate(self.layers._modules.items(), 1):\n            x = layer(x)\n            if i in self.target_layers:\n                output.append(normalize_activation(x))\n            if len(output) == len(self.target_layers):\n                break\n        return output\n\n\nclass SqueezeNet(BaseNet):\n    def __init__(self):\n        super(SqueezeNet, self).__init__()\n\n        self.layers = models.squeezenet1_1(True).features\n        self.target_layers = [2, 5, 8, 10, 11, 12, 13]\n        self.n_channels_list = [64, 128, 256, 384, 384, 512, 512]\n\n        self.set_requires_grad(False)\n\n\nclass AlexNet(BaseNet):\n    def __init__(self):\n        super(AlexNet, self).__init__()\n\n        self.layers = models.alexnet(True).features\n        self.target_layers = [2, 5, 8, 10, 12]\n        self.n_channels_list = [64, 192, 384, 256, 256]\n\n        self.set_requires_grad(False)\n\n\nclass VGG16(BaseNet):\n    def __init__(self):\n        super(VGG16, self).__init__()\n\n        self.layers = models.vgg16(weights=models.VGG16_Weights.IMAGENET1K_V1).features\n        self.target_layers = [4, 9, 16, 23, 30]\n        self.n_channels_list = [64, 128, 256, 512, 512]\n\n        self.set_requires_grad(False)\n"
  },
  {
    "path": "lpipsPyTorch/modules/utils.py",
    "content": "from collections import OrderedDict\n\nimport torch\n\n\ndef normalize_activation(x, eps=1e-10):\n    norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True))\n    return x / (norm_factor + eps)\n\n\ndef get_state_dict(net_type: str = 'alex', version: str = '0.1'):\n    # build url\n    url = 'https://raw.githubusercontent.com/richzhang/PerceptualSimilarity/' \\\n        + f'master/lpips/weights/v{version}/{net_type}.pth'\n\n    # download\n    old_state_dict = torch.hub.load_state_dict_from_url(\n        url, progress=True,\n        map_location=None if torch.cuda.is_available() else torch.device('cpu')\n    )\n\n    # rename keys\n    new_state_dict = OrderedDict()\n    for key, val in old_state_dict.items():\n        new_key = key\n        new_key = new_key.replace('lin', '')\n        new_key = new_key.replace('model.', '')\n        new_state_dict[new_key] = val\n\n    return new_state_dict\n"
  },
  {
    "path": "metrics.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nfrom pathlib import Path\nimport os\nfrom PIL import Image\nimport torch\nimport torchvision.transforms.functional as tf\nfrom utils.loss_utils import ssim\nfrom lpipsPyTorch import lpips\nimport json\nfrom tqdm import tqdm\nfrom utils.image_utils import psnr\nfrom argparse import ArgumentParser\n\ndef readImages(renders_dir, gt_dir):\n    renders = []\n    gts = []\n    image_names = []\n    for fname in os.listdir(renders_dir):\n        render = Image.open(renders_dir / fname)\n        gt = Image.open(gt_dir / fname)\n        renders.append(tf.to_tensor(render).unsqueeze(0)[:, :3, :, :].cuda())\n        gts.append(tf.to_tensor(gt).unsqueeze(0)[:, :3, :, :].cuda())\n        image_names.append(fname)\n    return renders, gts, image_names\n\ndef evaluate(model_paths):\n\n    full_dict = {}\n    per_view_dict = {}\n    full_dict_polytopeonly = {}\n    per_view_dict_polytopeonly = {}\n    print(\"\")\n\n    for scene_dir in model_paths:\n        try:\n            print(\"Scene:\", scene_dir)\n            full_dict[scene_dir] = {}\n            per_view_dict[scene_dir] = {}\n            full_dict_polytopeonly[scene_dir] = {}\n            per_view_dict_polytopeonly[scene_dir] = {}\n\n            test_dir = Path(scene_dir) / \"test\"\n\n            for method in os.listdir(test_dir):\n                print(\"Method:\", method)\n\n                full_dict[scene_dir][method] = {}\n                per_view_dict[scene_dir][method] = {}\n                full_dict_polytopeonly[scene_dir][method] = {}\n                per_view_dict_polytopeonly[scene_dir][method] = {}\n\n                method_dir = test_dir / method\n                gt_dir = method_dir/ \"gt\"\n                renders_dir = method_dir / \"renders\"\n                renders, gts, image_names = readImages(renders_dir, gt_dir)\n\n                ssims = []\n                psnrs = []\n                lpipss = []\n\n                for idx in tqdm(range(len(renders)), desc=\"Metric evaluation progress\"):\n                    ssims.append(ssim(renders[idx], gts[idx]))\n                    psnrs.append(psnr(renders[idx], gts[idx]))\n                    lpipss.append(lpips(renders[idx], gts[idx], net_type='vgg'))\n\n                print(\"  SSIM : {:>12.7f}\".format(torch.tensor(ssims).mean(), \".5\"))\n                print(\"  PSNR : {:>12.7f}\".format(torch.tensor(psnrs).mean(), \".5\"))\n                print(\"  LPIPS: {:>12.7f}\".format(torch.tensor(lpipss).mean(), \".5\"))\n                print(\"\")\n\n                full_dict[scene_dir][method].update({\"SSIM\": torch.tensor(ssims).mean().item(),\n                                                        \"PSNR\": torch.tensor(psnrs).mean().item(),\n                                                        \"LPIPS\": torch.tensor(lpipss).mean().item()})\n                per_view_dict[scene_dir][method].update({\"SSIM\": {name: ssim for ssim, name in zip(torch.tensor(ssims).tolist(), image_names)},\n                                                            \"PSNR\": {name: psnr for psnr, name in zip(torch.tensor(psnrs).tolist(), image_names)},\n                                                            \"LPIPS\": {name: lp for lp, name in zip(torch.tensor(lpipss).tolist(), image_names)}})\n\n            with open(scene_dir + \"/results.json\", 'w') as fp:\n                json.dump(full_dict[scene_dir], fp, indent=True)\n            with open(scene_dir + \"/per_view.json\", 'w') as fp:\n                json.dump(per_view_dict[scene_dir], fp, indent=True)\n        except:\n            print(\"Unable to compute metrics for model\", scene_dir)\n\nif __name__ == \"__main__\":\n    device = torch.device(\"cuda:0\")\n    torch.cuda.set_device(device)\n\n    # Set up command line argument parser\n    parser = ArgumentParser(description=\"Training script parameters\")\n    parser.add_argument('--model_paths', '-m', required=True, nargs=\"+\", type=str, default=[])\n    args = parser.parse_args()\n    evaluate(args.model_paths)\n"
  },
  {
    "path": "render.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport torch\nfrom scene import Scene\nimport os\nfrom tqdm import tqdm\nfrom os import makedirs\nfrom gaussian_renderer import render\nimport torchvision\nfrom utils.general_utils import safe_state\nfrom argparse import ArgumentParser\nfrom arguments import ModelParams, PipelineParams, get_combined_args\nfrom gaussian_renderer import GaussianModel\ntry:\n    from diff_gaussian_rasterization import SparseGaussianAdam\n    SPARSE_ADAM_AVAILABLE = True\nexcept:\n    SPARSE_ADAM_AVAILABLE = False\n\n\ndef render_set(model_path, name, iteration, views, gaussians, pipeline, background, train_test_exp, separate_sh):\n    render_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"renders\")\n    gts_path = os.path.join(model_path, name, \"ours_{}\".format(iteration), \"gt\")\n\n    makedirs(render_path, exist_ok=True)\n    makedirs(gts_path, exist_ok=True)\n\n    for idx, view in enumerate(tqdm(views, desc=\"Rendering progress\")):\n        rendering = render(view, gaussians, pipeline, background, use_trained_exp=train_test_exp, separate_sh=separate_sh)[\"render\"]\n        gt = view.original_image[0:3, :, :]\n\n        if args.train_test_exp:\n            rendering = rendering[..., rendering.shape[-1] // 2:]\n            gt = gt[..., gt.shape[-1] // 2:]\n\n        torchvision.utils.save_image(rendering, os.path.join(render_path, '{0:05d}'.format(idx) + \".png\"))\n        torchvision.utils.save_image(gt, os.path.join(gts_path, '{0:05d}'.format(idx) + \".png\"))\n\ndef render_sets(dataset : ModelParams, iteration : int, pipeline : PipelineParams, skip_train : bool, skip_test : bool, separate_sh: bool):\n    with torch.no_grad():\n        gaussians = GaussianModel(dataset.sh_degree)\n        scene = Scene(dataset, gaussians, load_iteration=iteration, shuffle=False)\n\n        bg_color = [1,1,1] if dataset.white_background else [0, 0, 0]\n        background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n        if not skip_train:\n             render_set(dataset.model_path, \"train\", scene.loaded_iter, scene.getTrainCameras(), gaussians, pipeline, background, dataset.train_test_exp, separate_sh)\n\n        if not skip_test:\n             render_set(dataset.model_path, \"test\", scene.loaded_iter, scene.getTestCameras(), gaussians, pipeline, background, dataset.train_test_exp, separate_sh)\n\nif __name__ == \"__main__\":\n    # Set up command line argument parser\n    parser = ArgumentParser(description=\"Testing script parameters\")\n    model = ModelParams(parser, sentinel=True)\n    pipeline = PipelineParams(parser)\n    parser.add_argument(\"--iteration\", default=-1, type=int)\n    parser.add_argument(\"--skip_train\", action=\"store_true\")\n    parser.add_argument(\"--skip_test\", action=\"store_true\")\n    parser.add_argument(\"--quiet\", action=\"store_true\")\n    args = get_combined_args(parser)\n    print(\"Rendering \" + args.model_path)\n\n    # Initialize system state (RNG)\n    safe_state(args.quiet)\n\n    render_sets(model.extract(args), args.iteration, pipeline.extract(args), args.skip_train, args.skip_test, SPARSE_ADAM_AVAILABLE)"
  },
  {
    "path": "results.md",
    "content": "# Evaluations\nWe evaluated the impact of the features we added on MipNeRF360, Tanks&Temples and Deep Blending datasets. [Exposure Compensation](#exposure-compensation) is evaluated separately. Note that [Default rasterizer](#default-rasterizer) refers to the original [3dgs rasterizer](https://github.com/graphdeco-inria/diff-gaussian-rasterization/tree/9c5c2028f6fbee2be239bc4c9421ff894fe4fbe0) and [Accelerated rasterizer](#accelerated-rasterizer) refers to the [taming-3dgs rasterizer](https://github.com/graphdeco-inria/diff-gaussian-rasterization/tree/3dgs_accel).\n\n## Default rasterizer\n\n### PSNR\n\n![all results PSNR](assets/charts/base_PSNR.png)\n\n***DR**:depth regularization, **AA**:antialiasing*\n\n<br>\n\n![nodepth/depth](assets/depth_comparison.png)\n\n### SSIM\n![all results SSIM](assets/charts/base_SSIM.png)\n\n***DR**:depth regularization, **AA**:antialiasing*\n\n### LPIPS\n![all results LPIPS](assets/charts/base_LPIPS.png)\n\n*lower is better, **DR**:depth regularization, **AA**:antialiasing*\n\n## Accelerated rasterizer\n\n### Default optimizer\n\nThese numbers were obtained using the accelerated rasterizer and `--optimizer_type default` when training.\n\n#### PSNR\n![all results PSNR](assets/charts/accel_default_PSNR.png)\n\n***DR**:depth regularization, **AA**:antialiasing*\n\n#### SSIM\n![all results SSIM](assets/charts/accel_default_SSIM.png)\n\n***DR**:depth regularization, **AA**:antialiasing*\n\n#### LPIPS\n![all results LPIPS](assets/charts/accel_default_LPIPS.png)\n\n*lower is better, **DR**:depth regularization, **AA**:antialiasing*\n\n### Sparse Adam optimizer\n\nThese numbers were obtained using the accelerated rasterizer and `--optimizer_type sparse_adam` when training.\n\n#### PSNR\n![all results PSNR](assets/charts/accel_sparse_adam_PSNR.png)\n\n***DR**:depth regularization, **AA**:antialiasing*\n\n#### SSIM\n![all results SSIM](assets/charts/accel_sparse_adam_SSIM.png)\n\n***DR**:depth regularization, **AA**:antialiasing*\n\n#### LPIPS\n![all results LPIPS](assets/charts/accel_sparse_adam_LPIPS.png)\n\n*lower is better, **DR**:depth regularization, **AA**:antialiasing*\n\n## Exposure compensation\n\nWe account for exposure variations between images by optimizing a 3x4 affine transform for each image. During training, this transform is applied to the colour of the rendered images.\nThe exposure compensation is designed to improve the inputs' coherence during training and is not applied during real-time navigation.\nEnabling the `--train_test_exp` option includes the left half of the test images in the training set, using only their right halves for testing, following the same testing methodology as NeRF-W and Mega-NeRF. This allows us to optimize the exposure affine transform for test views. However, since this setting alters the train/test splits, the resulting metrics are not comparable to those from models trained without it. Here we provide results with `--train_test_exp`, with and without exposure compensation.\n\n### PSNR\n\n![exposures_psnr](/assets/charts/exposure_PSNR.png)\n\n### SSIM\n\n![exposures_ssim](/assets/charts/exposure_SSIM.png)\n\n### LPIPS\n\n*Lower is better.*\n![exposures_lpips](/assets/charts/exposure_LPIPS.png)\n\n![noexposure/exposure](assets/Exposure_comparison.png)\n\n## Training times comparisons\n\nWe report the training times with all features enabled using the original 3dgs rasterizer *(baseline)* and the accelerated rasterizer with default optimizer then sparse adam.\n![Training-times](assets/charts/timings.png)\n"
  },
  {
    "path": "scene/__init__.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport os\nimport random\nimport json\nfrom utils.system_utils import searchForMaxIteration\nfrom scene.dataset_readers import sceneLoadTypeCallbacks\nfrom scene.gaussian_model import GaussianModel\nfrom arguments import ModelParams\nfrom utils.camera_utils import cameraList_from_camInfos, camera_to_JSON\n\nclass Scene:\n\n    gaussians : GaussianModel\n\n    def __init__(self, args : ModelParams, gaussians : GaussianModel, load_iteration=None, shuffle=True, resolution_scales=[1.0]):\n        \"\"\"b\n        :param path: Path to colmap scene main folder.\n        \"\"\"\n        self.model_path = args.model_path\n        self.loaded_iter = None\n        self.gaussians = gaussians\n\n        if load_iteration:\n            if load_iteration == -1:\n                self.loaded_iter = searchForMaxIteration(os.path.join(self.model_path, \"point_cloud\"))\n            else:\n                self.loaded_iter = load_iteration\n            print(\"Loading trained model at iteration {}\".format(self.loaded_iter))\n\n        self.train_cameras = {}\n        self.test_cameras = {}\n\n        if os.path.exists(os.path.join(args.source_path, \"sparse\")):\n            scene_info = sceneLoadTypeCallbacks[\"Colmap\"](args.source_path, args.images, args.depths, args.eval, args.train_test_exp)\n        elif os.path.exists(os.path.join(args.source_path, \"transforms_train.json\")):\n            print(\"Found transforms_train.json file, assuming Blender data set!\")\n            scene_info = sceneLoadTypeCallbacks[\"Blender\"](args.source_path, args.white_background, args.depths, args.eval)\n        else:\n            assert False, \"Could not recognize scene type!\"\n\n        if not self.loaded_iter:\n            with open(scene_info.ply_path, 'rb') as src_file, open(os.path.join(self.model_path, \"input.ply\") , 'wb') as dest_file:\n                dest_file.write(src_file.read())\n            json_cams = []\n            camlist = []\n            if scene_info.test_cameras:\n                camlist.extend(scene_info.test_cameras)\n            if scene_info.train_cameras:\n                camlist.extend(scene_info.train_cameras)\n            for id, cam in enumerate(camlist):\n                json_cams.append(camera_to_JSON(id, cam))\n            with open(os.path.join(self.model_path, \"cameras.json\"), 'w') as file:\n                json.dump(json_cams, file)\n\n        if shuffle:\n            random.shuffle(scene_info.train_cameras)  # Multi-res consistent random shuffling\n            random.shuffle(scene_info.test_cameras)  # Multi-res consistent random shuffling\n\n        self.cameras_extent = scene_info.nerf_normalization[\"radius\"]\n\n        for resolution_scale in resolution_scales:\n            print(\"Loading Training Cameras\")\n            self.train_cameras[resolution_scale] = cameraList_from_camInfos(scene_info.train_cameras, resolution_scale, args, scene_info.is_nerf_synthetic, False)\n            print(\"Loading Test Cameras\")\n            self.test_cameras[resolution_scale] = cameraList_from_camInfos(scene_info.test_cameras, resolution_scale, args, scene_info.is_nerf_synthetic, True)\n\n        if self.loaded_iter:\n            self.gaussians.load_ply(os.path.join(self.model_path,\n                                                           \"point_cloud\",\n                                                           \"iteration_\" + str(self.loaded_iter),\n                                                           \"point_cloud.ply\"), args.train_test_exp)\n        else:\n            self.gaussians.create_from_pcd(scene_info.point_cloud, scene_info.train_cameras, self.cameras_extent)\n\n    def save(self, iteration):\n        point_cloud_path = os.path.join(self.model_path, \"point_cloud/iteration_{}\".format(iteration))\n        self.gaussians.save_ply(os.path.join(point_cloud_path, \"point_cloud.ply\"))\n        exposure_dict = {\n            image_name: self.gaussians.get_exposure_from_name(image_name).detach().cpu().numpy().tolist()\n            for image_name in self.gaussians.exposure_mapping\n        }\n\n        with open(os.path.join(self.model_path, \"exposure.json\"), \"w\") as f:\n            json.dump(exposure_dict, f, indent=2)\n\n    def getTrainCameras(self, scale=1.0):\n        return self.train_cameras[scale]\n\n    def getTestCameras(self, scale=1.0):\n        return self.test_cameras[scale]\n"
  },
  {
    "path": "scene/cameras.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport torch\nfrom torch import nn\nimport numpy as np\nfrom utils.graphics_utils import getWorld2View2, getProjectionMatrix\nfrom utils.general_utils import PILtoTorch\nimport cv2\n\nclass Camera(nn.Module):\n    def __init__(self, resolution, colmap_id, R, T, FoVx, FoVy, depth_params, image, invdepthmap,\n                 image_name, uid,\n                 trans=np.array([0.0, 0.0, 0.0]), scale=1.0, data_device = \"cuda\",\n                 train_test_exp = False, is_test_dataset = False, is_test_view = False\n                 ):\n        super(Camera, self).__init__()\n\n        self.uid = uid\n        self.colmap_id = colmap_id\n        self.R = R\n        self.T = T\n        self.FoVx = FoVx\n        self.FoVy = FoVy\n        self.image_name = image_name\n\n        try:\n            self.data_device = torch.device(data_device)\n        except Exception as e:\n            print(e)\n            print(f\"[Warning] Custom device {data_device} failed, fallback to default cuda device\" )\n            self.data_device = torch.device(\"cuda\")\n\n        resized_image_rgb = PILtoTorch(image, resolution)\n        gt_image = resized_image_rgb[:3, ...]\n        self.alpha_mask = None\n        if resized_image_rgb.shape[0] == 4:\n            self.alpha_mask = resized_image_rgb[3:4, ...].to(self.data_device)\n        else: \n            self.alpha_mask = torch.ones_like(resized_image_rgb[0:1, ...].to(self.data_device))\n\n        if train_test_exp and is_test_view:\n            if is_test_dataset:\n                self.alpha_mask[..., :self.alpha_mask.shape[-1] // 2] = 0\n            else:\n                self.alpha_mask[..., self.alpha_mask.shape[-1] // 2:] = 0\n\n        self.original_image = gt_image.clamp(0.0, 1.0).to(self.data_device)\n        self.image_width = self.original_image.shape[2]\n        self.image_height = self.original_image.shape[1]\n\n        self.invdepthmap = None\n        self.depth_reliable = False\n        if invdepthmap is not None:\n            self.depth_mask = torch.ones_like(self.alpha_mask)\n            self.invdepthmap = cv2.resize(invdepthmap, resolution)\n            self.invdepthmap[self.invdepthmap < 0] = 0\n            self.depth_reliable = True\n\n            if depth_params is not None:\n                if depth_params[\"scale\"] < 0.2 * depth_params[\"med_scale\"] or depth_params[\"scale\"] > 5 * depth_params[\"med_scale\"]:\n                    self.depth_reliable = False\n                    self.depth_mask *= 0\n                \n                if depth_params[\"scale\"] > 0:\n                    self.invdepthmap = self.invdepthmap * depth_params[\"scale\"] + depth_params[\"offset\"]\n\n            if self.invdepthmap.ndim != 2:\n                self.invdepthmap = self.invdepthmap[..., 0]\n            self.invdepthmap = torch.from_numpy(self.invdepthmap[None]).to(self.data_device)\n\n        self.zfar = 100.0\n        self.znear = 0.01\n\n        self.trans = trans\n        self.scale = scale\n\n        self.world_view_transform = torch.tensor(getWorld2View2(R, T, trans, scale)).transpose(0, 1).cuda()\n        self.projection_matrix = getProjectionMatrix(znear=self.znear, zfar=self.zfar, fovX=self.FoVx, fovY=self.FoVy).transpose(0,1).cuda()\n        self.full_proj_transform = (self.world_view_transform.unsqueeze(0).bmm(self.projection_matrix.unsqueeze(0))).squeeze(0)\n        self.camera_center = self.world_view_transform.inverse()[3, :3]\n        \nclass MiniCam:\n    def __init__(self, width, height, fovy, fovx, znear, zfar, world_view_transform, full_proj_transform):\n        self.image_width = width\n        self.image_height = height    \n        self.FoVy = fovy\n        self.FoVx = fovx\n        self.znear = znear\n        self.zfar = zfar\n        self.world_view_transform = world_view_transform\n        self.full_proj_transform = full_proj_transform\n        view_inv = torch.inverse(self.world_view_transform)\n        self.camera_center = view_inv[3][:3]\n\n"
  },
  {
    "path": "scene/colmap_loader.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport numpy as np\nimport collections\nimport struct\n\nCameraModel = collections.namedtuple(\n    \"CameraModel\", [\"model_id\", \"model_name\", \"num_params\"])\nCamera = collections.namedtuple(\n    \"Camera\", [\"id\", \"model\", \"width\", \"height\", \"params\"])\nBaseImage = collections.namedtuple(\n    \"Image\", [\"id\", \"qvec\", \"tvec\", \"camera_id\", \"name\", \"xys\", \"point3D_ids\"])\nPoint3D = collections.namedtuple(\n    \"Point3D\", [\"id\", \"xyz\", \"rgb\", \"error\", \"image_ids\", \"point2D_idxs\"])\nCAMERA_MODELS = {\n    CameraModel(model_id=0, model_name=\"SIMPLE_PINHOLE\", num_params=3),\n    CameraModel(model_id=1, model_name=\"PINHOLE\", num_params=4),\n    CameraModel(model_id=2, model_name=\"SIMPLE_RADIAL\", num_params=4),\n    CameraModel(model_id=3, model_name=\"RADIAL\", num_params=5),\n    CameraModel(model_id=4, model_name=\"OPENCV\", num_params=8),\n    CameraModel(model_id=5, model_name=\"OPENCV_FISHEYE\", num_params=8),\n    CameraModel(model_id=6, model_name=\"FULL_OPENCV\", num_params=12),\n    CameraModel(model_id=7, model_name=\"FOV\", num_params=5),\n    CameraModel(model_id=8, model_name=\"SIMPLE_RADIAL_FISHEYE\", num_params=4),\n    CameraModel(model_id=9, model_name=\"RADIAL_FISHEYE\", num_params=5),\n    CameraModel(model_id=10, model_name=\"THIN_PRISM_FISHEYE\", num_params=12)\n}\nCAMERA_MODEL_IDS = dict([(camera_model.model_id, camera_model)\n                         for camera_model in CAMERA_MODELS])\nCAMERA_MODEL_NAMES = dict([(camera_model.model_name, camera_model)\n                           for camera_model in CAMERA_MODELS])\n\n\ndef qvec2rotmat(qvec):\n    return np.array([\n        [1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,\n         2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],\n         2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],\n        [2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],\n         1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,\n         2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],\n        [2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],\n         2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n         1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])\n\ndef rotmat2qvec(R):\n    Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat\n    K = np.array([\n        [Rxx - Ryy - Rzz, 0, 0, 0],\n        [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],\n        [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],\n        [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0\n    eigvals, eigvecs = np.linalg.eigh(K)\n    qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n    if qvec[0] < 0:\n        qvec *= -1\n    return qvec\n\nclass Image(BaseImage):\n    def qvec2rotmat(self):\n        return qvec2rotmat(self.qvec)\n\ndef read_next_bytes(fid, num_bytes, format_char_sequence, endian_character=\"<\"):\n    \"\"\"Read and unpack the next bytes from a binary file.\n    :param fid:\n    :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.\n    :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n    :param endian_character: Any of {@, =, <, >, !}\n    :return: Tuple of read and unpacked values.\n    \"\"\"\n    data = fid.read(num_bytes)\n    return struct.unpack(endian_character + format_char_sequence, data)\n\ndef read_points3D_text(path):\n    \"\"\"\n    see: src/base/reconstruction.cc\n        void Reconstruction::ReadPoints3DText(const std::string& path)\n        void Reconstruction::WritePoints3DText(const std::string& path)\n    \"\"\"\n    xyzs = None\n    rgbs = None\n    errors = None\n    num_points = 0\n    with open(path, \"r\") as fid:\n        while True:\n            line = fid.readline()\n            if not line:\n                break\n            line = line.strip()\n            if len(line) > 0 and line[0] != \"#\":\n                num_points += 1\n\n\n    xyzs = np.empty((num_points, 3))\n    rgbs = np.empty((num_points, 3))\n    errors = np.empty((num_points, 1))\n    count = 0\n    with open(path, \"r\") as fid:\n        while True:\n            line = fid.readline()\n            if not line:\n                break\n            line = line.strip()\n            if len(line) > 0 and line[0] != \"#\":\n                elems = line.split()\n                xyz = np.array(tuple(map(float, elems[1:4])))\n                rgb = np.array(tuple(map(int, elems[4:7])))\n                error = np.array(float(elems[7]))\n                xyzs[count] = xyz\n                rgbs[count] = rgb\n                errors[count] = error\n                count += 1\n\n    return xyzs, rgbs, errors\n\ndef read_points3D_binary(path_to_model_file):\n    \"\"\"\n    see: src/base/reconstruction.cc\n        void Reconstruction::ReadPoints3DBinary(const std::string& path)\n        void Reconstruction::WritePoints3DBinary(const std::string& path)\n    \"\"\"\n\n\n    with open(path_to_model_file, \"rb\") as fid:\n        num_points = read_next_bytes(fid, 8, \"Q\")[0]\n\n        xyzs = np.empty((num_points, 3))\n        rgbs = np.empty((num_points, 3))\n        errors = np.empty((num_points, 1))\n\n        for p_id in range(num_points):\n            binary_point_line_properties = read_next_bytes(\n                fid, num_bytes=43, format_char_sequence=\"QdddBBBd\")\n            xyz = np.array(binary_point_line_properties[1:4])\n            rgb = np.array(binary_point_line_properties[4:7])\n            error = np.array(binary_point_line_properties[7])\n            track_length = read_next_bytes(\n                fid, num_bytes=8, format_char_sequence=\"Q\")[0]\n            track_elems = read_next_bytes(\n                fid, num_bytes=8*track_length,\n                format_char_sequence=\"ii\"*track_length)\n            xyzs[p_id] = xyz\n            rgbs[p_id] = rgb\n            errors[p_id] = error\n    return xyzs, rgbs, errors\n\ndef read_intrinsics_text(path):\n    \"\"\"\n    Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n    \"\"\"\n    cameras = {}\n    with open(path, \"r\") as fid:\n        while True:\n            line = fid.readline()\n            if not line:\n                break\n            line = line.strip()\n            if len(line) > 0 and line[0] != \"#\":\n                elems = line.split()\n                camera_id = int(elems[0])\n                model = elems[1]\n                assert model == \"PINHOLE\", \"While the loader support other types, the rest of the code assumes PINHOLE\"\n                width = int(elems[2])\n                height = int(elems[3])\n                params = np.array(tuple(map(float, elems[4:])))\n                cameras[camera_id] = Camera(id=camera_id, model=model,\n                                            width=width, height=height,\n                                            params=params)\n    return cameras\n\ndef read_extrinsics_binary(path_to_model_file):\n    \"\"\"\n    see: src/base/reconstruction.cc\n        void Reconstruction::ReadImagesBinary(const std::string& path)\n        void Reconstruction::WriteImagesBinary(const std::string& path)\n    \"\"\"\n    images = {}\n    with open(path_to_model_file, \"rb\") as fid:\n        num_reg_images = read_next_bytes(fid, 8, \"Q\")[0]\n        for _ in range(num_reg_images):\n            binary_image_properties = read_next_bytes(\n                fid, num_bytes=64, format_char_sequence=\"idddddddi\")\n            image_id = binary_image_properties[0]\n            qvec = np.array(binary_image_properties[1:5])\n            tvec = np.array(binary_image_properties[5:8])\n            camera_id = binary_image_properties[8]\n            image_name = \"\"\n            current_char = read_next_bytes(fid, 1, \"c\")[0]\n            while current_char != b\"\\x00\":   # look for the ASCII 0 entry\n                image_name += current_char.decode(\"utf-8\")\n                current_char = read_next_bytes(fid, 1, \"c\")[0]\n            num_points2D = read_next_bytes(fid, num_bytes=8,\n                                           format_char_sequence=\"Q\")[0]\n            x_y_id_s = read_next_bytes(fid, num_bytes=24*num_points2D,\n                                       format_char_sequence=\"ddq\"*num_points2D)\n            xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])),\n                                   tuple(map(float, x_y_id_s[1::3]))])\n            point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))\n            images[image_id] = Image(\n                id=image_id, qvec=qvec, tvec=tvec,\n                camera_id=camera_id, name=image_name,\n                xys=xys, point3D_ids=point3D_ids)\n    return images\n\n\ndef read_intrinsics_binary(path_to_model_file):\n    \"\"\"\n    see: src/base/reconstruction.cc\n        void Reconstruction::WriteCamerasBinary(const std::string& path)\n        void Reconstruction::ReadCamerasBinary(const std::string& path)\n    \"\"\"\n    cameras = {}\n    with open(path_to_model_file, \"rb\") as fid:\n        num_cameras = read_next_bytes(fid, 8, \"Q\")[0]\n        for _ in range(num_cameras):\n            camera_properties = read_next_bytes(\n                fid, num_bytes=24, format_char_sequence=\"iiQQ\")\n            camera_id = camera_properties[0]\n            model_id = camera_properties[1]\n            model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name\n            width = camera_properties[2]\n            height = camera_properties[3]\n            num_params = CAMERA_MODEL_IDS[model_id].num_params\n            params = read_next_bytes(fid, num_bytes=8*num_params,\n                                     format_char_sequence=\"d\"*num_params)\n            cameras[camera_id] = Camera(id=camera_id,\n                                        model=model_name,\n                                        width=width,\n                                        height=height,\n                                        params=np.array(params))\n        assert len(cameras) == num_cameras\n    return cameras\n\n\ndef read_extrinsics_text(path):\n    \"\"\"\n    Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n    \"\"\"\n    images = {}\n    with open(path, \"r\") as fid:\n        while True:\n            line = fid.readline()\n            if not line:\n                break\n            line = line.strip()\n            if len(line) > 0 and line[0] != \"#\":\n                elems = line.split()\n                image_id = int(elems[0])\n                qvec = np.array(tuple(map(float, elems[1:5])))\n                tvec = np.array(tuple(map(float, elems[5:8])))\n                camera_id = int(elems[8])\n                image_name = elems[9]\n                elems = fid.readline().split()\n                xys = np.column_stack([tuple(map(float, elems[0::3])),\n                                       tuple(map(float, elems[1::3]))])\n                point3D_ids = np.array(tuple(map(int, elems[2::3])))\n                images[image_id] = Image(\n                    id=image_id, qvec=qvec, tvec=tvec,\n                    camera_id=camera_id, name=image_name,\n                    xys=xys, point3D_ids=point3D_ids)\n    return images\n\n\ndef read_colmap_bin_array(path):\n    \"\"\"\n    Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_dense.py\n\n    :param path: path to the colmap binary file.\n    :return: nd array with the floating point values in the value\n    \"\"\"\n    with open(path, \"rb\") as fid:\n        width, height, channels = np.genfromtxt(fid, delimiter=\"&\", max_rows=1,\n                                                usecols=(0, 1, 2), dtype=int)\n        fid.seek(0)\n        num_delimiter = 0\n        byte = fid.read(1)\n        while True:\n            if byte == b\"&\":\n                num_delimiter += 1\n                if num_delimiter >= 3:\n                    break\n            byte = fid.read(1)\n        array = np.fromfile(fid, np.float32)\n    array = array.reshape((width, height, channels), order=\"F\")\n    return np.transpose(array, (1, 0, 2)).squeeze()\n"
  },
  {
    "path": "scene/dataset_readers.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport os\nimport sys\nfrom PIL import Image\nfrom typing import NamedTuple\nfrom scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \\\n    read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text\nfrom utils.graphics_utils import getWorld2View2, focal2fov, fov2focal\nimport numpy as np\nimport json\nfrom pathlib import Path\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import SH2RGB\nfrom scene.gaussian_model import BasicPointCloud\n\nclass CameraInfo(NamedTuple):\n    uid: int\n    R: np.array\n    T: np.array\n    FovY: np.array\n    FovX: np.array\n    depth_params: dict\n    image_path: str\n    image_name: str\n    depth_path: str\n    width: int\n    height: int\n    is_test: bool\n\nclass SceneInfo(NamedTuple):\n    point_cloud: BasicPointCloud\n    train_cameras: list\n    test_cameras: list\n    nerf_normalization: dict\n    ply_path: str\n    is_nerf_synthetic: bool\n\ndef getNerfppNorm(cam_info):\n    def get_center_and_diag(cam_centers):\n        cam_centers = np.hstack(cam_centers)\n        avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True)\n        center = avg_cam_center\n        dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True)\n        diagonal = np.max(dist)\n        return center.flatten(), diagonal\n\n    cam_centers = []\n\n    for cam in cam_info:\n        W2C = getWorld2View2(cam.R, cam.T)\n        C2W = np.linalg.inv(W2C)\n        cam_centers.append(C2W[:3, 3:4])\n\n    center, diagonal = get_center_and_diag(cam_centers)\n    radius = diagonal * 1.1\n\n    translate = -center\n\n    return {\"translate\": translate, \"radius\": radius}\n\ndef readColmapCameras(cam_extrinsics, cam_intrinsics, depths_params, images_folder, depths_folder, test_cam_names_list):\n    cam_infos = []\n    for idx, key in enumerate(cam_extrinsics):\n        sys.stdout.write('\\r')\n        # the exact output you're looking for:\n        sys.stdout.write(\"Reading camera {}/{}\".format(idx+1, len(cam_extrinsics)))\n        sys.stdout.flush()\n\n        extr = cam_extrinsics[key]\n        intr = cam_intrinsics[extr.camera_id]\n        height = intr.height\n        width = intr.width\n\n        uid = intr.id\n        R = np.transpose(qvec2rotmat(extr.qvec))\n        T = np.array(extr.tvec)\n\n        if intr.model==\"SIMPLE_PINHOLE\":\n            focal_length_x = intr.params[0]\n            FovY = focal2fov(focal_length_x, height)\n            FovX = focal2fov(focal_length_x, width)\n        elif intr.model==\"PINHOLE\":\n            focal_length_x = intr.params[0]\n            focal_length_y = intr.params[1]\n            FovY = focal2fov(focal_length_y, height)\n            FovX = focal2fov(focal_length_x, width)\n        else:\n            assert False, \"Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!\"\n\n        n_remove = len(extr.name.split('.')[-1]) + 1\n        depth_params = None\n        if depths_params is not None:\n            try:\n                depth_params = depths_params[extr.name[:-n_remove]]\n            except:\n                print(\"\\n\", key, \"not found in depths_params\")\n\n        image_path = os.path.join(images_folder, extr.name)\n        image_name = extr.name\n        depth_path = os.path.join(depths_folder, f\"{extr.name[:-n_remove]}.png\") if depths_folder != \"\" else \"\"\n\n        cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, depth_params=depth_params,\n                              image_path=image_path, image_name=image_name, depth_path=depth_path,\n                              width=width, height=height, is_test=image_name in test_cam_names_list)\n        cam_infos.append(cam_info)\n\n    sys.stdout.write('\\n')\n    return cam_infos\n\ndef fetchPly(path):\n    plydata = PlyData.read(path)\n    vertices = plydata['vertex']\n    positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T\n    colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0\n    normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T\n    return BasicPointCloud(points=positions, colors=colors, normals=normals)\n\ndef storePly(path, xyz, rgb):\n    # Define the dtype for the structured array\n    dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'),\n            ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'),\n            ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')]\n    \n    normals = np.zeros_like(xyz)\n\n    elements = np.empty(xyz.shape[0], dtype=dtype)\n    attributes = np.concatenate((xyz, normals, rgb), axis=1)\n    elements[:] = list(map(tuple, attributes))\n\n    # Create the PlyData object and write to file\n    vertex_element = PlyElement.describe(elements, 'vertex')\n    ply_data = PlyData([vertex_element])\n    ply_data.write(path)\n\ndef readColmapSceneInfo(path, images, depths, eval, train_test_exp, llffhold=8):\n    try:\n        cameras_extrinsic_file = os.path.join(path, \"sparse/0\", \"images.bin\")\n        cameras_intrinsic_file = os.path.join(path, \"sparse/0\", \"cameras.bin\")\n        cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file)\n        cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file)\n    except:\n        cameras_extrinsic_file = os.path.join(path, \"sparse/0\", \"images.txt\")\n        cameras_intrinsic_file = os.path.join(path, \"sparse/0\", \"cameras.txt\")\n        cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file)\n        cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file)\n\n    depth_params_file = os.path.join(path, \"sparse/0\", \"depth_params.json\")\n    ## if depth_params_file isnt there AND depths file is here -> throw error\n    depths_params = None\n    if depths != \"\":\n        try:\n            with open(depth_params_file, \"r\") as f:\n                depths_params = json.load(f)\n            all_scales = np.array([depths_params[key][\"scale\"] for key in depths_params])\n            if (all_scales > 0).sum():\n                med_scale = np.median(all_scales[all_scales > 0])\n            else:\n                med_scale = 0\n            for key in depths_params:\n                depths_params[key][\"med_scale\"] = med_scale\n\n        except FileNotFoundError:\n            print(f\"Error: depth_params.json file not found at path '{depth_params_file}'.\")\n            sys.exit(1)\n        except Exception as e:\n            print(f\"An unexpected error occurred when trying to open depth_params.json file: {e}\")\n            sys.exit(1)\n\n    if eval:\n        if \"360\" in path:\n            llffhold = 8\n        if llffhold:\n            print(\"------------LLFF HOLD-------------\")\n            cam_names = [cam_extrinsics[cam_id].name for cam_id in cam_extrinsics]\n            cam_names = sorted(cam_names)\n            test_cam_names_list = [name for idx, name in enumerate(cam_names) if idx % llffhold == 0]\n        else:\n            with open(os.path.join(path, \"sparse/0\", \"test.txt\"), 'r') as file:\n                test_cam_names_list = [line.strip() for line in file]\n    else:\n        test_cam_names_list = []\n\n    reading_dir = \"images\" if images == None else images\n    cam_infos_unsorted = readColmapCameras(\n        cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, depths_params=depths_params,\n        images_folder=os.path.join(path, reading_dir), \n        depths_folder=os.path.join(path, depths) if depths != \"\" else \"\", test_cam_names_list=test_cam_names_list)\n    cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name)\n\n    train_cam_infos = [c for c in cam_infos if train_test_exp or not c.is_test]\n    test_cam_infos = [c for c in cam_infos if c.is_test]\n\n    nerf_normalization = getNerfppNorm(train_cam_infos)\n\n    ply_path = os.path.join(path, \"sparse/0/points3D.ply\")\n    bin_path = os.path.join(path, \"sparse/0/points3D.bin\")\n    txt_path = os.path.join(path, \"sparse/0/points3D.txt\")\n    if not os.path.exists(ply_path):\n        print(\"Converting point3d.bin to .ply, will happen only the first time you open the scene.\")\n        try:\n            xyz, rgb, _ = read_points3D_binary(bin_path)\n        except:\n            xyz, rgb, _ = read_points3D_text(txt_path)\n        storePly(ply_path, xyz, rgb)\n    try:\n        pcd = fetchPly(ply_path)\n    except:\n        pcd = None\n\n    scene_info = SceneInfo(point_cloud=pcd,\n                           train_cameras=train_cam_infos,\n                           test_cameras=test_cam_infos,\n                           nerf_normalization=nerf_normalization,\n                           ply_path=ply_path,\n                           is_nerf_synthetic=False)\n    return scene_info\n\ndef readCamerasFromTransforms(path, transformsfile, depths_folder, white_background, is_test, extension=\".png\"):\n    cam_infos = []\n\n    with open(os.path.join(path, transformsfile)) as json_file:\n        contents = json.load(json_file)\n        fovx = contents[\"camera_angle_x\"]\n\n        frames = contents[\"frames\"]\n        for idx, frame in enumerate(frames):\n            cam_name = os.path.join(path, frame[\"file_path\"] + extension)\n\n            # NeRF 'transform_matrix' is a camera-to-world transform\n            c2w = np.array(frame[\"transform_matrix\"])\n            # change from OpenGL/Blender camera axes (Y up, Z back) to COLMAP (Y down, Z forward)\n            c2w[:3, 1:3] *= -1\n\n            # get the world-to-camera transform and set R, T\n            w2c = np.linalg.inv(c2w)\n            R = np.transpose(w2c[:3,:3])  # R is stored transposed due to 'glm' in CUDA code\n            T = w2c[:3, 3]\n\n            image_path = os.path.join(path, cam_name)\n            image_name = Path(cam_name).stem\n            image = Image.open(image_path)\n\n            im_data = np.array(image.convert(\"RGBA\"))\n\n            bg = np.array([1,1,1]) if white_background else np.array([0, 0, 0])\n\n            norm_data = im_data / 255.0\n            arr = norm_data[:,:,:3] * norm_data[:, :, 3:4] + bg * (1 - norm_data[:, :, 3:4])\n            image = Image.fromarray(np.array(arr*255.0, dtype=np.byte), \"RGB\")\n\n            fovy = focal2fov(fov2focal(fovx, image.size[0]), image.size[1])\n            FovY = fovy \n            FovX = fovx\n\n            depth_path = os.path.join(depths_folder, f\"{image_name}.png\") if depths_folder != \"\" else \"\"\n\n            cam_infos.append(CameraInfo(uid=idx, R=R, T=T, FovY=FovY, FovX=FovX,\n                            image_path=image_path, image_name=image_name,\n                            width=image.size[0], height=image.size[1], depth_path=depth_path, depth_params=None, is_test=is_test))\n            \n    return cam_infos\n\ndef readNerfSyntheticInfo(path, white_background, depths, eval, extension=\".png\"):\n\n    depths_folder=os.path.join(path, depths) if depths != \"\" else \"\"\n    print(\"Reading Training Transforms\")\n    train_cam_infos = readCamerasFromTransforms(path, \"transforms_train.json\", depths_folder, white_background, False, extension)\n    print(\"Reading Test Transforms\")\n    test_cam_infos = readCamerasFromTransforms(path, \"transforms_test.json\", depths_folder, white_background, True, extension)\n    \n    if not eval:\n        train_cam_infos.extend(test_cam_infos)\n        test_cam_infos = []\n\n    nerf_normalization = getNerfppNorm(train_cam_infos)\n\n    ply_path = os.path.join(path, \"points3d.ply\")\n    if not os.path.exists(ply_path):\n        # Since this data set has no colmap data, we start with random points\n        num_pts = 100_000\n        print(f\"Generating random point cloud ({num_pts})...\")\n        \n        # We create random points inside the bounds of the synthetic Blender scenes\n        xyz = np.random.random((num_pts, 3)) * 2.6 - 1.3\n        shs = np.random.random((num_pts, 3)) / 255.0\n        pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))\n\n        storePly(ply_path, xyz, SH2RGB(shs) * 255)\n    try:\n        pcd = fetchPly(ply_path)\n    except:\n        pcd = None\n\n    scene_info = SceneInfo(point_cloud=pcd,\n                           train_cameras=train_cam_infos,\n                           test_cameras=test_cam_infos,\n                           nerf_normalization=nerf_normalization,\n                           ply_path=ply_path,\n                           is_nerf_synthetic=True)\n    return scene_info\n\nsceneLoadTypeCallbacks = {\n    \"Colmap\": readColmapSceneInfo,\n    \"Blender\" : readNerfSyntheticInfo\n}"
  },
  {
    "path": "scene/gaussian_model.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport torch\nimport numpy as np\nfrom utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation\nfrom torch import nn\nimport os\nimport json\nfrom utils.system_utils import mkdir_p\nfrom plyfile import PlyData, PlyElement\nfrom utils.sh_utils import RGB2SH\nfrom simple_knn._C import distCUDA2\nfrom utils.graphics_utils import BasicPointCloud\nfrom utils.general_utils import strip_symmetric, build_scaling_rotation\n\ntry:\n    from diff_gaussian_rasterization import SparseGaussianAdam\nexcept:\n    pass\n\nclass GaussianModel:\n\n    def setup_functions(self):\n        def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):\n            L = build_scaling_rotation(scaling_modifier * scaling, rotation)\n            actual_covariance = L @ L.transpose(1, 2)\n            symm = strip_symmetric(actual_covariance)\n            return symm\n        \n        self.scaling_activation = torch.exp\n        self.scaling_inverse_activation = torch.log\n\n        self.covariance_activation = build_covariance_from_scaling_rotation\n\n        self.opacity_activation = torch.sigmoid\n        self.inverse_opacity_activation = inverse_sigmoid\n\n        self.rotation_activation = torch.nn.functional.normalize\n\n\n    def __init__(self, sh_degree, optimizer_type=\"default\"):\n        self.active_sh_degree = 0\n        self.optimizer_type = optimizer_type\n        self.max_sh_degree = sh_degree  \n        self._xyz = torch.empty(0)\n        self._features_dc = torch.empty(0)\n        self._features_rest = torch.empty(0)\n        self._scaling = torch.empty(0)\n        self._rotation = torch.empty(0)\n        self._opacity = torch.empty(0)\n        self.max_radii2D = torch.empty(0)\n        self.xyz_gradient_accum = torch.empty(0)\n        self.denom = torch.empty(0)\n        self.optimizer = None\n        self.percent_dense = 0\n        self.spatial_lr_scale = 0\n        self.setup_functions()\n\n    def capture(self):\n        return (\n            self.active_sh_degree,\n            self._xyz,\n            self._features_dc,\n            self._features_rest,\n            self._scaling,\n            self._rotation,\n            self._opacity,\n            self.max_radii2D,\n            self.xyz_gradient_accum,\n            self.denom,\n            self.optimizer.state_dict(),\n            self.spatial_lr_scale,\n        )\n    \n    def restore(self, model_args, training_args):\n        (self.active_sh_degree, \n        self._xyz, \n        self._features_dc, \n        self._features_rest,\n        self._scaling, \n        self._rotation, \n        self._opacity,\n        self.max_radii2D, \n        xyz_gradient_accum, \n        denom,\n        opt_dict, \n        self.spatial_lr_scale) = model_args\n        self.training_setup(training_args)\n        self.xyz_gradient_accum = xyz_gradient_accum\n        self.denom = denom\n        self.optimizer.load_state_dict(opt_dict)\n\n    @property\n    def get_scaling(self):\n        return self.scaling_activation(self._scaling)\n    \n    @property\n    def get_rotation(self):\n        return self.rotation_activation(self._rotation)\n    \n    @property\n    def get_xyz(self):\n        return self._xyz\n    \n    @property\n    def get_features(self):\n        features_dc = self._features_dc\n        features_rest = self._features_rest\n        return torch.cat((features_dc, features_rest), dim=1)\n    \n    @property\n    def get_features_dc(self):\n        return self._features_dc\n    \n    @property\n    def get_features_rest(self):\n        return self._features_rest\n    \n    @property\n    def get_opacity(self):\n        return self.opacity_activation(self._opacity)\n    \n    @property\n    def get_exposure(self):\n        return self._exposure\n\n    def get_exposure_from_name(self, image_name):\n        if self.pretrained_exposures is None:\n            return self._exposure[self.exposure_mapping[image_name]]\n        else:\n            return self.pretrained_exposures[image_name]\n    \n    def get_covariance(self, scaling_modifier = 1):\n        return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)\n\n    def oneupSHdegree(self):\n        if self.active_sh_degree < self.max_sh_degree:\n            self.active_sh_degree += 1\n\n    def create_from_pcd(self, pcd : BasicPointCloud, cam_infos : int, spatial_lr_scale : float):\n        self.spatial_lr_scale = spatial_lr_scale\n        fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()\n        fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda())\n        features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()\n        features[:, :3, 0 ] = fused_color\n        features[:, 3:, 1:] = 0.0\n\n        print(\"Number of points at initialisation : \", fused_point_cloud.shape[0])\n\n        dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001)\n        scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)\n        rots = torch.zeros((fused_point_cloud.shape[0], 4), device=\"cuda\")\n        rots[:, 0] = 1\n\n        opacities = self.inverse_opacity_activation(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device=\"cuda\"))\n\n        self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))\n        self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))\n        self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))\n        self._scaling = nn.Parameter(scales.requires_grad_(True))\n        self._rotation = nn.Parameter(rots.requires_grad_(True))\n        self._opacity = nn.Parameter(opacities.requires_grad_(True))\n        self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n        self.exposure_mapping = {cam_info.image_name: idx for idx, cam_info in enumerate(cam_infos)}\n        self.pretrained_exposures = None\n        exposure = torch.eye(3, 4, device=\"cuda\")[None].repeat(len(cam_infos), 1, 1)\n        self._exposure = nn.Parameter(exposure.requires_grad_(True))\n\n    def training_setup(self, training_args):\n        self.percent_dense = training_args.percent_dense\n        self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n        self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n\n        l = [\n            {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, \"name\": \"xyz\"},\n            {'params': [self._features_dc], 'lr': training_args.feature_lr, \"name\": \"f_dc\"},\n            {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, \"name\": \"f_rest\"},\n            {'params': [self._opacity], 'lr': training_args.opacity_lr, \"name\": \"opacity\"},\n            {'params': [self._scaling], 'lr': training_args.scaling_lr, \"name\": \"scaling\"},\n            {'params': [self._rotation], 'lr': training_args.rotation_lr, \"name\": \"rotation\"}\n        ]\n\n        if self.optimizer_type == \"default\":\n            self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)\n        elif self.optimizer_type == \"sparse_adam\":\n            try:\n                self.optimizer = SparseGaussianAdam(l, lr=0.0, eps=1e-15)\n            except:\n                # A special version of the rasterizer is required to enable sparse adam\n                self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)\n\n        self.exposure_optimizer = torch.optim.Adam([self._exposure])\n\n        self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,\n                                                    lr_final=training_args.position_lr_final*self.spatial_lr_scale,\n                                                    lr_delay_mult=training_args.position_lr_delay_mult,\n                                                    max_steps=training_args.position_lr_max_steps)\n        \n        self.exposure_scheduler_args = get_expon_lr_func(training_args.exposure_lr_init, training_args.exposure_lr_final,\n                                                        lr_delay_steps=training_args.exposure_lr_delay_steps,\n                                                        lr_delay_mult=training_args.exposure_lr_delay_mult,\n                                                        max_steps=training_args.iterations)\n\n    def update_learning_rate(self, iteration):\n        ''' Learning rate scheduling per step '''\n        if self.pretrained_exposures is None:\n            for param_group in self.exposure_optimizer.param_groups:\n                param_group['lr'] = self.exposure_scheduler_args(iteration)\n\n        for param_group in self.optimizer.param_groups:\n            if param_group[\"name\"] == \"xyz\":\n                lr = self.xyz_scheduler_args(iteration)\n                param_group['lr'] = lr\n                return lr\n\n    def construct_list_of_attributes(self):\n        l = ['x', 'y', 'z', 'nx', 'ny', 'nz']\n        # All channels except the 3 DC\n        for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):\n            l.append('f_dc_{}'.format(i))\n        for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):\n            l.append('f_rest_{}'.format(i))\n        l.append('opacity')\n        for i in range(self._scaling.shape[1]):\n            l.append('scale_{}'.format(i))\n        for i in range(self._rotation.shape[1]):\n            l.append('rot_{}'.format(i))\n        return l\n\n    def save_ply(self, path):\n        mkdir_p(os.path.dirname(path))\n\n        xyz = self._xyz.detach().cpu().numpy()\n        normals = np.zeros_like(xyz)\n        f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n        f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()\n        opacities = self._opacity.detach().cpu().numpy()\n        scale = self._scaling.detach().cpu().numpy()\n        rotation = self._rotation.detach().cpu().numpy()\n\n        dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]\n\n        elements = np.empty(xyz.shape[0], dtype=dtype_full)\n        attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)\n        elements[:] = list(map(tuple, attributes))\n        el = PlyElement.describe(elements, 'vertex')\n        PlyData([el]).write(path)\n\n    def reset_opacity(self):\n        opacities_new = self.inverse_opacity_activation(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))\n        optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, \"opacity\")\n        self._opacity = optimizable_tensors[\"opacity\"]\n\n    def load_ply(self, path, use_train_test_exp = False):\n        plydata = PlyData.read(path)\n        if use_train_test_exp:\n            exposure_file = os.path.join(os.path.dirname(path), os.pardir, os.pardir, \"exposure.json\")\n            if os.path.exists(exposure_file):\n                with open(exposure_file, \"r\") as f:\n                    exposures = json.load(f)\n                self.pretrained_exposures = {image_name: torch.FloatTensor(exposures[image_name]).requires_grad_(False).cuda() for image_name in exposures}\n                print(f\"Pretrained exposures loaded.\")\n            else:\n                print(f\"No exposure to be loaded at {exposure_file}\")\n                self.pretrained_exposures = None\n\n        xyz = np.stack((np.asarray(plydata.elements[0][\"x\"]),\n                        np.asarray(plydata.elements[0][\"y\"]),\n                        np.asarray(plydata.elements[0][\"z\"])),  axis=1)\n        opacities = np.asarray(plydata.elements[0][\"opacity\"])[..., np.newaxis]\n\n        features_dc = np.zeros((xyz.shape[0], 3, 1))\n        features_dc[:, 0, 0] = np.asarray(plydata.elements[0][\"f_dc_0\"])\n        features_dc[:, 1, 0] = np.asarray(plydata.elements[0][\"f_dc_1\"])\n        features_dc[:, 2, 0] = np.asarray(plydata.elements[0][\"f_dc_2\"])\n\n        extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"f_rest_\")]\n        extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))\n        assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3\n        features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))\n        for idx, attr_name in enumerate(extra_f_names):\n            features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])\n        # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)\n        features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1))\n\n        scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"scale_\")]\n        scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))\n        scales = np.zeros((xyz.shape[0], len(scale_names)))\n        for idx, attr_name in enumerate(scale_names):\n            scales[:, idx] = np.asarray(plydata.elements[0][attr_name])\n\n        rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith(\"rot\")]\n        rot_names = sorted(rot_names, key = lambda x: int(x.split('_')[-1]))\n        rots = np.zeros((xyz.shape[0], len(rot_names)))\n        for idx, attr_name in enumerate(rot_names):\n            rots[:, idx] = np.asarray(plydata.elements[0][attr_name])\n\n        self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n        self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n        self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device=\"cuda\").transpose(1, 2).contiguous().requires_grad_(True))\n        self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n        self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n        self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device=\"cuda\").requires_grad_(True))\n\n        self.active_sh_degree = self.max_sh_degree\n\n    def replace_tensor_to_optimizer(self, tensor, name):\n        optimizable_tensors = {}\n        for group in self.optimizer.param_groups:\n            if group[\"name\"] == name:\n                stored_state = self.optimizer.state.get(group['params'][0], None)\n                stored_state[\"exp_avg\"] = torch.zeros_like(tensor)\n                stored_state[\"exp_avg_sq\"] = torch.zeros_like(tensor)\n\n                del self.optimizer.state[group['params'][0]]\n                group[\"params\"][0] = nn.Parameter(tensor.requires_grad_(True))\n                self.optimizer.state[group['params'][0]] = stored_state\n\n                optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n        return optimizable_tensors\n\n    def _prune_optimizer(self, mask):\n        optimizable_tensors = {}\n        for group in self.optimizer.param_groups:\n            stored_state = self.optimizer.state.get(group['params'][0], None)\n            if stored_state is not None:\n                stored_state[\"exp_avg\"] = stored_state[\"exp_avg\"][mask]\n                stored_state[\"exp_avg_sq\"] = stored_state[\"exp_avg_sq\"][mask]\n\n                del self.optimizer.state[group['params'][0]]\n                group[\"params\"][0] = nn.Parameter((group[\"params\"][0][mask].requires_grad_(True)))\n                self.optimizer.state[group['params'][0]] = stored_state\n\n                optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n            else:\n                group[\"params\"][0] = nn.Parameter(group[\"params\"][0][mask].requires_grad_(True))\n                optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n        return optimizable_tensors\n\n    def prune_points(self, mask):\n        valid_points_mask = ~mask\n        optimizable_tensors = self._prune_optimizer(valid_points_mask)\n\n        self._xyz = optimizable_tensors[\"xyz\"]\n        self._features_dc = optimizable_tensors[\"f_dc\"]\n        self._features_rest = optimizable_tensors[\"f_rest\"]\n        self._opacity = optimizable_tensors[\"opacity\"]\n        self._scaling = optimizable_tensors[\"scaling\"]\n        self._rotation = optimizable_tensors[\"rotation\"]\n\n        self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]\n\n        self.denom = self.denom[valid_points_mask]\n        self.max_radii2D = self.max_radii2D[valid_points_mask]\n        self.tmp_radii = self.tmp_radii[valid_points_mask]\n\n    def cat_tensors_to_optimizer(self, tensors_dict):\n        optimizable_tensors = {}\n        for group in self.optimizer.param_groups:\n            assert len(group[\"params\"]) == 1\n            extension_tensor = tensors_dict[group[\"name\"]]\n            stored_state = self.optimizer.state.get(group['params'][0], None)\n            if stored_state is not None:\n\n                stored_state[\"exp_avg\"] = torch.cat((stored_state[\"exp_avg\"], torch.zeros_like(extension_tensor)), dim=0)\n                stored_state[\"exp_avg_sq\"] = torch.cat((stored_state[\"exp_avg_sq\"], torch.zeros_like(extension_tensor)), dim=0)\n\n                del self.optimizer.state[group['params'][0]]\n                group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n                self.optimizer.state[group['params'][0]] = stored_state\n\n                optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n            else:\n                group[\"params\"][0] = nn.Parameter(torch.cat((group[\"params\"][0], extension_tensor), dim=0).requires_grad_(True))\n                optimizable_tensors[group[\"name\"]] = group[\"params\"][0]\n\n        return optimizable_tensors\n\n    def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation, new_tmp_radii):\n        d = {\"xyz\": new_xyz,\n        \"f_dc\": new_features_dc,\n        \"f_rest\": new_features_rest,\n        \"opacity\": new_opacities,\n        \"scaling\" : new_scaling,\n        \"rotation\" : new_rotation}\n\n        optimizable_tensors = self.cat_tensors_to_optimizer(d)\n        self._xyz = optimizable_tensors[\"xyz\"]\n        self._features_dc = optimizable_tensors[\"f_dc\"]\n        self._features_rest = optimizable_tensors[\"f_rest\"]\n        self._opacity = optimizable_tensors[\"opacity\"]\n        self._scaling = optimizable_tensors[\"scaling\"]\n        self._rotation = optimizable_tensors[\"rotation\"]\n\n        self.tmp_radii = torch.cat((self.tmp_radii, new_tmp_radii))\n        self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n        self.denom = torch.zeros((self.get_xyz.shape[0], 1), device=\"cuda\")\n        self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device=\"cuda\")\n\n    def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):\n        n_init_points = self.get_xyz.shape[0]\n        # Extract points that satisfy the gradient condition\n        padded_grad = torch.zeros((n_init_points), device=\"cuda\")\n        padded_grad[:grads.shape[0]] = grads.squeeze()\n        selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)\n        selected_pts_mask = torch.logical_and(selected_pts_mask,\n                                              torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)\n\n        stds = self.get_scaling[selected_pts_mask].repeat(N,1)\n        means =torch.zeros((stds.size(0), 3),device=\"cuda\")\n        samples = torch.normal(mean=means, std=stds)\n        rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1)\n        new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1) + self.get_xyz[selected_pts_mask].repeat(N, 1)\n        new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N))\n        new_rotation = self._rotation[selected_pts_mask].repeat(N,1)\n        new_features_dc = self._features_dc[selected_pts_mask].repeat(N,1,1)\n        new_features_rest = self._features_rest[selected_pts_mask].repeat(N,1,1)\n        new_opacity = self._opacity[selected_pts_mask].repeat(N,1)\n        new_tmp_radii = self.tmp_radii[selected_pts_mask].repeat(N)\n\n        self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation, new_tmp_radii)\n\n        prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device=\"cuda\", dtype=bool)))\n        self.prune_points(prune_filter)\n\n    def densify_and_clone(self, grads, grad_threshold, scene_extent):\n        # Extract points that satisfy the gradient condition\n        selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False)\n        selected_pts_mask = torch.logical_and(selected_pts_mask,\n                                              torch.max(self.get_scaling, dim=1).values <= self.percent_dense*scene_extent)\n        \n        new_xyz = self._xyz[selected_pts_mask]\n        new_features_dc = self._features_dc[selected_pts_mask]\n        new_features_rest = self._features_rest[selected_pts_mask]\n        new_opacities = self._opacity[selected_pts_mask]\n        new_scaling = self._scaling[selected_pts_mask]\n        new_rotation = self._rotation[selected_pts_mask]\n\n        new_tmp_radii = self.tmp_radii[selected_pts_mask]\n\n        self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation, new_tmp_radii)\n\n    def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size, radii):\n        grads = self.xyz_gradient_accum / self.denom\n        grads[grads.isnan()] = 0.0\n\n        self.tmp_radii = radii\n        self.densify_and_clone(grads, max_grad, extent)\n        self.densify_and_split(grads, max_grad, extent)\n\n        prune_mask = (self.get_opacity < min_opacity).squeeze()\n        if max_screen_size:\n            big_points_vs = self.max_radii2D > max_screen_size\n            big_points_ws = self.get_scaling.max(dim=1).values > 0.1 * extent\n            prune_mask = torch.logical_or(torch.logical_or(prune_mask, big_points_vs), big_points_ws)\n        self.prune_points(prune_mask)\n        tmp_radii = self.tmp_radii\n        self.tmp_radii = None\n\n        torch.cuda.empty_cache()\n\n    def add_densification_stats(self, viewspace_point_tensor, update_filter):\n        self.xyz_gradient_accum[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,:2], dim=-1, keepdim=True)\n        self.denom[update_filter] += 1\n"
  },
  {
    "path": "train.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport os\nimport torch\nfrom random import randint\nfrom utils.loss_utils import l1_loss, ssim\nfrom gaussian_renderer import render, network_gui\nimport sys\nfrom scene import Scene, GaussianModel\nfrom utils.general_utils import safe_state, get_expon_lr_func\nimport uuid\nfrom tqdm import tqdm\nfrom utils.image_utils import psnr\nfrom argparse import ArgumentParser, Namespace\nfrom arguments import ModelParams, PipelineParams, OptimizationParams\ntry:\n    from torch.utils.tensorboard import SummaryWriter\n    TENSORBOARD_FOUND = True\nexcept ImportError:\n    TENSORBOARD_FOUND = False\n\ntry:\n    from fused_ssim import fused_ssim\n    FUSED_SSIM_AVAILABLE = True\nexcept:\n    FUSED_SSIM_AVAILABLE = False\n\ntry:\n    from diff_gaussian_rasterization import SparseGaussianAdam\n    SPARSE_ADAM_AVAILABLE = True\nexcept:\n    SPARSE_ADAM_AVAILABLE = False\n\ndef training(dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from):\n\n    if not SPARSE_ADAM_AVAILABLE and opt.optimizer_type == \"sparse_adam\":\n        sys.exit(f\"Trying to use sparse adam but it is not installed, please install the correct rasterizer using pip install [3dgs_accel].\")\n\n    first_iter = 0\n    tb_writer = prepare_output_and_logger(dataset)\n    gaussians = GaussianModel(dataset.sh_degree, opt.optimizer_type)\n    scene = Scene(dataset, gaussians)\n    gaussians.training_setup(opt)\n    if checkpoint:\n        (model_params, first_iter) = torch.load(checkpoint)\n        gaussians.restore(model_params, opt)\n\n    bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0]\n    background = torch.tensor(bg_color, dtype=torch.float32, device=\"cuda\")\n\n    iter_start = torch.cuda.Event(enable_timing = True)\n    iter_end = torch.cuda.Event(enable_timing = True)\n\n    use_sparse_adam = opt.optimizer_type == \"sparse_adam\" and SPARSE_ADAM_AVAILABLE \n    depth_l1_weight = get_expon_lr_func(opt.depth_l1_weight_init, opt.depth_l1_weight_final, max_steps=opt.iterations)\n\n    viewpoint_stack = scene.getTrainCameras().copy()\n    viewpoint_indices = list(range(len(viewpoint_stack)))\n    ema_loss_for_log = 0.0\n    ema_Ll1depth_for_log = 0.0\n\n    progress_bar = tqdm(range(first_iter, opt.iterations), desc=\"Training progress\")\n    first_iter += 1\n    for iteration in range(first_iter, opt.iterations + 1):\n        if network_gui.conn == None:\n            network_gui.try_connect()\n        while network_gui.conn != None:\n            try:\n                net_image_bytes = None\n                custom_cam, do_training, pipe.convert_SHs_python, pipe.compute_cov3D_python, keep_alive, scaling_modifer = network_gui.receive()\n                if custom_cam != None:\n                    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\"]\n                    net_image_bytes = memoryview((torch.clamp(net_image, min=0, max=1.0) * 255).byte().permute(1, 2, 0).contiguous().cpu().numpy())\n                network_gui.send(net_image_bytes, dataset.source_path)\n                if do_training and ((iteration < int(opt.iterations)) or not keep_alive):\n                    break\n            except Exception as e:\n                network_gui.conn = None\n\n        iter_start.record()\n\n        gaussians.update_learning_rate(iteration)\n\n        # Every 1000 its we increase the levels of SH up to a maximum degree\n        if iteration % 1000 == 0:\n            gaussians.oneupSHdegree()\n\n        # Pick a random Camera\n        if not viewpoint_stack:\n            viewpoint_stack = scene.getTrainCameras().copy()\n            viewpoint_indices = list(range(len(viewpoint_stack)))\n        rand_idx = randint(0, len(viewpoint_indices) - 1)\n        viewpoint_cam = viewpoint_stack.pop(rand_idx)\n        vind = viewpoint_indices.pop(rand_idx)\n\n        # Render\n        if (iteration - 1) == debug_from:\n            pipe.debug = True\n\n        bg = torch.rand((3), device=\"cuda\") if opt.random_background else background\n\n        render_pkg = render(viewpoint_cam, gaussians, pipe, bg, use_trained_exp=dataset.train_test_exp, separate_sh=SPARSE_ADAM_AVAILABLE)\n        image, viewspace_point_tensor, visibility_filter, radii = render_pkg[\"render\"], render_pkg[\"viewspace_points\"], render_pkg[\"visibility_filter\"], render_pkg[\"radii\"]\n\n        if viewpoint_cam.alpha_mask is not None:\n            alpha_mask = viewpoint_cam.alpha_mask.cuda()\n            image *= alpha_mask\n\n        # Loss\n        gt_image = viewpoint_cam.original_image.cuda()\n        Ll1 = l1_loss(image, gt_image)\n        if FUSED_SSIM_AVAILABLE:\n            ssim_value = fused_ssim(image.unsqueeze(0), gt_image.unsqueeze(0))\n        else:\n            ssim_value = ssim(image, gt_image)\n\n        loss = (1.0 - opt.lambda_dssim) * Ll1 + opt.lambda_dssim * (1.0 - ssim_value)\n\n        # Depth regularization\n        Ll1depth_pure = 0.0\n        if depth_l1_weight(iteration) > 0 and viewpoint_cam.depth_reliable:\n            invDepth = render_pkg[\"depth\"]\n            mono_invdepth = viewpoint_cam.invdepthmap.cuda()\n            depth_mask = viewpoint_cam.depth_mask.cuda()\n\n            Ll1depth_pure = torch.abs((invDepth  - mono_invdepth) * depth_mask).mean()\n            Ll1depth = depth_l1_weight(iteration) * Ll1depth_pure \n            loss += Ll1depth\n            Ll1depth = Ll1depth.item()\n        else:\n            Ll1depth = 0\n\n        loss.backward()\n\n        iter_end.record()\n\n        with torch.no_grad():\n            # Progress bar\n            ema_loss_for_log = 0.4 * loss.item() + 0.6 * ema_loss_for_log\n            ema_Ll1depth_for_log = 0.4 * Ll1depth + 0.6 * ema_Ll1depth_for_log\n\n            if iteration % 10 == 0:\n                progress_bar.set_postfix({\"Loss\": f\"{ema_loss_for_log:.{7}f}\", \"Depth Loss\": f\"{ema_Ll1depth_for_log:.{7}f}\"})\n                progress_bar.update(10)\n            if iteration == opt.iterations:\n                progress_bar.close()\n\n            # Log and save\n            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)\n            if (iteration in saving_iterations):\n                print(\"\\n[ITER {}] Saving Gaussians\".format(iteration))\n                scene.save(iteration)\n\n            # Densification\n            if iteration < opt.densify_until_iter:\n                # Keep track of max radii in image-space for pruning\n                gaussians.max_radii2D[visibility_filter] = torch.max(gaussians.max_radii2D[visibility_filter], radii[visibility_filter])\n                gaussians.add_densification_stats(viewspace_point_tensor, visibility_filter)\n\n                if iteration > opt.densify_from_iter and iteration % opt.densification_interval == 0:\n                    size_threshold = 20 if iteration > opt.opacity_reset_interval else None\n                    gaussians.densify_and_prune(opt.densify_grad_threshold, 0.005, scene.cameras_extent, size_threshold, radii)\n                \n                if iteration % opt.opacity_reset_interval == 0 or (dataset.white_background and iteration == opt.densify_from_iter):\n                    gaussians.reset_opacity()\n\n            # Optimizer step\n            if iteration < opt.iterations:\n                gaussians.exposure_optimizer.step()\n                gaussians.exposure_optimizer.zero_grad(set_to_none = True)\n                if use_sparse_adam:\n                    visible = radii > 0\n                    gaussians.optimizer.step(visible, radii.shape[0])\n                    gaussians.optimizer.zero_grad(set_to_none = True)\n                else:\n                    gaussians.optimizer.step()\n                    gaussians.optimizer.zero_grad(set_to_none = True)\n\n            if (iteration in checkpoint_iterations):\n                print(\"\\n[ITER {}] Saving Checkpoint\".format(iteration))\n                torch.save((gaussians.capture(), iteration), scene.model_path + \"/chkpnt\" + str(iteration) + \".pth\")\n\ndef prepare_output_and_logger(args):    \n    if not args.model_path:\n        if os.getenv('OAR_JOB_ID'):\n            unique_str=os.getenv('OAR_JOB_ID')\n        else:\n            unique_str = str(uuid.uuid4())\n        args.model_path = os.path.join(\"./output/\", unique_str[0:10])\n        \n    # Set up output folder\n    print(\"Output folder: {}\".format(args.model_path))\n    os.makedirs(args.model_path, exist_ok = True)\n    with open(os.path.join(args.model_path, \"cfg_args\"), 'w') as cfg_log_f:\n        cfg_log_f.write(str(Namespace(**vars(args))))\n\n    # Create Tensorboard writer\n    tb_writer = None\n    if TENSORBOARD_FOUND:\n        tb_writer = SummaryWriter(args.model_path)\n    else:\n        print(\"Tensorboard not available: not logging progress\")\n    return tb_writer\n\ndef training_report(tb_writer, iteration, Ll1, loss, l1_loss, elapsed, testing_iterations, scene : Scene, renderFunc, renderArgs, train_test_exp):\n    if tb_writer:\n        tb_writer.add_scalar('train_loss_patches/l1_loss', Ll1.item(), iteration)\n        tb_writer.add_scalar('train_loss_patches/total_loss', loss.item(), iteration)\n        tb_writer.add_scalar('iter_time', elapsed, iteration)\n\n    # Report test and samples of training set\n    if iteration in testing_iterations:\n        torch.cuda.empty_cache()\n        validation_configs = ({'name': 'test', 'cameras' : scene.getTestCameras()}, \n                              {'name': 'train', 'cameras' : [scene.getTrainCameras()[idx % len(scene.getTrainCameras())] for idx in range(5, 30, 5)]})\n\n        for config in validation_configs:\n            if config['cameras'] and len(config['cameras']) > 0:\n                l1_test = 0.0\n                psnr_test = 0.0\n                for idx, viewpoint in enumerate(config['cameras']):\n                    image = torch.clamp(renderFunc(viewpoint, scene.gaussians, *renderArgs)[\"render\"], 0.0, 1.0)\n                    gt_image = torch.clamp(viewpoint.original_image.to(\"cuda\"), 0.0, 1.0)\n                    if train_test_exp:\n                        image = image[..., image.shape[-1] // 2:]\n                        gt_image = gt_image[..., gt_image.shape[-1] // 2:]\n                    if tb_writer and (idx < 5):\n                        tb_writer.add_images(config['name'] + \"_view_{}/render\".format(viewpoint.image_name), image[None], global_step=iteration)\n                        if iteration == testing_iterations[0]:\n                            tb_writer.add_images(config['name'] + \"_view_{}/ground_truth\".format(viewpoint.image_name), gt_image[None], global_step=iteration)\n                    l1_test += l1_loss(image, gt_image).mean().double()\n                    psnr_test += psnr(image, gt_image).mean().double()\n                psnr_test /= len(config['cameras'])\n                l1_test /= len(config['cameras'])          \n                print(\"\\n[ITER {}] Evaluating {}: L1 {} PSNR {}\".format(iteration, config['name'], l1_test, psnr_test))\n                if tb_writer:\n                    tb_writer.add_scalar(config['name'] + '/loss_viewpoint - l1_loss', l1_test, iteration)\n                    tb_writer.add_scalar(config['name'] + '/loss_viewpoint - psnr', psnr_test, iteration)\n\n        if tb_writer:\n            tb_writer.add_histogram(\"scene/opacity_histogram\", scene.gaussians.get_opacity, iteration)\n            tb_writer.add_scalar('total_points', scene.gaussians.get_xyz.shape[0], iteration)\n        torch.cuda.empty_cache()\n\nif __name__ == \"__main__\":\n    # Set up command line argument parser\n    parser = ArgumentParser(description=\"Training script parameters\")\n    lp = ModelParams(parser)\n    op = OptimizationParams(parser)\n    pp = PipelineParams(parser)\n    parser.add_argument('--ip', type=str, default=\"127.0.0.1\")\n    parser.add_argument('--port', type=int, default=6009)\n    parser.add_argument('--debug_from', type=int, default=-1)\n    parser.add_argument('--detect_anomaly', action='store_true', default=False)\n    parser.add_argument(\"--test_iterations\", nargs=\"+\", type=int, default=[7_000, 30_000])\n    parser.add_argument(\"--save_iterations\", nargs=\"+\", type=int, default=[7_000, 30_000])\n    parser.add_argument(\"--quiet\", action=\"store_true\")\n    parser.add_argument('--disable_viewer', action='store_true', default=False)\n    parser.add_argument(\"--checkpoint_iterations\", nargs=\"+\", type=int, default=[])\n    parser.add_argument(\"--start_checkpoint\", type=str, default = None)\n    args = parser.parse_args(sys.argv[1:])\n    args.save_iterations.append(args.iterations)\n    \n    print(\"Optimizing \" + args.model_path)\n\n    # Initialize system state (RNG)\n    safe_state(args.quiet)\n\n    # Start GUI server, configure and run training\n    if not args.disable_viewer:\n        network_gui.init(args.ip, args.port)\n    torch.autograd.set_detect_anomaly(args.detect_anomaly)\n    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)\n\n    # All done\n    print(\"\\nTraining complete.\")\n"
  },
  {
    "path": "utils/camera_utils.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nfrom scene.cameras import Camera\nimport numpy as np\nfrom utils.graphics_utils import fov2focal\nfrom PIL import Image\nimport cv2\n\nWARNED = False\n\ndef loadCam(args, id, cam_info, resolution_scale, is_nerf_synthetic, is_test_dataset):\n    image = Image.open(cam_info.image_path)\n\n    if cam_info.depth_path != \"\":\n        try:\n            if is_nerf_synthetic:\n                invdepthmap = cv2.imread(cam_info.depth_path, -1).astype(np.float32) / 512\n            else:\n                invdepthmap = cv2.imread(cam_info.depth_path, -1).astype(np.float32) / float(2**16)\n\n        except FileNotFoundError:\n            print(f\"Error: The depth file at path '{cam_info.depth_path}' was not found.\")\n            raise\n        except IOError:\n            print(f\"Error: Unable to open the image file '{cam_info.depth_path}'. It may be corrupted or an unsupported format.\")\n            raise\n        except Exception as e:\n            print(f\"An unexpected error occurred when trying to read depth at {cam_info.depth_path}: {e}\")\n            raise\n    else:\n        invdepthmap = None\n        \n    orig_w, orig_h = image.size\n    if args.resolution in [1, 2, 4, 8]:\n        resolution = round(orig_w/(resolution_scale * args.resolution)), round(orig_h/(resolution_scale * args.resolution))\n    else:  # should be a type that converts to float\n        if args.resolution == -1:\n            if orig_w > 1600:\n                global WARNED\n                if not WARNED:\n                    print(\"[ INFO ] Encountered quite large input images (>1.6K pixels width), rescaling to 1.6K.\\n \"\n                        \"If this is not desired, please explicitly specify '--resolution/-r' as 1\")\n                    WARNED = True\n                global_down = orig_w / 1600\n            else:\n                global_down = 1\n        else:\n            global_down = orig_w / args.resolution\n    \n\n        scale = float(global_down) * float(resolution_scale)\n        resolution = (int(orig_w / scale), int(orig_h / scale))\n\n    return Camera(resolution, colmap_id=cam_info.uid, R=cam_info.R, T=cam_info.T, \n                  FoVx=cam_info.FovX, FoVy=cam_info.FovY, depth_params=cam_info.depth_params,\n                  image=image, invdepthmap=invdepthmap,\n                  image_name=cam_info.image_name, uid=id, data_device=args.data_device,\n                  train_test_exp=args.train_test_exp, is_test_dataset=is_test_dataset, is_test_view=cam_info.is_test)\n\ndef cameraList_from_camInfos(cam_infos, resolution_scale, args, is_nerf_synthetic, is_test_dataset):\n    camera_list = []\n\n    for id, c in enumerate(cam_infos):\n        camera_list.append(loadCam(args, id, c, resolution_scale, is_nerf_synthetic, is_test_dataset))\n\n    return camera_list\n\ndef camera_to_JSON(id, camera : Camera):\n    Rt = np.zeros((4, 4))\n    Rt[:3, :3] = camera.R.transpose()\n    Rt[:3, 3] = camera.T\n    Rt[3, 3] = 1.0\n\n    W2C = np.linalg.inv(Rt)\n    pos = W2C[:3, 3]\n    rot = W2C[:3, :3]\n    serializable_array_2d = [x.tolist() for x in rot]\n    camera_entry = {\n        'id' : id,\n        'img_name' : camera.image_name,\n        'width' : camera.width,\n        'height' : camera.height,\n        'position': pos.tolist(),\n        'rotation': serializable_array_2d,\n        'fy' : fov2focal(camera.FovY, camera.height),\n        'fx' : fov2focal(camera.FovX, camera.width)\n    }\n    return camera_entry"
  },
  {
    "path": "utils/general_utils.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport torch\nimport sys\nfrom datetime import datetime\nimport numpy as np\nimport random\n\ndef inverse_sigmoid(x):\n    return torch.log(x/(1-x))\n\ndef PILtoTorch(pil_image, resolution):\n    resized_image_PIL = pil_image.resize(resolution)\n    resized_image = torch.from_numpy(np.array(resized_image_PIL)) / 255.0\n    if len(resized_image.shape) == 3:\n        return resized_image.permute(2, 0, 1)\n    else:\n        return resized_image.unsqueeze(dim=-1).permute(2, 0, 1)\n\ndef get_expon_lr_func(\n    lr_init, lr_final, lr_delay_steps=0, lr_delay_mult=1.0, max_steps=1000000\n):\n    \"\"\"\n    Copied from Plenoxels\n\n    Continuous learning rate decay function. Adapted from JaxNeRF\n    The returned rate is lr_init when step=0 and lr_final when step=max_steps, and\n    is log-linearly interpolated elsewhere (equivalent to exponential decay).\n    If lr_delay_steps>0 then the learning rate will be scaled by some smooth\n    function of lr_delay_mult, such that the initial learning rate is\n    lr_init*lr_delay_mult at the beginning of optimization but will be eased back\n    to the normal learning rate when steps>lr_delay_steps.\n    :param conf: config subtree 'lr' or similar\n    :param max_steps: int, the number of steps during optimization.\n    :return HoF which takes step as input\n    \"\"\"\n\n    def helper(step):\n        if step < 0 or (lr_init == 0.0 and lr_final == 0.0):\n            # Disable this parameter\n            return 0.0\n        if lr_delay_steps > 0:\n            # A kind of reverse cosine decay.\n            delay_rate = lr_delay_mult + (1 - lr_delay_mult) * np.sin(\n                0.5 * np.pi * np.clip(step / lr_delay_steps, 0, 1)\n            )\n        else:\n            delay_rate = 1.0\n        t = np.clip(step / max_steps, 0, 1)\n        log_lerp = np.exp(np.log(lr_init) * (1 - t) + np.log(lr_final) * t)\n        return delay_rate * log_lerp\n\n    return helper\n\ndef strip_lowerdiag(L):\n    uncertainty = torch.zeros((L.shape[0], 6), dtype=torch.float, device=\"cuda\")\n\n    uncertainty[:, 0] = L[:, 0, 0]\n    uncertainty[:, 1] = L[:, 0, 1]\n    uncertainty[:, 2] = L[:, 0, 2]\n    uncertainty[:, 3] = L[:, 1, 1]\n    uncertainty[:, 4] = L[:, 1, 2]\n    uncertainty[:, 5] = L[:, 2, 2]\n    return uncertainty\n\ndef strip_symmetric(sym):\n    return strip_lowerdiag(sym)\n\ndef build_rotation(r):\n    norm = torch.sqrt(r[:,0]*r[:,0] + r[:,1]*r[:,1] + r[:,2]*r[:,2] + r[:,3]*r[:,3])\n\n    q = r / norm[:, None]\n\n    R = torch.zeros((q.size(0), 3, 3), device='cuda')\n\n    r = q[:, 0]\n    x = q[:, 1]\n    y = q[:, 2]\n    z = q[:, 3]\n\n    R[:, 0, 0] = 1 - 2 * (y*y + z*z)\n    R[:, 0, 1] = 2 * (x*y - r*z)\n    R[:, 0, 2] = 2 * (x*z + r*y)\n    R[:, 1, 0] = 2 * (x*y + r*z)\n    R[:, 1, 1] = 1 - 2 * (x*x + z*z)\n    R[:, 1, 2] = 2 * (y*z - r*x)\n    R[:, 2, 0] = 2 * (x*z - r*y)\n    R[:, 2, 1] = 2 * (y*z + r*x)\n    R[:, 2, 2] = 1 - 2 * (x*x + y*y)\n    return R\n\ndef build_scaling_rotation(s, r):\n    L = torch.zeros((s.shape[0], 3, 3), dtype=torch.float, device=\"cuda\")\n    R = build_rotation(r)\n\n    L[:,0,0] = s[:,0]\n    L[:,1,1] = s[:,1]\n    L[:,2,2] = s[:,2]\n\n    L = R @ L\n    return L\n\ndef safe_state(silent):\n    old_f = sys.stdout\n    class F:\n        def __init__(self, silent):\n            self.silent = silent\n\n        def write(self, x):\n            if not self.silent:\n                if x.endswith(\"\\n\"):\n                    old_f.write(x.replace(\"\\n\", \" [{}]\\n\".format(str(datetime.now().strftime(\"%d/%m %H:%M:%S\")))))\n                else:\n                    old_f.write(x)\n\n        def flush(self):\n            old_f.flush()\n\n    sys.stdout = F(silent)\n\n    random.seed(0)\n    np.random.seed(0)\n    torch.manual_seed(0)\n    torch.cuda.set_device(torch.device(\"cuda:0\"))\n"
  },
  {
    "path": "utils/graphics_utils.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport torch\nimport math\nimport numpy as np\nfrom typing import NamedTuple\n\nclass BasicPointCloud(NamedTuple):\n    points : np.array\n    colors : np.array\n    normals : np.array\n\ndef geom_transform_points(points, transf_matrix):\n    P, _ = points.shape\n    ones = torch.ones(P, 1, dtype=points.dtype, device=points.device)\n    points_hom = torch.cat([points, ones], dim=1)\n    points_out = torch.matmul(points_hom, transf_matrix.unsqueeze(0))\n\n    denom = points_out[..., 3:] + 0.0000001\n    return (points_out[..., :3] / denom).squeeze(dim=0)\n\ndef getWorld2View(R, t):\n    Rt = np.zeros((4, 4))\n    Rt[:3, :3] = R.transpose()\n    Rt[:3, 3] = t\n    Rt[3, 3] = 1.0\n    return np.float32(Rt)\n\ndef getWorld2View2(R, t, translate=np.array([.0, .0, .0]), scale=1.0):\n    Rt = np.zeros((4, 4))\n    Rt[:3, :3] = R.transpose()\n    Rt[:3, 3] = t\n    Rt[3, 3] = 1.0\n\n    C2W = np.linalg.inv(Rt)\n    cam_center = C2W[:3, 3]\n    cam_center = (cam_center + translate) * scale\n    C2W[:3, 3] = cam_center\n    Rt = np.linalg.inv(C2W)\n    return np.float32(Rt)\n\ndef getProjectionMatrix(znear, zfar, fovX, fovY):\n    tanHalfFovY = math.tan((fovY / 2))\n    tanHalfFovX = math.tan((fovX / 2))\n\n    top = tanHalfFovY * znear\n    bottom = -top\n    right = tanHalfFovX * znear\n    left = -right\n\n    P = torch.zeros(4, 4)\n\n    z_sign = 1.0\n\n    P[0, 0] = 2.0 * znear / (right - left)\n    P[1, 1] = 2.0 * znear / (top - bottom)\n    P[0, 2] = (right + left) / (right - left)\n    P[1, 2] = (top + bottom) / (top - bottom)\n    P[3, 2] = z_sign\n    P[2, 2] = z_sign * zfar / (zfar - znear)\n    P[2, 3] = -(zfar * znear) / (zfar - znear)\n    return P\n\ndef fov2focal(fov, pixels):\n    return pixels / (2 * math.tan(fov / 2))\n\ndef focal2fov(focal, pixels):\n    return 2*math.atan(pixels/(2*focal))"
  },
  {
    "path": "utils/image_utils.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport torch\n\ndef mse(img1, img2):\n    return (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n\ndef psnr(img1, img2):\n    mse = (((img1 - img2)) ** 2).view(img1.shape[0], -1).mean(1, keepdim=True)\n    return 20 * torch.log10(1.0 / torch.sqrt(mse))\n"
  },
  {
    "path": "utils/loss_utils.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom math import exp\ntry:\n    from diff_gaussian_rasterization._C import fusedssim, fusedssim_backward\nexcept:\n    pass\n\nC1 = 0.01 ** 2\nC2 = 0.03 ** 2\n\nclass FusedSSIMMap(torch.autograd.Function):\n    @staticmethod\n    def forward(ctx, C1, C2, img1, img2):\n        ssim_map = fusedssim(C1, C2, img1, img2)\n        ctx.save_for_backward(img1.detach(), img2)\n        ctx.C1 = C1\n        ctx.C2 = C2\n        return ssim_map\n\n    @staticmethod\n    def backward(ctx, opt_grad):\n        img1, img2 = ctx.saved_tensors\n        C1, C2 = ctx.C1, ctx.C2\n        grad = fusedssim_backward(C1, C2, img1, img2, opt_grad)\n        return None, None, grad, None\n\ndef l1_loss(network_output, gt):\n    return torch.abs((network_output - gt)).mean()\n\ndef l2_loss(network_output, gt):\n    return ((network_output - gt) ** 2).mean()\n\ndef gaussian(window_size, sigma):\n    gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])\n    return gauss / gauss.sum()\n\ndef create_window(window_size, channel):\n    _1D_window = gaussian(window_size, 1.5).unsqueeze(1)\n    _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n    window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())\n    return window\n\ndef ssim(img1, img2, window_size=11, size_average=True):\n    channel = img1.size(-3)\n    window = create_window(window_size, channel)\n\n    if img1.is_cuda:\n        window = window.cuda(img1.get_device())\n    window = window.type_as(img1)\n\n    return _ssim(img1, img2, window, window_size, channel, size_average)\n\ndef _ssim(img1, img2, window, window_size, channel, size_average=True):\n    mu1 = F.conv2d(img1, window, padding=window_size // 2, groups=channel)\n    mu2 = F.conv2d(img2, window, padding=window_size // 2, groups=channel)\n\n    mu1_sq = mu1.pow(2)\n    mu2_sq = mu2.pow(2)\n    mu1_mu2 = mu1 * mu2\n\n    sigma1_sq = F.conv2d(img1 * img1, window, padding=window_size // 2, groups=channel) - mu1_sq\n    sigma2_sq = F.conv2d(img2 * img2, window, padding=window_size // 2, groups=channel) - mu2_sq\n    sigma12 = F.conv2d(img1 * img2, window, padding=window_size // 2, groups=channel) - mu1_mu2\n\n    C1 = 0.01 ** 2\n    C2 = 0.03 ** 2\n\n    ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n\n    if size_average:\n        return ssim_map.mean()\n    else:\n        return ssim_map.mean(1).mean(1).mean(1)\n\n\ndef fast_ssim(img1, img2):\n    ssim_map = FusedSSIMMap.apply(C1, C2, img1, img2)\n    return ssim_map.mean()\n"
  },
  {
    "path": "utils/make_depth_scale.py",
    "content": "import numpy as np\nimport argparse\nimport cv2\nfrom joblib import delayed, Parallel\nimport json\nfrom read_write_model import *\n\ndef get_scales(key, cameras, images, points3d_ordered, args):\n    image_meta = images[key]\n    cam_intrinsic = cameras[image_meta.camera_id]\n\n    pts_idx = images_metas[key].point3D_ids\n\n    mask = pts_idx >= 0\n    mask *= pts_idx < len(points3d_ordered)\n\n    pts_idx = pts_idx[mask]\n    valid_xys = image_meta.xys[mask]\n\n    if len(pts_idx) > 0:\n        pts = points3d_ordered[pts_idx]\n    else:\n        pts = np.array([0, 0, 0])\n\n    R = qvec2rotmat(image_meta.qvec)\n    pts = np.dot(pts, R.T) + image_meta.tvec\n\n    invcolmapdepth = 1. / pts[..., 2] \n    n_remove = len(image_meta.name.split('.')[-1]) + 1\n    invmonodepthmap = cv2.imread(f\"{args.depths_dir}/{image_meta.name[:-n_remove]}.png\", cv2.IMREAD_UNCHANGED)\n    \n    if invmonodepthmap is None:\n        return None\n    \n    if invmonodepthmap.ndim != 2:\n        invmonodepthmap = invmonodepthmap[..., 0]\n\n    invmonodepthmap = invmonodepthmap.astype(np.float32) / (2**16)\n    s = invmonodepthmap.shape[0] / cam_intrinsic.height\n\n    maps = (valid_xys * s).astype(np.float32)\n    valid = (\n        (maps[..., 0] >= 0) * \n        (maps[..., 1] >= 0) * \n        (maps[..., 0] < cam_intrinsic.width * s) * \n        (maps[..., 1] < cam_intrinsic.height * s) * (invcolmapdepth > 0))\n    \n    if valid.sum() > 10 and (invcolmapdepth.max() - invcolmapdepth.min()) > 1e-3:\n        maps = maps[valid, :]\n        invcolmapdepth = invcolmapdepth[valid]\n        invmonodepth = cv2.remap(invmonodepthmap, maps[..., 0], maps[..., 1], interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)[..., 0]\n        \n        ## Median / dev\n        t_colmap = np.median(invcolmapdepth)\n        s_colmap = np.mean(np.abs(invcolmapdepth - t_colmap))\n\n        t_mono = np.median(invmonodepth)\n        s_mono = np.mean(np.abs(invmonodepth - t_mono))\n        scale = s_colmap / s_mono\n        offset = t_colmap - t_mono * scale\n    else:\n        scale = 0\n        offset = 0\n    return {\"image_name\": image_meta.name[:-n_remove], \"scale\": scale, \"offset\": offset}\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--base_dir', default=\"../data/big_gaussians/standalone_chunks/campus\")\n    parser.add_argument('--depths_dir', default=\"../data/big_gaussians/standalone_chunks/campus/depths_any\")\n    parser.add_argument('--model_type', default=\"bin\")\n    args = parser.parse_args()\n\n\n    cam_intrinsics, images_metas, points3d = read_model(os.path.join(args.base_dir, \"sparse\", \"0\"), ext=f\".{args.model_type}\")\n\n    pts_indices = np.array([points3d[key].id for key in points3d])\n    pts_xyzs = np.array([points3d[key].xyz for key in points3d])\n    points3d_ordered = np.zeros([pts_indices.max()+1, 3])\n    points3d_ordered[pts_indices] = pts_xyzs\n\n    # depth_param_list = [get_scales(key, cam_intrinsics, images_metas, points3d_ordered, args) for key in images_metas]\n    depth_param_list = Parallel(n_jobs=-1, backend=\"threading\")(\n        delayed(get_scales)(key, cam_intrinsics, images_metas, points3d_ordered, args) for key in images_metas\n    )\n\n    depth_params = {\n        depth_param[\"image_name\"]: {\"scale\": depth_param[\"scale\"], \"offset\": depth_param[\"offset\"]}\n        for depth_param in depth_param_list if depth_param != None\n    }\n\n    with open(f\"{args.base_dir}/sparse/0/depth_params.json\", \"w\") as f:\n        json.dump(depth_params, f, indent=2)\n\n    print(0)\n"
  },
  {
    "path": "utils/read_write_model.py",
    "content": "# Copyright (c) 2023, ETH Zurich and UNC Chapel Hill.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n#     * Redistributions of source code must retain the above copyright\n#       notice, this list of conditions and the following disclaimer.\n#\n#     * Redistributions in binary form must reproduce the above copyright\n#       notice, this list of conditions and the following disclaimer in the\n#       documentation and/or other materials provided with the distribution.\n#\n#     * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of\n#       its contributors may be used to endorse or promote products derived\n#       from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n\nimport os\nimport collections\nimport numpy as np\nimport struct\nimport argparse\n\n\nCameraModel = collections.namedtuple(\n    \"CameraModel\", [\"model_id\", \"model_name\", \"num_params\"]\n)\nCamera = collections.namedtuple(\n    \"Camera\", [\"id\", \"model\", \"width\", \"height\", \"params\"]\n)\nBaseImage = collections.namedtuple(\n    \"Image\", [\"id\", \"qvec\", \"tvec\", \"camera_id\", \"name\", \"xys\", \"point3D_ids\"]\n)\nPoint3D = collections.namedtuple(\n    \"Point3D\", [\"id\", \"xyz\", \"rgb\", \"error\", \"image_ids\", \"point2D_idxs\"]\n)\n\n\nclass Image(BaseImage):\n    def qvec2rotmat(self):\n        return qvec2rotmat(self.qvec)\n\n\nCAMERA_MODELS = {\n    CameraModel(model_id=0, model_name=\"SIMPLE_PINHOLE\", num_params=3),\n    CameraModel(model_id=1, model_name=\"PINHOLE\", num_params=4),\n    CameraModel(model_id=2, model_name=\"SIMPLE_RADIAL\", num_params=4),\n    CameraModel(model_id=3, model_name=\"RADIAL\", num_params=5),\n    CameraModel(model_id=4, model_name=\"OPENCV\", num_params=8),\n    CameraModel(model_id=5, model_name=\"OPENCV_FISHEYE\", num_params=8),\n    CameraModel(model_id=6, model_name=\"FULL_OPENCV\", num_params=12),\n    CameraModel(model_id=7, model_name=\"FOV\", num_params=5),\n    CameraModel(model_id=8, model_name=\"SIMPLE_RADIAL_FISHEYE\", num_params=4),\n    CameraModel(model_id=9, model_name=\"RADIAL_FISHEYE\", num_params=5),\n    CameraModel(model_id=10, model_name=\"THIN_PRISM_FISHEYE\", num_params=12),\n}\nCAMERA_MODEL_IDS = dict(\n    [(camera_model.model_id, camera_model) for camera_model in CAMERA_MODELS]\n)\nCAMERA_MODEL_NAMES = dict(\n    [(camera_model.model_name, camera_model) for camera_model in CAMERA_MODELS]\n)\n\n\ndef read_next_bytes(fid, num_bytes, format_char_sequence, endian_character=\"<\"):\n    \"\"\"Read and unpack the next bytes from a binary file.\n    :param fid:\n    :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.\n    :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n    :param endian_character: Any of {@, =, <, >, !}\n    :return: Tuple of read and unpacked values.\n    \"\"\"\n    data = fid.read(num_bytes)\n    return struct.unpack(endian_character + format_char_sequence, data)\n\n\ndef write_next_bytes(fid, data, format_char_sequence, endian_character=\"<\"):\n    \"\"\"pack and write to a binary file.\n    :param fid:\n    :param data: data to send, if multiple elements are sent at the same time,\n    they should be encapsuled either in a list or a tuple\n    :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.\n    should be the same length as the data list or tuple\n    :param endian_character: Any of {@, =, <, >, !}\n    \"\"\"\n    if isinstance(data, (list, tuple)):\n        bytes = struct.pack(endian_character + format_char_sequence, *data)\n    else:\n        bytes = struct.pack(endian_character + format_char_sequence, data)\n    fid.write(bytes)\n\n\ndef read_cameras_text(path):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::WriteCamerasText(const std::string& path)\n        void Reconstruction::ReadCamerasText(const std::string& path)\n    \"\"\"\n    cameras = {}\n    with open(path, \"r\") as fid:\n        while True:\n            line = fid.readline()\n            if not line:\n                break\n            line = line.strip()\n            if len(line) > 0 and line[0] != \"#\":\n                elems = line.split()\n                camera_id = int(elems[0])\n                model = elems[1]\n                width = int(elems[2])\n                height = int(elems[3])\n                params = np.array(tuple(map(float, elems[4:])))\n                cameras[camera_id] = Camera(\n                    id=camera_id,\n                    model=model,\n                    width=width,\n                    height=height,\n                    params=params,\n                )\n    return cameras\n\n\ndef read_cameras_binary(path_to_model_file):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::WriteCamerasBinary(const std::string& path)\n        void Reconstruction::ReadCamerasBinary(const std::string& path)\n    \"\"\"\n    cameras = {}\n    with open(path_to_model_file, \"rb\") as fid:\n        num_cameras = read_next_bytes(fid, 8, \"Q\")[0]\n        for _ in range(num_cameras):\n            camera_properties = read_next_bytes(\n                fid, num_bytes=24, format_char_sequence=\"iiQQ\"\n            )\n            camera_id = camera_properties[0]\n            model_id = camera_properties[1]\n            model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name\n            width = camera_properties[2]\n            height = camera_properties[3]\n            num_params = CAMERA_MODEL_IDS[model_id].num_params\n            params = read_next_bytes(\n                fid,\n                num_bytes=8 * num_params,\n                format_char_sequence=\"d\" * num_params,\n            )\n            cameras[camera_id] = Camera(\n                id=camera_id,\n                model=model_name,\n                width=width,\n                height=height,\n                params=np.array(params),\n            )\n        assert len(cameras) == num_cameras\n    return cameras\n\n\ndef write_cameras_text(cameras, path):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::WriteCamerasText(const std::string& path)\n        void Reconstruction::ReadCamerasText(const std::string& path)\n    \"\"\"\n    HEADER = (\n        \"# Camera list with one line of data per camera:\\n\"\n        + \"#   CAMERA_ID, MODEL, WIDTH, HEIGHT, PARAMS[]\\n\"\n        + \"# Number of cameras: {}\\n\".format(len(cameras))\n    )\n    with open(path, \"w\") as fid:\n        fid.write(HEADER)\n        for _, cam in cameras.items():\n            to_write = [cam.id, cam.model, cam.width, cam.height, *cam.params]\n            line = \" \".join([str(elem) for elem in to_write])\n            fid.write(line + \"\\n\")\n\n\ndef write_cameras_binary(cameras, path_to_model_file):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::WriteCamerasBinary(const std::string& path)\n        void Reconstruction::ReadCamerasBinary(const std::string& path)\n    \"\"\"\n    with open(path_to_model_file, \"wb\") as fid:\n        write_next_bytes(fid, len(cameras), \"Q\")\n        for _, cam in cameras.items():\n            model_id = CAMERA_MODEL_NAMES[cam.model].model_id\n            camera_properties = [cam.id, model_id, cam.width, cam.height]\n            write_next_bytes(fid, camera_properties, \"iiQQ\")\n            for p in cam.params:\n                write_next_bytes(fid, float(p), \"d\")\n    return cameras\n\n\ndef read_images_text(path):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::ReadImagesText(const std::string& path)\n        void Reconstruction::WriteImagesText(const std::string& path)\n    \"\"\"\n    images = {}\n    with open(path, \"r\") as fid:\n        while True:\n            line = fid.readline()\n            if not line:\n                break\n            line = line.strip()\n            if len(line) > 0 and line[0] != \"#\":\n                elems = line.split()\n                image_id = int(elems[0])\n                qvec = np.array(tuple(map(float, elems[1:5])))\n                tvec = np.array(tuple(map(float, elems[5:8])))\n                camera_id = int(elems[8])\n                image_name = elems[9]\n                elems = fid.readline().split()\n                xys = np.column_stack(\n                    [\n                        tuple(map(float, elems[0::3])),\n                        tuple(map(float, elems[1::3])),\n                    ]\n                )\n                point3D_ids = np.array(tuple(map(int, elems[2::3])))\n                images[image_id] = Image(\n                    id=image_id,\n                    qvec=qvec,\n                    tvec=tvec,\n                    camera_id=camera_id,\n                    name=image_name,\n                    xys=xys,\n                    point3D_ids=point3D_ids,\n                )\n    return images\n\n\ndef read_images_binary(path_to_model_file):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::ReadImagesBinary(const std::string& path)\n        void Reconstruction::WriteImagesBinary(const std::string& path)\n    \"\"\"\n    images = {}\n    with open(path_to_model_file, \"rb\") as fid:\n        num_reg_images = read_next_bytes(fid, 8, \"Q\")[0]\n        for _ in range(num_reg_images):\n            binary_image_properties = read_next_bytes(\n                fid, num_bytes=64, format_char_sequence=\"idddddddi\"\n            )\n            image_id = binary_image_properties[0]\n            qvec = np.array(binary_image_properties[1:5])\n            tvec = np.array(binary_image_properties[5:8])\n            camera_id = binary_image_properties[8]\n            image_name = \"\"\n            current_char = read_next_bytes(fid, 1, \"c\")[0]\n            while current_char != b\"\\x00\":  # look for the ASCII 0 entry\n                image_name += current_char.decode(\"utf-8\")\n                current_char = read_next_bytes(fid, 1, \"c\")[0]\n            num_points2D = read_next_bytes(\n                fid, num_bytes=8, format_char_sequence=\"Q\"\n            )[0]\n            x_y_id_s = read_next_bytes(\n                fid,\n                num_bytes=24 * num_points2D,\n                format_char_sequence=\"ddq\" * num_points2D,\n            )\n            xys = np.column_stack(\n                [\n                    tuple(map(float, x_y_id_s[0::3])),\n                    tuple(map(float, x_y_id_s[1::3])),\n                ]\n            )\n            point3D_ids = np.array(tuple(map(int, x_y_id_s[2::3])))\n            images[image_id] = Image(\n                id=image_id,\n                qvec=qvec,\n                tvec=tvec,\n                camera_id=camera_id,\n                name=image_name,\n                xys=xys,\n                point3D_ids=point3D_ids,\n            )\n    return images\n\n\ndef write_images_text(images, path):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::ReadImagesText(const std::string& path)\n        void Reconstruction::WriteImagesText(const std::string& path)\n    \"\"\"\n    if len(images) == 0:\n        mean_observations = 0\n    else:\n        mean_observations = sum(\n            (len(img.point3D_ids) for _, img in images.items())\n        ) / len(images)\n    HEADER = (\n        \"# Image list with two lines of data per image:\\n\"\n        + \"#   IMAGE_ID, QW, QX, QY, QZ, TX, TY, TZ, CAMERA_ID, NAME\\n\"\n        + \"#   POINTS2D[] as (X, Y, POINT3D_ID)\\n\"\n        + \"# Number of images: {}, mean observations per image: {}\\n\".format(\n            len(images), mean_observations\n        )\n    )\n\n    with open(path, \"w\") as fid:\n        fid.write(HEADER)\n        for _, img in images.items():\n            image_header = [\n                img.id,\n                *img.qvec,\n                *img.tvec,\n                img.camera_id,\n                img.name,\n            ]\n            first_line = \" \".join(map(str, image_header))\n            fid.write(first_line + \"\\n\")\n\n            points_strings = []\n            for xy, point3D_id in zip(img.xys, img.point3D_ids):\n                points_strings.append(\" \".join(map(str, [*xy, point3D_id])))\n            fid.write(\" \".join(points_strings) + \"\\n\")\n\n\ndef write_images_binary(images, path_to_model_file):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::ReadImagesBinary(const std::string& path)\n        void Reconstruction::WriteImagesBinary(const std::string& path)\n    \"\"\"\n    with open(path_to_model_file, \"wb\") as fid:\n        write_next_bytes(fid, len(images), \"Q\")\n        for _, img in images.items():\n            write_next_bytes(fid, img.id, \"i\")\n            write_next_bytes(fid, img.qvec.tolist(), \"dddd\")\n            write_next_bytes(fid, img.tvec.tolist(), \"ddd\")\n            write_next_bytes(fid, img.camera_id, \"i\")\n            for char in img.name:\n                write_next_bytes(fid, char.encode(\"utf-8\"), \"c\")\n            write_next_bytes(fid, b\"\\x00\", \"c\")\n            write_next_bytes(fid, len(img.point3D_ids), \"Q\")\n            for xy, p3d_id in zip(img.xys, img.point3D_ids):\n                write_next_bytes(fid, [*xy, p3d_id], \"ddq\")\n\n\ndef read_points3D_text(path):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::ReadPoints3DText(const std::string& path)\n        void Reconstruction::WritePoints3DText(const std::string& path)\n    \"\"\"\n    points3D = {}\n    with open(path, \"r\") as fid:\n        while True:\n            line = fid.readline()\n            if not line:\n                break\n            line = line.strip()\n            if len(line) > 0 and line[0] != \"#\":\n                elems = line.split()\n                point3D_id = int(elems[0])\n                xyz = np.array(tuple(map(float, elems[1:4])))\n                rgb = np.array(tuple(map(int, elems[4:7])))\n                error = float(elems[7])\n                image_ids = np.array(tuple(map(int, elems[8::2])))\n                point2D_idxs = np.array(tuple(map(int, elems[9::2])))\n                points3D[point3D_id] = Point3D(\n                    id=point3D_id,\n                    xyz=xyz,\n                    rgb=rgb,\n                    error=error,\n                    image_ids=image_ids,\n                    point2D_idxs=point2D_idxs,\n                )\n    return points3D\n\n\ndef read_points3D_binary(path_to_model_file):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::ReadPoints3DBinary(const std::string& path)\n        void Reconstruction::WritePoints3DBinary(const std::string& path)\n    \"\"\"\n    points3D = {}\n    with open(path_to_model_file, \"rb\") as fid:\n        num_points = read_next_bytes(fid, 8, \"Q\")[0]\n        for _ in range(num_points):\n            binary_point_line_properties = read_next_bytes(\n                fid, num_bytes=43, format_char_sequence=\"QdddBBBd\"\n            )\n            point3D_id = binary_point_line_properties[0]\n            xyz = np.array(binary_point_line_properties[1:4])\n            rgb = np.array(binary_point_line_properties[4:7])\n            error = np.array(binary_point_line_properties[7])\n            track_length = read_next_bytes(\n                fid, num_bytes=8, format_char_sequence=\"Q\"\n            )[0]\n            track_elems = read_next_bytes(\n                fid,\n                num_bytes=8 * track_length,\n                format_char_sequence=\"ii\" * track_length,\n            )\n            image_ids = np.array(tuple(map(int, track_elems[0::2])))\n            point2D_idxs = np.array(tuple(map(int, track_elems[1::2])))\n            points3D[point3D_id] = Point3D(\n                id=point3D_id,\n                xyz=xyz,\n                rgb=rgb,\n                error=error,\n                image_ids=image_ids,\n                point2D_idxs=point2D_idxs,\n            )\n    return points3D\n\n\ndef write_points3D_text(points3D, path):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::ReadPoints3DText(const std::string& path)\n        void Reconstruction::WritePoints3DText(const std::string& path)\n    \"\"\"\n    if len(points3D) == 0:\n        mean_track_length = 0\n    else:\n        mean_track_length = sum(\n            (len(pt.image_ids) for _, pt in points3D.items())\n        ) / len(points3D)\n    HEADER = (\n        \"# 3D point list with one line of data per point:\\n\"\n        + \"#   POINT3D_ID, X, Y, Z, R, G, B, ERROR, TRACK[] as (IMAGE_ID, POINT2D_IDX)\\n\"\n        + \"# Number of points: {}, mean track length: {}\\n\".format(\n            len(points3D), mean_track_length\n        )\n    )\n\n    with open(path, \"w\") as fid:\n        fid.write(HEADER)\n        for _, pt in points3D.items():\n            point_header = [pt.id, *pt.xyz, *pt.rgb, pt.error]\n            fid.write(\" \".join(map(str, point_header)) + \" \")\n            track_strings = []\n            for image_id, point2D in zip(pt.image_ids, pt.point2D_idxs):\n                track_strings.append(\" \".join(map(str, [image_id, point2D])))\n            fid.write(\" \".join(track_strings) + \"\\n\")\n\n\ndef write_points3D_binary(points3D, path_to_model_file):\n    \"\"\"\n    see: src/colmap/scene/reconstruction.cc\n        void Reconstruction::ReadPoints3DBinary(const std::string& path)\n        void Reconstruction::WritePoints3DBinary(const std::string& path)\n    \"\"\"\n    with open(path_to_model_file, \"wb\") as fid:\n        write_next_bytes(fid, len(points3D), \"Q\")\n        for _, pt in points3D.items():\n            write_next_bytes(fid, pt.id, \"Q\")\n            write_next_bytes(fid, pt.xyz.tolist(), \"ddd\")\n            write_next_bytes(fid, pt.rgb.tolist(), \"BBB\")\n            write_next_bytes(fid, pt.error, \"d\")\n            track_length = pt.image_ids.shape[0]\n            write_next_bytes(fid, track_length, \"Q\")\n            for image_id, point2D_id in zip(pt.image_ids, pt.point2D_idxs):\n                write_next_bytes(fid, [image_id, point2D_id], \"ii\")\n\n\ndef detect_model_format(path, ext):\n    if (\n        os.path.isfile(os.path.join(path, \"cameras\" + ext))\n        and os.path.isfile(os.path.join(path, \"images\" + ext))\n        and os.path.isfile(os.path.join(path, \"points3D\" + ext))\n    ):\n        print(\"Detected model format: '\" + ext + \"'\")\n        return True\n\n    return False\n\n\ndef read_model(path, ext=\"\"):\n    # try to detect the extension automatically\n    if ext == \"\":\n        if detect_model_format(path, \".bin\"):\n            ext = \".bin\"\n        elif detect_model_format(path, \".txt\"):\n            ext = \".txt\"\n        else:\n            print(\"Provide model format: '.bin' or '.txt'\")\n            return\n\n    if ext == \".txt\":\n        cameras = read_cameras_text(os.path.join(path, \"cameras\" + ext))\n        images = read_images_text(os.path.join(path, \"images\" + ext))\n        points3D = read_points3D_text(os.path.join(path, \"points3D\") + ext)\n    else:\n        cameras = read_cameras_binary(os.path.join(path, \"cameras\" + ext))\n        images = read_images_binary(os.path.join(path, \"images\" + ext))\n        points3D = read_points3D_binary(os.path.join(path, \"points3D\") + ext)\n    return cameras, images, points3D\n\n\ndef write_model(cameras, images, points3D, path, ext=\".bin\"):\n    if ext == \".txt\":\n        write_cameras_text(cameras, os.path.join(path, \"cameras\" + ext))\n        write_images_text(images, os.path.join(path, \"images\" + ext))\n        write_points3D_text(points3D, os.path.join(path, \"points3D\") + ext)\n    else:\n        write_cameras_binary(cameras, os.path.join(path, \"cameras\" + ext))\n        write_images_binary(images, os.path.join(path, \"images\" + ext))\n        write_points3D_binary(points3D, os.path.join(path, \"points3D\") + ext)\n    return cameras, images, points3D\n\n\ndef qvec2rotmat(qvec):\n    return np.array(\n        [\n            [\n                1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2,\n                2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],\n                2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2],\n            ],\n            [\n                2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],\n                1 - 2 * qvec[1] ** 2 - 2 * qvec[3] ** 2,\n                2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1],\n            ],\n            [\n                2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],\n                2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],\n                1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2,\n            ],\n        ]\n    )\n\n\ndef rotmat2qvec(R):\n    Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat\n    K = (\n        np.array(\n            [\n                [Rxx - Ryy - Rzz, 0, 0, 0],\n                [Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],\n                [Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],\n                [Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz],\n            ]\n        )\n        / 3.0\n    )\n    eigvals, eigvecs = np.linalg.eigh(K)\n    qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]\n    if qvec[0] < 0:\n        qvec *= -1\n    return qvec\n\n\n# def main():\n#     parser = argparse.ArgumentParser(\n#         description=\"Read and write COLMAP binary and text models\"\n#     )\n#     parser.add_argument(\"--input_model\", help=\"path to input model folder\")\n#     parser.add_argument(\n#         \"--input_format\",\n#         choices=[\".bin\", \".txt\"],\n#         help=\"input model format\",\n#         default=\"\",\n#     )\n#     parser.add_argument(\"--output_model\", help=\"path to output model folder\")\n#     parser.add_argument(\n#         \"--output_format\",\n#         choices=[\".bin\", \".txt\"],\n#         help=\"outut model format\",\n#         default=\".txt\",\n#     )\n#     args = parser.parse_args()\n\n#     cameras, images, points3D = read_model(\n#         path=args.input_model, ext=args.input_format\n#     )\n\n#     print(\"num_cameras:\", len(cameras))\n#     print(\"num_images:\", len(images))\n#     print(\"num_points3D:\", len(points3D))\n\n#     if args.output_model is not None:\n#         write_model(\n#             cameras,\n#             images,\n#             points3D,\n#             path=args.output_model,\n#             ext=args.output_format,\n#         )\n\n\n# if __name__ == \"__main__\":\n#     main()\n"
  },
  {
    "path": "utils/sh_utils.py",
    "content": "#  Copyright 2021 The PlenOctree Authors.\n#  Redistribution and use in source and binary forms, with or without\n#  modification, are permitted provided that the following conditions are met:\n#\n#  1. Redistributions of source code must retain the above copyright notice,\n#  this list of conditions and the following disclaimer.\n#\n#  2. Redistributions in binary form must reproduce the above copyright notice,\n#  this list of conditions and the following disclaimer in the documentation\n#  and/or other materials provided with the distribution.\n#\n#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n#  POSSIBILITY OF SUCH DAMAGE.\n\nimport torch\n\nC0 = 0.28209479177387814\nC1 = 0.4886025119029199\nC2 = [\n    1.0925484305920792,\n    -1.0925484305920792,\n    0.31539156525252005,\n    -1.0925484305920792,\n    0.5462742152960396\n]\nC3 = [\n    -0.5900435899266435,\n    2.890611442640554,\n    -0.4570457994644658,\n    0.3731763325901154,\n    -0.4570457994644658,\n    1.445305721320277,\n    -0.5900435899266435\n]\nC4 = [\n    2.5033429417967046,\n    -1.7701307697799304,\n    0.9461746957575601,\n    -0.6690465435572892,\n    0.10578554691520431,\n    -0.6690465435572892,\n    0.47308734787878004,\n    -1.7701307697799304,\n    0.6258357354491761,\n]   \n\n\ndef eval_sh(deg, sh, dirs):\n    \"\"\"\n    Evaluate spherical harmonics at unit directions\n    using hardcoded SH polynomials.\n    Works with torch/np/jnp.\n    ... Can be 0 or more batch dimensions.\n    Args:\n        deg: int SH deg. Currently, 0-3 supported\n        sh: jnp.ndarray SH coeffs [..., C, (deg + 1) ** 2]\n        dirs: jnp.ndarray unit directions [..., 3]\n    Returns:\n        [..., C]\n    \"\"\"\n    assert deg <= 4 and deg >= 0\n    coeff = (deg + 1) ** 2\n    assert sh.shape[-1] >= coeff\n\n    result = C0 * sh[..., 0]\n    if deg > 0:\n        x, y, z = dirs[..., 0:1], dirs[..., 1:2], dirs[..., 2:3]\n        result = (result -\n                C1 * y * sh[..., 1] +\n                C1 * z * sh[..., 2] -\n                C1 * x * sh[..., 3])\n\n        if deg > 1:\n            xx, yy, zz = x * x, y * y, z * z\n            xy, yz, xz = x * y, y * z, x * z\n            result = (result +\n                    C2[0] * xy * sh[..., 4] +\n                    C2[1] * yz * sh[..., 5] +\n                    C2[2] * (2.0 * zz - xx - yy) * sh[..., 6] +\n                    C2[3] * xz * sh[..., 7] +\n                    C2[4] * (xx - yy) * sh[..., 8])\n\n            if deg > 2:\n                result = (result +\n                C3[0] * y * (3 * xx - yy) * sh[..., 9] +\n                C3[1] * xy * z * sh[..., 10] +\n                C3[2] * y * (4 * zz - xx - yy)* sh[..., 11] +\n                C3[3] * z * (2 * zz - 3 * xx - 3 * yy) * sh[..., 12] +\n                C3[4] * x * (4 * zz - xx - yy) * sh[..., 13] +\n                C3[5] * z * (xx - yy) * sh[..., 14] +\n                C3[6] * x * (xx - 3 * yy) * sh[..., 15])\n\n                if deg > 3:\n                    result = (result + C4[0] * xy * (xx - yy) * sh[..., 16] +\n                            C4[1] * yz * (3 * xx - yy) * sh[..., 17] +\n                            C4[2] * xy * (7 * zz - 1) * sh[..., 18] +\n                            C4[3] * yz * (7 * zz - 3) * sh[..., 19] +\n                            C4[4] * (zz * (35 * zz - 30) + 3) * sh[..., 20] +\n                            C4[5] * xz * (7 * zz - 3) * sh[..., 21] +\n                            C4[6] * (xx - yy) * (7 * zz - 1) * sh[..., 22] +\n                            C4[7] * xz * (xx - 3 * yy) * sh[..., 23] +\n                            C4[8] * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) * sh[..., 24])\n    return result\n\ndef RGB2SH(rgb):\n    return (rgb - 0.5) / C0\n\ndef SH2RGB(sh):\n    return sh * C0 + 0.5"
  },
  {
    "path": "utils/system_utils.py",
    "content": "#\n# Copyright (C) 2023, Inria\n# GRAPHDECO research group, https://team.inria.fr/graphdeco\n# All rights reserved.\n#\n# This software is free for non-commercial, research and evaluation use \n# under the terms of the LICENSE.md file.\n#\n# For inquiries contact  george.drettakis@inria.fr\n#\n\nfrom errno import EEXIST\nfrom os import makedirs, path\nimport os\n\ndef mkdir_p(folder_path):\n    # Creates a directory. equivalent to using mkdir -p on the command line\n    try:\n        makedirs(folder_path)\n    except OSError as exc: # Python >2.5\n        if exc.errno == EEXIST and path.isdir(folder_path):\n            pass\n        else:\n            raise\n\ndef searchForMaxIteration(folder):\n    saved_iters = [int(fname.split(\"_\")[-1]) for fname in os.listdir(folder)]\n    return max(saved_iters)\n"
  }
]