diff --git a/.devcontainer/docker-compose.yml b/.devcontainer/docker-compose.yml
index 6376422cf..de862fc1a 100644
--- a/.devcontainer/docker-compose.yml
+++ b/.devcontainer/docker-compose.yml
@@ -3,7 +3,7 @@ version: "3.8"
services:
nerfstudio:
shm_size: '12gb'
- image: dromni/nerfstudio:0.1.17
+ image: dromni/nerfstudio:0.1.18
# build:
# context: ..
# dockerfile: ./Dockerfile
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 000000000..e1590ed27
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,190 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+!scripts/downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# poetry
+# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
+# This is especially recommended for binary packages to ensure reproducibility, and is more
+# commonly ignored for libraries.
+# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
+#poetry.lock
+
+# pdm
+# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
+#pdm.lock
+# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
+# in version control.
+# https://pdm.fming.dev/#use-with-ide
+.pdm.toml
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.envrc
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+# PyCharm
+# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
+# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
+# and can be added to the global gitignore or merged into this file. For a more nuclear
+# option (not recommended) you can uncomment the following to ignore the entire idea folder.
+#.idea/
+
+# Experiments and outputs
+outputs/
+exports/
+renders/
+# tensorboard log files
+events.out.*
+
+# Data
+data
+
+# Misc
+old/
+temp*
+!temporal*
+.nfs*
+external/
+__MACOSX/
+node_modules/
+bash/
+cache/
+package-lock.json
+camera_paths/
+.DS_Store
+._.DS_Store
+*/**/.DS_Store
+*/**/._.DS_Store
+
diff --git a/.gitignore b/.gitignore
index d6f0cf5d9..ab8a4e108 100644
--- a/.gitignore
+++ b/.gitignore
@@ -184,3 +184,8 @@ bash/
cache/
package-lock.json
camera_paths/
+.DS_Store
+._.DS_Store
+*/**/.DS_Store
+*/**/._.DS_Store
+
diff --git a/Dockerfile b/Dockerfile
index a6417e419..2bdb5328b 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,6 +1,12 @@
# Define base image.
FROM nvidia/cuda:11.8.0-devel-ubuntu22.04
+# metainformation
+LABEL org.opencontainers.image.version = "0.1.18"
+LABEL org.opencontainers.image.source = "https://github.com/nerfstudio-project/nerfstudio"
+LABEL org.opencontainers.image.licenses = "Apache License 2.0"
+LABEL org.opencontainers.image.base.name="docker.io/library/nvidia/cuda:11.8.0-devel-ubuntu22.04"
+
# Variables used at build time.
## CUDA architectures, required by Colmap and tiny-cuda-nn.
## NOTE: All commonly used GPU architectures are included and supported here. To speedup the image build process remove all architectures but the one of your explicit GPU. Find details here: https://developer.nvidia.com/cuda-gpus (8.6 translates to 86 in the line below) or in the docs.
@@ -42,10 +48,12 @@ RUN apt-get update && \
libsuitesparse-dev \
nano \
protobuf-compiler \
+ python-is-python3 \
python3.10-dev \
python3-pip \
qtbase5-dev \
sudo \
+ vim-tiny \
wget && \
rm -rf /var/lib/apt/lists/*
@@ -56,7 +64,7 @@ RUN git clone --branch v0.6.0 https://github.com/google/glog.git --single-branch
mkdir build && \
cd build && \
cmake .. && \
- make -j && \
+ make -j `nproc` && \
make install && \
cd ../.. && \
rm -rf glog
@@ -70,7 +78,7 @@ RUN git clone --branch 2.1.0 https://ceres-solver.googlesource.com/ceres-solver.
mkdir build && \
cd build && \
cmake .. -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF && \
- make -j && \
+ make -j `nproc` && \
make install && \
cd ../.. && \
rm -rf ceres-solver
@@ -81,13 +89,12 @@ RUN git clone --branch 3.8 https://github.com/colmap/colmap.git --single-branch
mkdir build && \
cd build && \
cmake .. -DCUDA_ENABLED=ON \
- -DCUDA_NVCC_FLAGS="--std c++14" \
-DCMAKE_CUDA_ARCHITECTURES=${CUDA_ARCHITECTURES} && \
- make -j && \
+ make -j `nproc` && \
make install && \
cd ../.. && \
rm -rf colmap
-
+
# Create non root user and setup environment.
RUN useradd -m -d /home/user -g root -G sudo -u 1000 user
RUN usermod -aG sudo user
@@ -105,12 +112,25 @@ ENV PATH="${PATH}:/home/user/.local/bin"
SHELL ["/bin/bash", "-c"]
# Upgrade pip and install packages.
-RUN python3.10 -m pip install --upgrade pip setuptools pathtools promise
-# Install pytorch and submodules (Currently, we still use cu116 which is the latest version for toch 1.12.1 and is compatible with CUDA 11.8).
+RUN python3.10 -m pip install --upgrade pip setuptools pathtools promise pybind11
+# Install pytorch and submodules (Currently, we still use cu116 which is the latest version for torch 1.12.1 and is compatible with CUDA 11.8).
RUN python3.10 -m pip install torch==1.13.1+cu116 torchvision==0.14.1+cu116 --extra-index-url https://download.pytorch.org/whl/cu116
# Install tynyCUDNN (we need to set the target architectures as environment variable first).
ENV TCNN_CUDA_ARCHITECTURES=${CUDA_ARCHITECTURES}
-RUN python3.10 -m pip install git+https://github.com/NVlabs/tiny-cuda-nn.git#subdirectory=bindings/torch
+RUN python3.10 -m pip install git+https://github.com/NVlabs/tiny-cuda-nn.git@v1.6#subdirectory=bindings/torch
+
+# Install pycolmap 0.3.0, required by hloc.
+# TODO(https://github.com/colmap/pycolmap/issues/111) use wheel when available for Python 3.10
+RUN git clone --branch v0.3.0 --recursive https://github.com/colmap/pycolmap.git && \
+ cd pycolmap && \
+ python3.10 -m pip install . && \
+ cd ..
+
+# Install hloc master (last release (1.3) is too old) as alternative feature detector and matcher option for nerfstudio.
+RUN git clone --branch master --recursive https://github.com/cvg/Hierarchical-Localization && \
+ cd Hierarchical-Localization && \
+ python3.10 -m pip install -e . && \
+ cd ..
# Copy nerfstudio folder and give ownership to user.
ADD . /home/user/nerfstudio
diff --git a/colab/demo.ipynb b/colab/demo.ipynb
index d1c58ad6c..f88f3f494 100644
--- a/colab/demo.ipynb
+++ b/colab/demo.ipynb
@@ -7,7 +7,7 @@
"colab_type": "text"
},
"source": [
- "
"
+ "
"
]
},
{
@@ -109,8 +109,8 @@
"\n",
"# Installing TinyCuda\n",
"%cd /content/\n",
- "!gdown \"https://drive.google.com/u/0/uc?id=1mB3IxcpmTVmQN-So0t2lxjxbHvqWr2zf\" \n",
- "!pip install tinycudann-1.5-cp38-cp38-linux_x86_64.whl\n",
+ "!gdown \"https://drive.google.com/u/1/uc?id=12RL_NVgE9WGvr_fEsXEiuaJ1QESvQCPl&confirm=t\" \n",
+ "!pip install tinycudann-1.7-cp38-cp38-linux_x86_64.whl\n",
"\n",
"# Installing COLMAP\n",
"%cd /content/\n",
@@ -383,4 +383,4 @@
},
"nbformat": 4,
"nbformat_minor": 0
-}
+}
\ No newline at end of file
diff --git a/docs/developer_guides/pipelines/dataparsers.md b/docs/developer_guides/pipelines/dataparsers.md
index 40ef7f4fd..6b81803c2 100644
--- a/docs/developer_guides/pipelines/dataparsers.md
+++ b/docs/developer_guides/pipelines/dataparsers.md
@@ -69,8 +69,8 @@ class NerfstudioDataParserConfig(DataParserConfig):
"""How much to scale the region of interest by."""
orientation_method: Literal["pca", "up"] = "up"
"""The method to use for orientation."""
- train_split_percentage: float = 0.9
- """The percent of images to use for training. The remaining images are for eval."""
+ train_split_fraction: float = 0.9
+ """The fraction of images to use for training. The remaining images are for eval."""
@dataclass
class Nerfstudio(DataParser):
diff --git a/docs/quickstart/blender_addon.md b/docs/extensions/blender_addon.md
similarity index 95%
rename from docs/quickstart/blender_addon.md
rename to docs/extensions/blender_addon.md
index 425a873df..2f410ff4f 100644
--- a/docs/quickstart/blender_addon.md
+++ b/docs/extensions/blender_addon.md
@@ -11,7 +11,7 @@ This Blender add-on allows for compositing with a Nerfstudio render as a backgro
## Prerequisites
-[Blender](https://www.blender.org/) on Mac or Windows. The python file add-on can be downloaded from the main repo in the `scripts/blender` folder. Before starting, export the mesh or point cloud representation of the NeRF from Nerfstudio, which will be used as reference for the actual NeRF in the Blender scene. Mesh export at a good quality is preferred, however, if the export is not clear or the NeRF is very large, a detailed point cloud export will also work.
+First install [Blender](https://www.blender.org/). The python file add-on can be downloaded from the main repo in the `scripts/blender` folder. Before starting, export the mesh or point cloud representation of the NeRF from Nerfstudio, which will be used as reference for the actual NeRF in the Blender scene. Mesh export at a good quality is preferred, however, if the export is not clear or the NeRF is very large, a detailed point cloud export will also work.
## Add-on Setup Instructions
diff --git a/docs/extensions/imgs/desolation_unreal.png b/docs/extensions/imgs/desolation_unreal.png
new file mode 100644
index 000000000..3214d14a1
Binary files /dev/null and b/docs/extensions/imgs/desolation_unreal.png differ
diff --git a/docs/extensions/imgs/export_nvol.png b/docs/extensions/imgs/export_nvol.png
new file mode 100644
index 000000000..d00be381c
Binary files /dev/null and b/docs/extensions/imgs/export_nvol.png differ
diff --git a/docs/extensions/imgs/nvol_ready.png b/docs/extensions/imgs/nvol_ready.png
new file mode 100644
index 000000000..4d8d94715
Binary files /dev/null and b/docs/extensions/imgs/nvol_ready.png differ
diff --git a/docs/extensions/unreal_engine.md b/docs/extensions/unreal_engine.md
new file mode 100644
index 000000000..f533f2a56
--- /dev/null
+++ b/docs/extensions/unreal_engine.md
@@ -0,0 +1,40 @@
+# Exporting to Unreal Engine
+
+ ```{image} imgs/desolation_unreal.png
+ :width: 800
+ :align: center
+ :alt: NeRF in Unreal Engine
+ ```
+
+## Overview
+
+NeRFStudio models can be used in Unreal Engine if they are converted to an NVOL file. NVOL is a new standard file format to store NeRFs in a fast and efficient way. NVOL files can be obtained from NeRFStudio checkpoints files (.ckpt) using the [Volinga Suite](https://volinga.ai/).
+
+:::{admonition} Note
+:class: warning
+Volinga Suite is not yet publicly available. If you are interested in converting your models to NVOL, sign up for the beta at [volinga.ai](https://volinga.ai).
+:::
+
+
+## Exporting your model to NVOL
+Currently NVOL file only supports Volinga model (which is based on nerfacto). You can train your model using the following command:
+
+```bash
+ns-train volinga --data /path/to/your/data --vis viewer
+```
+
+Once the training is done, you can find your checkpoint file in the `outputs/path-to-your-data/volinga` folder. Then, you can drag it to Volinga Suite to export it to NVOL.
+
+ ```{image} imgs/export_nvol.png
+ :width: 400
+ :align: center
+ :alt: Nvol export in Voliga Suite
+ ```
+
+Once the NVOL is ready, you can download it and use it in Unreal Engine.
+
+ ```{image} imgs/nvol_ready.png
+ :width: 800
+ :align: center
+ :alt: NVOL ready to use
+ ```
\ No newline at end of file
diff --git a/docs/index.md b/docs/index.md
index 88e4c90ae..b03e8712b 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -52,10 +52,16 @@ quickstart/custom_dataset
quickstart/viewer_quickstart
quickstart/export_geometry
quickstart/data_conventions
-quickstart/blender_addon
Contributing
```
+```{toctree}
+:hidden:
+:caption: Extensions
+extensions/blender_addon
+extensions/unreal_engine
+```
+
```{toctree}
:hidden:
:caption: NeRFology
diff --git a/docs/nerfology/methods/semantic_nerfw.md b/docs/nerfology/methods/semantic_nerfw.md
index 3888fdf8a..b023418da 100644
--- a/docs/nerfology/methods/semantic_nerfw.md
+++ b/docs/nerfology/methods/semantic_nerfw.md
@@ -22,16 +22,16 @@ The transient embeddings are still under development. Please stay tuned.
### Running Model
-Download the Friends Dataset
+Download the sitcoms3D Dataset
```bash
-ns-download-data friends
+ns-download-data sitcoms3d
```
```bash
ns-train semantic-nerfw
```
-This model defaults to using the "friends" dataset from the paper ["The One Where They Reconstructed 3D Humans and Environments in TV Shows"](https://ethanweber.me/sitcoms3D/).
+This model defaults to using the "sitcoms3D" dataset from the paper ["The One Where They Reconstructed 3D Humans and Environments in TV Shows"](https://ethanweber.me/sitcoms3D/).
diff --git a/docs/quickstart/installation.md b/docs/quickstart/installation.md
index 81a64b024..2a2db4453 100644
--- a/docs/quickstart/installation.md
+++ b/docs/quickstart/installation.md
@@ -127,7 +127,7 @@ pip install -e .[docs]
Instead of installing and compiling prerequisites, setting up the environment and installing dependencies, a ready to use docker image is provided.
### Prerequisites
Docker ([get docker](https://docs.docker.com/get-docker/)) and nvidia GPU drivers ([get nvidia drivers](https://www.nvidia.de/Download/index.aspx?lang=de)), capable of working with CUDA 11.8, must be installed.
-The docker image can then either be pulled from [here](https://hub.docker.com/r/dromni/nerfstudio/tags) (replace with the actual version, e.g. 0.1.17)
+The docker image can then either be pulled from [here](https://hub.docker.com/r/dromni/nerfstudio/tags) (replace with the actual version, e.g. 0.1.18)
```bash
docker pull dromni/nerfstudio:
```
@@ -135,6 +135,14 @@ or be built from the repository using
```bash
docker build --tag nerfstudio -f Dockerfile .
```
+
+To restrict to only CUDA architectures that you have available locally, use the `CUDA_ARCHITECTURES`
+build arg and look up [the compute capability for your GPU](https://developer.nvidia.com/cuda-gpus).
+For example, here's how to build with support for GeForce 30xx series GPUs:
+```bash
+docker build --build-arg CUDA_ARCHITECTURES=86 -tag nerfstudio-86 .
+```
+
### Using an interactive container
The docker container can be launched with an interactive terminal where nerfstudio commands can be entered as usual. Some parameters are required and some are strongly recommended for usage as following:
```bash
@@ -144,6 +152,7 @@ docker run --gpus all \ # Give the conta
-p 7007:7007 \ # Map port from local machine to docker container (required to access the web interface/UI).
--rm \ # Remove container after it is closed (recommended).
-it \ # Start container in interactive mode.
+ --shm-size=12gb \ # Increase memory assigned to container to avoid memory limitations, default is 64 MB (recommended).
dromni/nerfstudio: # Docker image name if you pulled from docker hub.
<--- OR --->
nerfstudio # Docker image tag if you built the image from the Dockerfile by yourself using the command from above.
@@ -151,7 +160,7 @@ docker run --gpus all \ # Give the conta
### Call nerfstudio commands directly
Besides, the container can also directly be used by adding the nerfstudio command to the end.
```bash
-docker run --gpus all -v /folder/of/your/data:/workspace/ -v /home//.cache/:/home/user/.cache/ -p 7007:7007 --rm -it # Parameters.
+docker run --gpus all -v /folder/of/your/data:/workspace/ -v /home//.cache/:/home/user/.cache/ -p 7007:7007 --rm -it --shm-size=12gb # Parameters.
dromni/nerfstudio: \ # Docker image name
ns-process-data video --data /workspace/video.mp4 # Smaple command of nerfstudio.
```
@@ -165,6 +174,7 @@ docker run --gpus all -v /folder/of/your/data:/workspace/ -v /home//.
- The docker image (respectively Ubuntu 22.04) comes with Python3.10, no older version of Python is installed.
- If you call the container with commands directly, you still might want to add the interactive terminal ('-it') flag to get live log outputs of the nerfstudio scripts. In case the container is used in an automated environment the flag should be discarded.
- The current version of docker is built for multi-architecture (CUDA architectures) use. The target architecture(s) must be defined at build time for Colmap and tinyCUDNN to be able to compile properly. If your GPU architecture is not covered by the following table you need to replace the number in the line ```ARG CUDA_ARCHITECTURES=90;89;86;80;75;70;61;52;37``` to your specific architecture. It also is a good idea to remove all architectures but yours (e.g. ```ARG CUDA_ARCHITECTURES=86```) to speedup the docker build process a lot.
+- To avoid memory issues or limitations during processing, it is recommended to use either ```--shm-size=12gb``` or ```--ipc=host``` to increase the memory available to the docker container. 12gb as in the example is only a suggestion and may be replaced by other values depending on your hardware and requirements.
**Currently supported CUDA architectures in the docker image**
diff --git a/nerfstudio/cameras/camera_paths.py b/nerfstudio/cameras/camera_paths.py
index a43504694..a313cad4d 100644
--- a/nerfstudio/cameras/camera_paths.py
+++ b/nerfstudio/cameras/camera_paths.py
@@ -38,7 +38,7 @@ def get_interpolated_camera_path(cameras: Cameras, steps: int) -> Cameras:
A new set of cameras along a path.
"""
Ks = cameras.get_intrinsics_matrices().cpu().numpy()
- poses = cameras.camera_to_worlds().cpu().numpy()
+ poses = cameras.camera_to_worlds.cpu().numpy()
poses, Ks = get_interpolated_poses_many(poses, Ks, steps_per_transition=steps)
cameras = Cameras(fx=Ks[:, 0, 0], fy=Ks[:, 1, 1], cx=Ks[0, 0, 2], cy=Ks[0, 1, 2], camera_to_worlds=poses)
diff --git a/nerfstudio/cameras/camera_utils.py b/nerfstudio/cameras/camera_utils.py
index bb6430717..b1dd5a267 100644
--- a/nerfstudio/cameras/camera_utils.py
+++ b/nerfstudio/cameras/camera_utils.py
@@ -21,13 +21,14 @@ from typing import List, Optional, Tuple
import numpy as np
import torch
+from numpy.typing import ArrayLike
from torchtyping import TensorType
from typing_extensions import Literal
_EPS = np.finfo(float).eps * 4.0
-def unit_vector(data, axis: Optional[int] = None) -> np.ndarray:
+def unit_vector(data: ArrayLike, axis: Optional[int] = None) -> np.ndarray:
"""Return ndarray normalized by length, i.e. Euclidean norm, along axis.
Args:
@@ -46,7 +47,7 @@ def unit_vector(data, axis: Optional[int] = None) -> np.ndarray:
return data
-def quaternion_from_matrix(matrix, isprecise: bool = False) -> np.ndarray:
+def quaternion_from_matrix(matrix: ArrayLike, isprecise: bool = False) -> np.ndarray:
"""Return quaternion from rotation matrix.
Args:
@@ -102,7 +103,9 @@ def quaternion_from_matrix(matrix, isprecise: bool = False) -> np.ndarray:
return q
-def quaternion_slerp(quat0, quat1, fraction: float, spin: int = 0, shortestpath: bool = True) -> np.ndarray:
+def quaternion_slerp(
+ quat0: ArrayLike, quat1: ArrayLike, fraction: float, spin: int = 0, shortestpath: bool = True
+) -> np.ndarray:
"""Return spherical linear interpolation between two quaternions.
Args:
quat0: first quaternion
@@ -136,7 +139,7 @@ def quaternion_slerp(quat0, quat1, fraction: float, spin: int = 0, shortestpath:
return q0
-def quaternion_matrix(quaternion) -> np.ndarray:
+def quaternion_matrix(quaternion: ArrayLike) -> np.ndarray:
"""Return homogeneous rotation matrix from quaternion.
Args:
@@ -158,7 +161,7 @@ def quaternion_matrix(quaternion) -> np.ndarray:
)
-def get_interpolated_poses(pose_a, pose_b, steps: int = 10) -> List[float]:
+def get_interpolated_poses(pose_a: ArrayLike, pose_b: ArrayLike, steps: int = 10) -> List[float]:
"""Return interpolation of poses with specified number of steps.
Args:
poseA: first pose
@@ -178,7 +181,7 @@ def get_interpolated_poses(pose_a, pose_b, steps: int = 10) -> List[float]:
pose = np.identity(4)
pose[:3, :3] = quaternion_matrix(quat)[:3, :3]
pose[:3, 3] = tran
- poses_ab.append(pose)
+ poses_ab.append(pose[:3])
return poses_ab
@@ -215,17 +218,21 @@ def get_interpolated_poses_many(
tuple of new poses and intrinsics
"""
traj = []
- Ks = []
+ k_interp = []
for idx in range(poses.shape[0] - 1):
pose_a = poses[idx]
pose_b = poses[idx + 1]
poses_ab = get_interpolated_poses(pose_a, pose_b, steps=steps_per_transition)
traj += poses_ab
- Ks += get_interpolated_k(Ks[idx], Ks[idx + 1], steps_per_transition)
- return torch.stack(traj, dim=0), torch.stack(Ks, dim=0)
+ k_interp += get_interpolated_k(Ks[idx], Ks[idx + 1], steps=steps_per_transition)
+
+ traj = np.stack(traj, axis=0)
+ k_interp = np.stack(k_interp, axis=0)
+
+ return torch.tensor(traj), torch.tensor(k_interp)
-def normalize(x) -> TensorType[...]:
+def normalize(x: torch.Tensor) -> TensorType[...]:
"""Returns a normalized vector."""
return x / torch.linalg.norm(x)
@@ -245,7 +252,7 @@ def normalize_with_norm(x: torch.Tensor, dim: int) -> Tuple[torch.Tensor, torch.
return x / norm, norm
-def viewmatrix(lookat, up, pos) -> TensorType[...]:
+def viewmatrix(lookat: torch.Tensor, up: torch.Tensor, pos: torch.Tensor) -> TensorType[...]:
"""Returns a camera transformation matrix.
Args:
diff --git a/nerfstudio/cameras/cameras.py b/nerfstudio/cameras/cameras.py
index 80b7f6487..e0ed08e4f 100644
--- a/nerfstudio/cameras/cameras.py
+++ b/nerfstudio/cameras/cameras.py
@@ -19,7 +19,6 @@ import base64
import math
import os
from dataclasses import dataclass
-from distutils.util import strtobool
from enum import Enum, auto
from typing import Dict, List, Optional, Tuple, Union
@@ -34,8 +33,11 @@ import nerfstudio.utils.poses as pose_utils
from nerfstudio.cameras import camera_utils
from nerfstudio.cameras.rays import RayBundle
from nerfstudio.data.scene_box import SceneBox
+from nerfstudio.utils.misc import strtobool
from nerfstudio.utils.tensor_dataclass import TensorDataclass
+TORCH_DEVICE = Union[torch.device, str] # pylint: disable=invalid-name
+
class CameraType(Enum):
"""Supported camera types."""
@@ -109,7 +111,7 @@ class Cameras(TensorDataclass):
]
] = CameraType.PERSPECTIVE,
times: Optional[TensorType["num_cameras"]] = None,
- ):
+ ) -> None:
"""Initializes the Cameras object.
Note on Input Tensor Dimensions: All of these tensors have items of dimensions TensorType[3, 4]
@@ -148,7 +150,7 @@ class Cameras(TensorDataclass):
self._use_nerfacc = strtobool(os.environ.get("INTERSECT_WITH_NERFACC", "TRUE"))
- def _init_get_fc_xy(self, fc_xy, name):
+ def _init_get_fc_xy(self, fc_xy: Union[float, torch.Tensor], name: str) -> torch.Tensor:
"""
Parses the input focal length / principle point x or y and returns a tensor of the correct shape
@@ -243,7 +245,7 @@ class Cameras(TensorDataclass):
raise ValueError("Height must be an int, tensor, or None, received: " + str(type(h_w)))
return h_w
- def _init_get_times(self, times):
+ def _init_get_times(self, times: Union[None, torch.Tensor]) -> Union[None, torch.Tensor]:
if times is None:
times = None
elif isinstance(times, torch.Tensor):
@@ -255,7 +257,7 @@ class Cameras(TensorDataclass):
return times
@property
- def device(self):
+ def device(self) -> TORCH_DEVICE:
"""Returns the device that the camera is on."""
return self.camera_to_worlds.device
@@ -270,7 +272,7 @@ class Cameras(TensorDataclass):
return self.width
@property
- def is_jagged(self):
+ def is_jagged(self) -> bool:
"""
Returns whether or not the cameras are "jagged" (i.e. the height and widths are different, meaning that
you cannot concatenate the image coordinate maps together)
diff --git a/nerfstudio/cameras/rays.py b/nerfstudio/cameras/rays.py
index c65315c26..fd4e8129e 100644
--- a/nerfstudio/cameras/rays.py
+++ b/nerfstudio/cameras/rays.py
@@ -17,7 +17,7 @@ Some ray datastructures.
"""
import random
from dataclasses import dataclass
-from typing import Callable, Dict, Optional
+from typing import Callable, Dict, Optional, Union
import torch
from torchtyping import TensorType
@@ -25,6 +25,8 @@ from torchtyping import TensorType
from nerfstudio.utils.math import Gaussians, conical_frustum_to_gaussian
from nerfstudio.utils.tensor_dataclass import TensorDataclass
+TORCH_DEVICE = Union[str, torch.device] # pylint: disable=invalid-name
+
@dataclass
class Frustums(TensorDataclass):
@@ -77,7 +79,7 @@ class Frustums(TensorDataclass):
)
@classmethod
- def get_mock_frustum(cls, device="cpu") -> "Frustums":
+ def get_mock_frustum(cls, device: Optional[TORCH_DEVICE] = "cpu") -> "Frustums":
"""Helper function to generate a placeholder frustum.
Returns:
@@ -169,7 +171,7 @@ class RayBundle(TensorDataclass):
"""
self.camera_indices = torch.ones_like(self.origins[..., 0:1]).long() * camera_index
- def __len__(self):
+ def __len__(self) -> int:
num_rays = torch.numel(self.origins) // self.origins.shape[-1]
return num_rays
diff --git a/nerfstudio/configs/experiment_config.py b/nerfstudio/configs/experiment_config.py
index b73b9c55e..765c64ef7 100644
--- a/nerfstudio/configs/experiment_config.py
+++ b/nerfstudio/configs/experiment_config.py
@@ -98,7 +98,12 @@ class ExperimentConfig(InstantiateConfig):
def set_experiment_name(self) -> None:
"""Dynamically set the experiment name"""
if self.experiment_name is None:
- self.experiment_name = str(self.pipeline.datamanager.data).replace("../", "").replace("/", "-")
+ datapath = self.pipeline.datamanager.data
+ if datapath is not None:
+ datapath = datapath.parent if datapath.is_file() else datapath
+ self.experiment_name = str(datapath.stem)
+ else:
+ self.experiment_name = "unnamed"
def get_base_dir(self) -> Path:
"""Retrieve the base directory to set relative paths"""
diff --git a/nerfstudio/configs/method_configs.py b/nerfstudio/configs/method_configs.py
index cf3fc20ce..9134e4f58 100644
--- a/nerfstudio/configs/method_configs.py
+++ b/nerfstudio/configs/method_configs.py
@@ -37,7 +37,6 @@ from nerfstudio.data.datamanagers.variable_res_datamanager import (
from nerfstudio.data.dataparsers.blender_dataparser import BlenderDataParserConfig
from nerfstudio.data.dataparsers.dnerf_dataparser import DNeRFDataParserConfig
from nerfstudio.data.dataparsers.dycheck_dataparser import DycheckDataParserConfig
-from nerfstudio.data.dataparsers.friends_dataparser import FriendsDataParserConfig
from nerfstudio.data.dataparsers.instant_ngp_dataparser import (
InstantNGPDataParserConfig,
)
@@ -45,6 +44,7 @@ from nerfstudio.data.dataparsers.nerfstudio_dataparser import NerfstudioDataPars
from nerfstudio.data.dataparsers.phototourism_dataparser import (
PhototourismDataParserConfig,
)
+from nerfstudio.data.dataparsers.sitcoms3d_dataparser import Sitcoms3DDataParserConfig
from nerfstudio.engine.optimizers import AdamOptimizerConfig, RAdamOptimizerConfig
from nerfstudio.engine.schedulers import ExponentialDecaySchedulerConfig
from nerfstudio.engine.trainer import TrainerConfig
@@ -67,6 +67,7 @@ method_configs: Dict[str, TrainerConfig] = {}
descriptions = {
"nerfacto": "Recommended real-time model tuned for real captures. This model will be continually updated.",
"depth-nerfacto": "Nerfacto with depth supervision.",
+ "volinga": "Real-time rendering model from Volinga. Directly exportable to NVOL format at https://volinga.ai/",
"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",
"mipnerf": "High quality model for bounded scenes. (slow)",
@@ -142,6 +143,47 @@ method_configs["depth-nerfacto"] = TrainerConfig(
vis="viewer",
)
+method_configs["volinga"] = TrainerConfig(
+ method_name="volinga",
+ steps_per_eval_batch=500,
+ steps_per_save=2000,
+ max_num_iterations=30000,
+ mixed_precision=True,
+ pipeline=VanillaPipelineConfig(
+ datamanager=VanillaDataManagerConfig(
+ dataparser=NerfstudioDataParserConfig(),
+ train_num_rays_per_batch=4096,
+ eval_num_rays_per_batch=4096,
+ camera_optimizer=CameraOptimizerConfig(
+ mode="SO3xR3", optimizer=AdamOptimizerConfig(lr=6e-4, eps=1e-8, weight_decay=1e-2)
+ ),
+ ),
+ model=NerfactoModelConfig(
+ eval_num_rays_per_chunk=1 << 15,
+ hidden_dim=32,
+ hidden_dim_color=32,
+ hidden_dim_transient=32,
+ num_nerf_samples_per_ray=24,
+ proposal_net_args_list=[
+ {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 128, "use_linear": True},
+ {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 256, "use_linear": True},
+ ],
+ ),
+ ),
+ optimizers={
+ "proposal_networks": {
+ "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15),
+ "scheduler": None,
+ },
+ "fields": {
+ "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15),
+ "scheduler": None,
+ },
+ },
+ viewer=ViewerConfig(num_rays_per_chunk=1 << 15),
+ vis="viewer",
+)
+
method_configs["instant-ngp"] = TrainerConfig(
method_name="instant-ngp",
steps_per_eval_batch=500,
@@ -219,7 +261,7 @@ method_configs["semantic-nerfw"] = TrainerConfig(
mixed_precision=True,
pipeline=VanillaPipelineConfig(
datamanager=SemanticDataManagerConfig(
- dataparser=FriendsDataParserConfig(), train_num_rays_per_batch=4096, eval_num_rays_per_batch=8192
+ dataparser=Sitcoms3DDataParserConfig(), train_num_rays_per_batch=4096, eval_num_rays_per_batch=8192
),
model=SemanticNerfWModelConfig(eval_num_rays_per_chunk=1 << 16),
),
diff --git a/nerfstudio/data/datamanagers/base_datamanager.py b/nerfstudio/data/datamanagers/base_datamanager.py
index db4ae8ebb..dd0109c1d 100644
--- a/nerfstudio/data/datamanagers/base_datamanager.py
+++ b/nerfstudio/data/datamanagers/base_datamanager.py
@@ -36,11 +36,13 @@ from nerfstudio.cameras.camera_optimizers import CameraOptimizerConfig
from nerfstudio.cameras.cameras import CameraType
from nerfstudio.cameras.rays import RayBundle
from nerfstudio.configs.base_config import InstantiateConfig
+from nerfstudio.data.dataparsers.arkitscenes_dataparser import (
+ ARKitScenesDataParserConfig,
+)
from nerfstudio.data.dataparsers.base_dataparser import DataparserOutputs
from nerfstudio.data.dataparsers.blender_dataparser import BlenderDataParserConfig
from nerfstudio.data.dataparsers.dnerf_dataparser import DNeRFDataParserConfig
from nerfstudio.data.dataparsers.dycheck_dataparser import DycheckDataParserConfig
-from nerfstudio.data.dataparsers.friends_dataparser import FriendsDataParserConfig
from nerfstudio.data.dataparsers.instant_ngp_dataparser import (
InstantNGPDataParserConfig,
)
@@ -50,8 +52,15 @@ from nerfstudio.data.dataparsers.nuscenes_dataparser import NuScenesDataParserCo
from nerfstudio.data.dataparsers.phototourism_dataparser import (
PhototourismDataParserConfig,
)
+from nerfstudio.data.dataparsers.scannet_dataparser import ScanNetDataParserConfig
+from nerfstudio.data.dataparsers.sdfstudio_dataparser import SDFStudioDataParserConfig
+from nerfstudio.data.dataparsers.sitcoms3d_dataparser import Sitcoms3DDataParserConfig
from nerfstudio.data.datasets.base_dataset import InputDataset
-from nerfstudio.data.pixel_samplers import EquirectangularPixelSampler, PixelSampler
+from nerfstudio.data.pixel_samplers import (
+ EquirectangularPixelSampler,
+ PatchPixelSampler,
+ PixelSampler,
+)
from nerfstudio.data.utils.dataloaders import (
CacheDataloader,
FixedIndicesEvalDataloader,
@@ -69,13 +78,16 @@ AnnotatedDataParserUnion = tyro.conf.OmitSubcommandPrefixes[ # Omit prefixes of
{
"nerfstudio-data": NerfstudioDataParserConfig(),
"minimal-parser": MinimalDataParserConfig(),
+ "arkit-data": ARKitScenesDataParserConfig(),
"blender-data": BlenderDataParserConfig(),
- "friends-data": FriendsDataParserConfig(),
"instant-ngp-data": InstantNGPDataParserConfig(),
"nuscenes-data": NuScenesDataParserConfig(),
"dnerf-data": DNeRFDataParserConfig(),
"phototourism-data": PhototourismDataParserConfig(),
"dycheck-data": DycheckDataParserConfig(),
+ "scannet-data": ScanNetDataParserConfig(),
+ "sdfstudio-data": SDFStudioDataParserConfig(),
+ "sitcoms3d-data": Sitcoms3DDataParserConfig(),
},
prefix_names=False, # Omit prefixes in subcommands themselves.
)
@@ -275,10 +287,7 @@ class DataManager(nn.Module):
@dataclass
class VanillaDataManagerConfig(DataManagerConfig):
- """Configuration for data manager instantiation; DataManager is in charge of keeping the train/eval dataparsers;
- After instantiation, data manager holds both train/eval datasets and is in charge of returning unpacked
- train/eval data at each iteration
- """
+ """A basic data manager"""
_target: Type = field(default_factory=lambda: VanillaDataManager)
"""Target class to instantiate."""
@@ -309,6 +318,8 @@ class VanillaDataManagerConfig(DataManagerConfig):
"""The scale factor for scaling spatial data such as images, mask, semantics
along with relevant information about camera intrinsics
"""
+ patch_size: int = 1
+ """Size of patch to sample from. If >1, patch-based sampling will be used."""
class VanillaDataManager(DataManager): # pylint: disable=abstract-method
@@ -377,6 +388,9 @@ class VanillaDataManager(DataManager): # pylint: disable=abstract-method
self, dataset: InputDataset, *args: Any, **kwargs: Any
) -> PixelSampler:
"""Infer pixel sampler to use."""
+ if self.config.patch_size > 1:
+ return PatchPixelSampler(*args, **kwargs, patch_size=self.config.patch_size)
+
# If all images are equirectangular, use equirectangular pixel sampler
is_equirectangular = dataset.cameras.camera_type == CameraType.EQUIRECTANGULAR.value
if is_equirectangular.all():
diff --git a/nerfstudio/data/dataparsers/arkitscenes_dataparser.py b/nerfstudio/data/dataparsers/arkitscenes_dataparser.py
new file mode 100644
index 000000000..736f9941b
--- /dev/null
+++ b/nerfstudio/data/dataparsers/arkitscenes_dataparser.py
@@ -0,0 +1,211 @@
+# Copyright 2022 The Nerfstudio Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Data parser for ARKitScenes dataset"""
+import math
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Type
+
+import cv2
+import numpy as np
+import torch
+
+from nerfstudio.cameras.cameras import Cameras, CameraType
+from nerfstudio.data.dataparsers.base_dataparser import (
+ DataParser,
+ DataParserConfig,
+ DataparserOutputs,
+)
+from nerfstudio.data.scene_box import SceneBox
+
+
+# Taken from https://github.com/apple/ARKitScenes/blob/main/threedod/benchmark_scripts/utils/tenFpsDataLoader.py
+def traj_string_to_matrix(traj_string: str):
+ """convert traj_string into translation and rotation matrices
+ Args:
+ traj_string: A space-delimited file where each line represents a camera position at a particular timestamp.
+ The file has seven columns:
+ * Column 1: timestamp
+ * Columns 2-4: rotation (axis-angle representation in radians)
+ * Columns 5-7: translation (usually in meters)
+ Returns:
+ ts: translation matrix
+ Rt: rotation matrix
+ """
+ tokens = traj_string.split()
+ assert len(tokens) == 7
+ ts = tokens[0]
+ # Rotation in angle axis
+ angle_axis = [float(tokens[1]), float(tokens[2]), float(tokens[3])]
+ r_w_to_p, _ = cv2.Rodrigues(np.asarray(angle_axis))
+ # Translation
+ t_w_to_p = np.asarray([float(tokens[4]), float(tokens[5]), float(tokens[6])])
+ extrinsics = np.eye(4, 4)
+ extrinsics[:3, :3] = r_w_to_p
+ extrinsics[:3, -1] = t_w_to_p
+ Rt = np.linalg.inv(extrinsics)
+ return (ts, Rt)
+
+
+@dataclass
+class ARKitScenesDataParserConfig(DataParserConfig):
+ """ARKitScenes dataset config.
+ ARKitScenes dataset (http://github.com/apple/ARKitScenes) is a large-scale 3D dataset of indoor scenes.
+ This dataparser uses 3D deteciton subset of the ARKitScenes dataset.
+ """
+
+ _target: Type = field(default_factory=lambda: ARKitScenes)
+ """target class to instantiate"""
+ data: Path = Path("data/ARKitScenes/3dod/Validation/41069021")
+ """Path to ARKitScenes folder with densely extracted scenes."""
+ scene_scale: float = 1.0
+ """How much to scale the region of interest by."""
+ center_poses: bool = True
+ """Whether to center the poses."""
+ scale_poses: bool = True
+ """Whether to automatically scale the poses to fit in +/- 1 bounding box."""
+ train_split_fraction: float = 0.9
+ """The fraction of images to use for training. The remaining images are for eval."""
+ depth_unit_scale_factor: float = 1e-3
+ """Scales the depth values to meters. Default value is 0.001 for a millimeter to meter conversion."""
+
+
+@dataclass
+class ARKitScenes(DataParser):
+ """ARKitScenes DatasetParser"""
+
+ config: ARKitScenesDataParserConfig
+
+ def _generate_dataparser_outputs(self, split="train"):
+ video_id = self.config.data.name
+
+ image_dir = self.config.data / f"{video_id}_frames" / "lowres_wide"
+ depth_dir = self.config.data / f"{video_id}_frames" / "lowres_depth"
+ intrinsics_dir = self.config.data / f"{video_id}_frames" / "lowres_wide_intrinsics"
+ pose_file = self.config.data / f"{video_id}_frames" / "lowres_wide.traj"
+
+ frame_ids = [x.name for x in sorted(depth_dir.iterdir())]
+ frame_ids = [x.split(".png")[0].split("_")[1] for x in frame_ids]
+ frame_ids.sort()
+
+ poses_from_traj = {}
+ with open(pose_file, "r", encoding="utf-8") as f:
+ traj = f.readlines()
+
+ for line in traj:
+ poses_from_traj[f"{round(float(line.split(' ')[0]), 3):.3f}"] = np.array(
+ traj_string_to_matrix(line)[1].tolist()
+ )
+
+ image_filenames, depth_filenames, intrinsics, poses = [], [], [], []
+ w, h, _, _, _, _ = np.loadtxt(list(sorted(intrinsics_dir.iterdir()))[0]) # Get image size from first intrinsic
+
+ for frame_id in frame_ids:
+ intrinsic = self._get_intrinsic(intrinsics_dir, frame_id, video_id)
+ frame_pose = self._get_pose(frame_id, poses_from_traj)
+
+ intrinsics.append(intrinsic)
+ image_filenames.append(image_dir / f"{video_id}_{frame_id}.png")
+ depth_filenames.append(depth_dir / f"{video_id}_{frame_id}.png")
+ poses.append(frame_pose)
+
+ # filter image_filenames and poses based on train/eval split percentage
+ num_images = len(image_filenames)
+ num_train_images = math.ceil(num_images * self.config.train_split_fraction)
+ num_eval_images = num_images - num_train_images
+ i_all = np.arange(num_images)
+ i_train = np.linspace(
+ 0, num_images - 1, num_train_images, dtype=int
+ ) # equally spaced training images starting and ending at 0 and num_images-1
+ i_eval = np.setdiff1d(i_all, i_train) # eval images are the remaining images
+ assert len(i_eval) == num_eval_images
+ if split == "train":
+ indices = i_train
+ elif split in ["val", "test"]:
+ indices = i_eval
+ else:
+ raise ValueError(f"Unknown dataparser split {split}")
+
+ poses = torch.from_numpy(np.stack(poses).astype(np.float32))
+ intrinsics = torch.from_numpy(np.stack(intrinsics).astype(np.float32))
+
+ if self.config.center_poses:
+ poses[:, :3, 3] -= poses[:, :3, 3].mean(dim=0)
+
+ if self.config.scale_poses:
+ poses[:, :3, 3] /= poses[:, :3, 3].abs().max()
+
+ # Choose image_filenames and poses based on split, but after auto orient and scaling the poses.
+ image_filenames = [image_filenames[i] for i in indices]
+ depth_filenames = [depth_filenames[i] for i in indices] if len(depth_filenames) > 0 else []
+ intrinsics = intrinsics[indices.tolist()]
+ poses = poses[indices.tolist()]
+
+ # in x,y,z order
+ # assumes that the scene is centered at the origin
+ aabb_scale = self.config.scene_scale
+ scene_box = SceneBox(
+ aabb=torch.tensor(
+ [[-aabb_scale, -aabb_scale, -aabb_scale], [aabb_scale, aabb_scale, aabb_scale]], dtype=torch.float32
+ )
+ )
+
+ cameras = Cameras(
+ fx=intrinsics[:, 0, 0],
+ fy=intrinsics[:, 1, 1],
+ cx=intrinsics[:, 0, 2],
+ cy=intrinsics[:, 1, 2],
+ height=int(h),
+ width=int(w),
+ camera_to_worlds=poses[:, :3, :4],
+ camera_type=CameraType.PERSPECTIVE,
+ )
+
+ dataparser_outputs = DataparserOutputs(
+ image_filenames=image_filenames,
+ cameras=cameras,
+ scene_box=scene_box,
+ metadata={
+ "depth_filenames": depth_filenames if len(depth_filenames) > 0 else None,
+ "depth_unit_scale_factor": self.config.depth_unit_scale_factor,
+ },
+ )
+ return dataparser_outputs
+
+ @staticmethod
+ def _get_intrinsic(intrinsics_dir: Path, frame_id: str, video_id: str):
+ intrinsic_fn = intrinsics_dir / f"{video_id}_{frame_id}.pincam"
+
+ if not intrinsic_fn.exists():
+ intrinsic_fn = intrinsics_dir / f"{video_id}_{float(frame_id) - 0.001:.3f}.pincam"
+
+ if not intrinsic_fn.exists():
+ intrinsic_fn = intrinsics_dir / f"{video_id}_{float(frame_id) + 0.001:.3f}.pincam"
+
+ _, _, fx, fy, hw, hh = np.loadtxt(intrinsic_fn)
+ intrinsic = np.asarray([[fx, 0, hw], [0, fy, hh], [0, 0, 1]])
+ return intrinsic
+
+ @staticmethod
+ def _get_pose(frame_id: str, poses_from_traj: dict):
+ if str(frame_id) in poses_from_traj:
+ frame_pose = np.array(poses_from_traj[str(frame_id)])
+ else:
+ for my_key in poses_from_traj:
+ if abs(float(frame_id) - float(my_key)) < 0.005:
+ frame_pose = np.array(poses_from_traj[str(my_key)])
+
+ frame_pose[0:3, 1:3] *= -1
+ return frame_pose
diff --git a/nerfstudio/data/dataparsers/minimal_dataparser.py b/nerfstudio/data/dataparsers/minimal_dataparser.py
index b6ffd8518..2fa2218a4 100644
--- a/nerfstudio/data/dataparsers/minimal_dataparser.py
+++ b/nerfstudio/data/dataparsers/minimal_dataparser.py
@@ -62,7 +62,7 @@ class MinimalDataParser(DataParser):
"semantics": Semantics(
filenames=semantics["filenames"].tolist(),
classes=semantics["classes"].tolist(),
- colors=semantics["colors"].tolist(),
+ colors=torch.from_numpy(semantics["colors"]),
mask_classes=semantics["mask_classes"].tolist(),
)
}
diff --git a/nerfstudio/data/dataparsers/nerfstudio_dataparser.py b/nerfstudio/data/dataparsers/nerfstudio_dataparser.py
index b407936a4..035e2da2d 100644
--- a/nerfstudio/data/dataparsers/nerfstudio_dataparser.py
+++ b/nerfstudio/data/dataparsers/nerfstudio_dataparser.py
@@ -60,8 +60,8 @@ class NerfstudioDataParserConfig(DataParserConfig):
"""Whether to center the poses."""
auto_scale_poses: bool = True
"""Whether to automatically scale the poses to fit in +/- 1 bounding box."""
- train_split_percentage: float = 0.9
- """The percent of images to use for training. The remaining images are for eval."""
+ train_split_fraction: float = 0.9
+ """The fraction of images to use for training. The remaining images are for eval."""
depth_unit_scale_factor: float = 1e-3
"""Scales the depth values to meters. Default value is 0.001 for a millimeter to meter conversion."""
@@ -184,7 +184,7 @@ class Nerfstudio(DataParser):
# filter image_filenames and poses based on train/eval split percentage
num_images = len(image_filenames)
- num_train_images = math.ceil(num_images * self.config.train_split_percentage)
+ num_train_images = math.ceil(num_images * self.config.train_split_fraction)
num_eval_images = num_images - num_train_images
i_all = np.arange(num_images)
i_train = np.linspace(
diff --git a/nerfstudio/data/dataparsers/nuscenes_dataparser.py b/nerfstudio/data/dataparsers/nuscenes_dataparser.py
index 9269f555f..6b35cf356 100644
--- a/nerfstudio/data/dataparsers/nuscenes_dataparser.py
+++ b/nerfstudio/data/dataparsers/nuscenes_dataparser.py
@@ -20,6 +20,7 @@ from pathlib import Path
from typing import Optional, Tuple, Type
import numpy as np
+import pyquaternion
import torch
from nuscenes.nuscenes import NuScenes as NuScenesDatabase
from typing_extensions import Literal
@@ -31,14 +32,19 @@ from nerfstudio.data.dataparsers.base_dataparser import (
DataparserOutputs,
)
from nerfstudio.data.scene_box import SceneBox
-from nerfstudio.process_data.colmap_utils import qvec2rotmat
-def rotation_translation_to_pose(r_vec, t_vec):
+def rotation_translation_to_pose(r_quat, t_vec):
"""Convert quaternion rotation and translation vectors to 4x4 matrix"""
pose = np.eye(4)
- pose[:3, :3] = qvec2rotmat(r_vec)
+
+ # NB: Nuscenes recommends pyquaternion, which uses scalar-first format (w x y z)
+ # https://github.com/nutonomy/nuscenes-devkit/issues/545#issuecomment-766509242
+ # https://github.com/KieranWynn/pyquaternion/blob/99025c17bab1c55265d61add13375433b35251af/pyquaternion/quaternion.py#L299
+ # https://fzheng.me/2017/11/12/quaternion_conventions_en/
+ pose[:3, :3] = pyquaternion.Quaternion(r_quat).rotation_matrix
+
pose[:3, 3] = t_vec
return pose
@@ -66,7 +72,7 @@ class NuScenesDataParserConfig(DataParserConfig):
mask_dir: Optional[Path] = None
"""Path to masks of dynamic objects."""
- train_split_percentage: float = 0.9
+ train_split_fraction: float = 0.9
"""The percent of images to use for training. The remaining images are for eval."""
verbose: bool = False
@@ -160,7 +166,7 @@ class NuScenes(DataParser):
# filter image_filenames and poses based on train/eval split percentage
num_snapshots = len(samples)
- num_train_snapshots = math.ceil(num_snapshots * self.config.train_split_percentage)
+ num_train_snapshots = math.ceil(num_snapshots * self.config.train_split_fraction)
num_eval_snapshots = num_snapshots - num_train_snapshots
i_all = np.arange(num_snapshots)
i_train = np.linspace(
diff --git a/nerfstudio/data/dataparsers/phototourism_dataparser.py b/nerfstudio/data/dataparsers/phototourism_dataparser.py
index bb401d9dc..5b5287d3d 100644
--- a/nerfstudio/data/dataparsers/phototourism_dataparser.py
+++ b/nerfstudio/data/dataparsers/phototourism_dataparser.py
@@ -33,7 +33,13 @@ from nerfstudio.data.dataparsers.base_dataparser import (
DataparserOutputs,
)
from nerfstudio.data.scene_box import SceneBox
-from nerfstudio.data.utils.colmap_utils import read_cameras_binary, read_images_binary
+
+# TODO(1480) use pycolmap instead of colmap_parsing_utils
+# import pycolmap
+from nerfstudio.data.utils.colmap_parsing_utils import (
+ read_cameras_binary,
+ read_images_binary,
+)
CONSOLE = Console(width=120)
@@ -50,8 +56,8 @@ class PhototourismDataParserConfig(DataParserConfig):
"""How much to scale the camera origins by."""
alpha_color: str = "white"
"""alpha color of background"""
- train_split_percentage: float = 0.9
- """The percent of images to use for training. The remaining images are for eval."""
+ train_split_fraction: float = 0.9
+ """The fraction of images to use for training. The remaining images are for eval."""
scene_scale: float = 1.0
"""How much to scale the region of interest by."""
orientation_method: Literal["pca", "up", "none"] = "up"
@@ -76,11 +82,14 @@ class Phototourism(DataParser):
# pylint: disable=too-many-statements
def _generate_dataparser_outputs(self, split="train"):
-
image_filenames = []
poses = []
with CONSOLE.status(f"[bold green]Reading phototourism images and poses for {split} split...") as _:
+ # TODO(1480) use pycolmap
+ # recon = pycolmap.Reconstruction(self.data / "dense" / "sparse")
+ # cams = recon.cameras
+ # imgs = recon.images
cams = read_cameras_binary(self.data / "dense/sparse/cameras.bin")
imgs = read_images_binary(self.data / "dense/sparse/images.bin")
@@ -119,7 +128,7 @@ class Phototourism(DataParser):
# filter image_filenames and poses based on train/eval split percentage
num_images = len(image_filenames)
- num_train_images = math.ceil(num_images * self.config.train_split_percentage)
+ num_train_images = math.ceil(num_images * self.config.train_split_fraction)
num_eval_images = num_images - num_train_images
i_all = np.arange(num_images)
i_train = np.linspace(
diff --git a/nerfstudio/data/dataparsers/scannet_dataparser.py b/nerfstudio/data/dataparsers/scannet_dataparser.py
new file mode 100644
index 000000000..80d0dd688
--- /dev/null
+++ b/nerfstudio/data/dataparsers/scannet_dataparser.py
@@ -0,0 +1,160 @@
+# Copyright 2022 The Nerfstudio Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Data parser for ScanNet dataset"""
+import math
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Type
+
+import cv2
+import numpy as np
+import torch
+
+from nerfstudio.cameras.cameras import Cameras, CameraType
+from nerfstudio.data.dataparsers.base_dataparser import (
+ DataParser,
+ DataParserConfig,
+ DataparserOutputs,
+)
+from nerfstudio.data.scene_box import SceneBox
+
+
+@dataclass
+class ScanNetDataParserConfig(DataParserConfig):
+ """ScanNet dataset config.
+ ScanNet dataset (https://www.scan-net.org/) is a large-scale 3D dataset of indoor scenes.
+ This dataparser assumes that the dense stream was extracted from .sens files.
+ Expected structure of scene directory:
+ - color/
+ - depth/
+ - intrinsic/
+ - pose/
+ """
+
+ _target: Type = field(default_factory=lambda: ScanNet)
+ """target class to instantiate"""
+ data: Path = Path("data/scannet/scene0423_02")
+ """Path to ScanNet folder with densely extracted scenes."""
+ scene_scale: float = 1.0
+ """How much to scale the region of interest by."""
+ center_poses: bool = True
+ """Whether to center the poses."""
+ scale_poses: bool = True
+ """Whether to automatically scale the poses to fit in +/- 1 bounding box."""
+ train_split_fraction: float = 0.9
+ """The fraction of images to use for training. The remaining images are for eval."""
+ depth_unit_scale_factor: float = 1e-3
+ """Scales the depth values to meters. Default value is 0.001 for a millimeter to meter conversion."""
+
+
+@dataclass
+class ScanNet(DataParser):
+ """ScanNet DatasetParser"""
+
+ config: ScanNetDataParserConfig
+
+ def _generate_dataparser_outputs(self, split="train"):
+ image_dir = self.config.data / "color"
+ depth_dir = self.config.data / "depth"
+ pose_dir = self.config.data / "pose"
+
+ img_dir_sorted = list(sorted(image_dir.iterdir(), key=lambda x: int(x.name.split(".")[0])))
+ depth_dir_sorted = list(sorted(depth_dir.iterdir(), key=lambda x: int(x.name.split(".")[0])))
+ pose_dir_sorted = list(sorted(pose_dir.iterdir(), key=lambda x: int(x.name.split(".")[0])))
+
+ first_img = cv2.imread(img_dir_sorted[0].as_posix())
+ h, w, _ = first_img.shape
+
+ image_filenames = []
+ depth_filenames = []
+ intrinsics = []
+ poses = []
+
+ K = np.loadtxt(self.config.data / "intrinsic" / "intrinsic_color.txt")
+ for img, depth, pose in zip(img_dir_sorted, depth_dir_sorted, pose_dir_sorted):
+ pose = np.loadtxt(pose)
+ pose[0:3, 1:3] *= -1
+
+ # We cannot accept files directly, as some of the poses are invalid
+ if np.isinf(pose).any():
+ continue
+
+ poses.append(pose)
+ intrinsics.append(K)
+ image_filenames.append(img)
+ depth_filenames.append(depth)
+
+ # filter image_filenames and poses based on train/eval split percentage
+ num_images = len(image_filenames)
+ num_train_images = math.ceil(num_images * self.config.train_split_fraction)
+ num_eval_images = num_images - num_train_images
+ i_all = np.arange(num_images)
+ i_train = np.linspace(
+ 0, num_images - 1, num_train_images, dtype=int
+ ) # equally spaced training images starting and ending at 0 and num_images-1
+ i_eval = np.setdiff1d(i_all, i_train) # eval images are the remaining images
+ assert len(i_eval) == num_eval_images
+ if split == "train":
+ indices = i_train
+ elif split in ["val", "test"]:
+ indices = i_eval
+ else:
+ raise ValueError(f"Unknown dataparser split {split}")
+
+ poses = torch.from_numpy(np.stack(poses).astype(np.float32))
+ intrinsics = torch.from_numpy(np.stack(intrinsics).astype(np.float32))
+
+ if self.config.center_poses:
+ poses[:, :3, 3] -= poses[:, :3, 3].mean(dim=0)
+
+ if self.config.scale_poses:
+ poses[:, :3, 3] /= poses[:, :3, 3].abs().max()
+
+ # Choose image_filenames and poses based on split, but after auto orient and scaling the poses.
+ image_filenames = [image_filenames[i] for i in indices]
+ depth_filenames = [depth_filenames[i] for i in indices] if len(depth_filenames) > 0 else []
+ intrinsics = intrinsics[indices.tolist()]
+ poses = poses[indices.tolist()]
+
+ # in x,y,z order
+ # assumes that the scene is centered at the origin
+ aabb_scale = self.config.scene_scale
+ scene_box = SceneBox(
+ aabb=torch.tensor(
+ [[-aabb_scale, -aabb_scale, -aabb_scale], [aabb_scale, aabb_scale, aabb_scale]], dtype=torch.float32
+ )
+ )
+
+ cameras = Cameras(
+ fx=intrinsics[:, 0, 0],
+ fy=intrinsics[:, 1, 1],
+ cx=intrinsics[:, 0, 2],
+ cy=intrinsics[:, 1, 2],
+ height=h,
+ width=w,
+ camera_to_worlds=poses[:, :3, :4],
+ camera_type=CameraType.PERSPECTIVE,
+ )
+
+ dataparser_outputs = DataparserOutputs(
+ image_filenames=image_filenames,
+ cameras=cameras,
+ scene_box=scene_box,
+ metadata={
+ "depth_filenames": depth_filenames if len(depth_filenames) > 0 else None,
+ "depth_unit_scale_factor": self.config.depth_unit_scale_factor,
+ },
+ )
+ return dataparser_outputs
diff --git a/nerfstudio/data/dataparsers/friends_dataparser.py b/nerfstudio/data/dataparsers/sitcoms3d_dataparser.py
similarity index 90%
rename from nerfstudio/data/dataparsers/friends_dataparser.py
rename to nerfstudio/data/dataparsers/sitcoms3d_dataparser.py
index 604dbd7c0..b6906ce22 100644
--- a/nerfstudio/data/dataparsers/friends_dataparser.py
+++ b/nerfstudio/data/dataparsers/sitcoms3d_dataparser.py
@@ -12,7 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Data parser for friends dataset"""
+"""Data parser for sitcoms3D dataset.
+
+The dataset is from the paper ["The One Where They Reconstructed 3D Humans and
+Environments in TV Shows"](https://ethanweber.me/sitcoms3D/)
+"""
+
from __future__ import annotations
from dataclasses import dataclass, field
@@ -36,12 +41,12 @@ CONSOLE = Console()
@dataclass
-class FriendsDataParserConfig(DataParserConfig):
- """Friends dataset parser config"""
+class Sitcoms3DDataParserConfig(DataParserConfig):
+ """sitcoms3D dataset parser config"""
- _target: Type = field(default_factory=lambda: Friends)
+ _target: Type = field(default_factory=lambda: Sitcoms3D)
"""target class to instantiate"""
- data: Path = Path("data/friends/TBBT-big_living_room")
+ data: Path = Path("data/sitcoms3d/TBBT-big_living_room")
"""Directory specifying location of data."""
include_semantics: bool = True
"""whether or not to include loading of semantics data"""
@@ -49,15 +54,15 @@ class FriendsDataParserConfig(DataParserConfig):
scene_scale: float = 2.0
"""
Sets the bounding cube to have edge length of this size.
- The longest dimension of the Friends axis-aligned bbox will be scaled to this value.
+ The longest dimension of the Sitcoms3D axis-aligned bbox will be scaled to this value.
"""
@dataclass
-class Friends(DataParser):
- """Friends Dataset"""
+class Sitcoms3D(DataParser):
+ """Sitcoms3D Dataset"""
- config: FriendsDataParserConfig
+ config: Sitcoms3DDataParserConfig
def _generate_dataparser_outputs(self, split="train"): # pylint: disable=unused-argument,too-many-statements
diff --git a/nerfstudio/data/utils/colmap_utils.py b/nerfstudio/data/utils/colmap_parsing_utils.py
similarity index 98%
rename from nerfstudio/data/utils/colmap_utils.py
rename to nerfstudio/data/utils/colmap_parsing_utils.py
index 2615d00d9..652e2795e 100644
--- a/nerfstudio/data/utils/colmap_utils.py
+++ b/nerfstudio/data/utils/colmap_parsing_utils.py
@@ -1,3 +1,11 @@
+"""
+This file copied with small modifications from:
+ * https://github.com/colmap/colmap/blob/1a4d0bad2e90aa65ce997c9d1779518eaed998d5/scripts/python/read_write_model.py
+
+TODO(1480) Delete this file when moving to pycolmap.
+
+"""
+
# Copyright (c) 2018, ETH Zurich and UNC Chapel Hill.
# All rights reserved.
#
diff --git a/nerfstudio/data/utils/dataloaders.py b/nerfstudio/data/utils/dataloaders.py
index 23d712d7e..c4e155102 100644
--- a/nerfstudio/data/utils/dataloaders.py
+++ b/nerfstudio/data/utils/dataloaders.py
@@ -116,7 +116,7 @@ class CacheDataloader(DataLoader):
"""Returns a collated batch."""
batch_list = self._get_batch_list()
collated_batch = self.collate_fn(batch_list)
- collated_batch = get_dict_to_torch(collated_batch, device=self.device, exclude=["image"])
+ collated_batch = get_dict_to_torch(collated_batch, device=self.device)
return collated_batch
def __iter__(self):
@@ -183,7 +183,7 @@ class EvalDataloader(DataLoader):
"""
ray_bundle = self.cameras.generate_rays(camera_indices=image_idx, keep_shape=True)
batch = self.input_dataset[image_idx]
- batch = get_dict_to_torch(batch, device=self.device, exclude=["image"])
+ batch = get_dict_to_torch(batch, device=self.device)
return ray_bundle, batch
diff --git a/nerfstudio/engine/callbacks.py b/nerfstudio/engine/callbacks.py
index 3c7219d67..6be1d8097 100644
--- a/nerfstudio/engine/callbacks.py
+++ b/nerfstudio/engine/callbacks.py
@@ -79,7 +79,7 @@ class TrainingCallback:
self.args = args if args is not None else []
self.kwargs = kwargs if kwargs is not None else {}
- def run_callback(self, step: int):
+ def run_callback(self, step: int) -> None:
"""Callback to run after training step
Args:
@@ -92,7 +92,7 @@ class TrainingCallback:
if step in self.iters:
self.func(*self.args, **self.kwargs, step=step)
- def run_callback_at_location(self, step: int, location: TrainingCallbackLocation):
+ def run_callback_at_location(self, step: int, location: TrainingCallbackLocation) -> None:
"""Runs the callback if it's supposed to be run at the given location.
Args:
diff --git a/nerfstudio/engine/optimizers.py b/nerfstudio/engine/optimizers.py
index 786c51115..8a2a063b2 100644
--- a/nerfstudio/engine/optimizers.py
+++ b/nerfstudio/engine/optimizers.py
@@ -44,7 +44,7 @@ class OptimizerConfig(base_config.PrintableConfig):
# TODO: somehow make this more generic. i dont like the idea of overriding the setup function
# but also not sure how to go about passing things into predefined torch objects.
- def setup(self, params) -> Any:
+ def setup(self, params) -> torch.optim.Optimizer:
"""Returns the instantiated object using the config."""
kwargs = vars(self).copy()
kwargs.pop("_target")
@@ -66,6 +66,8 @@ class RAdamOptimizerConfig(OptimizerConfig):
"""Basic optimizer config with RAdam"""
_target: Type = torch.optim.RAdam
+ weight_decay: float = 0
+ """The weight decay to use."""
class Optimizers:
@@ -76,7 +78,7 @@ class Optimizers:
param_groups: A dictionary of parameter groups to optimize.
"""
- def __init__(self, config: Dict[str, Any], param_groups: Dict[str, List[Parameter]]):
+ def __init__(self, config: Dict[str, Any], param_groups: Dict[str, List[Parameter]]) -> None:
self.config = config
self.optimizers = {}
self.schedulers = {}
@@ -127,7 +129,7 @@ class Optimizers:
torch.nn.utils.clip_grad_norm_(self.parameters[param_group], max_norm)
grad_scaler.step(optimizer)
- def optimizer_step_all(self):
+ def optimizer_step_all(self) -> None:
"""Run step for all optimizers."""
for param_group, optimizer in self.optimizers.items():
# note that they key is the parameter name
diff --git a/nerfstudio/engine/schedulers.py b/nerfstudio/engine/schedulers.py
index d4554c7d8..0b6586ffc 100644
--- a/nerfstudio/engine/schedulers.py
+++ b/nerfstudio/engine/schedulers.py
@@ -40,7 +40,7 @@ class Scheduler:
config: SchedulerConfig
- def __init__(self, config: SchedulerConfig):
+ def __init__(self, config: SchedulerConfig) -> None:
super().__init__()
self.config = config
diff --git a/nerfstudio/engine/trainer.py b/nerfstudio/engine/trainer.py
index 28c2f7b33..a4a09e7b1 100644
--- a/nerfstudio/engine/trainer.py
+++ b/nerfstudio/engine/trainer.py
@@ -23,7 +23,7 @@ import os
import time
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Dict, List, Optional, Tuple, Type
+from typing import Dict, List, Optional, Tuple, Type, Union
import torch
from rich.console import Console
@@ -50,6 +50,11 @@ from nerfstudio.viewer.server import viewer_utils
CONSOLE = Console(width=120)
+TRAIN_INTERATION_OUTPUT = Tuple[ # pylint: disable=invalid-name
+ torch.Tensor, Dict[str, torch.Tensor], Dict[str, torch.Tensor]
+]
+TORCH_DEVICE = Union[torch.device, str] # pylint: disable=invalid-name
+
@dataclass
class TrainerConfig(ExperimentConfig):
@@ -104,27 +109,27 @@ class Trainer:
optimizers: Optimizers
callbacks: List[TrainingCallback]
- def __init__(self, config: TrainerConfig, local_rank: int = 0, world_size: int = 1):
+ def __init__(self, config: TrainerConfig, local_rank: int = 0, world_size: int = 1) -> None:
self.config = config
self.local_rank = local_rank
self.world_size = world_size
- self.device = "cpu" if world_size == 0 else f"cuda:{local_rank}"
- self.mixed_precision = self.config.mixed_precision
+ self.device: TORCH_DEVICE = "cpu" if world_size == 0 else f"cuda:{local_rank}"
+ self.mixed_precision: bool = self.config.mixed_precision
if self.device == "cpu":
self.mixed_precision = False
CONSOLE.print("Mixed precision is disabled for CPU training.")
- self._start_step = 0
+ self._start_step: int = 0
# optimizers
self.grad_scaler = GradScaler(enabled=self.mixed_precision)
- self.viewer_state = None
-
- self.base_dir = config.get_base_dir()
+ self.base_dir: Path = config.get_base_dir()
# directory to save checkpoints
- self.checkpoint_dir = config.get_checkpoint_dir()
+ self.checkpoint_dir: Path = config.get_checkpoint_dir()
CONSOLE.log(f"Saving checkpoints to: {self.checkpoint_dir}")
- def setup(self, test_mode: Literal["test", "val", "inference"] = "val"):
+ self.viewer_state = None
+
+ def setup(self, test_mode: Literal["test", "val", "inference"] = "val") -> None:
"""Setup the Trainer by calling other setup functions.
Args:
@@ -258,7 +263,7 @@ class Trainer:
self._always_render(step)
@check_main_thread
- def _always_render(self, step):
+ def _always_render(self, step: int) -> None:
if self.viewer_state is not None:
while True:
self.viewer_state.vis["renderingState/isTraining"].write(False)
@@ -272,7 +277,7 @@ class Trainer:
and not self.config.is_tensorboard_enabled()
and not self.config.is_wandb_enabled()
):
- string = (
+ string: str = (
"[NOTE] Not running eval iterations since only viewer is enabled.\n"
"Use [yellow]--vis {wandb, tensorboard, viewer+wandb, viewer+tensorboard}[/yellow] to run with eval."
)
@@ -290,7 +295,7 @@ class Trainer:
self._always_render(self._start_step)
@check_viewer_enabled
- def _update_viewer_state(self, step: int):
+ def _update_viewer_state(self, step: int) -> None:
"""Updates the viewer state by rendering out scene with current pipeline
Returns the time taken to render scene.
@@ -299,7 +304,7 @@ class Trainer:
"""
assert self.viewer_state is not None
with TimeWriter(writer, EventName.ITER_VIS_TIME, step=step) as _:
- num_rays_per_batch = self.pipeline.datamanager.get_train_rays_per_batch()
+ num_rays_per_batch: int = self.pipeline.datamanager.get_train_rays_per_batch()
try:
self.viewer_state.update_scene(self, step, self.pipeline.model, num_rays_per_batch)
except RuntimeError:
@@ -310,7 +315,7 @@ class Trainer:
)
@check_viewer_enabled
- def _update_viewer_rays_per_sec(self, train_t: TimeWriter, vis_t: TimeWriter, step: int):
+ def _update_viewer_rays_per_sec(self, train_t: TimeWriter, vis_t: TimeWriter, step: int) -> None:
"""Performs update on rays/sec calculation for training
Args:
@@ -318,7 +323,7 @@ class Trainer:
vis_t: timer object carrying time to execute visualization step
step: current step
"""
- train_num_rays_per_batch = self.pipeline.datamanager.get_train_rays_per_batch()
+ train_num_rays_per_batch: int = self.pipeline.datamanager.get_train_rays_per_batch()
writer.put_time(
name=EventName.TRAIN_RAYS_PER_SEC,
duration=train_num_rays_per_batch / (train_t.duration - vis_t.duration),
@@ -328,14 +333,14 @@ class Trainer:
def _load_checkpoint(self) -> None:
"""Helper function to load pipeline and optimizer from prespecified checkpoint"""
- load_dir = self.config.load_dir
+ load_dir: Path = self.config.load_dir
if load_dir is not None:
load_step = self.config.load_step
if load_step is None:
print("Loading latest checkpoint from load_dir")
# NOTE: this is specific to the checkpoint name format
load_step = sorted(int(x[x.find("-") + 1 : x.find(".")]) for x in os.listdir(load_dir))[-1]
- load_path = load_dir / f"step-{load_step:09d}.ckpt"
+ load_path: Path = load_dir / f"step-{load_step:09d}.ckpt"
assert load_path.exists(), f"Checkpoint {load_path} does not exist"
loaded_state = torch.load(load_path, map_location="cpu")
self._start_step = loaded_state["step"] + 1
@@ -358,7 +363,7 @@ class Trainer:
if not self.checkpoint_dir.exists():
self.checkpoint_dir.mkdir(parents=True, exist_ok=True)
# save the checkpoint
- ckpt_path = self.checkpoint_dir / f"step-{step:09d}.ckpt"
+ ckpt_path: Path = self.checkpoint_dir / f"step-{step:09d}.ckpt"
torch.save(
{
"step": step,
@@ -378,14 +383,14 @@ class Trainer:
f.unlink()
@profiler.time_function
- def train_iteration(self, step: int) -> Tuple[torch.Tensor, Dict[str, torch.Tensor], Dict[str, torch.Tensor]]:
+ def train_iteration(self, step: int) -> TRAIN_INTERATION_OUTPUT:
"""Run one iteration with a batch of inputs. Returns dictionary of model losses.
Args:
step: Current training step.
"""
self.optimizers.zero_grad_all()
- cpu_or_cuda_str = self.device.split(":")[0]
+ cpu_or_cuda_str: str = self.device.split(":")[0]
with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision):
_, loss_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step)
loss = functools.reduce(torch.add, loss_dict.values())
@@ -411,7 +416,7 @@ class Trainer:
@check_eval_enabled
@profiler.time_function
- def eval_iteration(self, step):
+ def eval_iteration(self, step: int) -> None:
"""Run one iteration with different batch/image/all image evaluations depending on step size.
Args:
diff --git a/nerfstudio/exporter/texture_utils.py b/nerfstudio/exporter/texture_utils.py
index 9f2825ce3..4001d1c60 100644
--- a/nerfstudio/exporter/texture_utils.py
+++ b/nerfstudio/exporter/texture_utils.py
@@ -22,7 +22,7 @@ from __future__ import annotations
import math
from pathlib import Path
-from typing import Optional, Tuple
+from typing import Optional, Tuple, Union
import mediapy as media
import numpy as np
@@ -39,6 +39,8 @@ from nerfstudio.utils.rich_utils import get_progress
CONSOLE = Console(width=120)
+TORCH_DEVICE = Union[torch.device, str] # pylint: disable=invalid-name
+
def get_parallelogram_area(
p: TensorType["bs":..., 2], v0: TensorType["bs":..., 2], v1: TensorType["bs":..., 2]
@@ -56,7 +58,9 @@ def get_parallelogram_area(
return (p[..., 0] - v0[..., 0]) * (v1[..., 1] - v0[..., 1]) - (p[..., 1] - v0[..., 1]) * (v1[..., 0] - v0[..., 0])
-def get_texture_image(num_pixels_w, num_pixels_h, device):
+def get_texture_image(
+ num_pixels_w: int, num_pixels_h: int, device: TORCH_DEVICE
+) -> Tuple[TensorType["num_pixels_h", "num_pixels_w", 2], TensorType["num_pixels_h", "num_pixels_w", 2]]:
"""Get a texture image."""
px_w = 1.0 / num_pixels_w
px_h = 1.0 / num_pixels_h
@@ -80,7 +84,11 @@ def unwrap_mesh_per_uv_triangle(
faces: TensorType["num_faces", 3],
vertex_normals: TensorType["num_verts", 3],
px_per_uv_triangle: int,
-):
+) -> Tuple[
+ TensorType["num_faces", 3, 2],
+ TensorType["num_pixels", "num_pixels", 3],
+ TensorType["num_pixels", "num_pixels", "num_pixels"],
+]:
"""Unwrap a mesh to a UV texture. This is done by making a grid of rectangles in the UV texture map
and then having two triangles per rectangle. Then the texture image is rasterized and uses barycentric
interpolation to get the origins and directions, per pixel, that are needed to render the NeRF with.
@@ -331,7 +339,7 @@ def export_textured_mesh(
unwrap_method: Literal["xatlas", "custom"] = "xatlas",
raylen_method: Literal["edge", "none"] = "edge",
num_pixels_per_side=1024,
-):
+) -> None:
"""Textures a mesh using the radiance field from the Pipeline.
The mesh is written to an OBJ file in the output directory,
along with the corresponding material and texture files.
diff --git a/nerfstudio/exporter/tsdf_utils.py b/nerfstudio/exporter/tsdf_utils.py
index 049f6354d..2249fde23 100644
--- a/nerfstudio/exporter/tsdf_utils.py
+++ b/nerfstudio/exporter/tsdf_utils.py
@@ -37,6 +37,8 @@ from nerfstudio.pipelines.base_pipeline import Pipeline
CONSOLE = Console(width=120)
+TORCH_DEVICE = Union[torch.device, str] # pylint: disable=invalid-name
+
@dataclass
class TSDF:
@@ -59,7 +61,7 @@ class TSDF:
truncation_margin: float = 5.0
"""Margin for truncation."""
- def to(self, device: str):
+ def to(self, device: TORCH_DEVICE):
"""Move the tensors to the specified device.
Args:
@@ -74,12 +76,12 @@ class TSDF:
return self
@property
- def device(self):
+ def device(self) -> TORCH_DEVICE:
"""Returns the device that voxel_coords is on."""
return self.voxel_coords.device
@property
- def truncation(self):
+ def truncation(self) -> float:
"""Returns the truncation distance."""
# TODO: clean this up
truncation = self.voxel_size[0] * self.truncation_margin
@@ -136,7 +138,7 @@ class TSDF:
return Mesh(vertices=vertices, faces=faces, normals=normals, colors=colors)
@classmethod
- def export_mesh(cls, mesh: Mesh, filename: str):
+ def export_mesh(cls, mesh: Mesh, filename: str) -> None:
"""Exports the mesh to a file.
We use pymeshlab to export the mesh as a PLY file.
@@ -172,7 +174,7 @@ class TSDF:
depth_images: TensorType["batch", 1, "height", "width"],
color_images: Optional[TensorType["batch", 3, "height", "width"]] = None,
mask_images: Optional[TensorType["batch", 1, "height", "width"]] = None,
- ):
+ ) -> None:
"""Integrates a batch of depth images into the TSDF.
Args:
@@ -242,7 +244,6 @@ class TSDF:
# Sequentially update the TSDF...
for i in range(batch_size):
-
valid_points_i = valid_points[i]
valid_points_i_shape = valid_points_i.view(*shape) # [xdim, ydim, zdim]
@@ -281,7 +282,7 @@ def export_tsdf_mesh(
use_bounding_box: bool = True,
bounding_box_min: Tuple[float, float, float] = (-1.0, -1.0, -1.0),
bounding_box_max: Tuple[float, float, float] = (1.0, 1.0, 1.0),
-):
+) -> None:
"""Export a TSDF mesh from a pipeline.
Args:
diff --git a/nerfstudio/field_components/encodings.py b/nerfstudio/field_components/encodings.py
index 9cdd85e61..f77c17f4d 100644
--- a/nerfstudio/field_components/encodings.py
+++ b/nerfstudio/field_components/encodings.py
@@ -469,11 +469,94 @@ class TensorVMEncoding(Encoding):
)
line_coef = F.interpolate(self.line_coef.data, size=(resolution, 1), mode="bilinear", align_corners=True)
- # TODO(ethan): are these torch.nn.Parameters needed?
self.plane_coef, self.line_coef = torch.nn.Parameter(plane_coef), torch.nn.Parameter(line_coef)
self.resolution = resolution
+class TriplaneEncoding(Encoding):
+ """Learned triplane encoding
+
+ The encoding at [i,j,k] is an n dimensional vector corresponding to the element-wise product of the
+ three n dimensional vectors at plane_coeff[i,j], plane_coeff[i,k], and plane_coeff[j,k].
+
+ This allows for marginally more expressivity than the TensorVMEncoding, and each component is self standing
+ and symmetrical, unlike with VM decomposition where we needed one component with a vector along all the x, y, z
+ directions for symmetry.
+
+ This can be thought of as 3 planes of features perpendicular to the x, y, and z axes, respectively and intersecting
+ at the origin, and the encoding being the element-wise product of the element at the projection of [i, j, k] on
+ these planes.
+
+ The use for this is in representing a tensor decomp of a 4D embedding tensor: (x, y, z, feature_size)
+
+ This will return a tensor of shape (bs:..., num_components)
+
+ Args:
+ resolution: Resolution of grid.
+ num_components: The number of scalar triplanes to use (ie: output feature size)
+ init_scale: The scale of the initial values of the planes
+ product: Whether to use the element-wise product of the planes or the sum
+ """
+
+ plane_coef: TensorType[3, "num_components", "resolution", "resolution"]
+
+ def __init__(
+ self,
+ resolution: int = 32,
+ num_components: int = 64,
+ init_scale: float = 0.1,
+ reduce: Literal["sum", "product"] = "sum",
+ ) -> None:
+ super().__init__(in_dim=3)
+
+ self.resolution = resolution
+ self.num_components = num_components
+ self.init_scale = init_scale
+ self.reduce = reduce
+
+ self.plane_coef = nn.Parameter(
+ self.init_scale * torch.randn((3, self.num_components, self.resolution, self.resolution))
+ )
+
+ def get_out_dim(self) -> int:
+ return self.num_components
+
+ def forward(self, in_tensor: TensorType["bs":..., 3]) -> TensorType["bs":..., "num_components", "featuresize"]:
+ """Sample features from this encoder. Expects in_tensor to be in range [0, resolution]"""
+
+ original_shape = in_tensor.shape
+ in_tensor = in_tensor.reshape(-1, 3)
+
+ plane_coord = torch.stack([in_tensor[..., [0, 1]], in_tensor[..., [0, 2]], in_tensor[..., [1, 2]]], dim=0)
+
+ # Stop gradients from going to sampler
+ plane_coord = plane_coord.detach().view(3, -1, 1, 2)
+ plane_features = F.grid_sample(
+ self.plane_coef, plane_coord, align_corners=True
+ ) # [3, num_components, flattened_bs, 1]
+
+ if self.reduce == "product":
+ plane_features = plane_features.prod(0).squeeze(-1).T # [flattened_bs, num_components]
+ else:
+ plane_features = plane_features.sum(0).squeeze(-1).T
+
+ return plane_features.reshape(*original_shape[:-1], self.num_components)
+
+ @torch.no_grad()
+ def upsample_grid(self, resolution: int) -> None:
+ """Upsamples underlying feature grid
+
+ Args:
+ resolution: Target resolution.
+ """
+ plane_coef = F.interpolate(
+ self.plane_coef.data, size=(resolution, resolution), mode="bilinear", align_corners=True
+ )
+
+ self.plane_coef = torch.nn.Parameter(plane_coef)
+ self.resolution = resolution
+
+
class SHEncoding(Encoding):
"""Spherical harmonic encoding
diff --git a/nerfstudio/fields/base_field.py b/nerfstudio/fields/base_field.py
index 5bf49bf5e..e20774d88 100644
--- a/nerfstudio/fields/base_field.py
+++ b/nerfstudio/fields/base_field.py
@@ -96,7 +96,7 @@ class Field(nn.Module):
density_embedding: Density embeddings to condition on.
"""
- def forward(self, ray_samples: RaySamples, compute_normals: bool = False):
+ def forward(self, ray_samples: RaySamples, compute_normals: bool = False) -> Dict[FieldHeadNames, TensorType]:
"""Evaluates the field at points along the ray.
Args:
diff --git a/nerfstudio/fields/density_fields.py b/nerfstudio/fields/density_fields.py
index 1584deedf..dcab3865d 100644
--- a/nerfstudio/fields/density_fields.py
+++ b/nerfstudio/fields/density_fields.py
@@ -17,11 +17,10 @@ Proposal network field.
"""
-from typing import Optional
+from typing import Optional, Tuple
import numpy as np
import torch
-from torch.nn.parameter import Parameter
from torchtyping import TensorType
from nerfstudio.cameras.rays import RaySamples
@@ -50,23 +49,27 @@ class HashMLPDensityField(Field):
def __init__(
self,
- aabb,
+ aabb: TensorType,
num_layers: int = 2,
hidden_dim: int = 64,
spatial_distortion: Optional[SpatialDistortion] = None,
- use_linear=False,
- num_levels=8,
- max_res=1024,
- base_res=16,
- log2_hashmap_size=18,
- features_per_level=2,
+ use_linear: bool = False,
+ num_levels: int = 8,
+ max_res: int = 1024,
+ base_res: int = 16,
+ log2_hashmap_size: int = 18,
+ features_per_level: int = 2,
) -> None:
super().__init__()
- self.aabb = Parameter(aabb, requires_grad=False)
+ self.register_buffer("aabb", aabb)
self.spatial_distortion = spatial_distortion
self.use_linear = use_linear
growth_factor = np.exp((np.log(max_res) - np.log(base_res)) / (num_levels - 1))
+ self.register_buffer("max_res", torch.tensor(max_res))
+ self.register_buffer("num_levels", torch.tensor(num_levels))
+ self.register_buffer("log2_hashmap_size", torch.tensor(log2_hashmap_size))
+
config = {
"encoding": {
"otype": "HashGrid",
@@ -96,12 +99,15 @@ class HashMLPDensityField(Field):
self.encoding = tcnn.Encoding(n_input_dims=3, encoding_config=config["encoding"])
self.linear = torch.nn.Linear(self.encoding.n_output_dims, 1)
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, None]:
if self.spatial_distortion is not None:
positions = self.spatial_distortion(ray_samples.frustums.get_positions())
positions = (positions + 2.0) / 4.0
else:
positions = SceneBox.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb)
+ # Make sure the tcnn gets inputs between 0 and 1.
+ selector = ((positions > 0.0) & (positions < 1.0)).all(dim=-1)
+ positions = positions * selector[..., None]
positions_flat = positions.view(-1, 3)
if not self.use_linear:
density_before_activation = (
@@ -115,7 +121,8 @@ class HashMLPDensityField(Field):
# softplus, because it enables high post-activation (float32) density outputs
# from smaller internal (float16) parameters.
density = trunc_exp(density_before_activation)
+ density = density * selector[..., None]
return density, None
- def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None):
+ def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None) -> dict:
return {}
diff --git a/nerfstudio/fields/instant_ngp_field.py b/nerfstudio/fields/instant_ngp_field.py
index 846ea121e..102912ba7 100644
--- a/nerfstudio/fields/instant_ngp_field.py
+++ b/nerfstudio/fields/instant_ngp_field.py
@@ -17,7 +17,7 @@ Instant-NGP field implementations using tiny-cuda-nn, torch, ....
"""
-from typing import Optional
+from typing import Dict, Optional, Tuple
import torch
from nerfacc import ContractionType, contract
@@ -38,7 +38,7 @@ except ImportError:
pass
-def get_normalized_directions(directions: TensorType["bs":..., 3]):
+def get_normalized_directions(directions: TensorType["bs":..., 3]) -> TensorType["bs":..., 3]:
"""SH encoding must be in the range [0, 1]
Args:
@@ -67,13 +67,13 @@ class TCNNInstantNGPField(Field):
def __init__(
self,
- aabb,
+ aabb: TensorType,
num_layers: int = 2,
hidden_dim: int = 64,
geo_feat_dim: int = 15,
num_layers_color: int = 3,
hidden_dim_color: int = 64,
- use_appearance_embedding: bool = False,
+ use_appearance_embedding: Optional[bool] = False,
num_images: Optional[int] = None,
appearance_embedding_dim: int = 32,
contraction_type: ContractionType = ContractionType.UN_BOUNDED_SPHERE,
@@ -138,7 +138,7 @@ class TCNNInstantNGPField(Field):
},
)
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, TensorType]:
positions = ray_samples.frustums.get_positions()
positions_flat = positions.view(-1, 3)
positions_flat = contract(x=positions_flat, roi=self.aabb, type=self.contraction_type)
@@ -152,7 +152,9 @@ class TCNNInstantNGPField(Field):
density = trunc_exp(density_before_activation.to(positions))
return density, base_mlp_out
- def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None):
+ def get_outputs(
+ self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None
+ ) -> Dict[FieldHeadNames, TensorType]:
directions = get_normalized_directions(ray_samples.frustums.directions)
directions_flat = directions.view(-1, 3)
diff --git a/nerfstudio/fields/nerfacto_field.py b/nerfstudio/fields/nerfacto_field.py
index 1c3865fee..830962edf 100644
--- a/nerfstudio/fields/nerfacto_field.py
+++ b/nerfstudio/fields/nerfacto_field.py
@@ -55,7 +55,7 @@ except ImportError:
pass
-def get_normalized_directions(directions: TensorType["bs":..., 3]):
+def get_normalized_directions(directions: TensorType["bs":..., 3]) -> TensorType["bs":..., 3]:
"""SH encoding must be in the range [0, 1]
Args:
@@ -92,7 +92,7 @@ class TCNNNerfactoField(Field):
def __init__(
self,
- aabb,
+ aabb: TensorType,
num_images: int,
num_layers: int = 2,
hidden_dim: int = 64,
@@ -109,15 +109,20 @@ class TCNNNerfactoField(Field):
use_transient_embedding: bool = False,
use_semantics: bool = False,
num_semantic_classes: int = 100,
+ pass_semantic_gradients: bool = False,
use_pred_normals: bool = False,
use_average_appearance_embedding: bool = False,
- spatial_distortion: Optional[SpatialDistortion] = None,
+ spatial_distortion: SpatialDistortion = None,
) -> None:
super().__init__()
- self.aabb = Parameter(aabb, requires_grad=False)
+ self.register_buffer("aabb", aabb)
self.geo_feat_dim = geo_feat_dim
+ self.register_buffer("max_res", torch.tensor(max_res))
+ self.register_buffer("num_levels", torch.tensor(num_levels))
+ self.register_buffer("log2_hashmap_size", torch.tensor(log2_hashmap_size))
+
self.spatial_distortion = spatial_distortion
self.num_images = num_images
self.appearance_embedding_dim = appearance_embedding_dim
@@ -126,9 +131,10 @@ class TCNNNerfactoField(Field):
self.use_transient_embedding = use_transient_embedding
self.use_semantics = use_semantics
self.use_pred_normals = use_pred_normals
+ self.pass_semantic_gradients = pass_semantic_gradients
- base_res = 16
- features_per_level = 2
+ base_res: int = 16
+ features_per_level: int = 2
growth_factor = np.exp((np.log(max_res) - np.log(base_res)) / (num_levels - 1))
self.direction_encoding = tcnn.Encoding(
@@ -227,7 +233,7 @@ class TCNNNerfactoField(Field):
},
)
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, TensorType]:
"""Computes and returns the densities."""
if self.spatial_distortion is not None:
positions = ray_samples.frustums.get_positions()
@@ -235,6 +241,9 @@ class TCNNNerfactoField(Field):
positions = (positions + 2.0) / 4.0
else:
positions = SceneBox.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb)
+ # Make sure the tcnn gets inputs between 0 and 1.
+ selector = ((positions > 0.0) & (positions < 1.0)).all(dim=-1)
+ positions = positions * selector[..., None]
self._sample_locations = positions
if not self._sample_locations.requires_grad:
self._sample_locations.requires_grad = True
@@ -247,9 +256,12 @@ class TCNNNerfactoField(Field):
# softplus, because it enables high post-activation (float32) density outputs
# from smaller internal (float16) parameters.
density = trunc_exp(density_before_activation.to(positions))
+ density = density * selector[..., None]
return density, base_mlp_out
- def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None):
+ def get_outputs(
+ self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None
+ ) -> Dict[FieldHeadNames, TensorType]:
assert density_embedding is not None
outputs = {}
if ray_samples.camera_indices is None:
@@ -291,13 +303,10 @@ class TCNNNerfactoField(Field):
# semantics
if self.use_semantics:
- density_embedding_copy = density_embedding.clone().detach()
- semantics_input = torch.cat(
- [
- density_embedding_copy.view(-1, self.geo_feat_dim),
- ],
- dim=-1,
- )
+ semantics_input = density_embedding.view(-1, self.geo_feat_dim)
+ if not self.pass_semantic_gradients:
+ semantics_input = semantics_input.detach()
+
x = self.mlp_semantics(semantics_input).view(*outputs_shape, -1).to(directions)
outputs[FieldHeadNames.SEMANTICS] = self.field_head_semantics(x)
@@ -332,7 +341,7 @@ class TorchNerfactoField(Field):
def __init__(
self,
- aabb,
+ aabb: TensorType,
num_images: int,
position_encoding: Encoding = HashEncoding(),
direction_encoding: Encoding = SHEncoding(),
@@ -375,7 +384,7 @@ class TorchNerfactoField(Field):
for field_head in self.field_heads:
field_head.set_in_dim(self.mlp_head.get_out_dim()) # type: ignore
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, TensorType]:
if self.spatial_distortion is not None:
positions = ray_samples.frustums.get_positions()
positions = self.spatial_distortion(positions)
@@ -389,7 +398,6 @@ class TorchNerfactoField(Field):
def get_outputs(
self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None
) -> Dict[FieldHeadNames, TensorType]:
-
outputs_shape = ray_samples.frustums.directions.shape[:-1]
if ray_samples.camera_indices is None:
@@ -420,4 +428,4 @@ class TorchNerfactoField(Field):
return outputs
-field_implementation_to_class = {"tcnn": TCNNNerfactoField, "torch": TorchNerfactoField}
+field_implementation_to_class: Dict[str, Field] = {"tcnn": TCNNNerfactoField, "torch": TorchNerfactoField}
diff --git a/nerfstudio/fields/nerfplayer_nerfacto_field.py b/nerfstudio/fields/nerfplayer_nerfacto_field.py
index e87df3b03..0b186464f 100644
--- a/nerfstudio/fields/nerfplayer_nerfacto_field.py
+++ b/nerfstudio/fields/nerfplayer_nerfacto_field.py
@@ -17,7 +17,7 @@ Field implementations for NeRFPlayer (https://arxiv.org/abs/2210.15947) implemen
"""
-from typing import Optional
+from typing import Dict, Optional, Tuple
import numpy as np
import torch
@@ -47,7 +47,7 @@ except ImportError:
pass
-def get_normalized_directions(directions: TensorType["bs":..., 3]):
+def get_normalized_directions(directions: TensorType["bs":..., 3]) -> TensorType["bs":..., 3]:
"""SH encoding must be in the range [0, 1]
Args:
@@ -74,16 +74,16 @@ class TemporalHashMLPDensityField(Field):
def __init__(
self,
- aabb,
+ aabb: TensorType,
temporal_dim: int = 64,
num_layers: int = 2,
hidden_dim: int = 64,
spatial_distortion: Optional[SpatialDistortion] = None,
- num_levels=8,
- max_res=1024,
- base_res=16,
- log2_hashmap_size=18,
- features_per_level=2,
+ num_levels: int = 8,
+ max_res: int = 1024,
+ base_res: int = 16,
+ log2_hashmap_size: int = 18,
+ features_per_level: int = 2,
) -> None:
super().__init__()
# from .temporal_grid import test; test() # DEBUG
@@ -137,7 +137,7 @@ class TemporalHashMLPDensityField(Field):
density, _ = self.get_density(ray_samples)
return density
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, None]:
if self.spatial_distortion is not None:
positions = self.spatial_distortion(ray_samples.frustums.get_positions())
positions = (positions + 2.0) / 4.0
@@ -154,7 +154,7 @@ class TemporalHashMLPDensityField(Field):
density = trunc_exp(density_before_activation)
return density, None
- def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None):
+ def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None) -> dict:
return {}
@@ -186,7 +186,7 @@ class NerfplayerNerfactoField(Field):
def __init__(
self,
- aabb,
+ aabb: TensorType,
num_images: int,
num_layers: int = 2,
hidden_dim: int = 64,
@@ -318,7 +318,7 @@ class NerfplayerNerfactoField(Field):
},
)
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, TensorType]:
"""Computes and returns the densities."""
if self.spatial_distortion is not None:
positions = ray_samples.frustums.get_positions()
@@ -339,7 +339,9 @@ class NerfplayerNerfactoField(Field):
density = trunc_exp(density_before_activation.to(positions))
return density, base_mlp_out
- def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None):
+ def get_outputs(
+ self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None
+ ) -> Dict[FieldHeadNames, TensorType]:
assert density_embedding is not None
outputs = {}
if ray_samples.camera_indices is None:
diff --git a/nerfstudio/fields/nerfplayer_ngp_field.py b/nerfstudio/fields/nerfplayer_ngp_field.py
index ed1cf250e..829ff0d33 100644
--- a/nerfstudio/fields/nerfplayer_ngp_field.py
+++ b/nerfstudio/fields/nerfplayer_ngp_field.py
@@ -17,7 +17,7 @@ NeRFPlayer (https://arxiv.org/abs/2210.15947) field implementations with Instant
"""
-from typing import Optional
+from typing import Dict, Optional, Tuple
import torch
from nerfacc import ContractionType, contract
@@ -68,7 +68,7 @@ class NerfplayerNGPField(Field):
def __init__(
self,
- aabb,
+ aabb: TensorType,
temporal_dim: int = 16,
num_levels: int = 16,
features_per_level: int = 2,
@@ -144,7 +144,7 @@ class NerfplayerNGPField(Field):
},
)
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, TensorType]:
positions = ray_samples.frustums.get_positions()
positions_flat = positions.view(-1, 3)
positions_flat = contract(x=positions_flat, roi=self.aabb, type=self.contraction_type)
@@ -161,7 +161,9 @@ class NerfplayerNGPField(Field):
density = trunc_exp(density_before_activation.to(positions))
return density, base_mlp_out
- def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None):
+ def get_outputs(
+ self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None
+ ) -> Dict[FieldHeadNames, TensorType]:
directions = get_normalized_directions(ray_samples.frustums.directions)
directions_flat = directions.view(-1, 3)
diff --git a/nerfstudio/fields/nerfw_field.py b/nerfstudio/fields/nerfw_field.py
index 483f5b502..377c900ea 100644
--- a/nerfstudio/fields/nerfw_field.py
+++ b/nerfstudio/fields/nerfw_field.py
@@ -109,7 +109,7 @@ class VanillaNerfWField(Field):
self.field_head_transient_rgb = TransientRGBFieldHead(in_dim=self.mlp_transient.get_out_dim())
self.field_head_transient_density = TransientDensityFieldHead(in_dim=self.mlp_transient.get_out_dim())
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, TensorType]:
"""Computes and returns the densities."""
encoded_xyz = self.position_encoding(ray_samples.frustums.get_positions())
encoded_xyz = self.position_encoding(ray_samples.frustums.get_positions())
diff --git a/nerfstudio/fields/semantic_nerf_field.py b/nerfstudio/fields/semantic_nerf_field.py
index 11fdb142a..08026b0a2 100644
--- a/nerfstudio/fields/semantic_nerf_field.py
+++ b/nerfstudio/fields/semantic_nerf_field.py
@@ -88,7 +88,7 @@ class SemanticNerfField(Field):
in_dim=self.mlp_semantic.get_out_dim(), num_classes=self.num_semantic_classes
)
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, TensorType]:
encoded_xyz = self.position_encoding(ray_samples.frustums.get_positions())
base_mlp_out = self.mlp_base(encoded_xyz)
density = self.field_head_density(base_mlp_out)
diff --git a/nerfstudio/fields/tensorf_field.py b/nerfstudio/fields/tensorf_field.py
index ac0c242f3..bbadc54f0 100644
--- a/nerfstudio/fields/tensorf_field.py
+++ b/nerfstudio/fields/tensorf_field.py
@@ -15,7 +15,7 @@
"""TensoRF Field"""
-from typing import Optional
+from typing import Dict, Optional
import torch
from torch import nn
@@ -35,7 +35,7 @@ class TensoRFField(Field):
def __init__(
self,
- aabb,
+ aabb: TensorType,
# the aabb bounding box of the dataset
feature_encoding: Encoding = Identity(in_dim=3),
# the encoding method used for appearance encoding outputs
@@ -83,7 +83,7 @@ class TensoRFField(Field):
self.field_output_rgb = RGBFieldHead(in_dim=self.mlp_head.get_out_dim(), activation=nn.Sigmoid())
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> TensorType:
positions = SceneBox.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb)
positions = positions * 2 - 1
density = self.density_encoding(positions)
@@ -118,7 +118,7 @@ class TensoRFField(Field):
compute_normals: bool = False,
mask: Optional[TensorType] = None,
bg_color: Optional[TensorType] = None,
- ):
+ ) -> Dict[FieldHeadNames, TensorType]:
if compute_normals is True:
raise ValueError("Surface normals are not currently supported with TensoRF")
if mask is not None and bg_color is not None:
diff --git a/nerfstudio/fields/vanilla_nerf_field.py b/nerfstudio/fields/vanilla_nerf_field.py
index 45511c1d1..03e496d48 100644
--- a/nerfstudio/fields/vanilla_nerf_field.py
+++ b/nerfstudio/fields/vanilla_nerf_field.py
@@ -58,7 +58,7 @@ class NeRFField(Field):
head_mlp_num_layers: int = 2,
head_mlp_layer_width: int = 128,
skip_connections: Tuple[int] = (4,),
- field_heads: Tuple[FieldHead] = (RGBFieldHead(),),
+ field_heads: Optional[Tuple[FieldHead]] = (RGBFieldHead(),),
use_integrated_encoding: bool = False,
spatial_distortion: Optional[SpatialDistortion] = None,
) -> None:
@@ -88,7 +88,7 @@ class NeRFField(Field):
for field_head in self.field_heads:
field_head.set_in_dim(self.mlp_head.get_out_dim()) # type: ignore
- def get_density(self, ray_samples: RaySamples):
+ def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType, TensorType]:
if self.use_integrated_encoding:
gaussian_samples = ray_samples.frustums.get_gaussian_blob()
if self.spatial_distortion is not None:
diff --git a/nerfstudio/model_components/renderers.py b/nerfstudio/model_components/renderers.py
index 3d01bddea..5e488bc35 100644
--- a/nerfstudio/model_components/renderers.py
+++ b/nerfstudio/model_components/renderers.py
@@ -183,7 +183,7 @@ class SHRenderer(nn.Module):
rgb = torch.sum(sh, dim=-1) + 0.5 # [..., num_samples, 3]
if self.activation is not None:
- self.activation(rgb)
+ rgb = self.activation(rgb)
if not self.training:
rgb = torch.nan_to_num(rgb)
diff --git a/nerfstudio/models/nerfacto.py b/nerfstudio/models/nerfacto.py
index bf92968da..53173640a 100644
--- a/nerfstudio/models/nerfacto.py
+++ b/nerfstudio/models/nerfacto.py
@@ -73,6 +73,12 @@ class NerfactoModelConfig(ModelConfig):
"""How far along the ray to stop sampling."""
background_color: Literal["random", "last_sample", "black", "white"] = "last_sample"
"""Whether to randomize the background color."""
+ hidden_dim: int = 64
+ """Dimension of hidden layers"""
+ hidden_dim_color: int = 64
+ """Dimension of hidden layers for color network"""
+ hidden_dim_transient: int = 64
+ """Dimension of hidden layers for transient network"""
num_levels: int = 16
"""Number of levels of the hashmap for the base mlp."""
max_res: int = 2048
@@ -93,8 +99,8 @@ class NerfactoModelConfig(ModelConfig):
"""Use the same proposal network. Otherwise use different ones."""
proposal_net_args_list: List[Dict] = field(
default_factory=lambda: [
- {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 128},
- {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 256},
+ {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 128, "use_linear": False},
+ {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 256, "use_linear": False},
]
)
"""Arguments for the proposal density fields."""
@@ -120,6 +126,8 @@ class NerfactoModelConfig(ModelConfig):
"""Whether use single jitter or not for the proposal networks."""
predict_normals: bool = False
"""Whether to predict normals or not."""
+ disable_scene_contraction: bool = False
+ """Whether to disable scene contraction or not."""
class NerfactoModel(Model):
@@ -135,14 +143,20 @@ class NerfactoModel(Model):
"""Set the fields and modules."""
super().populate_modules()
- scene_contraction = SceneContraction(order=float("inf"))
+ if self.config.disable_scene_contraction:
+ scene_contraction = None
+ else:
+ scene_contraction = SceneContraction(order=float("inf"))
# Fields
self.field = TCNNNerfactoField(
self.scene_box.aabb,
+ hidden_dim=self.config.hidden_dim,
num_levels=self.config.num_levels,
max_res=self.config.max_res,
log2_hashmap_size=self.config.log2_hashmap_size,
+ hidden_dim_color=self.config.hidden_dim_color,
+ hidden_dim_transient=self.config.hidden_dim_transient,
spatial_distortion=scene_contraction,
num_images=self.num_train_data,
use_pred_normals=self.config.predict_normals,
diff --git a/nerfstudio/models/semantic_nerfw.py b/nerfstudio/models/semantic_nerfw.py
index 22957d268..4324e1eeb 100644
--- a/nerfstudio/models/semantic_nerfw.py
+++ b/nerfstudio/models/semantic_nerfw.py
@@ -61,6 +61,8 @@ class SemanticNerfWModelConfig(NerfactoModelConfig):
_target: Type = field(default_factory=lambda: SemanticNerfWModel)
use_transient_embedding: bool = False
"""Whether to use transient embedding."""
+ semantic_loss_weight: float = 1.0
+ pass_semantic_gradients: bool = False
class SemanticNerfWModel(Model):
@@ -76,6 +78,7 @@ class SemanticNerfWModel(Model):
assert "semantics" in metadata.keys() and isinstance(metadata["semantics"], Semantics)
self.semantics = metadata["semantics"]
super().__init__(config=config, **kwargs)
+ self.colormap = self.semantics.colors.clone().detach().to(self.device)
def populate_modules(self):
"""Set the fields and modules."""
@@ -98,6 +101,7 @@ class SemanticNerfWModel(Model):
use_transient_embedding=self.config.use_transient_embedding,
use_semantics=True,
num_semantic_classes=len(self.semantics.classes),
+ pass_semantic_gradients=self.config.pass_semantic_gradients,
)
# Build the proposal network(s)
@@ -207,13 +211,16 @@ class SemanticNerfWModel(Model):
outputs["density_transient"] = field_outputs[FieldHeadNames.TRANSIENT_DENSITY]
# semantics
+ semantic_weights = weights_static
+ if not self.config.pass_semantic_gradients:
+ semantic_weights = semantic_weights.detach()
outputs["semantics"] = self.renderer_semantics(
- field_outputs[FieldHeadNames.SEMANTICS], weights=weights_static.detach()
+ field_outputs[FieldHeadNames.SEMANTICS], weights=semantic_weights
)
# semantics colormaps
semantic_labels = torch.argmax(torch.nn.functional.softmax(outputs["semantics"], dim=-1), dim=-1)
- outputs["semantics_colormap"] = self.semantics.colors[semantic_labels]
+ outputs["semantics_colormap"] = self.colormap.to(self.device)[semantic_labels]
return outputs
@@ -243,7 +250,9 @@ class SemanticNerfWModel(Model):
loss_dict["rgb_loss"] = self.rgb_loss(image, outputs["rgb"])
# semantic loss
- loss_dict["semantics_loss"] = self.cross_entropy_loss(outputs["semantics"], batch["semantics"][..., 0].long())
+ loss_dict["semantics_loss"] = self.config.semantic_loss_weight * self.cross_entropy_loss(
+ outputs["semantics"], batch["semantics"][..., 0].long()
+ )
return loss_dict
def get_image_metrics_and_images(
@@ -287,7 +296,7 @@ class SemanticNerfWModel(Model):
# semantics
semantic_labels = torch.argmax(torch.nn.functional.softmax(outputs["semantics"], dim=-1), dim=-1)
- images_dict["semantics_colormap"] = self.semantics.colors[semantic_labels]
+ images_dict["semantics_colormap"] = self.colormap.to(self.device)[semantic_labels]
# valid mask
images_dict["mask"] = batch["mask"].repeat(1, 1, 3)
diff --git a/nerfstudio/models/tensorf.py b/nerfstudio/models/tensorf.py
index 48310fde2..3b27354d1 100644
--- a/nerfstudio/models/tensorf.py
+++ b/nerfstudio/models/tensorf.py
@@ -27,6 +27,7 @@ from torch.nn import Parameter
from torchmetrics import PeakSignalNoiseRatio
from torchmetrics.functional import structural_similarity_index_measure
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
+from typing_extensions import Literal
from nerfstudio.cameras.rays import RayBundle
from nerfstudio.configs.config_utils import to_immutable_dict
@@ -35,7 +36,12 @@ from nerfstudio.engine.callbacks import (
TrainingCallbackAttributes,
TrainingCallbackLocation,
)
-from nerfstudio.field_components.encodings import NeRFEncoding, TensorVMEncoding
+from nerfstudio.field_components.encodings import (
+ NeRFEncoding,
+ TensorCPEncoding,
+ TensorVMEncoding,
+ TriplaneEncoding,
+)
from nerfstudio.field_components.field_heads import FieldHeadNames
from nerfstudio.fields.tensorf_field import TensoRFField
from nerfstudio.model_components.losses import MSELoss
@@ -72,6 +78,7 @@ class TensoRFModelConfig(ModelConfig):
"""Number of components in color encoding"""
appearance_dim: int = 27
"""Number of channels for color encoding"""
+ tensorf_encoding: Literal["triplane", "vm", "cp"] = "vm"
class TensoRFModel(Model):
@@ -166,14 +173,35 @@ class TensoRFModel(Model):
super().populate_modules()
# setting up fields
- density_encoding = TensorVMEncoding(
- resolution=self.init_resolution,
- num_components=self.num_den_components,
- )
- color_encoding = TensorVMEncoding(
- resolution=self.init_resolution,
- num_components=self.num_color_components,
- )
+ if self.config.tensorf_encoding == "vm":
+ density_encoding = TensorVMEncoding(
+ resolution=self.init_resolution,
+ num_components=self.num_den_components,
+ )
+ color_encoding = TensorVMEncoding(
+ resolution=self.init_resolution,
+ num_components=self.num_color_components,
+ )
+ elif self.config.tensorf_encoding == "cp":
+ density_encoding = TensorCPEncoding(
+ resolution=self.init_resolution,
+ num_components=self.num_den_components,
+ )
+ color_encoding = TensorCPEncoding(
+ resolution=self.init_resolution,
+ num_components=self.num_color_components,
+ )
+ elif self.config.tensorf_encoding == "triplane":
+ density_encoding = TriplaneEncoding(
+ resolution=self.init_resolution,
+ num_components=self.num_den_components,
+ )
+ color_encoding = TriplaneEncoding(
+ resolution=self.init_resolution,
+ num_components=self.num_color_components,
+ )
+ else:
+ raise ValueError(f"Encoding {self.config.tensorf_encoding} not supported")
feature_encoding = NeRFEncoding(in_dim=self.appearance_dim, num_frequencies=2, min_freq_exp=0, max_freq_exp=2)
direction_encoding = NeRFEncoding(in_dim=3, num_frequencies=2, min_freq_exp=0, max_freq_exp=2)
diff --git a/nerfstudio/pipelines/base_pipeline.py b/nerfstudio/pipelines/base_pipeline.py
index 1ef5ffea5..6db227971 100644
--- a/nerfstudio/pipelines/base_pipeline.py
+++ b/nerfstudio/pipelines/base_pipeline.py
@@ -21,7 +21,7 @@ import typing
from abc import abstractmethod
from dataclasses import dataclass, field
from time import time
-from typing import Any, Dict, List, Optional, Type, Union, cast
+from typing import Any, Dict, List, Mapping, Optional, Type, Union, cast
import torch
import torch.distributed as dist
@@ -108,6 +108,14 @@ class Pipeline(nn.Module):
"""Returns the device that the model is on."""
return self.model.device
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
+ model_state = {
+ key.replace("_model.", ""): value for key, value in state_dict.items() if key.startswith("_model.")
+ }
+ pipeline_state = {key: value for key, value in state_dict.items() if not key.startswith("_model.")}
+ self._model.load_state_dict(model_state, strict=strict)
+ super().load_state_dict(pipeline_state, strict=False)
+
@profiler.time_function
def get_train_loss_dict(self, step: int):
"""This function gets your training loss dict. This will be responsible for
@@ -372,7 +380,7 @@ class VanillaPipeline(Pipeline):
"""
state = {key.replace("module.", ""): value for key, value in loaded_state.items()}
self._model.update_to_step(step)
- self.load_state_dict(state, strict=False)
+ self.load_state_dict(state, strict=True)
def get_training_callbacks(
self, training_callback_attributes: TrainingCallbackAttributes
diff --git a/nerfstudio/plugins/registry.py b/nerfstudio/plugins/registry.py
index 365f05a12..9e7a61c8d 100644
--- a/nerfstudio/plugins/registry.py
+++ b/nerfstudio/plugins/registry.py
@@ -21,6 +21,7 @@ import typing as t
from rich.progress import Console
+from nerfstudio.engine.trainer import TrainerConfig
from nerfstudio.plugins.types import MethodSpecification
if sys.version_info < (3, 10):
@@ -30,7 +31,7 @@ else:
CONSOLE = Console(width=120)
-def discover_methods():
+def discover_methods() -> t.Tuple[t.Dict[str, TrainerConfig], t.Dict[str, str]]:
"""
Discovers all methods registered using the `nerfstudio.method_configs` entrypoint.
"""
diff --git a/nerfstudio/process_data/colmap_utils.py b/nerfstudio/process_data/colmap_utils.py
index 9db20647f..f8254f0a8 100644
--- a/nerfstudio/process_data/colmap_utils.py
+++ b/nerfstudio/process_data/colmap_utils.py
@@ -1,145 +1,50 @@
-"""
-Here we have modified code taken from COLMAP for parsing data in the COLMAP format.
-Original file at:
-https://github.com/colmap/colmap/blob/1a4d0bad2e90aa65ce997c9d1779518eaed998d5/scripts/python/read_write_model.py.
-"""
+# Copyright 2022 The Nerfstudio Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
-# Copyright (c) 2022, ETH Zurich and UNC Chapel Hill.
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# * Neither the name of ETH Zurich and UNC Chapel Hill nor the names of
-# its contributors may be used to endorse or promote products derived
-# from this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-#
-# Author: Johannes L. Schoenberger (jsch-at-demuc-dot-de)
+"""
+Tools supporting the execution of COLMAP and preparation of COLMAP-based datasets for nerstudio training.
+"""
import json
-import os
-import struct
-from dataclasses import dataclass
-from io import BufferedReader
from pathlib import Path
-from typing import Dict, Optional, Tuple
+from typing import Any, Dict, Optional
import appdirs
+import cv2
import numpy as np
import requests
+import torch
from rich.console import Console
from rich.progress import track
from typing_extensions import Literal
+# TODO(1480) use pycolmap instead of colmap_parsing_utils
+# import pycolmap
+from nerfstudio.data.utils.colmap_parsing_utils import (
+ qvec2rotmat,
+ read_cameras_binary,
+ read_images_binary,
+ read_points3d_binary,
+)
from nerfstudio.process_data.process_data_utils import CameraModel
+from nerfstudio.utils import colormaps
from nerfstudio.utils.rich_utils import status
from nerfstudio.utils.scripts import run_command
CONSOLE = Console(width=120)
-@dataclass
-class ColmapCameraModel:
- """Camera model"""
-
- model_id: int
- """Model identifier"""
- model_name: str
- """Model name"""
- num_params: int
- """Number of parameters"""
-
-
-@dataclass
-class Camera:
- """Camera"""
-
- id: int
- """Camera identifier"""
- model: str
- """Camera model"""
- width: int
- """Image width"""
- height: int
- """Image height"""
- params: np.ndarray
- """Camera parameters"""
-
-
-@dataclass
-class Image:
- """Data the corresponds to a single image"""
-
- id: int
- """Image identifier"""
- qvec: np.ndarray
- """Quaternion vector"""
- tvec: np.ndarray
- """Translation vector"""
- camera_id: int
- """Camera identifier"""
- name: str
- """Image name"""
- xys: np.ndarray
- """2D points"""
- point3d_ids: np.ndarray
- """Point3D identifiers"""
-
-
-@dataclass
-class Point3D:
- """Data that corresponds to a single 3D point"""
-
- id: int
- """Point3D identifier"""
- xyz: np.ndarray
- """3D point"""
- rgb: np.ndarray
- """Color"""
- error: float
- """Reconstruction error"""
- image_ids: np.ndarray
- """Image identifiers"""
- point2d_idxs: np.ndarray
- """Point2D indices"""
-
-
-COLMAP_CAMERA_MODELS = [
- ColmapCameraModel(model_id=0, model_name="SIMPLE_PINHOLE", num_params=3),
- ColmapCameraModel(model_id=1, model_name="PINHOLE", num_params=4),
- ColmapCameraModel(model_id=2, model_name="SIMPLE_RADIAL", num_params=4),
- ColmapCameraModel(model_id=3, model_name="RADIAL", num_params=5),
- ColmapCameraModel(model_id=4, model_name="OPENCV", num_params=8),
- ColmapCameraModel(model_id=5, model_name="OPENCV_FISHEYE", num_params=8),
- ColmapCameraModel(model_id=6, model_name="FULL_OPENCV", num_params=12),
- ColmapCameraModel(model_id=7, model_name="FOV", num_params=5),
- ColmapCameraModel(model_id=8, model_name="SIMPLE_RADIAL_FISHEYE", num_params=4),
- ColmapCameraModel(model_id=9, model_name="RADIAL_FISHEYE", num_params=5),
- ColmapCameraModel(model_id=10, model_name="THIN_PRISM_FISHEYE", num_params=12),
-]
-COLMAP_CAMERA_MODEL_IDS = {camera_model.model_id: camera_model for camera_model in COLMAP_CAMERA_MODELS}
-COLMAP_CAMERA_MODEL_NAMES = {camera_model.model_name: camera_model for camera_model in COLMAP_CAMERA_MODELS}
-
-
def get_colmap_version(colmap_cmd: str, default_version=3.8) -> float:
"""Returns the version of COLMAP.
This code assumes that colmap returns a version string of the form
@@ -159,310 +64,6 @@ def get_colmap_version(colmap_cmd: str, default_version=3.8) -> float:
return default_version
-def read_next_bytes(fid: BufferedReader, num_bytes: int, format_char_sequence, endian_character: str = "<"):
- """Read and unpack the next bytes from a binary file.
-
- Args:
- fid: Open file
- num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc.
- format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}.
- endian_character: Any of {@, =, <, >, !}
- Tuple of read and unpacked values.
- """
- data = fid.read(num_bytes)
- return struct.unpack(endian_character + format_char_sequence, data)
-
-
-def read_cameras_text(path: Path) -> Dict[int, Camera]:
- """Parse COLMAP cameras.txt file into a dictionary of Camera objects.
-
- Args:
- path: Path to cameras.txt file.
- Returns:
- Dictionary of Camera objects.
- """
- cameras = {}
- with open(path, encoding="utf-8") as fid:
- while True:
- line = fid.readline()
- if not line:
- break
- line = line.strip()
- if len(line) > 0 and line[0] != "#":
- elems = line.split()
- camera_id = int(elems[0])
- model = elems[1]
- width = int(elems[2])
- height = int(elems[3])
- params = np.array(tuple(map(float, elems[4:])))
- cameras[camera_id] = Camera(id=camera_id, model=model, width=width, height=height, params=params)
- return cameras
-
-
-def read_cameras_binary(path_to_model_file: Path) -> Dict[int, Camera]:
- """Parse COLMAP cameras.bin file into a dictionary of Camera objects.
-
- Args:
- path_to_model_file: Path to cameras.bin file.
- Returns:
- Dictionary of Camera objects.
- """
- cameras = {}
- with open(path_to_model_file, "rb") as fid:
- num_cameras = read_next_bytes(fid, 8, "Q")[0]
- for _ in range(num_cameras):
- camera_properties = read_next_bytes(fid, num_bytes=24, format_char_sequence="iiQQ")
- camera_id = camera_properties[0]
- model_id = camera_properties[1]
- model_name = COLMAP_CAMERA_MODEL_IDS[camera_properties[1]].model_name
- width = camera_properties[2]
- height = camera_properties[3]
- num_params = COLMAP_CAMERA_MODEL_IDS[model_id].num_params
- params = read_next_bytes(fid, num_bytes=8 * num_params, format_char_sequence="d" * num_params)
- cameras[camera_id] = Camera(
- id=camera_id, model=model_name, width=width, height=height, params=np.array(params)
- )
- assert len(cameras) == num_cameras
- return cameras
-
-
-def read_images_text(path: Path) -> Dict[int, Image]:
- """Parse COLMAP images.txt file into a dictionary of Image objects.
-
- Args:
- path: Path to images.txt file.
- Returns:
- Dictionary of Image objects.
- """
- images = {}
- with open(path, encoding="utf-8") as fid:
- while True:
- line = fid.readline()
- if not line:
- break
- line = line.strip()
- if len(line) > 0 and line[0] != "#":
- elems = line.split()
- image_id = int(elems[0])
- qvec = np.array(tuple(map(float, elems[1:5])))
- tvec = np.array(tuple(map(float, elems[5:8])))
- camera_id = int(elems[8])
- image_name = elems[9]
- elems = fid.readline().split()
- xys = np.column_stack([tuple(map(float, elems[0::3])), tuple(map(float, elems[1::3]))])
- point3d_ids = np.array(tuple(map(int, elems[2::3])))
- images[image_id] = Image(
- id=image_id,
- qvec=qvec,
- tvec=tvec,
- camera_id=camera_id,
- name=image_name,
- xys=xys,
- point3d_ids=point3d_ids,
- )
- return images
-
-
-def read_images_binary(path_to_model_file: Path) -> Dict[int, Image]:
- """Parse COLMAP images.bin file into a dictionary of Image objects.
-
- Args:
- path_to_model_file: Path to images.bin file.
- Returns:
- Dictionary of Image objects.
- """
- images = {}
- with open(path_to_model_file, "rb") as fid:
- num_reg_images = read_next_bytes(fid, 8, "Q")[0]
- for _ in range(num_reg_images):
- binary_image_properties = read_next_bytes(fid, num_bytes=64, format_char_sequence="idddddddi")
- image_id = binary_image_properties[0]
- qvec = np.array(binary_image_properties[1:5])
- tvec = np.array(binary_image_properties[5:8])
- camera_id = binary_image_properties[8]
- image_name = ""
- current_char = read_next_bytes(fid, 1, "c")[0]
- while current_char != b"\x00": # look for the ASCII 0 entry
- image_name += current_char.decode("utf-8")
- current_char = read_next_bytes(fid, 1, "c")[0]
- num_points2d = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[0]
- x_y_id_s = read_next_bytes(fid, num_bytes=24 * num_points2d, format_char_sequence="ddq" * num_points2d)
- xys = np.column_stack([tuple(map(float, x_y_id_s[0::3])), tuple(map(float, x_y_id_s[1::3]))])
- point3d_ids = np.array(tuple(map(int, x_y_id_s[2::3])))
- images[image_id] = Image(
- id=image_id,
- qvec=qvec,
- tvec=tvec,
- camera_id=camera_id,
- name=image_name,
- xys=xys,
- point3d_ids=point3d_ids,
- )
- return images
-
-
-def read_points3d_text(path) -> Dict[int, Point3D]:
- """Parse COLMAP points3D.txt file into a dictionary of Point3D objects.
-
- Args:
- path: Path to points3D.txt file.
- Returns:
- Dictionary of Point3D objects.
- """
- points3d = {}
- with open(path, encoding="utf-8") as fid:
- while True:
- line = fid.readline()
- if not line:
- break
- line = line.strip()
- if len(line) > 0 and line[0] != "#":
- elems = line.split()
- point3d_id = int(elems[0])
- xyz = np.array(tuple(map(float, elems[1:4])))
- rgb = np.array(tuple(map(int, elems[4:7])))
- error = float(elems[7])
- image_ids = np.array(tuple(map(int, elems[8::2])))
- point2d_idxs = np.array(tuple(map(int, elems[9::2])))
- points3d[point3d_id] = Point3D(
- id=point3d_id, xyz=xyz, rgb=rgb, error=error, image_ids=image_ids, point2d_idxs=point2d_idxs
- )
- return points3d
-
-
-def read_points3d_binary(path_to_model_file: Path) -> Dict[int, Point3D]:
- """Parse COLMAP points3D.bin file into a dictionary of Point3D objects.
-
- Args:
- path_to_model_file: Path to points3D.bin file.
- Returns:
- Dictionary of Point3D objects.
- """
- points3d = {}
- with open(path_to_model_file, "rb") as fid:
- num_points = read_next_bytes(fid, 8, "Q")[0]
- for _ in range(num_points):
- binary_point_line_properties = read_next_bytes(fid, num_bytes=43, format_char_sequence="QdddBBBd")
- point3d_id = binary_point_line_properties[0]
- xyz = np.array(binary_point_line_properties[1:4])
- rgb = np.array(binary_point_line_properties[4:7])
- error = np.array(binary_point_line_properties[7])
- track_length = read_next_bytes(fid, num_bytes=8, format_char_sequence="Q")[0]
- track_elems = read_next_bytes(fid, num_bytes=8 * track_length, format_char_sequence="ii" * track_length)
- image_ids = np.array(tuple(map(int, track_elems[0::2])))
- point2d_idxs = np.array(tuple(map(int, track_elems[1::2])))
- points3d[point3d_id] = Point3D(
- id=point3d_id, xyz=xyz, rgb=rgb, error=float(error), image_ids=image_ids, point2d_idxs=point2d_idxs
- )
- return points3d
-
-
-def detect_model_format(path: Path, ext: str) -> bool:
- """Detect the format of the model file.
-
- Args:
- path: Path to the model file.
- ext: Extension to test.
- Returns:
- True if the model file is the tested extension, False otherwise.
- """
-
- if (
- os.path.isfile(path / f"cameras{ext}")
- and os.path.isfile(path / f"images{ext}")
- and os.path.isfile(path / f"points3D{ext}")
- ):
- print("Detected model format: '" + ext + "'")
- return True
-
- return False
-
-
-def read_model(path: Path, ext: Optional[str] = None) -> Tuple[Dict[int, Camera], Dict[int, Image], Dict[int, Point3D]]:
- """Read a COLMAP model from a directory.
-
- Args:
- path: Path to the model directory.
- ext: Extension of the model files. If None, the function will try to detect the format.
- Returns:
- Tuple of dictionaries of Camera, Image, and Point3D objects.
- """
- # try to detect the extension automatically
- if ext is None:
- if detect_model_format(path, ".bin"):
- ext = ".bin"
- elif detect_model_format(path, ".txt"):
- ext = ".txt"
- else:
- raise ValueError("Provide model format: '.bin' or '.txt'")
-
- if ext == ".txt":
- cameras = read_cameras_text(path / f"cameras{ext}")
- images = read_images_text(path / f"images{ext}")
- points3d = read_points3d_text(path / f"points3D{ext}")
- else:
- cameras = read_cameras_binary(path / f"cameras{ext}")
- images = read_images_binary(path / f"images{ext}")
- points3d = read_points3d_binary(path / f"points3D{ext}")
- return cameras, images, points3d
-
-
-def qvec2rotmat(qvec) -> np.ndarray:
- """Convert quaternion to rotation matrix.
-
- Args:
- qvec: Quaternion vector of shape (4,).
- Returns:
- Rotation matrix of shape (3, 3).
- """
- return np.array(
- [
- [
- 1 - 2 * qvec[2] ** 2 - 2 * qvec[3] ** 2,
- 2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
- 2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2],
- ],
- [
- 2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
- 1 - 2 * qvec[1] ** 2 - 2 * qvec[3] ** 2,
- 2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1],
- ],
- [
- 2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
- 2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
- 1 - 2 * qvec[1] ** 2 - 2 * qvec[2] ** 2,
- ],
- ]
- )
-
-
-def rotmat2qvec(R):
- """Convert rotation matrix to quaternion.
-
- Args:
- R: Rotation matrix of shape (3, 3).
- Returns:
- Quaternion vector of shape (4,).
- """
- rxx, ryx, rzx, rxy, ryy, rzy, rxz, ryz, rzz = R.flat
- K = (
- np.array(
- [
- [rxx - ryy - rzz, 0, 0, 0],
- [ryx + rxy, ryy - rxx - rzz, 0, 0],
- [rzx + rxz, rzy + ryz, rzz - rxx - ryy, 0],
- [ryz - rzy, rzx - rxz, rxy - ryx, rxx + ryy + rzz],
- ]
- )
- / 3.0
- )
- eigvals, eigvecs = np.linalg.eigh(K)
- qvec = eigvecs[np.array([3, 0, 1, 2]), np.argmax(eigvals)]
- if qvec[0] < 0:
- qvec *= -1
- return qvec
-
-
def get_vocab_tree() -> Path:
"""Return path to vocab tree. Downloads vocab tree if it doesn't exist.
@@ -581,83 +182,277 @@ def run_colmap(
CONSOLE.log("[bold green]:tada: Done refining intrinsics.")
+def parse_colmap_camera_params(camera) -> Dict[str, Any]: # pylint: disable=too-many-statements
+ """
+ Parses all currently supported COLMAP cameras into the transforms.json metadata
+
+ Args:
+ camera: COLMAP camera
+ Returns:
+ transforms.json metadata containing camera's intrinsics and distortion parameters
+
+ """
+ out: Dict[str, Any] = {
+ "w": camera.width,
+ "h": camera.height,
+ }
+
+ # Parameters match https://github.com/colmap/colmap/blob/dev/src/base/camera_models.h
+ camera_params = camera.params
+ if camera.model == "SIMPLE_PINHOLE":
+ # du = 0
+ # dv = 0
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[0])
+ out["cx"] = float(camera_params[1])
+ out["cy"] = float(camera_params[2])
+ out["k1"] = 0.0
+ out["k2"] = 0.0
+ out["p1"] = 0.0
+ out["p2"] = 0.0
+ camera_model = CameraModel.OPENCV
+ elif camera.model == "PINHOLE":
+ # f, cx, cy, k
+
+ # du = 0
+ # dv = 0
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[1])
+ out["cx"] = float(camera_params[2])
+ out["cy"] = float(camera_params[3])
+ out["k1"] = 0.0
+ out["k2"] = 0.0
+ out["p1"] = 0.0
+ out["p2"] = 0.0
+ camera_model = CameraModel.OPENCV
+ elif camera.model == "SIMPLE_RADIAL":
+ # f, cx, cy, k
+
+ # r2 = u**2 + v**2;
+ # radial = k * r2
+ # du = u * radial
+ # dv = u * radial
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[0])
+ out["cx"] = float(camera_params[1])
+ out["cy"] = float(camera_params[2])
+ out["k1"] = float(camera_params[3])
+ out["k2"] = 0.0
+ out["p1"] = 0.0
+ out["p2"] = 0.0
+ camera_model = CameraModel.OPENCV
+ elif camera.model == "RADIAL":
+ # f, cx, cy, k1, k2
+
+ # r2 = u**2 + v**2;
+ # radial = k1 * r2 + k2 * r2 ** 2
+ # du = u * radial
+ # dv = v * radial
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[0])
+ out["cx"] = float(camera_params[1])
+ out["cy"] = float(camera_params[2])
+ out["k1"] = float(camera_params[3])
+ out["k2"] = float(camera_params[4])
+ out["p1"] = 0.0
+ out["p2"] = 0.0
+ camera_model = CameraModel.OPENCV
+ elif camera.model == "OPENCV":
+ # fx, fy, cx, cy, k1, k2, p1, p2
+
+ # uv = u * v;
+ # r2 = u**2 + v**2
+ # radial = k1 * r2 + k2 * r2 ** 2
+ # du = u * radial + 2 * p1 * u*v + p2 * (r2 + 2 * u**2)
+ # dv = v * radial + 2 * p2 * u*v + p1 * (r2 + 2 * v**2)
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[1])
+ out["cx"] = float(camera_params[2])
+ out["cy"] = float(camera_params[3])
+ out["k1"] = float(camera_params[4])
+ out["k2"] = float(camera_params[5])
+ out["p1"] = float(camera_params[6])
+ out["p2"] = float(camera_params[7])
+ camera_model = CameraModel.OPENCV
+ elif camera.model == "OPENCV_FISHEYE":
+ # fx, fy, cx, cy, k1, k2, k3, k4
+
+ # r = sqrt(u**2 + v**2)
+
+ # if r > eps:
+ # theta = atan(r)
+ # theta2 = theta ** 2
+ # theta4 = theta2 ** 2
+ # theta6 = theta4 * theta2
+ # theta8 = theta4 ** 2
+ # thetad = theta * (1 + k1 * theta2 + k2 * theta4 + k3 * theta6 + k4 * theta8)
+ # du = u * thetad / r - u;
+ # dv = v * thetad / r - v;
+ # else:
+ # du = dv = 0
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[1])
+ out["cx"] = float(camera_params[2])
+ out["cy"] = float(camera_params[3])
+ out["k1"] = float(camera_params[4])
+ out["k2"] = float(camera_params[5])
+ out["k3"] = float(camera_params[6])
+ out["k4"] = float(camera_params[7])
+ camera_model = CameraModel.OPENCV_FISHEYE
+ elif camera.model == "FULL_OPENCV":
+ # fx, fy, cx, cy, k1, k2, p1, p2, k3, k4, k5, k6
+
+ # u2 = u ** 2
+ # uv = u * v
+ # v2 = v ** 2
+ # r2 = u2 + v2
+ # r4 = r2 * r2
+ # r6 = r4 * r2
+ # radial = (1 + k1 * r2 + k2 * r4 + k3 * r6) /
+ # (1 + k4 * r2 + k5 * r4 + k6 * r6)
+ # du = u * radial + 2 * p1 * uv + p2 * (r2 + 2 * u2) - u
+ # dv = v * radial + 2 * p2 * uv + p1 * (r2 + 2 * v2) - v
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[1])
+ out["cx"] = float(camera_params[2])
+ out["cy"] = float(camera_params[3])
+ out["k1"] = float(camera_params[4])
+ out["k2"] = float(camera_params[5])
+ out["p1"] = float(camera_params[6])
+ out["p2"] = float(camera_params[7])
+ out["k3"] = float(camera_params[8])
+ out["k4"] = float(camera_params[9])
+ out["k5"] = float(camera_params[10])
+ out["k6"] = float(camera_params[11])
+ raise NotImplementedError(f"{camera.model} camera model is not supported yet!")
+ elif camera.model == "FOV":
+ # fx, fy, cx, cy, omega
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[1])
+ out["cx"] = float(camera_params[2])
+ out["cy"] = float(camera_params[3])
+ out["omega"] = float(camera_params[4])
+ raise NotImplementedError(f"{camera.model} camera model is not supported yet!")
+ elif camera.model == "SIMPLE_RADIAL_FISHEYE":
+ # f, cx, cy, k
+
+ # r = sqrt(u ** 2 + v ** 2)
+ # if r > eps:
+ # theta = atan(r)
+ # theta2 = theta ** 2
+ # thetad = theta * (1 + k * theta2)
+ # du = u * thetad / r - u;
+ # dv = v * thetad / r - v;
+ # else:
+ # du = dv = 0
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[0])
+ out["cx"] = float(camera_params[1])
+ out["cy"] = float(camera_params[2])
+ out["k1"] = float(camera_params[3])
+ out["k2"] = 0.0
+ out["k3"] = 0.0
+ out["k4"] = 0.0
+ camera_model = CameraModel.OPENCV_FISHEYE
+ elif camera.model == "RADIAL_FISHEYE":
+ # f, cx, cy, k1, k2
+
+ # r = sqrt(u ** 2 + v ** 2)
+ # if r > eps:
+ # theta = atan(r)
+ # theta2 = theta ** 2
+ # theta4 = theta2 ** 2
+ # thetad = theta * (1 + k * theta2)
+ # thetad = theta * (1 + k1 * theta2 + k2 * theta4)
+ # du = u * thetad / r - u;
+ # dv = v * thetad / r - v;
+ # else:
+ # du = dv = 0
+ out["fl_x"] = float(camera_params[0])
+ out["fl_y"] = float(camera_params[0])
+ out["cx"] = float(camera_params[1])
+ out["cy"] = float(camera_params[2])
+ out["k1"] = float(camera_params[3])
+ out["k2"] = float(camera_params[4])
+ out["k3"] = 0
+ out["k4"] = 0
+ camera_model = CameraModel.OPENCV_FISHEYE
+ else:
+ # THIN_PRISM_FISHEYE not supported!
+ raise NotImplementedError(f"{camera.model} camera model is not supported yet!")
+
+ out["camera_model"] = camera_model.value
+ return out
+
+
def colmap_to_json(
- cameras_path: Path,
- images_path: Path,
+ recon_dir: Path,
output_dir: Path,
- camera_model: CameraModel,
camera_mask_path: Optional[Path] = None,
+ image_id_to_depth_path: Optional[Dict[int, Path]] = None,
+ image_rename_map: Optional[Dict[str, str]] = None,
) -> int:
"""Converts COLMAP's cameras.bin and images.bin to a JSON file.
Args:
- cameras_path: Path to the cameras.bin file.
- images_path: Path to the images.bin file.
+ recon_dir: Path to the reconstruction directory, e.g. "sparse/0"
output_dir: Path to the output directory.
- camera_mask_path: Path to the camera mask.
camera_model: Camera model used.
+ camera_mask_path: Path to the camera mask.
+ image_id_to_depth_path: When including sfm-based depth, embed these depth file paths in the exported json
+ image_rename_map: Use these image names instead of the names embedded in the COLMAP db
Returns:
The number of registered images.
"""
- cameras = read_cameras_binary(cameras_path)
- images = read_images_binary(images_path)
-
- # Only supports one camera
- camera_params = cameras[1].params
+ # TODO(1480) use pycolmap
+ # recon = pycolmap.Reconstruction(recon_dir)
+ # cam_id_to_camera = recon.cameras
+ # im_id_to_image = recon.images
+ cam_id_to_camera = read_cameras_binary(recon_dir / "cameras.bin")
+ im_id_to_image = read_images_binary(recon_dir / "images.bin")
frames = []
- for _, im_data in images.items():
+ for im_id, im_data in im_id_to_image.items():
+ # NB: COLMAP uses Eigen / scalar-first quaternions
+ # * https://colmap.github.io/format.html
+ # * https://github.com/colmap/colmap/blob/bf3e19140f491c3042bfd85b7192ef7d249808ec/src/base/pose.cc#L75
+ # the `rotation_matrix()` handles that format for us.
+
+ # TODO(1480) BEGIN use pycolmap API
+ # rotation = im_data.rotation_matrix()
rotation = qvec2rotmat(im_data.qvec)
+
translation = im_data.tvec.reshape(3, 1)
w2c = np.concatenate([rotation, translation], 1)
w2c = np.concatenate([w2c, np.array([[0, 0, 0, 1]])], 0)
c2w = np.linalg.inv(w2c)
- # Convert from COLMAP's camera coordinate system to ours
+ # Convert from COLMAP's camera coordinate system (OpenCV) to ours (OpenGL)
c2w[0:3, 1:3] *= -1
c2w = c2w[np.array([1, 0, 2, 3]), :]
c2w[2, :] *= -1
- name = Path(f"./images/{im_data.name}")
+ name = im_data.name
+ if image_rename_map is not None:
+ name = image_rename_map[name]
+ name = Path(f"./images/{name}")
frame = {
"file_path": name.as_posix(),
"transform_matrix": c2w.tolist(),
+ "colmap_im_id": im_id,
}
if camera_mask_path is not None:
frame["mask_path"] = camera_mask_path.relative_to(camera_mask_path.parent.parent).as_posix()
+ if image_id_to_depth_path is not None:
+ depth_path = image_id_to_depth_path[im_id]
+ frame["depth_file_path"] = str(depth_path)
frames.append(frame)
- out = {
- "fl_x": float(camera_params[0]),
- "fl_y": float(camera_params[1]),
- "cx": float(camera_params[2]),
- "cy": float(camera_params[3]),
- "w": cameras[1].width,
- "h": cameras[1].height,
- "camera_model": camera_model.value,
- }
-
- if camera_model == CameraModel.OPENCV:
- out.update(
- {
- "k1": float(camera_params[4]),
- "k2": float(camera_params[5]),
- "p1": float(camera_params[6]),
- "p2": float(camera_params[7]),
- }
- )
- if camera_model == CameraModel.OPENCV_FISHEYE:
- out.update(
- {
- "k1": float(camera_params[4]),
- "k2": float(camera_params[5]),
- "k3": float(camera_params[6]),
- "k4": float(camera_params[7]),
- }
- )
-
+ if set(cam_id_to_camera.keys()) != {1}:
+ raise RuntimeError("Only single camera shared for all images is supported.")
+ out = parse_colmap_camera_params(cam_id_to_camera[1])
out["frames"] = frames
with open(output_dir / "transforms.json", "w", encoding="utf-8") as f:
@@ -666,6 +461,151 @@ def colmap_to_json(
return len(frames)
+def create_sfm_depth(
+ recon_dir: Path,
+ output_dir: Path,
+ verbose: bool = True,
+ depth_scale_to_integer_factor: float = 1000.0,
+ min_depth: float = 0.001,
+ max_depth: float = 10000,
+ max_repoj_err: float = 2.5,
+ min_n_visible: int = 2,
+ include_depth_debug: bool = False,
+ input_images_dir: Optional[Path] = None,
+) -> Dict[int, Path]:
+ """Converts COLMAP's points3d.bin to sparse depth map images encoded as
+ 16-bit "millimeter depth" PNGs.
+
+ Notes:
+ * This facility does NOT use COLMAP dense reconstruction; it creates depth
+ maps from sparse SfM points here.
+ * COLMAP does *not* reconstruct metric depth unless you give it calibrated
+ (metric) intrinsics as input. Therefore, "depth" in this function has
+ potentially ambiguous units.
+
+ Args:
+ recon_dir: Path to the reconstruction directory, e.g. "sparse/0"
+ output_dir: Path to the output directory.
+ verbose: If True, logs progress of depth image creation.
+ depth_scale_to_integer_factor: Use this parameter to tune the conversion of
+ raw depth measurements to integer depth values. This value should
+ be equal to 1. / `depth_unit_scale_factor`, where
+ `depth_unit_scale_factor` is the value you provide at training time.
+ E.g. for millimeter depth, leave `depth_unit_scale_factor` at 1e-3
+ and depth_scale_to_integer_factor at 1000.
+ min_depth: Discard points closer than this to the camera.
+ max_depth: Discard points farther than this from the camera.
+ max_repoj_err: Discard points with reprojection error greater than this
+ amount (in pixels).
+ min_n_visible: Discard 3D points that have been triangulated with fewer
+ than this many frames.
+ include_depth_debug: Also include debug images showing depth overlaid
+ upon RGB.
+ Returns:
+ Depth file paths indexed by COLMAP image id
+ """
+
+ # TODO(1480) use pycolmap
+ # recon = pycolmap.Reconstruction(recon_dir)
+ # ptid_to_info = recon.points3D
+ # cam_id_to_camera = recon.cameras
+ # im_id_to_image = recon.images
+ ptid_to_info = read_points3d_binary(recon_dir / "points3D.bin")
+ cam_id_to_camera = read_cameras_binary(recon_dir / "cameras.bin")
+ im_id_to_image = read_images_binary(recon_dir / "images.bin")
+
+ # Only support first camera
+ CAMERA_ID = 1 # pylint: disable=invalid-name
+ W = cam_id_to_camera[CAMERA_ID].width
+ H = cam_id_to_camera[CAMERA_ID].height
+
+ if verbose:
+ iter_images = track(
+ im_id_to_image.items(), total=len(im_id_to_image.items()), description="Creating depth maps ..."
+ )
+ else:
+ iter_images = iter(im_id_to_image.items())
+
+ image_id_to_depth_path = {}
+ for im_id, im_data in iter_images:
+ # TODO(1480) BEGIN delete when abandoning colmap_parsing_utils
+ pids = [pid for pid in im_data.point3D_ids if pid != -1]
+ xyz_world = np.array([ptid_to_info[pid].xyz for pid in pids])
+ rotation = qvec2rotmat(im_data.qvec)
+ z = (rotation @ xyz_world.T)[-1] + im_data.tvec[-1]
+ errors = np.array([ptid_to_info[pid].error for pid in pids])
+ n_visible = np.array([len(ptid_to_info[pid].image_ids) for pid in pids])
+ uv = np.array([im_data.xys[i] for i in range(len(im_data.xys)) if im_data.point3D_ids[i] != -1])
+ # TODO(1480) END delete when abandoning colmap_parsing_utils
+
+ # TODO(1480) BEGIN use pycolmap API
+
+ # # Get only keypoints that have corresponding triangulated 3D points
+ # p2ds = im_data.get_valid_points2D()
+
+ # xyz_world = np.array([ptid_to_info[p2d.point3D_id].xyz for p2d in p2ds])
+
+ # # COLMAP OpenCV convention: z is always positive
+ # z = (im_data.rotation_matrix() @ xyz_world.T)[-1] + im_data.tvec[-1]
+
+ # # Mean reprojection error in image space
+ # errors = np.array([ptid_to_info[p2d.point3D_id].error for p2d in p2ds])
+
+ # # Number of frames in which each frame is visible
+ # n_visible = np.array([ptid_to_info[p2d.point3D_id].track.length() for p2d in p2ds])
+
+ # Note: these are *unrectified* pixel coordinates that should match the original input
+ # no matter the camera model
+ # uv = np.array([p2d.xy for p2d in p2ds])
+
+ # TODO(1480) END use pycolmap API
+
+ idx = np.where(
+ (z >= min_depth)
+ & (z <= max_depth)
+ & (errors <= max_repoj_err)
+ & (n_visible >= min_n_visible)
+ & (uv[:, 0] >= 0)
+ & (uv[:, 0] < W)
+ & (uv[:, 1] >= 0)
+ & (uv[:, 1] < H)
+ )
+ z = z[idx]
+ uv = uv[idx]
+
+ uu, vv = uv[:, 0].astype(int), uv[:, 1].astype(int)
+ depth = np.zeros((H, W), dtype=np.float32)
+ depth[vv, uu] = z
+
+ # E.g. if `depth` is metric and in units of meters, and `depth_scale_to_integer_factor`
+ # is 1000, then `depth_img` will be integer millimeters.
+ depth_img = (depth_scale_to_integer_factor * depth).astype(np.uint16)
+
+ out_name = str(im_data.name)
+ depth_path = output_dir / out_name
+ cv2.imwrite(str(depth_path), depth_img)
+
+ image_id_to_depth_path[im_id] = depth_path
+
+ if include_depth_debug:
+ assert input_images_dir is not None, "Need explicit input_images_dir for debug images"
+ assert input_images_dir.exists(), input_images_dir
+
+ depth_flat = depth.flatten()[:, None]
+ overlay = 255.0 * colormaps.apply_depth_colormap(torch.from_numpy(depth_flat)).numpy()
+ overlay = overlay.reshape([H, W, 3])
+ input_image_path = input_images_dir / im_data.name
+ input_image = cv2.imread(str(input_image_path))
+ debug = 0.3 * input_image + 0.7 + overlay
+
+ out_name = out_name + ".debug.jpg"
+ output_path = output_dir / "debug_depth" / out_name
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ cv2.imwrite(str(output_path), debug.astype(np.uint8))
+
+ return image_id_to_depth_path
+
+
def get_matching_summary(num_intial_frames: int, num_matched_frames: int) -> str:
"""Returns a summary of the matching results.
diff --git a/nerfstudio/process_data/hloc_utils.py b/nerfstudio/process_data/hloc_utils.py
index 17bd0120c..0f46dd12c 100644
--- a/nerfstudio/process_data/hloc_utils.py
+++ b/nerfstudio/process_data/hloc_utils.py
@@ -28,6 +28,7 @@ from typing_extensions import Literal
from nerfstudio.process_data.process_data_utils import CameraModel
try:
+ # TODO(1480) un-hide pycolmap import
import pycolmap
from hloc import (
extract_features,
@@ -95,14 +96,16 @@ def run_hloc(
pairs_from_retrieval.main(retrieval_path, sfm_pairs, num_matched=num_matched)
match_features.main(matcher_conf, sfm_pairs, features=features, matches=matches)
- image_options = pycolmap.ImageReaderOptions(camera_model=camera_model.value)
+ image_options = pycolmap.ImageReaderOptions( # pylint: disable=c-extension-no-member
+ camera_model=camera_model.value
+ )
reconstruction.main(
sfm_dir,
image_dir,
sfm_pairs,
features,
matches,
- camera_mode=pycolmap.CameraMode.SINGLE,
+ camera_mode=pycolmap.CameraMode.SINGLE, # pylint: disable=c-extension-no-member
image_options=image_options,
verbose=verbose,
)
diff --git a/nerfstudio/process_data/polycam_utils.py b/nerfstudio/process_data/polycam_utils.py
index 079ff16f7..a101c5062 100644
--- a/nerfstudio/process_data/polycam_utils.py
+++ b/nerfstudio/process_data/polycam_utils.py
@@ -216,7 +216,9 @@ def process_depth_maps(
# Downscale depth maps
summary_log.append(
- process_data_utils.downscale_images(depth_dir, num_downscales, folder_name="depth", verbose=verbose)
+ process_data_utils.downscale_images(
+ depth_dir, num_downscales, folder_name="depths", nearest_neighbor=True, verbose=verbose
+ )
)
return summary_log, polycam_depth_maps_filenames
diff --git a/nerfstudio/process_data/process_data_utils.py b/nerfstudio/process_data/process_data_utils.py
index 2d78469eb..6b94bbaa9 100644
--- a/nerfstudio/process_data/process_data_utils.py
+++ b/nerfstudio/process_data/process_data_utils.py
@@ -24,7 +24,7 @@ from typing import List, Optional, Tuple
import cv2
import numpy as np
from rich.console import Console
-from typing_extensions import Literal
+from typing_extensions import Literal, OrderedDict
from nerfstudio.utils.rich_utils import status
from nerfstudio.utils.scripts import run_command
@@ -113,6 +113,13 @@ def convert_video_to_images(
A tuple containing summary of the conversion and the number of extracted frames.
"""
+ if video_path.is_dir():
+ CONSOLE.print(f"[bold red]Error: Video path is a directory, not a path: {video_path}")
+ sys.exit(1)
+ if video_path.exists() is False:
+ CONSOLE.print(f"[bold red]Error: Video does not exist: {video_path}")
+ sys.exit(1)
+
with status(msg="Converting video to images...", spinner="bouncingBall", verbose=verbose):
# delete existing images in folder
for img in image_dir.glob("*.png"):
@@ -242,7 +249,7 @@ def copy_and_upscale_polycam_depth_maps_list(
return copied_depth_map_paths
-def copy_images(data: Path, image_dir: Path, verbose) -> int:
+def copy_images(data: Path, image_dir: Path, verbose) -> OrderedDict[Path, Path]:
"""Copy images from a directory to a new directory.
Args:
@@ -250,7 +257,7 @@ def copy_images(data: Path, image_dir: Path, verbose) -> int:
image_dir: Path to the output directory.
verbose: If True, print extra logging.
Returns:
- The number of images copied.
+ The mapping from the original filenames to the new ones.
"""
with status(msg="[bold yellow]Copying images...", spinner="bouncingBall", verbose=verbose):
image_paths = list_images(data)
@@ -259,12 +266,17 @@ def copy_images(data: Path, image_dir: Path, verbose) -> int:
CONSOLE.log("[bold red]:skull: No usable images in the data folder.")
sys.exit(1)
- num_frames = len(copy_images_list(image_paths, image_dir, verbose))
-
- return num_frames
+ copied_images = copy_images_list(image_paths=image_paths, image_dir=image_dir, verbose=verbose)
+ return OrderedDict((original_path, new_path) for original_path, new_path in zip(image_paths, copied_images))
-def downscale_images(image_dir: Path, num_downscales: int, folder_name: str = "images", verbose: bool = False) -> str:
+def downscale_images(
+ image_dir: Path,
+ num_downscales: int,
+ folder_name: str = "images",
+ nearest_neighbor: bool = False,
+ verbose: bool = False,
+) -> str:
"""Downscales the images in the directory. Uses FFMPEG.
Assumes images are named frame_00001.png, frame_00002.png, etc.
@@ -273,6 +285,7 @@ def downscale_images(image_dir: Path, num_downscales: int, folder_name: str = "i
image_dir: Path to the directory containing the images.
num_downscales: Number of times to downscale the images. Downscales by 2 each time.
folder_name: Name of the output folder
+ nearest_neighbor: Use nearest neighbor sampling (useful for depth images)
verbose: If True, logs the output of the command.
Returns:
@@ -292,10 +305,13 @@ def downscale_images(image_dir: Path, num_downscales: int, folder_name: str = "i
# Using %05d ffmpeg commands appears to be unreliable (skips images), so use scandir.
files = os.scandir(image_dir)
for f in files:
+ if f.is_dir():
+ continue
filename = f.name
+ nn_flag = "" if not nearest_neighbor else ":flags=neighbor"
ffmpeg_cmd = [
f'ffmpeg -y -noautorotate -i "{image_dir / filename}" ',
- f"-q:v 2 -vf scale=iw/{downscale_factor}:ih/{downscale_factor} ",
+ f"-q:v 2 -vf scale=iw/{downscale_factor}:ih/{downscale_factor}{nn_flag} ",
f'"{downscale_dir / filename}"',
]
ffmpeg_cmd = " ".join(ffmpeg_cmd)
diff --git a/nerfstudio/process_data/record3d_utils.py b/nerfstudio/process_data/record3d_utils.py
index d24292817..ed7393086 100644
--- a/nerfstudio/process_data/record3d_utils.py
+++ b/nerfstudio/process_data/record3d_utils.py
@@ -46,6 +46,8 @@ def record3d_to_json(images_paths: List[Path], metadata_path: Path, output_dir:
metadata_dict = io.load_from_json(metadata_path)
poses_data = np.array(metadata_dict["poses"]) # (N, 3, 4)
+ # NB: Record3D / scipy use "scalar-last" format quaternions (x y z w)
+ # https://fzheng.me/2017/11/12/quaternion_conventions_en/
camera_to_worlds = np.concatenate(
[Rotation.from_quat(poses_data[:, :4]).as_matrix(), poses_data[:, 4:, None]],
axis=-1,
diff --git a/nerfstudio/utils/colormaps.py b/nerfstudio/utils/colormaps.py
index 18d7aa86f..aae1b2a92 100644
--- a/nerfstudio/utils/colormaps.py
+++ b/nerfstudio/utils/colormaps.py
@@ -31,7 +31,7 @@ def apply_colormap(image: TensorType["bs":..., 1], cmap="viridis") -> TensorType
cmap: Colormap for image.
Returns:
- TensorType: Colored image
+ TensorType: Colored image with colors in [0, 1]
"""
colormap = cm.get_cmap(cmap)
@@ -62,7 +62,7 @@ def apply_depth_colormap(
cmap: Colormap to apply.
Returns:
- Colored depth image
+ Colored depth image with colors in [0, 1]
"""
near_plane = near_plane or float(torch.min(depth))
diff --git a/nerfstudio/utils/install_checks.py b/nerfstudio/utils/install_checks.py
index 05e505d4e..6393ed423 100644
--- a/nerfstudio/utils/install_checks.py
+++ b/nerfstudio/utils/install_checks.py
@@ -28,7 +28,6 @@ def check_ffmpeg_installed():
if ffmpeg_path is None:
CONSOLE.print("[bold red]Could not find ffmpeg. Please install ffmpeg.")
print("See https://ffmpeg.org/download.html for installation instructions.")
- print("ffmpeg is only necessary if using videos as input.")
sys.exit(1)
diff --git a/nerfstudio/utils/misc.py b/nerfstudio/utils/misc.py
index 5c4541426..88a76e8fc 100644
--- a/nerfstudio/utils/misc.py
+++ b/nerfstudio/utils/misc.py
@@ -16,6 +16,7 @@
Miscellaneous helper code.
"""
+
from typing import Any, Callable, Dict, List, Optional, Union
import torch
@@ -147,3 +148,10 @@ def update_avg(prev_avg: float, new_val: float, step: int) -> float:
float: new updated average
"""
return (step * prev_avg + new_val) / (step + 1)
+
+
+def strtobool(val) -> bool:
+ """Cheap replacement for `distutils.util.strtobool()` which is deprecated
+ FMI https://stackoverflow.com/a/715468
+ """
+ return val.lower() in ("yes", "y", "true", "t", "on", "1")
diff --git a/nerfstudio/viewer/server/viewer_utils.py b/nerfstudio/viewer/server/viewer_utils.py
index 0abd1eaf3..35b63e9f6 100644
--- a/nerfstudio/viewer/server/viewer_utils.py
+++ b/nerfstudio/viewer/server/viewer_utils.py
@@ -72,11 +72,13 @@ def get_viewer_version() -> str:
@check_main_thread
-def setup_viewer(config: cfg.ViewerConfig, log_filename: Path, datapath: str):
+def setup_viewer(config: cfg.ViewerConfig, log_filename: Path, datapath: Path):
"""Sets up the viewer if enabled
Args:
config: the configuration to instantiate viewer
+ log_filename: the log filename to write to
+ datapath: the path to the dataset
"""
viewer_state = ViewerState(config, log_filename=log_filename, datapath=datapath)
banner_messages = [f"Viewer at: {viewer_state.viewer_url}"]
@@ -252,14 +254,16 @@ class ViewerState:
Args:
config: viewer setup configuration
+ log_filename: filename to log viewer output to
+ datapath: path to data
"""
- def __init__(self, config: cfg.ViewerConfig, log_filename: Path, datapath: str):
+ def __init__(self, config: cfg.ViewerConfig, log_filename: Path, datapath: Path):
self.config = config
self.vis = None
self.viewer_url = None
self.log_filename = log_filename
- self.datapath = datapath
+ self.datapath = datapath.parent if datapath.is_file() else datapath
if self.config.launch_bridge_server:
# start the viewer bridge server
assert self.config.websocket_port is not None
@@ -754,6 +758,9 @@ class ViewerState:
if OutputTypes.RGB_FINE in self.output_list:
viewer_output_list.remove(OutputTypes.RGB_FINE)
viewer_output_list.insert(0, OutputTypes.RGB)
+ # remove semantics, which crashes viewer; semantics_colormap is OK
+ if "semantics" in self.output_list:
+ viewer_output_list.remove("semantics")
self.vis["renderingState/output_options"].write(viewer_output_list)
reformatted_output = self._process_invalid_output(self.prev_output_type)
diff --git a/pyproject.toml b/pyproject.toml
index 0ce681905..670e22c31 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -32,16 +32,19 @@ dependencies = [
"mediapy>=1.1.0",
"msgpack>=1.0.4",
"msgpack_numpy>=0.4.8",
- "nerfacc==0.3.3",
+ "nerfacc==0.3.5",
"open3d>=0.16.0",
"opencv-python==4.6.0.66",
"Pillow>=9.3.0",
"plotly>=5.7.0",
"protobuf<=3.20.3,!=3.20.0",
+ # TODO(1480) enable when pycolmap windows wheels are available
+ # "pycolmap==0.3.0",
"pyequilib>=0.5.6",
"pymeshlab>=2022.2.post2",
"pyngrok>=5.1.0",
"python-socketio>=5.7.1",
+ "pyquaternion>=0.9.9",
"requests",
"rich>=12.5.1",
"scikit-image>=0.19.3",
diff --git a/scripts/benchmarking/launch_train_blender.sh b/scripts/benchmarking/launch_train_blender.sh
index 8f7148c03..cbdd7d754 100644
--- a/scripts/benchmarking/launch_train_blender.sh
+++ b/scripts/benchmarking/launch_train_blender.sh
@@ -28,7 +28,7 @@ fi
method_opts=()
if [ "$method_name" = "nerfacto" ]; then
# https://github.com/nerfstudio-project/nerfstudio/issues/806#issuecomment-1284327844
- method_opts=(--pipeline.model.background-color white --pipeline.model.proposal-initial-sampler uniform --pipeline.model.near-plane 2. --pipeline.model.far-plane 6. --pipeline.datamanager.camera-optimizer.mode off --pipeline.model.use-average-appearance-embedding False)
+ method_opts=(--pipeline.model.background-color white --pipeline.model.proposal-initial-sampler uniform --pipeline.model.near-plane 2. --pipeline.model.far-plane 6. --pipeline.datamanager.camera-optimizer.mode off --pipeline.model.use-average-appearance-embedding False --pipeline.model.distortion-loss-mult 0 --pipeline.model.disable-scene-contraction True)
fi
shift $((OPTIND-1))
diff --git a/scripts/downloads/download_data.py b/scripts/downloads/download_data.py
index b6775a339..3339b50bc 100644
--- a/scripts/downloads/download_data.py
+++ b/scripts/downloads/download_data.py
@@ -62,22 +62,25 @@ class BlenderDownload(DatasetDownload):
@dataclass
-class FriendsDownload(DatasetDownload):
- """Download the friends dataset."""
+class Sitcoms3DDownload(DatasetDownload):
+ """Download the sitcoms3D dataset."""
def download(self, save_dir: Path):
- """Download the friends dataset."""
+ """Download the sitcoms3D dataset."""
# https://drive.google.com/file/d/1sgKr0ZO7BQC0FYinAnRSxobIWNucAST5/view?usp=sharing
- friends_file_id = "1sgKr0ZO7BQC0FYinAnRSxobIWNucAST5"
+ sitcoms3d_file_id = "1sgKr0ZO7BQC0FYinAnRSxobIWNucAST5"
# Download the files
- url = f"https://drive.google.com/uc?id={friends_file_id}"
- download_path = str(save_dir / "friends.zip")
+ url = f"https://drive.google.com/uc?id={sitcoms3d_file_id}"
+ download_path = str(save_dir / "sitcoms3d.zip")
gdown.download(url, output=download_path)
with zipfile.ZipFile(download_path, "r") as zip_ref:
zip_ref.extractall(str(save_dir))
os.remove(download_path)
+ # The folder name of the downloaded dataset is the previously using 'friends/'
+ if os.path.exists(str(save_dir / "friends/")):
+ os.rename(str(save_dir / "friends/"), str(save_dir / "sitcoms3d/"))
def grab_file_id(zip_url: str) -> str:
@@ -358,7 +361,7 @@ class SDFstudioDemoDownload(DatasetDownload):
Commands = Union[
Annotated[BlenderDownload, tyro.conf.subcommand(name="blender")],
- Annotated[FriendsDownload, tyro.conf.subcommand(name="friends")],
+ Annotated[Sitcoms3DDownload, tyro.conf.subcommand(name="sitcoms3d")],
Annotated[NerfstudioDownload, tyro.conf.subcommand(name="nerfstudio")],
Annotated[Record3dDownload, tyro.conf.subcommand(name="record3d")],
Annotated[DNerfDownload, tyro.conf.subcommand(name="dnerf")],
@@ -375,7 +378,7 @@ def main(
- nerfstudio: Growing collection of real-world scenes. Use the `capture_name` argument to specify
which capture to download.
- blender: Blender synthetic scenes realeased with NeRF.
- - friends: Friends TV show scenes.
+ - sitcoms3d: Friends TV show scenes.
- record3d: Record3d dataset.
- dnerf: D-NeRF dataset.
- phototourism: PhotoTourism dataset. Use the `capture_name` argument to specify which capture to download.
diff --git a/scripts/process_data.py b/scripts/process_data.py
index 7b6bb7922..7c39afd1f 100644
--- a/scripts/process_data.py
+++ b/scripts/process_data.py
@@ -8,7 +8,7 @@ import sys
import zipfile
from dataclasses import dataclass
from pathlib import Path
-from typing import Tuple, Union
+from typing import Dict, Optional, Tuple, Union
import numpy as np
import tyro
@@ -91,11 +91,16 @@ class ProcessImages:
"""
gpu: bool = True
"""If True, use GPU."""
+ use_sfm_depth: bool = False
+ """If True, export and use depth maps induced from SfM points."""
+ include_depth_debug: bool = False
+ """If --use-sfm-depth and this flag is True, also export debug images showing SfM overlaid upon input images."""
verbose: bool = False
"""If True, print extra logging."""
- def main(self) -> None:
+ def main(self) -> None: # pylint: disable=R0915
"""Process images into a nerfstudio dataset."""
+ # pylint: disable=too-many-statements
require_cameras_exist = False
colmap_model_path = self.output_dir / Path(self.colmap_model_path)
if self.colmap_model_path != DEFAULT_COLMAP_PATH:
@@ -112,6 +117,7 @@ class ProcessImages:
install_checks.check_ffmpeg_installed()
install_checks.check_colmap_installed()
+ image_rename_map: Optional[Dict[str, str]] = None
self.output_dir.mkdir(parents=True, exist_ok=True)
image_dir = self.output_dir / "images"
image_dir.mkdir(parents=True, exist_ok=True)
@@ -129,7 +135,11 @@ class ProcessImages:
# Copy and downscale images
if not self.skip_image_processing:
# Copy images to output directory
- num_frames = process_data_utils.copy_images(self.data, image_dir=image_dir, verbose=self.verbose)
+ image_rename_map_paths = process_data_utils.copy_images(
+ self.data, image_dir=image_dir, verbose=self.verbose
+ )
+ image_rename_map = dict((a.name, b.name) for a, b in image_rename_map_paths.items())
+ num_frames = len(image_rename_map)
summary_log.append(f"Starting with {num_frames} images")
# Downscale images
@@ -152,14 +162,36 @@ class ProcessImages:
self._run_colmap(image_dir, colmap_dir)
+ # Colmap uses renamed images
+ image_rename_map = None
+
+ # Export depth maps
+ if self.use_sfm_depth:
+ depth_dir = self.output_dir / "depth"
+ depth_dir.mkdir(parents=True, exist_ok=True)
+ image_id_to_depth_path = colmap_utils.create_sfm_depth(
+ recon_dir=colmap_dir / "sparse" / "0",
+ output_dir=depth_dir,
+ include_depth_debug=self.include_depth_debug,
+ input_images_dir=image_dir,
+ verbose=self.verbose,
+ )
+ summary_log.append(
+ process_data_utils.downscale_images(
+ depth_dir, self.num_downscales, folder_name="depths", nearest_neighbor=True, verbose=self.verbose
+ )
+ )
+ else:
+ image_id_to_depth_path = None
+
# Save transforms.json
if (colmap_model_path / "cameras.bin").exists():
with CONSOLE.status("[bold yellow]Saving results to transforms.json", spinner="balloon"):
num_matched_frames = colmap_utils.colmap_to_json(
- cameras_path=colmap_model_path / "cameras.bin",
- images_path=colmap_model_path / "images.bin",
+ recon_dir=colmap_model_path,
output_dir=self.output_dir,
- camera_model=CAMERA_MODELS[self.camera_type],
+ image_id_to_depth_path=image_id_to_depth_path,
+ image_rename_map=image_rename_map,
)
summary_log.append(f"Colmap matched {num_matched_frames} images")
summary_log.append(colmap_utils.get_matching_summary(num_frames, num_matched_frames))
@@ -262,12 +294,16 @@ class ProcessVideo:
"""Create circle crop mask. The radius is the percent of the image diagonal."""
percent_crop: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0)
"""Percent of the image to crop. (top, bottom, left, right)"""
+ use_sfm_depth: bool = False
+ """If True, export and use depth maps induced from SfM points."""
+ include_depth_debug: bool = False
+ """If --use-sfm-depth and this flag is True, also export debug images showing SfM overlaid upon input images."""
gpu: bool = True
"""If True, use GPU."""
verbose: bool = False
"""If True, print extra logging."""
- def main(self) -> None:
+ def main(self) -> None: # pylint: disable=R0915
"""Process video into a nerfstudio dataset."""
install_checks.check_ffmpeg_installed()
install_checks.check_colmap_installed()
@@ -362,15 +398,34 @@ class ProcessVideo:
CONSOLE.log("[bold red]Invalid combination of sfm_tool, feature_type, and matcher_type, exiting")
sys.exit(1)
+ # Export depth maps
+ if self.use_sfm_depth:
+ depth_dir = self.output_dir / "depth"
+ depth_dir.mkdir(parents=True, exist_ok=True)
+ image_id_to_depth_path = colmap_utils.create_sfm_depth(
+ recon_dir=colmap_dir / "sparse" / "0",
+ output_dir=depth_dir,
+ include_depth_debug=self.include_depth_debug,
+ input_images_dir=image_dir,
+ verbose=self.verbose,
+ )
+ summary_log.append(
+ process_data_utils.downscale_images(
+ depth_dir, self.num_downscales, folder_name="depths", nearest_neighbor=True, verbose=self.verbose
+ )
+ )
+ else:
+ image_id_to_depth_path = None
+
# Save transforms.json
if (colmap_dir / "sparse" / "0" / "cameras.bin").exists():
with CONSOLE.status("[bold yellow]Saving results to transforms.json", spinner="balloon"):
num_matched_frames = colmap_utils.colmap_to_json(
- cameras_path=colmap_dir / "sparse" / "0" / "cameras.bin",
- images_path=colmap_dir / "sparse" / "0" / "images.bin",
+ recon_dir=colmap_dir / "sparse" / "0",
output_dir=self.output_dir,
- camera_model=CAMERA_MODELS[self.camera_type],
+ image_id_to_depth_path=image_id_to_depth_path,
camera_mask_path=mask_path,
+ image_rename_map=None,
)
summary_log.append(f"Colmap matched {num_matched_frames} images")
summary_log.append(colmap_utils.get_matching_summary(num_extracted_frames, num_matched_frames))
@@ -415,6 +470,10 @@ class ProcessInsta360:
"""If True, skips COLMAP and generates transforms.json if possible."""
colmap_cmd: str = "colmap"
"""How to call the COLMAP executable."""
+ use_sfm_depth: bool = False
+ """If True, export and use depth maps induced from SfM points."""
+ include_depth_debug: bool = False
+ """If --use-sfm-depth and this flag is True, also export debug images showing SfM overlaid upon input images."""
gpu: bool = True
"""If True, use GPU."""
verbose: bool = False
@@ -482,14 +541,33 @@ class ProcessInsta360:
colmap_cmd=self.colmap_cmd,
)
+ # Export depth maps
+ if self.use_sfm_depth:
+ depth_dir = self.output_dir / "depth"
+ depth_dir.mkdir(parents=True, exist_ok=True)
+ image_id_to_depth_path = colmap_utils.create_sfm_depth(
+ recon_dir=colmap_dir / "sparse" / "0",
+ output_dir=depth_dir,
+ include_depth_debug=self.include_depth_debug,
+ input_images_dir=image_dir,
+ verbose=self.verbose,
+ )
+ summary_log.append(
+ process_data_utils.downscale_images(
+ depth_dir, self.num_downscales, folder_name="depths", nearest_neighbor=True, verbose=self.verbose
+ )
+ )
+ else:
+ image_id_to_depth_path = None
+
# Save transforms.json
if (colmap_dir / "sparse" / "0" / "cameras.bin").exists():
with CONSOLE.status("[bold yellow]Saving results to transforms.json", spinner="balloon"):
num_matched_frames = colmap_utils.colmap_to_json(
- cameras_path=colmap_dir / "sparse" / "0" / "cameras.bin",
- images_path=colmap_dir / "sparse" / "0" / "images.bin",
+ recon_dir=colmap_dir / "sparse" / "0",
output_dir=self.output_dir,
- camera_model=CAMERA_MODELS["fisheye"],
+ image_id_to_depth_path=image_id_to_depth_path,
+ image_rename_map=None,
)
summary_log.append(f"Colmap matched {num_matched_frames} images")
summary_log.append(colmap_utils.get_matching_summary(num_extracted_frames, num_matched_frames))
diff --git a/scripts/render.py b/scripts/render.py
index 4466c5385..ce2f79dc2 100644
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -28,7 +28,11 @@ from rich.progress import (
from torchtyping import TensorType
from typing_extensions import Literal, assert_never
-from nerfstudio.cameras.camera_paths import get_path_from_json, get_spiral_path
+from nerfstudio.cameras.camera_paths import (
+ get_interpolated_camera_path,
+ get_path_from_json,
+ get_spiral_path,
+)
from nerfstudio.cameras.cameras import Cameras, CameraType
from nerfstudio.data.scene_box import SceneBox
from nerfstudio.model_components import renderers
@@ -94,7 +98,6 @@ def _render_trajectory_video(
with progress:
for camera_idx in progress.track(range(cameras.size), description=""):
-
aabb_box = None
if crop_data is not None:
bounding_box_min = crop_data.center - crop_data.scale / 2.0
@@ -249,14 +252,20 @@ def get_crop_from_json(camera_json: Dict[str, Any]) -> Optional[CropData]:
@dataclass
class RenderTrajectory:
- """Load a checkpoint, render a trajectory, and save to a video file."""
+ """Load a checkpoint, render a trajectory, and save to a video file.
+ The following trajectory options are available,
+ filename: Load from trajectory created using viewer or blender vfx plugin.
+ interpolate: Create trajectory by interpolating between eval dataset images.
+ spiral: Create a spiral trajectory (can be hit or miss).
+ """
load_config: Path
"""Path to config YAML file."""
rendered_output_names: List[str] = field(default_factory=lambda: ["rgb"])
"""Name of the renderer outputs to use. rgb, depth, etc. concatenates them along y axis"""
- traj: Literal["spiral", "filename"] = "spiral"
- """Trajectory to render."""
+ traj: Literal["spiral", "filename", "interpolate"] = "spiral"
+ """Trajectory type to render. Select between spiral-shaped trajectory, trajectory loaded from
+ a viewer-generated file and interpolated camera paths from the eval dataset."""
downscale_factor: int = 1
"""Scaling factor to apply to the camera image resolution."""
camera_path_filename: Path = Path("camera_path.json")
@@ -267,6 +276,8 @@ class RenderTrajectory:
"""How long the video should be."""
output_format: Literal["images", "video"] = "video"
"""How to save output data."""
+ interpolation_steps: int = 10
+ """Number of interpolation steps between eval dataset cameras."""
eval_num_rays_per_chunk: Optional[int] = None
"""Specifies number of rays per chunk during eval."""
@@ -275,7 +286,7 @@ class RenderTrajectory:
_, pipeline, _ = eval_setup(
self.load_config,
eval_num_rays_per_chunk=self.eval_num_rays_per_chunk,
- test_mode="test" if self.traj == "spiral" else "inference",
+ test_mode="test" if self.traj in ["spiral", "interpolate"] else "inference",
)
install_checks.check_ffmpeg_installed()
@@ -303,6 +314,11 @@ class RenderTrajectory:
camera_type = CameraType.PERSPECTIVE
crop_data = get_crop_from_json(camera_path)
camera_path = get_path_from_json(camera_path)
+ elif self.traj == "interpolate":
+ camera_type = CameraType.PERSPECTIVE
+ camera_path = get_interpolated_camera_path(
+ cameras=pipeline.datamanager.eval_dataloader.cameras, steps=self.interpolation_steps
+ )
else:
assert_never(self.traj)
diff --git a/scripts/viewer/run_viewer.py b/scripts/viewer/run_viewer.py
index 336a424b1..c48b23d9b 100644
--- a/scripts/viewer/run_viewer.py
+++ b/scripts/viewer/run_viewer.py
@@ -58,11 +58,11 @@ class RunViewer:
self._start_viewer(config, pipeline)
- def _start_viewer(self, config: TrainerConfig, pipeline):
+ def _start_viewer(self, config: TrainerConfig, pipeline: Pipeline):
base_dir = config.get_base_dir()
viewer_log_path = base_dir / config.viewer.relative_log_filename
viewer_state, banner_messages = viewer_utils.setup_viewer(
- config.viewer, log_filename=viewer_log_path, datapath=config.pipeline.datamanager.dataparser.data
+ config.viewer, log_filename=viewer_log_path, datapath=pipeline.datamanager.get_datapath()
)
# We don't need logging, but writer.GLOBAL_BUFFER needs to be populated
diff --git a/setup.cfg b/setup.cfg
deleted file mode 100644
index e69de29bb..000000000
diff --git a/tests/pipelines/test_vanilla_pipeline.py b/tests/pipelines/test_vanilla_pipeline.py
new file mode 100644
index 000000000..69581ce27
--- /dev/null
+++ b/tests/pipelines/test_vanilla_pipeline.py
@@ -0,0 +1,79 @@
+"""
+Test pipeline
+"""
+from pathlib import Path
+
+# pylint: disable=too-few-public-methods
+# pylint: disable=no-self-use
+# pylint: disable=missing-class-docstring
+# pylint: disable=unused-argument
+# pylint: disable=abstract-method
+import torch
+from torch import nn
+
+from nerfstudio.cameras.cameras import Cameras
+from nerfstudio.data.datasets.base_dataset import DataparserOutputs, InputDataset
+from nerfstudio.pipelines.base_pipeline import (
+ Model,
+ ModelConfig,
+ VanillaDataManagerConfig,
+ VanillaPipeline,
+ VanillaPipelineConfig,
+)
+
+
+class MockedDataManager:
+ """Mocked data manager"""
+
+ def __init__(self, *args, **kwargs):
+ num_images = 0
+ self.train_dataset = InputDataset(
+ DataparserOutputs(
+ image_filenames=[Path("filename.png")] * num_images,
+ cameras=Cameras(
+ camera_to_worlds=torch.ones([num_images, 3, 4], dtype=torch.float32),
+ fx=1.0,
+ fy=1.0,
+ cx=1.0,
+ cy=1.0,
+ width=2,
+ height=2,
+ ),
+ )
+ )
+
+ def to(self, *args, **kwargs):
+ "Mocked to"
+ return self
+
+
+def test_load_state_dict():
+ """Test pipeline load_state_dict calls model's load_state_dict"""
+ was_called = False
+
+ class MockedModel(Model): #
+ """Mocked model"""
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.register_parameter("param", nn.Parameter(torch.ones((3,))))
+
+ def load_state_dict(self, state_dict, strict=True):
+ """Mocked load_state_dict"""
+ nonlocal was_called
+ was_called = True
+ assert strict
+ assert "param" in state_dict
+
+ config = VanillaPipelineConfig(
+ datamanager=VanillaDataManagerConfig(
+ _target=MockedDataManager,
+ ),
+ model=ModelConfig(_target=MockedModel),
+ )
+ pipeline = VanillaPipeline(config, "cpu")
+ state_dict = pipeline.state_dict()
+ state_dict["_model.param"].mul_(2) # pylint: disable=unsubscriptable-object
+ pipeline.load_pipeline(state_dict, 0)
+ assert was_called
+ assert pipeline.model.param[0].item() == 2
diff --git a/tests/process_data/test_misc.py b/tests/process_data/test_misc.py
new file mode 100644
index 000000000..a300687ee
--- /dev/null
+++ b/tests/process_data/test_misc.py
@@ -0,0 +1,63 @@
+"""
+Test misc data utils
+"""
+
+import numpy as np
+from pyquaternion import Quaternion
+from scipy.spatial.transform import Rotation
+
+# TODO(1480) use pycolmap instead of colmap_parsing_utils
+# import pycolmap
+from nerfstudio.data.utils.colmap_parsing_utils import qvec2rotmat
+
+
+def test_scalar_first_scalar_last_quaternions():
+ """Many nerfstudio datasets use quaternions for pose rotations. Some use
+ scalar-first format and others use scalar-last. However internally
+ nerfstudio uses rotation *matrices* / projection matrices. This test
+ helps document differences in quaternion encodings & conversion to
+ rotation matrices.
+
+ FMI see call sites in nerfstudio where the various libraries are used. You
+ might also consult this detailed reference:
+ * "Why and How to Avoid the Flipped Quaternion Multiplication"
+ Sommer et al.
+ https://arxiv.org/abs/1801.07478
+ """
+
+ # Pick an arbitrary euler rotation; note that different communities
+ # also use different rotation axes (e.g. Euler vs Tait-Bryan ...)
+ rot = Rotation.from_euler("xyz", np.array([10.0, 20.0, 30.0]), degrees=True)
+
+ # scalar-last
+ xyzw = rot.as_quat()
+ assert np.allclose(xyzw, np.array([0.03813458, 0.18930786, 0.23929834, 0.95154852]))
+
+ # scalar-first
+ wxyz = xyzw[[3, 0, 1, 2]]
+ assert np.allclose(wxyz, np.array([0.95154852, 0.03813458, 0.18930786, 0.23929834]))
+
+ # Expected Rotation matrix
+ # fmt: off
+ R_expected = np.array( # pylint: disable=invalid-name
+ [
+ [ 0.81379768, -0.44096961, 0.37852231],
+ [ 0.46984631, 0.88256412, 0.01802831],
+ [-0.34202014, 0.16317591, 0.92541658]
+ ]
+ )
+ # fmt: on
+
+ # Record3D / scipy
+ R = Rotation.from_quat(xyzw).as_matrix()
+ assert np.allclose(R, R_expected)
+
+ # Nuscenes / pyquaternion
+ R = Quaternion(wxyz).rotation_matrix
+ assert np.allclose(R, R_expected)
+
+ # COLMAP
+ # TODO(1480) use pycolmap
+ # R = pycolmap.qvec_to_rotmat(wxyz)
+ R = qvec2rotmat(wxyz)
+ assert np.allclose(R, R_expected)
diff --git a/tests/test_train.py b/tests/test_train.py
index f3f4e2c2c..1e5c55cd5 100644
--- a/tests/test_train.py
+++ b/tests/test_train.py
@@ -21,6 +21,7 @@ BLACKLIST = [
"instant-ngp",
"instant-ngp-bounded",
"nerfacto",
+ "volinga",
"phototourism",
"depth-nerfacto",
"nerfplayer-ngp",
diff --git a/tests/utils/test_aabb_intersection.py b/tests/utils/test_aabb_intersection.py
index 1e01dae0b..1d6ba34b9 100644
--- a/tests/utils/test_aabb_intersection.py
+++ b/tests/utils/test_aabb_intersection.py
@@ -5,11 +5,11 @@ import importlib
import math
import os
import random
-from distutils.util import strtobool
import torch
from nerfstudio.utils.math import intersect_aabb
+from nerfstudio.utils.misc import strtobool
test_device = torch.device("cuda" if torch.cuda.is_available() else "cpu")