Merge branch 'main' into cmk/ns_add_plotly

This commit is contained in:
Gina Wu committed 2024-06-21 19:05:27 -07:00
commit b4a35190ba
26 files changed
+9713 -226

No files matched your search

+3
View File
@@ -188,3 +188,6 @@ camera_paths/
*/**/.DS_Store */**/.DS_Store
*/**/._.DS_Store */**/._.DS_Store
# pixi environments
.pixi
/third_party
+32 -25
View File
@@ -1,11 +1,14 @@
ARG CUDA_VERSION=11.8.0 ARG CUDA_VERSION=11.8.0
ARG OS_VERSION=22.04 ARG OS_VERSION=22.04
ARG USER_ID=1000
# Define base image. # Define base image.
FROM nvidia/cuda:${CUDA_VERSION}-devel-ubuntu${OS_VERSION} FROM nvidia/cuda:${CUDA_VERSION}-devel-ubuntu${OS_VERSION}
ARG CUDA_VERSION ARG CUDA_VERSION
ARG OS_VERSION ARG OS_VERSION
ARG USER_ID
# Define username, user uid and gid
ARG USERNAME=user
ARG USER_UID=1000
ARG USER_GID=$USER_UID
# metainformation # metainformation
LABEL org.opencontainers.image.version = "0.1.18" LABEL org.opencontainers.image.version = "0.1.18"
@@ -102,30 +105,38 @@ RUN git clone --branch 3.8 https://github.com/colmap/colmap.git --single-branch
cd ../.. && \ cd ../.. && \
rm -rf colmap rm -rf colmap
# Create non root user and setup environment. # Create non root user, add it to custom group and setup environment.
RUN useradd -m -d /home/user -g root -G sudo -u ${USER_ID} user RUN groupadd --gid $USER_GID $USERNAME \
RUN usermod -aG sudo user && useradd --uid $USER_UID --gid $USER_GID -m $USERNAME -d /home/${USERNAME} --shell /usr/bin/bash
# Set user password # OPTIONAL
RUN echo "user:user" | chpasswd # If sudo privilages are not required comment below line
# Ensure sudo group users are not asked for a password when using sudo command by ammending sudoers file # Create simple password for user and add it to sudo group
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers # Update group so that it is not required to type password for commands: apt update/upgrade/install/remove
RUN echo "${USERNAME}:password" | chpasswd \
&& usermod -aG sudo ${USERNAME} \
&& echo "%sudo ALL=NOPASSWD:/usr/bin/apt-get update, /usr/bin/apt-get upgrade, /usr/bin/apt-get install, /usr/bin/apt-get remove" >> /etc/sudoers
# Switch to new uer and workdir. # Create workspace folder and change ownership to new user
USER ${USER_ID} RUN mkdir /workspace && chown ${USER_UID}:${USER_GID} /workspace
WORKDIR /home/user
# Switch to new user and workdir.
USER ${USER_UID}
WORKDIR /home/${USERNAME}
# Add local user binary folder to PATH variable. # Add local user binary folder to PATH variable.
ENV PATH="${PATH}:/home/user/.local/bin" ENV PATH="${PATH}:/home/${USERNAME}/.local/bin"
SHELL ["/bin/bash", "-c"]
# Upgrade pip and install packages. # Upgrade pip and install packages.
RUN python3.10 -m pip install --no-cache-dir --upgrade pip setuptools pathtools promise pybind11 RUN python3.10 -m pip install --no-cache-dir --upgrade pip setuptools pathtools promise pybind11 omegaconf
# Install pytorch and submodules # Install pytorch and submodules
RUN CUDA_VER=${CUDA_VERSION%.*} && CUDA_VER=${CUDA_VER//./} && python3.10 -m pip install --no-cache-dir \ # echo "${CUDA_VERSION}" | sed 's/.$//' | tr -d '.' -- CUDA_VERSION -> delete last digit -> delete all '.'
RUN CUDA_VER=$(echo "${CUDA_VERSION}" | sed 's/.$//' | tr -d '.') && python3.10 -m pip install --no-cache-dir \
torch==2.0.1+cu${CUDA_VER} \ torch==2.0.1+cu${CUDA_VER} \
torchvision==0.15.2+cu${CUDA_VER} \ torchvision==0.15.2+cu${CUDA_VER} \
--extra-index-url https://download.pytorch.org/whl/cu${CUDA_VER} --extra-index-url https://download.pytorch.org/whl/cu${CUDA_VER}
# Install tynyCUDNN (we need to set the target architectures as environment variable first).
# Install tiny-cuda-nn (we need to set the target architectures as environment variable first).
ENV TCNN_CUDA_ARCHITECTURES=${CUDA_ARCHITECTURES} ENV TCNN_CUDA_ARCHITECTURES=${CUDA_ARCHITECTURES}
RUN python3.10 -m pip install --no-cache-dir git+https://github.com/NVlabs/tiny-cuda-nn.git@v1.6#subdirectory=bindings/torch RUN python3.10 -m pip install --no-cache-dir git+https://github.com/NVlabs/tiny-cuda-nn.git@v1.6#subdirectory=bindings/torch
@@ -156,23 +167,19 @@ RUN git clone --recursive https://github.com/cvg/pixel-perfect-sfm.git && \
python3.10 -m pip install --no-cache-dir -e . && \ python3.10 -m pip install --no-cache-dir -e . && \
cd .. cd ..
RUN python3.10 -m pip install --no-cache-dir omegaconf
# Copy nerfstudio folder and give ownership to user. # Copy nerfstudio folder and give ownership to user.
ADD . /home/user/nerfstudio COPY --chown=${USER_UID}:${USER_GID} . /home/${USERNAME}/nerfstudio
USER root
RUN chown -R user /home/user/nerfstudio
USER ${USER_ID}
# Install nerfstudio dependencies. # Install nerfstudio dependencies.
RUN cd nerfstudio && \ RUN cd nerfstudio && \
python3.10 -m pip install --no-cache-dir -e . && \ python3.10 -m pip install --no-cache-dir -e . && \
cd .. cd ..
# Change working directory # Switch to workspace folder and install nerfstudio cli auto completion
WORKDIR /workspace WORKDIR /workspace
# Install nerfstudio cli auto completion
RUN ns-install-cli --mode install RUN ns-install-cli --mode install
# Bash as default entrypoint. # Bash as default entrypoint.
CMD /bin/bash -l CMD /bin/bash -l
# Force changing password on first container run
# Change line above: CMD /bin/bash -l -> CMD /bin/bash -l -c passwd && /usr/bin/bash -l
+2
View File
@@ -159,6 +159,8 @@ This documentation is organized into 3 parts:
- [PyNeRF](nerfology/methods/pynerf.md): Pyramidal Neural Radiance Fields - [PyNeRF](nerfology/methods/pynerf.md): Pyramidal Neural Radiance Fields
- [SeaThru-NeRF](nerfology/methods/seathru_nerf.md): Neural Radiance Field for subsea scenes - [SeaThru-NeRF](nerfology/methods/seathru_nerf.md): Neural Radiance Field for subsea scenes
- [Zip-NeRF](nerfology/methods/zipnerf.md): Anti-Aliased Grid-Based Neural Radiance Fields - [Zip-NeRF](nerfology/methods/zipnerf.md): Anti-Aliased Grid-Based Neural Radiance Fields
- [NeRFtoGSandBack](nerfology/methods/nerf2gs2nerf.md): Converting back and forth between NeRF and GS to get the best of both approaches.
- [OpenNeRF](nerfology/methods/opennerf.md): OpenSet 3D Neural Scene Segmentation
**Eager to contribute a method?** We'd love to see you use nerfstudio in implementing new (or even existing) methods! Please view our {ref}`guide<own_method_docs>` for more details about how to add to this list! **Eager to contribute a method?** We'd love to see you use nerfstudio in implementing new (or even existing) methods! Please view our {ref}`guide<own_method_docs>` for more details about how to add to this list!
+2
View File
@@ -45,6 +45,8 @@ The following methods are supported in nerfstudio:
SeaThru-NeRF<seathru_nerf.md> SeaThru-NeRF<seathru_nerf.md>
Zip-NeRF<zipnerf.md> Zip-NeRF<zipnerf.md>
BioNeRF<bionerf.md> BioNeRF<bionerf.md>
NeRFtoGSandBack<nerf2gs2nerf.md>
OpenNeRF<opennerf.md>
``` ```
(own_method_docs)= (own_method_docs)=
+86
View File
@@ -0,0 +1,86 @@
# From NeRFs to Gaussian Splats, and Back
This is the implementation of [From NeRFs to Gaussian Splats, and Back](https://arxiv.org/abs/2405.09717); An efficient procedure to convert back and forth between NeRF and GS, and thereby get the best of both approaches. New dataset in the paper can be downloaded from [this google drive link](https://drive.google.com/drive/folders/1xvbONL4EVgHxaHMsV101455l_jNgyaUM?usp=sharing). The official code can be found [here](https://github.com/grasp-lyrl/NeRFtoGSandBack).
<video id="teaser" muted autoplay playsinline loop controls width="100%">
<source id="mp4" src="https://github.com/grasp-lyrl/NeRFtoGSandBack/blob/main/assets/Giannini_demo_compressed.mp4" type="video/mp4">
</video>
## Installation
This repository follows the nerfstudio method [template](https://github.com/nerfstudio-project/nerfstudio-method-template/tree/main)
### 0. Install Nerfstudio dependencies
Please follow the Nerfstudio [installation guide](https://docs.nerf.studio/quickstart/installation.html) to create an environment and install dependencies.
### 1. Install the repository
Clone and navigate into this repository. Run the following commands:
`pip install -e nerfsh`
and
`pip install -e nerfgs`.
Finally, run `ns-install-cli`.
### 2. Check installation
Run `ns-train --help`. You should be able to find two methods, `nerfsh` and `nerfgs`, in the list of methods.
## Downloading data
You could download the Giannini-Hall and aspen datasets from [this google drive link](https://drive.google.com/drive/folders/19TV6kdVGcmg3cGZ1bNIUnBBMD-iQjRbG). Our new dataset (Wissahickon and Locust-Walk) can be downloaded from [this google drive link](https://drive.google.com/drive/folders/1xvbONL4EVgHxaHMsV101455l_jNgyaUM?usp=sharing).
## NeRFGS: NeRFs to Gaussian Splats
### Training NeRF-SH
Run the following command for training. Replace `DATA_PATH` with the data directory location.
`ns-train nerfsh --data DATA_PATH --pipeline.model.camera-optimizer.mode off `
To train on Wissahickon or Locust-Walk dataset, you need to add `nerfstudio-data --eval-mode filename` to properly split training and validation data, i.e.,
`ns-train nerfsh --data DATA_PATH --pipeline.model.camera-optimizer.mode off nerfstudio-data --eval-mode filename`
### NeRFGS: Converting NeRF-SH to Guassian splats
Replace `CONFIG_LOCATION` with the location of config file saved after training.
`ns-export-nerfsh --load-config CONFIG_LOCATION --output-dir exports/nerfgs/ --num-points 2000000 --remove-outliers True --normal-method open3d --use_bounding_box False`
### Visualize converted Gaussian splats
Replace `DATA_PATH` with the data directory location. You also need to add `nerfstudio-data --eval-mode filename` if train on Wissahickon or Locust-Walk.
`ns-train nerfgs --data DATA_PATH --max-num-iterations 1 --pipeline.model.ply-file-path exports/nerfgs/nerfgs.ply`
### Fintuned NeRFGS
We reduces the learning rate for finetuning. You also need to add `nerfstudio-data --eval-mode filename` if train on Wissahickon or Locust-Walk.
`ns-train nerfgs --data DATA_PATH --pipeline.model.ply-file-path exports/nerfgs/nerfgs.ply --max-num-iterations 5000 --pipeline.model.sh-degree-interval 0 --pipeline.model.warmup-length 100 --optimizers.xyz.optimizer.lr 0.00001 --optimizers.xyz.scheduler.lr-pre-warmup 0.0000001 --optimizers.xyz.scheduler.lr-final 0.0000001 --optimizers.features-dc.optimizer.lr 0.01 --optimizers.features-rest.optimizer.lr 0.001 --optimizers.opacity.optimizer.lr 0.05 --optimizers.scaling.optimizer.lr 0.01 --optimizers.rotation.optimizer.lr 0.0000000001 --optimizers.camera-opt.optimizer.lr 0.0000000001 --optimizers.camera-opt.scheduler.lr-pre-warmup 0.0000000001 --optimizers.camera-opt.scheduler.lr-final 0.0000000001`
## GSNeRF: Gaussian Splats to NeRFs
### Scene modification
Coming soon
### Rendering new training images
In the new dataset, training images are rendered from splats. Replace `CONFIG_LOCATION` with the location of config file saved after training.
`ns-nerfgs-render --load-config CONFIG_LOCATION --render-output-path exports/splatting_data --export-nerf-gs-data`
### GSNeRF: Training on new training images
`ns-train nerfsh --data exports/splatting_data --pipeline.model.camera-optimizer.mode off nerfstudio-data --eval-mode filename`
## Extending the method
The conversion from NeRF to GS has inefficiency as mentioned at the discussion section of the paper. We welcome your efforts to reduce the inefficiency! The code for conversion is mainly in `nerfsh/nerfsh/nerfsh_exporter.py`.
## Method
<p align="center">
<img src="https://github.com/grasp-lyrl/NeRFtoGSandBack/blob/main/assets/overview.jpg">
</p>
### NeRF-SH
The NeRF-SH field structure is shown above in the overview figure. NeRF-SH is modified from Nerfacto to predict spherical harmonics (degree 3 by default) for each rgb channel. The volumetric rendering process remains unchanges: at each point along a ray, we predict the spherical harmonics and calculate color based on the view direction.
### NeRFGS
Given a trained NeRF-SH, we extract pointcloud based on rendered depth, following the pointcloud export pipeline in Nerfstudio. In addition to exporting the location of each point, we export spherical harmonic coefficients and density predicted by NeRF-SH. We exclude rays with low opacity or corresponding to the sky. We initialize each Gaussian as isotropic where the scale depends on the sparsity of points in the neighborhood. Specifically, the scale of each Gaussian is half of the average distance between each point and its three nearest neighbors. To avoid large Gaussians, the scale is clipped between 0 and 0.8-th quantile of the scales in the scene. The exported Gaussian splats already captures the geometric and photometric properties of the scene. To obtain fine-grained splats and remove outliers during exportation, we finetune the splats using training views.
### GSNeRF
After editing the Gaussian splats, rendered training views from edited Gaussian splats can be used to create a new dataset. The new dataset can be used to train/update other models (especially implicit representations that are difficult to edited directly).
+46
View File
@@ -0,0 +1,46 @@
# OpenNeRF
## OpenSet 3D Neural Scene Segmentation with Pixel-wise Features and Rendered Novel Views
```{button-link} https://opennerf.github.io/
:color: primary
:outline:
Paper Website
```
## Installation
Detailed installation instructions can be found at our [Project Page](https://github.com/opennerf/opennerf?tab=readme-ov-file#installation).
## Running OpenNeRF
Once installed, run:
```bash
ns-train opennerf --help
```
## Method
<img src=https://opennerf.github.io/static/images/teaser.png />
### Overview
Large visual-language models (VLMs), like CLIP, enable open-set image segmentation to segment arbitrary concepts from an image in a zero-shot manner. This goes beyond the traditional closed-set assumption, i.e., where models can only segment classes from a pre-defined training set. More recently, first works on open-set segmentation in 3D scenes have appeared in the literature. These methods are heavily influenced by closed-set 3D convolutional approaches that process point clouds or polygon meshes. However, these 3D scene representations do not align well with the image-based nature of the visual-language models. Indeed, point cloud and 3D meshes typically have a lower resolution than images and the reconstructed 3D scene geometry might not project well to the underlying 2D image sequences used to compute pixel-aligned CLIP features. To address these challenges, we propose OpenNeRF which naturally operates on posed images and directly encodes the VLM features within the NeRF. This is similar in spirit to LERF, however our work shows that using pixel-wise VLM features (instead of global CLIP features) results in an overall less complex architecture without the need for additional DINO regularization. Our OpenNeRF further leverages NeRF's ability to render novel views and extract open-set VLM features from areas that are not well observed in the initial posed images. For 3D point cloud segmentation on Replica, OpenNeRF outperforms recent open-vocabulary methods such as LERF and OpenScene by at least +4.9 mIoU.
## Zero-Shot 3D Semantic Segmentation on Replica
<img src="https://opennerf.github.io/static/visualizations/final_office0_.gif" />
<img src="https://opennerf.github.io/static/visualizations/final_office1_.gif" />
<img src="https://opennerf.github.io/static/visualizations/final_office2_.gif" />
## BibTeX
```
@inproceedings{engelmann2024opennerf,
title={{OpenNeRF: Open Set 3D Neural Scene Segmentation with Pixel-Wise Features and Rendered Novel Views}},
author={Engelmann, Francis and Manhardt, Fabian and Niemeyer, Michael and Tateno, Keisuke and Pollefeys, Marc and Tombari, Federico},
booktitle={International Conference on Learning Representations},
year={2024}
}
```
+2 -2
View File
@@ -39,13 +39,13 @@ We provide a few additional variants:
| `splatfacto-big` | More Gaussians, Higher Quality | ~12GB | Slower | | `splatfacto-big` | More Gaussians, Higher Quality | ~12GB | Slower |
A full evalaution of Nerfstudio's implementation of Gaussian Splatting against the original Inria method can be found [here](https://docs.gsplat.studio/tests/eval.html). A full evalaution of Nerfstudio's implementation of Gaussian Splatting against the original Inria method can be found [here](https://docs.gsplat.studio/main/tests/eval.html).
#### Quality and Regularization #### Quality and Regularization
The default settings provided maintain a balance between speed, quality, and splat file size, but if you care more about quality than training speed or size, you can decrease the alpha cull threshold The default settings provided maintain a balance between speed, quality, and splat file size, but if you care more about quality than training speed or size, you can decrease the alpha cull threshold
(threshold to delete translucent gaussians) and disable culling after 15k steps like so: `ns-train splatfacto --pipeline.model.cull_alpha_thresh=0.005 --pipeline.model.continue_cull_post_densification=False --data <data>` (threshold to delete translucent gaussians) and disable culling after 15k steps like so: `ns-train splatfacto --pipeline.model.cull_alpha_thresh=0.005 --pipeline.model.continue_cull_post_densification=False --data <data>`
A common artifact in splatting is long, spikey gaussians. [PhysGaussian](https://xpandora.github.io/PhysGaussian/) proposes a scale regularizer that encourages gaussians to be more evenly shaped. To enable this, set the `use_scale_regularization` flag to `True`. A common artifact in splatting is long, spikey gaussians. [PhysGaussian](https://xpandora.github.io/PhysGaussian/) proposes a scale regularizer that encourages gaussians to be more evenly shaped. To enable this, set the `pipeline.model.use_scale_regularization` flag to `True`.
### Details ### Details
For more details on the method, see the [original paper](https://arxiv.org/abs/2308.04079). Additionally, for a detailed derivation of the gradients used in the gsplat library, see [here](https://arxiv.org/abs/2312.02121). For more details on the method, see the [original paper](https://arxiv.org/abs/2308.04079). Additionally, for a detailed derivation of the gradients used in the gsplat library, see [here](https://arxiv.org/abs/2312.02121).
+74 -2
View File
@@ -14,6 +14,8 @@ Install [Git](https://git-scm.com/downloads).
Install Visual Studio 2022. This must be done before installing CUDA. The necessary components are included in the `Desktop Development with C++` workflow (also called `C++ Build Tools` in the BuildTools edition). Install Visual Studio 2022. This must be done before installing CUDA. The necessary components are included in the `Desktop Development with C++` workflow (also called `C++ Build Tools` in the BuildTools edition).
Install Visual Studio Build Tools. If MSVC 143 does not work (usually will fail if your version > 17.10), you may also need to install MSVC 142 for Visual Studio 2019. Ensure your CUDA environment is set up properly.
Nerfstudio requires `python >= 3.8`. We recommend using conda to manage dependencies. Make sure to install [Conda](https://docs.conda.io/en/latest/miniconda.html) before proceeding. Nerfstudio requires `python >= 3.8`. We recommend using conda to manage dependencies. Make sure to install [Conda](https://docs.conda.io/en/latest/miniconda.html) before proceeding.
::::: :::::
@@ -76,14 +78,55 @@ conda install -c "nvidia/label/cuda-11.7.1" cuda-toolkit
::: :::
:::: ::::
### tiny-cuda-nn ### Install tiny-cuda-nn/gsplat
::::::{tab-set}
:::::{tab-item} Linux
After pytorch and ninja, install the torch bindings for tiny-cuda-nn: After pytorch and ninja, install the torch bindings for tiny-cuda-nn:
```bash ```bash
pip install ninja git+https://github.com/NVlabs/tiny-cuda-nn/#subdirectory=bindings/torch pip install ninja git+https://github.com/NVlabs/tiny-cuda-nn/#subdirectory=bindings/torch
``` ```
:::::
:::::{tab-item} Windows
Activate your Visual C++ environment:
Navigate to the directory where `vcvars64.bat` is located. This path might vary depending on your installation. A common path is:
```
C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build
```
Run the following command:
```bash
./vcvars64.bat
```
If the above command does not work, try activating an older version of VC:
```bash
./vcvarsall.bat x64 -vcvars_ver=<your_VC++_compiler_toolset_version>
```
Replace `<your_VC++_compiler_toolset_version>` with the version of your VC++ compiler toolset. The version number should appear in the same folder.
For example:
```bash
./vcvarsall.bat x64 -vcvars_ver=14.29
```
Install `gsplat` from source:
```bash
pip install git+https://github.com/nerfstudio-project/gsplat.git
```
Install the torch bindings for tiny-cuda-nn:
```bash
pip install git+https://github.com/NVlabs/tiny-cuda-nn/#subdirectory=bindings/torch
```
:::::
::::::
## Installing nerfstudio ## Installing nerfstudio
**From pip** **From pip**
@@ -122,6 +165,35 @@ pip install -e .[dev]
pip install -e .[docs] pip install -e .[docs]
``` ```
## Using Pixi
[Pixi](https://pixi.sh/latest/) is a fast software package manager built on top of the existing conda ecosystem. Spins up development environments quickly on Windows, macOS and Linux. (Currently only linux is supported for nerfstudio)
### Prerequisites
Make sure to have pixi installed, detailed instructions [here](https://pixi.sh/latest/)
TLDR for linux:
```bash
curl -fsSL https://pixi.sh/install.sh | bash
```
### Install Pixi Environmnent
After Pixi is installed, you can run
```bash
pixi run post-install
pixi shell
```
This will install all enviroment dependancies including colmap, tinycudann and hloc, and the active the conda environment
you could also run
```bash
pixi run post-install
pixi run train-example-nerf
```
to download an example dataset and run nerfacto straight away
## Use docker image ## Use docker image
Instead of installing and compiling prerequisites, setting up the environment and installing dependencies, a ready to use docker image is provided. Instead of installing and compiling prerequisites, setting up the environment and installing dependencies, a ready to use docker image is provided.
+15 -6
View File
@@ -157,15 +157,24 @@ class CameraOptimizer(nn.Module):
if self.config.mode == "off": if self.config.mode == "off":
return camera.camera_to_worlds return camera.camera_to_worlds
assert camera.metadata is not None, "Must provide id of camera in its metadata" if camera.metadata is None or "cam_idx" not in camera.metadata:
if "cam_idx" not in camera.metadata: # Viser cameras
# Evalutaion cams?
return camera.camera_to_worlds return camera.camera_to_worlds
camera_idx = camera.metadata["cam_idx"] camera_idx = camera.metadata["cam_idx"]
adj = self(torch.tensor([camera_idx], dtype=torch.long, device=camera.device)) # type: ignore adj = self(torch.tensor([camera_idx], dtype=torch.long)).to(camera.device) # type: ignore
adj = torch.cat([adj, torch.Tensor([0, 0, 0, 1])[None, None].to(adj)], dim=1)
return torch.bmm(camera.camera_to_worlds, adj) return torch.cat(
[
# Apply rotation to directions in world coordinates, without touching the origin.
# Equivalent to: directions -> correction[:3,:3] @ directions
torch.bmm(adj[..., :3, :3], camera.camera_to_worlds[..., :3, :3]),
# Apply translation in world coordinate, independently of rotation.
# Equivalent to: origins -> origins + correction[:3,3]
camera.camera_to_worlds[..., :3, 3:] + adj[..., :3, 3:],
],
dim=-1,
)
def get_loss_dict(self, loss_dict: dict) -> None: def get_loss_dict(self, loss_dict: dict) -> None:
"""Add regularization""" """Add regularization"""
+1 -1
View File
@@ -170,7 +170,7 @@ class Cameras(TensorDataclass):
name: The name of the variable. Used for error messages name: The name of the variable. Used for error messages
""" """
if isinstance(fc_xy, float): if isinstance(fc_xy, float):
fc_xy = torch.Tensor([fc_xy], device=self.device) fc_xy = torch.tensor([fc_xy], device=self.device)
elif isinstance(fc_xy, torch.Tensor): elif isinstance(fc_xy, torch.Tensor):
if fc_xy.ndim == 0 or fc_xy.shape[-1] != 1: if fc_xy.ndim == 0 or fc_xy.shape[-1] != 1:
fc_xy = fc_xy.unsqueeze(-1) fc_xy = fc_xy.unsqueeze(-1)
+30
View File
@@ -238,6 +238,36 @@ To enable SIGNeRF, you must install it first by running:
) )
) )
# NeRF-SH
external_methods.append(
ExternalMethod(
"""[bold yellow]NeRF-SH[/bold yellow]
For more information visit: https://docs.nerf.studio/nerfology/methods/nerf2gs2nerf.html
To enable NeRF-SH, you must install it first by running:
[grey]pip install git+https://github.com/grasp-lyrl/NeRFtoGSandBack.git#subdirectory=nerfsh[/grey]""",
configurations=[
("nerfsh", "NeRF-SH, used in paper"),
],
pip_package="git+https://github.com/grasp-lyrl/NeRFtoGSandBack.git#subdirectory=nerfsh",
)
)
# NeRFGS
external_methods.append(
ExternalMethod(
"""[bold yellow]NeRFGS[/bold yellow]
For more information visit: https://docs.nerf.studio/nerfology/methods/nerf2gs2nerf.html
To enable NeRFGS, you must install it first by running:
[grey]pip install git+https://github.com/grasp-lyrl/NeRFtoGSandBack.git#subdirectory=nerfgs[/grey]""",
configurations=[
("nerfgs", "NeRFGS, used in paper"),
],
pip_package="git+https://github.com/grasp-lyrl/NeRFtoGSandBack.git#subdirectory=nerfgs",
)
)
@dataclass @dataclass
class ExternalMethodDummyTrainerConfig: class ExternalMethodDummyTrainerConfig:
+2
View File
@@ -68,6 +68,7 @@ from nerfstudio.plugins.registry import discover_methods
method_configs: Dict[str, Union[TrainerConfig, ExternalMethodDummyTrainerConfig]] = {} method_configs: Dict[str, Union[TrainerConfig, ExternalMethodDummyTrainerConfig]] = {}
descriptions = { descriptions = {
"nerfacto": "Recommended real-time model tuned for real captures. This model will be continually updated.", "nerfacto": "Recommended real-time model tuned for real captures. This model will be continually updated.",
"nerfacto-huge": "Larger version of Nerfacto with higher quality.",
"depth-nerfacto": "Nerfacto with depth supervision.", "depth-nerfacto": "Nerfacto with depth supervision.",
"instant-ngp": "Implementation of Instant-NGP. Recommended real-time model for unbounded scenes.", "instant-ngp": "Implementation of Instant-NGP. Recommended real-time model for unbounded scenes.",
"instant-ngp-bounded": "Implementation of Instant-NGP. Recommended for bounded real and synthetic scenes", "instant-ngp-bounded": "Implementation of Instant-NGP. Recommended for bounded real and synthetic scenes",
@@ -81,6 +82,7 @@ descriptions = {
"neus": "Implementation of NeuS. (slow)", "neus": "Implementation of NeuS. (slow)",
"neus-facto": "Implementation of NeuS-Facto. (slow)", "neus-facto": "Implementation of NeuS-Facto. (slow)",
"splatfacto": "Gaussian Splatting model", "splatfacto": "Gaussian Splatting model",
"splatfacto-big": "Larger version of Splatfacto with higher quality.",
} }
method_configs["nerfacto"] = TrainerConfig( method_configs["nerfacto"] = TrainerConfig(
@@ -30,6 +30,7 @@ from pathlib import Path
from typing import Dict, ForwardRef, Generic, List, Literal, Optional, Tuple, Type, Union, cast, get_args, get_origin from typing import Dict, ForwardRef, Generic, List, Literal, Optional, Tuple, Type, Union, cast, get_args, get_origin
import cv2 import cv2
import fpsample
import numpy as np import numpy as np
import torch import torch
from rich.progress import track from rich.progress import track
@@ -62,12 +63,22 @@ class FullImageDatamanagerConfig(DataManagerConfig):
new images. If -1, never pick new images.""" new images. If -1, never pick new images."""
eval_image_indices: Optional[Tuple[int, ...]] = (0,) eval_image_indices: Optional[Tuple[int, ...]] = (0,)
"""Specifies the image indices to use during eval; if None, uses all.""" """Specifies the image indices to use during eval; if None, uses all."""
cache_images: Literal["cpu", "gpu"] = "cpu" cache_images: Literal["cpu", "gpu"] = "gpu"
"""Whether to cache images in memory. If "cpu", caches on cpu. If "gpu", caches on device.""" """Whether to cache images in memory. If "cpu", caches on cpu. If "gpu", caches on device."""
cache_images_type: Literal["uint8", "float32"] = "float32" cache_images_type: Literal["uint8", "float32"] = "float32"
"""The image type returned from manager, caching images in uint8 saves memory""" """The image type returned from manager, caching images in uint8 saves memory"""
max_thread_workers: Optional[int] = None max_thread_workers: Optional[int] = None
"""The maximum number of threads to use for caching images. If None, uses all available threads.""" """The maximum number of threads to use for caching images. If None, uses all available threads."""
train_cameras_sampling_strategy: Literal["random", "fps"] = "random"
"""Specifies which sampling strategy is used to generate train cameras, 'random' means sampling
uniformly random without replacement, 'fps' means farthest point sampling which is helpful to reduce the artifacts
due to oversampling subsets of cameras that are very close to each other."""
train_cameras_sampling_seed: int = 42
"""Random seed for sampling train cameras. Fixing seed may help reduce variance of trained models across
different runs."""
fps_reset_every: int = 100
"""The number of iterations before one resets fps sampler repeatly, which is essentially drawing fps_reset_every
samples from the pool of all training cameras without replacement before a new round of sampling starts."""
class FullImageDatamanager(DataManager, Generic[TDataset]): class FullImageDatamanager(DataManager, Generic[TDataset]):
@@ -123,12 +134,48 @@ class FullImageDatamanager(DataManager, Generic[TDataset]):
self.exclude_batch_keys_from_device.remove("image") self.exclude_batch_keys_from_device.remove("image")
# Some logic to make sure we sample every camera in equal amounts # Some logic to make sure we sample every camera in equal amounts
self.train_unseen_cameras = [i for i in range(len(self.train_dataset))] self.train_unseen_cameras = self.sample_train_cameras()
self.eval_unseen_cameras = [i for i in range(len(self.eval_dataset))] self.eval_unseen_cameras = [i for i in range(len(self.eval_dataset))]
assert len(self.train_unseen_cameras) > 0, "No data found in dataset" assert len(self.train_unseen_cameras) > 0, "No data found in dataset"
super().__init__() super().__init__()
def sample_train_cameras(self):
"""Return a list of camera indices sampled using the strategy specified by
self.config.train_cameras_sampling_strategy"""
num_train_cameras = len(self.train_dataset)
if self.config.train_cameras_sampling_strategy == "random":
if not hasattr(self, "random_generator"):
self.random_generator = random.Random(self.config.train_cameras_sampling_seed)
indices = list(range(num_train_cameras))
self.random_generator.shuffle(indices)
return indices
elif self.config.train_cameras_sampling_strategy == "fps":
if not hasattr(self, "train_unsampled_epoch_count"):
np.random.seed(self.config.train_cameras_sampling_seed) # fix random seed of fpsample
self.train_unsampled_epoch_count = np.zeros(num_train_cameras)
camera_origins = self.train_dataset.cameras.camera_to_worlds[..., 3].numpy()
# We concatenate camera origins with weighted train_unsampled_epoch_count because we want to
# increase the chance to sample camera that hasn't been sampled in consecutive epochs previously.
# We assume the camera origins are also rescaled, so the weight 0.1 is relative to the scale of scene
data = np.concatenate(
(camera_origins, 0.1 * np.expand_dims(self.train_unsampled_epoch_count, axis=-1)), axis=-1
)
n = self.config.fps_reset_every
if num_train_cameras < n:
CONSOLE.log(
f"num_train_cameras={num_train_cameras} is smaller than fps_reset_ever={n}, the behavior of "
"camera sampler will be very similar to sampling random without replacement (default setting)."
)
n = num_train_cameras
kdline_fps_samples_idx = fpsample.bucket_fps_kdline_sampling(data, n, h=3)
self.train_unsampled_epoch_count += 1
self.train_unsampled_epoch_count[kdline_fps_samples_idx] = 0
return kdline_fps_samples_idx.tolist()
else:
raise ValueError(f"Unknown train camera sampling strategy: {self.config.train_cameras_sampling_strategy}")
@cached_property @cached_property
def cached_train(self) -> List[Dict[str, torch.Tensor]]: def cached_train(self) -> List[Dict[str, torch.Tensor]]:
"""Get the training images. Will load and undistort the images the """Get the training images. Will load and undistort the images the
@@ -161,7 +208,7 @@ class FullImageDatamanager(DataManager, Generic[TDataset]):
f'The size of image ({data["image"].shape[1]}, {data["image"].shape[0]}) loaded ' f'The size of image ({data["image"].shape[1]}, {data["image"].shape[0]}) loaded '
f'does not match the camera parameters ({camera.width.item(), camera.height.item()})' f'does not match the camera parameters ({camera.width.item(), camera.height.item()})'
) )
if camera.distortion_params is None: if camera.distortion_params is None or torch.all(camera.distortion_params == 0):
return data return data
K = camera.get_intrinsics_matrices().numpy() K = camera.get_intrinsics_matrices().numpy()
distortion_params = camera.distortion_params.numpy() distortion_params = camera.distortion_params.numpy()
@@ -200,11 +247,15 @@ class FullImageDatamanager(DataManager, Generic[TDataset]):
cache["image"] = cache["image"].to(self.device) cache["image"] = cache["image"].to(self.device)
if "mask" in cache: if "mask" in cache:
cache["mask"] = cache["mask"].to(self.device) cache["mask"] = cache["mask"].to(self.device)
if "depth" in cache:
cache["depth"] = cache["depth"].to(self.device)
self.train_cameras = self.train_dataset.cameras.to(self.device)
elif cache_images_device == "cpu": elif cache_images_device == "cpu":
for cache in undistorted_images: for cache in undistorted_images:
cache["image"] = cache["image"].pin_memory() cache["image"] = cache["image"].pin_memory()
if "mask" in cache: if "mask" in cache:
cache["mask"] = cache["mask"].pin_memory() cache["mask"] = cache["mask"].pin_memory()
self.train_cameras = self.train_dataset.cameras
else: else:
assert_never(cache_images_device) assert_never(cache_images_device)
@@ -288,16 +339,16 @@ class FullImageDatamanager(DataManager, Generic[TDataset]):
"""Returns the next training batch """Returns the next training batch
Returns a Camera instead of raybundle""" Returns a Camera instead of raybundle"""
image_idx = self.train_unseen_cameras.pop(random.randint(0, len(self.train_unseen_cameras) - 1)) image_idx = self.train_unseen_cameras.pop(0)
# Make sure to re-populate the unseen cameras list if we have exhausted it # Make sure to re-populate the unseen cameras list if we have exhausted it
if len(self.train_unseen_cameras) == 0: if len(self.train_unseen_cameras) == 0:
self.train_unseen_cameras = [i for i in range(len(self.train_dataset))] self.train_unseen_cameras = self.sample_train_cameras()
data = deepcopy(self.cached_train[image_idx]) data = self.cached_train[image_idx]
data["image"] = data["image"].to(self.device) data["image"] = data["image"].to(self.device)
assert len(self.train_dataset.cameras.shape) == 1, "Assumes single batch dimension" assert len(self.train_cameras.shape) == 1, "Assumes single batch dimension"
camera = self.train_dataset.cameras[image_idx : image_idx + 1].to(self.device) camera = self.train_cameras[image_idx : image_idx + 1].to(self.device)
if camera.metadata is None: if camera.metadata is None:
camera.metadata = {} camera.metadata = {}
camera.metadata["cam_idx"] = image_idx camera.metadata["cam_idx"] = image_idx
@@ -307,15 +358,7 @@ class FullImageDatamanager(DataManager, Generic[TDataset]):
"""Returns the next evaluation batch """Returns the next evaluation batch
Returns a Camera instead of raybundle""" Returns a Camera instead of raybundle"""
image_idx = self.eval_unseen_cameras.pop(random.randint(0, len(self.eval_unseen_cameras) - 1)) return self.next_eval_image(step=step)
# Make sure to re-populate the unseen cameras list if we have exhausted it
if len(self.eval_unseen_cameras) == 0:
self.eval_unseen_cameras = [i for i in range(len(self.eval_dataset))]
data = deepcopy(self.cached_eval[image_idx])
data["image"] = data["image"].to(self.device)
assert len(self.eval_dataset.cameras.shape) == 1, "Assumes single batch dimension"
camera = self.eval_dataset.cameras[image_idx : image_idx + 1].to(self.device)
return camera, data
def next_eval_image(self, step: int) -> Tuple[Cameras, Dict]: def next_eval_image(self, step: int) -> Tuple[Cameras, Dict]:
"""Returns the next evaluation batch """Returns the next evaluation batch
+20 -3
View File
@@ -30,6 +30,7 @@ from jaxtyping import Float
from rich.progress import BarColumn, Progress, TaskProgressColumn, TextColumn, TimeRemainingColumn from rich.progress import BarColumn, Progress, TaskProgressColumn, TextColumn, TimeRemainingColumn
from torch import Tensor from torch import Tensor
from nerfstudio.cameras.camera_optimizers import CameraOptimizer
from nerfstudio.cameras.cameras import Cameras from nerfstudio.cameras.cameras import Cameras
from nerfstudio.cameras.rays import RayBundle from nerfstudio.cameras.rays import RayBundle
from nerfstudio.data.datasets.base_dataset import InputDataset from nerfstudio.data.datasets.base_dataset import InputDataset
@@ -283,11 +284,14 @@ def render_trajectory(
return images, depths return images, depths
def collect_camera_poses_for_dataset(dataset: Optional[InputDataset]) -> List[Dict[str, Any]]: def collect_camera_poses_for_dataset(
dataset: Optional[InputDataset], camera_optimizer: Optional[CameraOptimizer] = None
) -> List[Dict[str, Any]]:
"""Collects rescaled, translated and optimised camera poses for a dataset. """Collects rescaled, translated and optimised camera poses for a dataset.
Args: Args:
dataset: Dataset to collect camera poses for. dataset: Dataset to collect camera poses for.
camera_optimizer: Camera optimizer that has been used for adjusting the poses
Returns: Returns:
List of dicts containing camera poses. List of dicts containing camera poses.
@@ -304,7 +308,15 @@ def collect_camera_poses_for_dataset(dataset: Optional[InputDataset]) -> List[Di
# new cameras are in cameras, whereas image paths are stored in a private member of the dataset # new cameras are in cameras, whereas image paths are stored in a private member of the dataset
for idx in range(len(cameras)): for idx in range(len(cameras)):
image_filename = image_filenames[idx] image_filename = image_filenames[idx]
transform = cameras.camera_to_worlds[idx].tolist() if camera_optimizer is None:
transform = cameras.camera_to_worlds[idx].tolist()
else:
# print('exporting optimized camera pose for camera %d' % idx)
camera = cameras[idx : idx + 1]
assert camera.metadata is not None
camera.metadata["cam_idx"] = idx
transform = camera_optimizer.apply_to_camera(camera).tolist()[0]
frames.append( frames.append(
{ {
"file_path": str(image_filename), "file_path": str(image_filename),
@@ -331,7 +343,12 @@ def collect_camera_poses(pipeline: VanillaPipeline) -> Tuple[List[Dict[str, Any]
eval_dataset = pipeline.datamanager.eval_dataset eval_dataset = pipeline.datamanager.eval_dataset
assert isinstance(eval_dataset, InputDataset) assert isinstance(eval_dataset, InputDataset)
train_frames = collect_camera_poses_for_dataset(train_dataset) camera_optimizer = None
if hasattr(pipeline.model, "camera_optimizer"):
camera_optimizer = pipeline.model.camera_optimizer
train_frames = collect_camera_poses_for_dataset(train_dataset, camera_optimizer)
# Note: returning original poses, even if --eval-mode=all
eval_frames = collect_camera_poses_for_dataset(eval_dataset) eval_frames = collect_camera_poses_for_dataset(eval_dataset)
return train_frames, eval_frames return train_frames, eval_frames
+124 -128
View File
@@ -14,35 +14,35 @@
# limitations under the License. # limitations under the License.
""" """
NeRF implementation that combines many recent advancements. Gaussian Splatting implementation that combines many recent advancements.
""" """
from __future__ import annotations from __future__ import annotations
import math import math
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple, Type, Union from typing import Dict, List, Literal, Optional, Tuple, Type, Union
import numpy as np import numpy as np
import torch import torch
from gsplat._torch_impl import quat_to_rotmat from gsplat.cuda_legacy._torch_impl import quat_to_rotmat
from gsplat.project_gaussians import project_gaussians
from gsplat.rasterize import rasterize_gaussians try:
from gsplat.sh import num_sh_bases, spherical_harmonics from gsplat.rendering import rasterization
except ImportError:
print("Please install gsplat>=1.0.0")
from gsplat.cuda_legacy._wrapper import num_sh_bases
from pytorch_msssim import SSIM from pytorch_msssim import SSIM
from torch.nn import Parameter from torch.nn import Parameter
from typing_extensions import Literal
from nerfstudio.cameras.camera_optimizers import CameraOptimizer, CameraOptimizerConfig from nerfstudio.cameras.camera_optimizers import CameraOptimizer, CameraOptimizerConfig
from nerfstudio.cameras.cameras import Cameras from nerfstudio.cameras.cameras import Cameras
from nerfstudio.data.scene_box import OrientedBox from nerfstudio.data.scene_box import OrientedBox
from nerfstudio.engine.callbacks import TrainingCallback, TrainingCallbackAttributes, TrainingCallbackLocation from nerfstudio.engine.callbacks import TrainingCallback, TrainingCallbackAttributes, TrainingCallbackLocation
from nerfstudio.engine.optimizers import Optimizers from nerfstudio.engine.optimizers import Optimizers
# need following import for background color override
from nerfstudio.model_components import renderers
from nerfstudio.models.base_model import Model, ModelConfig from nerfstudio.models.base_model import Model, ModelConfig
from nerfstudio.utils.colors import get_color from nerfstudio.utils.colors import get_color
from nerfstudio.utils.misc import torch_compile
from nerfstudio.utils.rich_utils import CONSOLE from nerfstudio.utils.rich_utils import CONSOLE
@@ -91,10 +91,30 @@ def resize_image(image: torch.Tensor, d: int):
""" """
import torch.nn.functional as tf import torch.nn.functional as tf
image = image.to(torch.float32)
weight = (1.0 / (d * d)) * torch.ones((1, 1, d, d), dtype=torch.float32, device=image.device) weight = (1.0 / (d * d)) * torch.ones((1, 1, d, d), dtype=torch.float32, device=image.device)
return tf.conv2d(image.permute(2, 0, 1)[:, None, ...], weight, stride=d).squeeze(1).permute(1, 2, 0) return tf.conv2d(image.permute(2, 0, 1)[:, None, ...], weight, stride=d).squeeze(1).permute(1, 2, 0)
@torch_compile()
def get_viewmat(optimized_camera_to_world):
"""
function that converts c2w to gsplat world2camera matrix, using compile for some speed
"""
R = optimized_camera_to_world[:, :3, :3] # 3 x 3
T = optimized_camera_to_world[:, :3, 3:4] # 3 x 1
# flip the z and y axes to align with gsplat conventions
R = R * torch.tensor([[[1, -1, -1]]], device=R.device, dtype=R.dtype)
# analytic matrix inverse to get world2camera matrix
R_inv = R.transpose(1, 2)
T_inv = -torch.bmm(R_inv, T)
viewmat = torch.zeros(R.shape[0], 4, 4, device=R.device, dtype=R.dtype)
viewmat[:, 3, 3] = 1.0 # homogenous
viewmat[:, :3, :3] = R_inv
viewmat[:, :3, 3:4] = T_inv
return viewmat
@dataclass @dataclass
class SplatfactoModelConfig(ModelConfig): class SplatfactoModelConfig(ModelConfig):
"""Splatfacto Model Config, nerfstudio's implementation of Gaussian Splatting""" """Splatfacto Model Config, nerfstudio's implementation of Gaussian Splatting"""
@@ -394,17 +414,14 @@ class SplatfactoModel(Model):
with torch.no_grad(): with torch.no_grad():
# keep track of a moving average of grad norms # keep track of a moving average of grad norms
visible_mask = (self.radii > 0).flatten() visible_mask = (self.radii > 0).flatten()
assert self.xys.absgrad is not None # type: ignore grads = self.xys.absgrad[0][visible_mask].norm(dim=-1) # type: ignore
grads = self.xys.absgrad.detach().norm(dim=-1) # type: ignore
# print(f"grad norm min {grads.min().item()} max {grads.max().item()} mean {grads.mean().item()} size {grads.shape}") # print(f"grad norm min {grads.min().item()} max {grads.max().item()} mean {grads.mean().item()} size {grads.shape}")
if self.xys_grad_norm is None: if self.xys_grad_norm is None:
self.xys_grad_norm = grads self.xys_grad_norm = torch.zeros(self.num_points, device=self.device, dtype=torch.float32)
self.vis_counts = torch.ones_like(self.xys_grad_norm) self.vis_counts = torch.ones(self.num_points, device=self.device, dtype=torch.float32)
else: assert self.vis_counts is not None
assert self.vis_counts is not None self.vis_counts[visible_mask] += 1
self.vis_counts[visible_mask] = self.vis_counts[visible_mask] + 1 self.xys_grad_norm[visible_mask] += grads
self.xys_grad_norm[visible_mask] = grads[visible_mask] + self.xys_grad_norm[visible_mask]
# update the max screen size, as a ratio of number of pixels # update the max screen size, as a ratio of number of pixels
if self.max_2Dsize is None: if self.max_2Dsize is None:
self.max_2Dsize = torch.zeros_like(self.radii, dtype=torch.float32) self.max_2Dsize = torch.zeros_like(self.radii, dtype=torch.float32)
@@ -454,7 +471,6 @@ class SplatfactoModel(Model):
self.gauss_params[name] = torch.nn.Parameter( self.gauss_params[name] = torch.nn.Parameter(
torch.cat([param.detach(), split_params[name], dup_params[name]], dim=0) torch.cat([param.detach(), split_params[name], dup_params[name]], dim=0)
) )
# append zeros to the max_2Dsize tensor # append zeros to the max_2Dsize tensor
self.max_2Dsize = torch.cat( self.max_2Dsize = torch.cat(
[ [
@@ -528,8 +544,8 @@ class SplatfactoModel(Model):
toobigs = (torch.exp(self.scales).max(dim=-1).values > self.config.cull_scale_thresh).squeeze() toobigs = (torch.exp(self.scales).max(dim=-1).values > self.config.cull_scale_thresh).squeeze()
if self.step < self.config.stop_screen_size_at: if self.step < self.config.stop_screen_size_at:
# cull big screen space # cull big screen space
assert self.max_2Dsize is not None if self.max_2Dsize is not None:
toobigs = toobigs | (self.max_2Dsize > self.config.cull_screen_size).squeeze() toobigs = toobigs | (self.max_2Dsize > self.config.cull_screen_size).squeeze()
culls = culls | toobigs culls = culls | toobigs
toobigs_count = torch.sum(toobigs).item() toobigs_count = torch.sum(toobigs).item()
for name, param in self.gauss_params.items(): for name, param in self.gauss_params.items():
@@ -656,6 +672,20 @@ class SplatfactoModel(Model):
accumulation = background.new_zeros(*rgb.shape[:2], 1) accumulation = background.new_zeros(*rgb.shape[:2], 1)
return {"rgb": rgb, "depth": depth, "accumulation": accumulation, "background": background} return {"rgb": rgb, "depth": depth, "accumulation": accumulation, "background": background}
def _get_background_color(self):
if self.config.background_color == "random":
if self.training:
background = torch.rand(3, device=self.device)
else:
background = self.background_color.to(self.device)
elif self.config.background_color == "white":
background = torch.ones(3, device=self.device)
elif self.config.background_color == "black":
background = torch.zeros(3, device=self.device)
else:
raise ValueError(f"Unknown background color {self.config.background_color}")
return background
def get_outputs(self, camera: Cameras) -> Dict[str, Union[torch.Tensor, List]]: def get_outputs(self, camera: Cameras) -> Dict[str, Union[torch.Tensor, List]]:
"""Takes in a Ray Bundle and returns a dictionary of outputs. """Takes in a Ray Bundle and returns a dictionary of outputs.
@@ -669,54 +699,22 @@ class SplatfactoModel(Model):
if not isinstance(camera, Cameras): if not isinstance(camera, Cameras):
print("Called get_outputs with not a camera") print("Called get_outputs with not a camera")
return {} return {}
assert camera.shape[0] == 1, "Only one camera at a time"
# get the background color
if self.training: if self.training:
optimized_camera_to_world = self.camera_optimizer.apply_to_camera(camera)[0, ...] assert camera.shape[0] == 1, "Only one camera at a time"
optimized_camera_to_world = self.camera_optimizer.apply_to_camera(camera)
if self.config.background_color == "random":
background = torch.rand(3, device=self.device)
elif self.config.background_color == "white":
background = torch.ones(3, device=self.device)
elif self.config.background_color == "black":
background = torch.zeros(3, device=self.device)
else:
background = self.background_color.to(self.device)
else: else:
optimized_camera_to_world = camera.camera_to_worlds[0, ...] optimized_camera_to_world = camera.camera_to_worlds
if renderers.BACKGROUND_COLOR_OVERRIDE is not None:
background = renderers.BACKGROUND_COLOR_OVERRIDE.to(self.device)
else:
background = self.background_color.to(self.device)
# cropping
if self.crop_box is not None and not self.training: if self.crop_box is not None and not self.training:
crop_ids = self.crop_box.within(self.means).squeeze() crop_ids = self.crop_box.within(self.means).squeeze()
if crop_ids.sum() == 0: if crop_ids.sum() == 0:
return self.get_empty_outputs(int(camera.width.item()), int(camera.height.item()), background) return self.get_empty_outputs(
int(camera.width.item()), int(camera.height.item()), self.background_color
)
else: else:
crop_ids = None crop_ids = None
camera_downscale = self._get_downscale_factor()
camera.rescale_output_resolution(1 / camera_downscale)
# shift the camera to center of scene looking at center
R = optimized_camera_to_world[:3, :3] # 3 x 3
T = optimized_camera_to_world[:3, 3:4] # 3 x 1
# flip the z and y axes to align with gsplat conventions
R_edit = torch.diag(torch.tensor([1, -1, -1], device=self.device, dtype=R.dtype))
R = R @ R_edit
# analytic matrix inverse to get world2camera matrix
R_inv = R.T
T_inv = -R_inv @ T
viewmat = torch.eye(4, device=R.device, dtype=R.dtype)
viewmat[:3, :3] = R_inv
viewmat[:3, 3:4] = T_inv
# calculate the FOV of the camera given fx and fy, width and height
cx = camera.cx.item()
cy = camera.cy.item()
W, H = int(camera.width.item()), int(camera.height.item())
self.last_size = (H, W)
if crop_ids is not None: if crop_ids is not None:
opacities_crop = self.opacities[crop_ids] opacities_crop = self.opacities[crop_ids]
@@ -734,80 +732,78 @@ class SplatfactoModel(Model):
quats_crop = self.quats quats_crop = self.quats
colors_crop = torch.cat((features_dc_crop[:, None, :], features_rest_crop), dim=1) colors_crop = torch.cat((features_dc_crop[:, None, :], features_rest_crop), dim=1)
BLOCK_WIDTH = 16 # this controls the tile size of rasterization, 16 is a good default BLOCK_WIDTH = 16 # this controls the tile size of rasterization, 16 is a good default
self.xys, depths, self.radii, conics, comp, num_tiles_hit, cov3d = project_gaussians( # type: ignore camera_scale_fac = self._get_downscale_factor()
means_crop, camera.rescale_output_resolution(1 / camera_scale_fac)
torch.exp(scales_crop), viewmat = get_viewmat(optimized_camera_to_world)
1, K = camera.get_intrinsics_matrices().cuda()
quats_crop / quats_crop.norm(dim=-1, keepdim=True), W, H = int(camera.width.item()), int(camera.height.item())
viewmat.squeeze()[:3, :], self.last_size = (H, W)
camera.fx.item(), camera.rescale_output_resolution(camera_scale_fac) # type: ignore
camera.fy.item(),
cx,
cy,
H,
W,
BLOCK_WIDTH,
) # type: ignore
# rescale the camera back to original dimensions before returning
camera.rescale_output_resolution(camera_downscale)
if (self.radii).sum() == 0:
return self.get_empty_outputs(W, H, background)
if self.config.sh_degree > 0:
viewdirs = means_crop.detach() - optimized_camera_to_world.detach()[:3, 3] # (N, 3)
n = min(self.step // self.config.sh_degree_interval, self.config.sh_degree)
rgbs = spherical_harmonics(n, viewdirs, colors_crop) # input unnormalized viewdirs
rgbs = torch.clamp(rgbs + 0.5, min=0.0) # type: ignore
else:
rgbs = torch.sigmoid(colors_crop[:, 0, :])
assert (num_tiles_hit > 0).any() # type: ignore
# apply the compensation of screen space blurring to gaussians # apply the compensation of screen space blurring to gaussians
if self.config.rasterize_mode == "antialiased": if self.config.rasterize_mode not in ["antialiased", "classic"]:
opacities = torch.sigmoid(opacities_crop) * comp[:, None]
elif self.config.rasterize_mode == "classic":
opacities = torch.sigmoid(opacities_crop)
else:
raise ValueError("Unknown rasterize_mode: %s", self.config.rasterize_mode) raise ValueError("Unknown rasterize_mode: %s", self.config.rasterize_mode)
rgb, alpha = rasterize_gaussians( # type: ignore
self.xys,
depths,
self.radii,
conics,
num_tiles_hit, # type: ignore
rgbs,
opacities,
H,
W,
BLOCK_WIDTH,
background=background,
return_alpha=True,
) # type: ignore
alpha = alpha[..., None]
rgb = torch.clamp(rgb, max=1.0) # type: ignore
depth_im = None
if self.config.output_depth_during_training or not self.training: if self.config.output_depth_during_training or not self.training:
depth_im = rasterize_gaussians( # type: ignore render_mode = "RGB+ED"
self.xys, else:
depths, render_mode = "RGB"
self.radii,
conics,
num_tiles_hit, # type: ignore
depths[:, None].repeat(1, 3),
opacities,
H,
W,
BLOCK_WIDTH,
background=torch.zeros(3, device=self.device),
)[..., 0:1] # type: ignore
depth_im = torch.where(alpha > 0, depth_im / alpha, depth_im.detach().max())
return {"rgb": rgb, "depth": depth_im, "accumulation": alpha, "background": background} # type: ignore if self.config.sh_degree > 0:
sh_degree_to_use = min(self.step // self.config.sh_degree_interval, self.config.sh_degree)
else:
colors_crop = torch.sigmoid(colors_crop)
sh_degree_to_use = None
render, alpha, info = rasterization(
means=means_crop,
quats=quats_crop / quats_crop.norm(dim=-1, keepdim=True),
scales=torch.exp(scales_crop),
opacities=torch.sigmoid(opacities_crop).squeeze(-1),
colors=colors_crop,
viewmats=viewmat, # [1, 4, 4]
Ks=K, # [1, 3, 3]
width=W,
height=H,
tile_size=BLOCK_WIDTH,
packed=False,
near_plane=0.01,
far_plane=1e10,
render_mode=render_mode,
sh_degree=sh_degree_to_use,
sparse_grad=False,
absgrad=True,
rasterize_mode=self.config.rasterize_mode,
# set some threshold to disregrad small gaussians for faster rendering.
# radius_clip=3.0,
)
if self.training and info["means2d"].requires_grad:
info["means2d"].retain_grad()
self.xys = info["means2d"] # [1, N, 2]
self.radii = info["radii"][0] # [N]
alpha = alpha[:, ...]
background = self._get_background_color()
rgb = render[:, ..., :3] + (1 - alpha) * background
rgb = torch.clamp(rgb, 0.0, 1.0)
if render_mode == "RGB+ED":
depth_im = render[:, ..., 3:4]
depth_im = torch.where(alpha > 0, depth_im, depth_im.detach().max()).squeeze(0)
else:
depth_im = None
if background.shape[0] == 3 and not self.training:
background = background.expand(H, W, 3)
return {
"rgb": rgb.squeeze(0), # type: ignore
"depth": depth_im, # type: ignore
"accumulation": alpha.squeeze(0), # type: ignore
"background": background, # type: ignore
} # type: ignore
def get_gt_img(self, image: torch.Tensor): def get_gt_img(self, image: torch.Tensor):
"""Compute groundtruth image with iteration dependent downscale factor for evaluation purpose """Compute groundtruth image with iteration dependent downscale factor for evaluation purpose
+31 -9
View File
@@ -345,12 +345,19 @@ class VanillaPipeline(Pipeline):
return metrics_dict, images_dict return metrics_dict, images_dict
@profiler.time_function @profiler.time_function
def get_average_eval_image_metrics( def get_average_image_metrics(
self, step: Optional[int] = None, output_path: Optional[Path] = None, get_std: bool = False self,
data_loader,
image_prefix: str,
step: Optional[int] = None,
output_path: Optional[Path] = None,
get_std: bool = False,
): ):
"""Iterate over all the images in the eval dataset and get the average. """Iterate over all the images in the dataset and get the average.
Args: Args:
data_loader: the data loader to iterate over
image_prefix: prefix to use for the saved image filenames
step: current training step step: current training step
output_path: optional path to save rendered images to output_path: optional path to save rendered images to
get_std: Set True if you want to return std with the mean metric. get_std: Set True if you want to return std with the mean metric.
@@ -360,8 +367,7 @@ class VanillaPipeline(Pipeline):
""" """
self.eval() self.eval()
metrics_dict_list = [] metrics_dict_list = []
assert isinstance(self.datamanager, (VanillaDataManager, ParallelDataManager, FullImageDatamanager)) num_images = len(data_loader)
num_images = len(self.datamanager.fixed_indices_eval_dataloader)
if output_path is not None: if output_path is not None:
output_path.mkdir(exist_ok=True, parents=True) output_path.mkdir(exist_ok=True, parents=True)
with Progress( with Progress(
@@ -371,9 +377,9 @@ class VanillaPipeline(Pipeline):
MofNCompleteColumn(), MofNCompleteColumn(),
transient=True, transient=True,
) as progress: ) as progress:
task = progress.add_task("[green]Evaluating all eval images...", total=num_images) task = progress.add_task("[green]Evaluating all images...", total=num_images)
idx = 0 idx = 0
for camera, batch in self.datamanager.fixed_indices_eval_dataloader: for camera, batch in data_loader:
# time this the following line # time this the following line
inner_start = time() inner_start = time()
outputs = self.model.get_outputs_for_camera(camera=camera) outputs = self.model.get_outputs_for_camera(camera=camera)
@@ -383,7 +389,9 @@ class VanillaPipeline(Pipeline):
if output_path is not None: if output_path is not None:
for key in image_dict.keys(): for key in image_dict.keys():
image = image_dict[key] # [H, W, C] order image = image_dict[key] # [H, W, C] order
vutils.save_image(image.permute(2, 0, 1).cpu(), output_path / f"eval_{key}_{idx:04d}.png") vutils.save_image(
image.permute(2, 0, 1).cpu(), output_path / f"{image_prefix}_{key}_{idx:04d}.png"
)
assert "num_rays_per_sec" not in metrics_dict assert "num_rays_per_sec" not in metrics_dict
metrics_dict["num_rays_per_sec"] = (num_rays / (time() - inner_start)).item() metrics_dict["num_rays_per_sec"] = (num_rays / (time() - inner_start)).item()
@@ -393,7 +401,7 @@ class VanillaPipeline(Pipeline):
metrics_dict_list.append(metrics_dict) metrics_dict_list.append(metrics_dict)
progress.advance(task) progress.advance(task)
idx = idx + 1 idx = idx + 1
# average the metrics list
metrics_dict = {} metrics_dict = {}
for key in metrics_dict_list[0].keys(): for key in metrics_dict_list[0].keys():
if get_std: if get_std:
@@ -406,9 +414,23 @@ class VanillaPipeline(Pipeline):
metrics_dict[key] = float( metrics_dict[key] = float(
torch.mean(torch.tensor([metrics_dict[key] for metrics_dict in metrics_dict_list])) torch.mean(torch.tensor([metrics_dict[key] for metrics_dict in metrics_dict_list]))
) )
self.train() self.train()
return metrics_dict return metrics_dict
@profiler.time_function
def get_average_eval_image_metrics(
self, step: Optional[int] = None, output_path: Optional[Path] = None, get_std: bool = False
):
"""Get the average metrics for evaluation images."""
"""Get the average metrics for evaluation images."""
assert isinstance(self.datamanager, (VanillaDataManager, ParallelDataManager, FullImageDatamanager))
image_prefix = "eval"
return self.get_average_image_metrics(
self.datamanager.fixed_indices_eval_dataloader, image_prefix, step, output_path, get_std
)
def load_pipeline(self, loaded_state: Dict[str, Any], step: int) -> None: def load_pipeline(self, loaded_state: Dict[str, Any], step: int) -> None:
"""Load the checkpoint from the given path """Load the checkpoint from the given path
@@ -162,7 +162,9 @@ class ColmapConverterToNerfstudioDataset(BaseConverterToNerfstudioDataset):
depth_dir = self.output_dir / "depth" depth_dir = self.output_dir / "depth"
depth_dir.mkdir(parents=True, exist_ok=True) depth_dir.mkdir(parents=True, exist_ok=True)
image_id_to_depth_path = colmap_utils.create_sfm_depth( image_id_to_depth_path = colmap_utils.create_sfm_depth(
recon_dir=self.output_dir / self.default_colmap_path(), recon_dir=self.absolute_colmap_model_path
if self.skip_colmap
else self.output_dir / self.default_colmap_path(),
output_dir=depth_dir, output_dir=depth_dir,
include_depth_debug=self.include_depth_debug, include_depth_debug=self.include_depth_debug,
input_images_dir=self.image_dir, input_images_dir=self.image_dir,
@@ -244,7 +246,7 @@ class ColmapConverterToNerfstudioDataset(BaseConverterToNerfstudioDataset):
def __post_init__(self) -> None: def __post_init__(self) -> None:
super().__post_init__() super().__post_init__()
install_checks.check_ffmpeg_installed() install_checks.check_ffmpeg_installed()
install_checks.check_colmap_installed() install_checks.check_colmap_installed(self.colmap_cmd)
if self.crop_bottom < 0.0 or self.crop_bottom > 1: if self.crop_bottom < 0.0 or self.crop_bottom > 1:
raise RuntimeError("crop_bottom must be set between 0 and 1.") raise RuntimeError("crop_bottom must be set between 0 and 1.")
+23 -23
View File
@@ -26,29 +26,6 @@ from typing import Literal
from nerfstudio.process_data.process_data_utils import CameraModel from nerfstudio.process_data.process_data_utils import CameraModel
from nerfstudio.utils.rich_utils import CONSOLE from nerfstudio.utils.rich_utils import CONSOLE
try:
# TODO(1480) un-hide pycolmap import
import pycolmap
from hloc import ( # type: ignore
extract_features,
match_features,
pairs_from_exhaustive,
pairs_from_retrieval,
reconstruction,
)
except ImportError:
_HAS_HLOC = False
else:
_HAS_HLOC = True
try:
from pixsfm.refine_hloc import PixSfM # type: ignore
except ImportError:
_HAS_PIXSFM = False
else:
_HAS_PIXSFM = True
def run_hloc( def run_hloc(
image_dir: Path, image_dir: Path,
@@ -88,6 +65,29 @@ def run_hloc(
refine_pixsfm: If True, refine the reconstruction using pixel-perfect-sfm. refine_pixsfm: If True, refine the reconstruction using pixel-perfect-sfm.
use_single_camera_mode: If True, uses one camera for all frames. Otherwise uses one camera per frame. use_single_camera_mode: If True, uses one camera for all frames. Otherwise uses one camera per frame.
""" """
try:
# TODO(1480) un-hide pycolmap import
import pycolmap
from hloc import ( # type: ignore
extract_features,
match_features,
pairs_from_exhaustive,
pairs_from_retrieval,
reconstruction,
)
except ImportError:
_HAS_HLOC = False
else:
_HAS_HLOC = True
try:
from pixsfm.refine_hloc import PixSfM # type: ignore
except ImportError:
_HAS_PIXSFM = False
else:
_HAS_PIXSFM = True
if not _HAS_HLOC: if not _HAS_HLOC:
CONSOLE.print( CONSOLE.print(
f"[bold red]Error: To use this set of parameters ({feature_type}/{matcher_type}/hloc), " f"[bold red]Error: To use this set of parameters ({feature_type}/{matcher_type}/hloc), "
@@ -171,6 +171,7 @@ def download_capture_name(save_dir: Path, dataset_name: str, capture_name: str,
with zipfile.ZipFile(download_path, "r") as zip_ref: with zipfile.ZipFile(download_path, "r") as zip_ref:
zip_ref.extractall(tmp_path) zip_ref.extractall(tmp_path)
inner_folders = os.listdir(tmp_path) inner_folders = os.listdir(tmp_path)
inner_folders = [folder for folder in inner_folders if folder != "__MACOSX"]
assert len(inner_folders) == 1, f"There is more than one folder inside this zip file: {inner_folders}" assert len(inner_folders) == 1, f"There is more than one folder inside this zip file: {inner_folders}"
folder = os.path.join(tmp_path, inner_folders[0]) folder = os.path.join(tmp_path, inner_folders[0])
shutil.rmtree(target_path) shutil.rmtree(target_path)
@@ -41,6 +41,8 @@ eyefultower_downloads = [
"seating_area", "seating_area",
"table", "table",
"workshop", "workshop",
"raf_emptyroom",
"raf_furnishedroom",
] ]
# Crop radii empirically chosen to try to avoid hitting the rig base or go out of bounds # Crop radii empirically chosen to try to avoid hitting the rig base or go out of bounds
+3
View File
@@ -152,6 +152,9 @@ class ProcessPolycam(BaseConverterToNerfstudioDataset):
zip_ref.extractall(self.output_dir) zip_ref.extractall(self.output_dir)
extracted_folder = zip_ref.namelist()[0].split("/")[0] extracted_folder = zip_ref.namelist()[0].split("/")[0]
self.data = self.output_dir / extracted_folder self.data = self.output_dir / extracted_folder
if not (self.data / "keyframes").exists():
# new versions of polycam data have a different structure, strip the last dir off
self.data = self.output_dir
if (self.data / "keyframes" / "corrected_images").exists() and not self.use_uncorrected_images: if (self.data / "keyframes" / "corrected_images").exists() and not self.use_uncorrected_images:
polycam_image_dir = self.data / "keyframes" / "corrected_images" polycam_image_dir = self.data / "keyframes" / "corrected_images"
+2 -2
View File
@@ -134,8 +134,8 @@ def apply_depth_colormap(
Colored depth image with colors in [0, 1] Colored depth image with colors in [0, 1]
""" """
near_plane = near_plane or float(torch.min(depth)) near_plane = near_plane if near_plane is not None else float(torch.min(depth))
far_plane = far_plane or float(torch.max(depth)) far_plane = far_plane if far_plane is not None else float(torch.max(depth))
depth = (depth - near_plane) / (far_plane - near_plane + 1e-10) depth = (depth - near_plane) / (far_plane - near_plane + 1e-10)
depth = torch.clip(depth, 0, 1) depth = torch.clip(depth, 0, 1)
+4 -3
View File
@@ -15,6 +15,7 @@
"""Helpers for checking if programs are installed""" """Helpers for checking if programs are installed"""
import shutil import shutil
import subprocess
import sys import sys
from nerfstudio.utils.rich_utils import CONSOLE from nerfstudio.utils.rich_utils import CONSOLE
@@ -29,10 +30,10 @@ def check_ffmpeg_installed():
sys.exit(1) sys.exit(1)
def check_colmap_installed(): def check_colmap_installed(colmap_cmd: str):
"""Checks if colmap is installed.""" """Checks if colmap is installed."""
colmap_path = shutil.which("colmap") out = subprocess.run(f"{colmap_cmd} -h", capture_output=True, shell=True, check=False)
if colmap_path is None: if out.returncode != 0:
CONSOLE.print("[bold red]Could not find COLMAP. Please install COLMAP.") CONSOLE.print("[bold red]Could not find COLMAP. Please install COLMAP.")
print("See https://colmap.github.io/install.html for installation instructions.") print("See https://colmap.github.io/install.html for installation instructions.")
sys.exit(1) sys.exit(1)
+9105
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
[project]
name = "nerfstudio"
description = "All-in-one repository for state-of-the-art NeRFs"
channels = ["nvidia/label/cuda-11.8.0", "nvidia", "conda-forge", "pytorch"]
platforms = ["linux-64"]
[system-requirements]
libc = { family="glibc", version="2.30" }
[tasks]
# || operator in pixi allows running a command after only if the command before || fails
tcnn-install = "python -c 'import tinycudann as tcnn' || python -m pip install ninja git+https://github.com/NVlabs/tiny-cuda-nn/#subdirectory=bindings/torch"
make-third_party-dir = {cmd="ls third_party || mkdir third_party"}
clone-hloc = {cmd="ls Hierarchical-Localization || git clone --recursive https://github.com/cvg/Hierarchical-Localization/", cwd = "third_party", depends_on=["make-third_party-dir"] }
hloc-install = {cmd="python -m pip install -e .", cwd = "third_party/Hierarchical-Localization" , depends_on=["clone-hloc"], outputs=["third_party/Hierarchical-Localization/hloc.egg-info/PKG-INFO"]}
post-install = {cmd="pwd", depends_on=["hloc-install", "tcnn-install"]}
download-dozer-data = {cmd="ls data/nerfstudio/dozer || ns-download-data nerfstudio --capture-name dozer"}
train-example-splat = {cmd="ns-train splatfacto --data data/nerfstudio/dozer/", depends_on=["post-install", "download-dozer-data"]}
train-example-nerf = {cmd="ns-train nerfacto --data data/nerfstudio/dozer/", depends_on=["post-install", "download-dozer-data"]}
[dependencies]
python = ">=3.8,<3.11"
pip = ">=24.0,<25"
cuda = {version = "*", channel="nvidia/label/cuda-11.8.0"}
pytorch-cuda = {version = "11.8.*", channel="pytorch"}
pytorch = {version = ">=2.2.0,<2.3", channel="pytorch"}
torchvision = {version = ">=0.17.0,<0.18", channel="pytorch"}
pyarrow = ">=15.0.2,<15.1"
colmap = ">=3.9.1,<3.10"
[pypi-dependencies]
nerfstudio = { path = ".", editable = true}
+4 -3
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "nerfstudio" name = "nerfstudio"
version = "1.0.3" version = "1.1.3"
description = "All-in-one repository for state-of-the-art NeRFs" description = "All-in-one repository for state-of-the-art NeRFs"
readme = "README.md" readme = "README.md"
license = { text="Apache 2.0"} license = { text="Apache 2.0"}
@@ -63,10 +63,11 @@ dependencies = [
"xatlas", "xatlas",
"trimesh>=3.20.2", "trimesh>=3.20.2",
"timm==0.6.7", "timm==0.6.7",
"gsplat>=0.1.11", "gsplat==1.0.0",
"pytorch-msssim", "pytorch-msssim",
"pathos", "pathos",
"packaging" "packaging",
"fpsample"
] ]
[project.urls] [project.urls]