mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-04 14:58:55 +08:00
merge from main
This commit is contained in:
commit
a0c38e8430
144 files changed
+8884
-8219
No files matched your search
+1
-1
@@ -12,7 +12,7 @@ build/
|
|||||||
develop-eggs/
|
develop-eggs/
|
||||||
dist/
|
dist/
|
||||||
downloads/
|
downloads/
|
||||||
!scripts/downloads/
|
!nerfstudio/scripts/downloads/
|
||||||
eggs/
|
eggs/
|
||||||
.eggs/
|
.eggs/
|
||||||
lib/
|
lib/
|
||||||
|
|||||||
@@ -15,10 +15,10 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Set up Python 3.7.13
|
- name: Set up Python 3.8.13
|
||||||
uses: actions/setup-python@v4
|
uses: actions/setup-python@v4
|
||||||
with:
|
with:
|
||||||
python-version: '3.7.13'
|
python-version: '3.8.13'
|
||||||
- uses: actions/cache@v2
|
- uses: actions/cache@v2
|
||||||
with:
|
with:
|
||||||
path: ${{ env.pythonLocation }}
|
path: ${{ env.pythonLocation }}
|
||||||
@@ -28,17 +28,17 @@ jobs:
|
|||||||
pip install --upgrade --upgrade-strategy eager -e .[dev]
|
pip install --upgrade --upgrade-strategy eager -e .[dev]
|
||||||
- name: Run license checks
|
- name: Run license checks
|
||||||
run: |
|
run: |
|
||||||
./scripts/licensing/license_headers.sh --check
|
./nerfstudio/scripts/licensing/license_headers.sh --check
|
||||||
- name: Check notebook cell metadata
|
- name: Check notebook cell metadata
|
||||||
run: |
|
run: |
|
||||||
python ./scripts/docs/add_nb_tags.py --check
|
python ./nerfstudio/scripts/docs/add_nb_tags.py --check
|
||||||
- name: Run isort
|
- name: Run isort
|
||||||
run: isort docs/ nerfstudio/ scripts/ tests/ --profile black --check
|
run: isort docs/ nerfstudio/ tests/ --profile black --check
|
||||||
- name: Run Black
|
- name: Run Black
|
||||||
run: black docs/ nerfstudio/ scripts/ tests/ --check
|
run: black docs/ nerfstudio/ tests/ --check
|
||||||
- name: Python Pylint
|
- name: Python Pylint
|
||||||
run: |
|
run: |
|
||||||
pylint nerfstudio tests scripts
|
pylint nerfstudio tests
|
||||||
- name: Test with pytest
|
- name: Test with pytest
|
||||||
run: |
|
run: |
|
||||||
pytest
|
pytest
|
||||||
+1
-1
@@ -12,7 +12,7 @@ build/
|
|||||||
develop-eggs/
|
develop-eggs/
|
||||||
dist/
|
dist/
|
||||||
downloads/
|
downloads/
|
||||||
!scripts/downloads/
|
!nerfstudio/scripts/downloads/
|
||||||
eggs/
|
eggs/
|
||||||
.eggs/
|
.eggs/
|
||||||
lib/
|
lib/
|
||||||
|
|||||||
Vendored
+12
-12
@@ -30,7 +30,7 @@
|
|||||||
"name": "Python: train",
|
"name": "Python: train",
|
||||||
"type": "python",
|
"type": "python",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "scripts/train.py",
|
"program": "nerfstudio/scripts/train.py",
|
||||||
"console": "integratedTerminal",
|
"console": "integratedTerminal",
|
||||||
"args": [
|
"args": [
|
||||||
"instant_ngp",
|
"instant_ngp",
|
||||||
@@ -42,7 +42,7 @@
|
|||||||
"name": "Python: train ngp",
|
"name": "Python: train ngp",
|
||||||
"type": "python",
|
"type": "python",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "scripts/train.py",
|
"program": "nerfstudio/scripts/train.py",
|
||||||
"console": "integratedTerminal",
|
"console": "integratedTerminal",
|
||||||
"args": ["instant_ngp"]
|
"args": ["instant_ngp"]
|
||||||
},
|
},
|
||||||
@@ -50,7 +50,7 @@
|
|||||||
"name": "Python: train ngp nerfstudio",
|
"name": "Python: train ngp nerfstudio",
|
||||||
"type": "python",
|
"type": "python",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "scripts/train.py",
|
"program": "nerfstudio/scripts/train.py",
|
||||||
"console": "integratedTerminal",
|
"console": "integratedTerminal",
|
||||||
"args": [
|
"args": [
|
||||||
"instant_ngp",
|
"instant_ngp",
|
||||||
@@ -70,7 +70,7 @@
|
|||||||
"name": "Python: train ngp-friends",
|
"name": "Python: train ngp-friends",
|
||||||
"type": "python",
|
"type": "python",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "scripts/train.py",
|
"program": "nerfstudio/scripts/train.py",
|
||||||
"console": "integratedTerminal",
|
"console": "integratedTerminal",
|
||||||
"args": [
|
"args": [
|
||||||
"instant_ngp",
|
"instant_ngp",
|
||||||
@@ -89,7 +89,7 @@
|
|||||||
"name": "Python: train semantic_nerfw",
|
"name": "Python: train semantic_nerfw",
|
||||||
"type": "python",
|
"type": "python",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "scripts/train.py",
|
"program": "nerfstudio/scripts/train.py",
|
||||||
"console": "integratedTerminal",
|
"console": "integratedTerminal",
|
||||||
"args": ["semantic_nerf"]
|
"args": ["semantic_nerf"]
|
||||||
},
|
},
|
||||||
@@ -97,10 +97,10 @@
|
|||||||
"name": "Python: NeuS on Replica",
|
"name": "Python: NeuS on Replica",
|
||||||
"type": "python",
|
"type": "python",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "scripts/train.py",
|
"program": "nerfstudio/scripts/train.py",
|
||||||
"console": "integratedTerminal",
|
"console": "integratedTerminal",
|
||||||
"justMyCode": false,
|
"justMyCode": false,
|
||||||
"env": {"CUDA_VISIBLE_DEVICES":"0"},
|
"env": { "CUDA_VISIBLE_DEVICES": "0" },
|
||||||
"args": [
|
"args": [
|
||||||
"neus",
|
"neus",
|
||||||
"--pipeline.model.sdf-field.inside-outside=True",
|
"--pipeline.model.sdf-field.inside-outside=True",
|
||||||
@@ -116,10 +116,10 @@
|
|||||||
"name": "Python: NeuS-facto on Replica",
|
"name": "Python: NeuS-facto on Replica",
|
||||||
"type": "python",
|
"type": "python",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "scripts/train.py",
|
"program": "nerfstudio/scripts/train.py",
|
||||||
"console": "integratedTerminal",
|
"console": "integratedTerminal",
|
||||||
"justMyCode": false,
|
"justMyCode": false,
|
||||||
"env": {"CUDA_VISIBLE_DEVICES":"0"},
|
"env": { "CUDA_VISIBLE_DEVICES": "0" },
|
||||||
"args": [
|
"args": [
|
||||||
"neus-facto",
|
"neus-facto",
|
||||||
"--pipeline.model.sdf-field.inside-outside=True",
|
"--pipeline.model.sdf-field.inside-outside=True",
|
||||||
@@ -135,10 +135,10 @@
|
|||||||
"name": "Python: NeuS-facto on DTU (no mono-prior)",
|
"name": "Python: NeuS-facto on DTU (no mono-prior)",
|
||||||
"type": "python",
|
"type": "python",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"program": "scripts/train.py",
|
"program": "nerfstudio/scripts/train.py",
|
||||||
"console": "integratedTerminal",
|
"console": "integratedTerminal",
|
||||||
"justMyCode": false,
|
"justMyCode": false,
|
||||||
"env": {"CUDA_VISIBLE_DEVICES":"0"},
|
"env": { "CUDA_VISIBLE_DEVICES": "0" },
|
||||||
"args": [
|
"args": [
|
||||||
"neus-facto",
|
"neus-facto",
|
||||||
"--pipeline.model.sdf-field.inside-outside=False",
|
"--pipeline.model.sdf-field.inside-outside=False",
|
||||||
@@ -148,6 +148,6 @@
|
|||||||
"--include_mono_prior=False",
|
"--include_mono_prior=False",
|
||||||
"--auto-orient=True"
|
"--auto-orient=True"
|
||||||
]
|
]
|
||||||
},
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -87,7 +87,7 @@ You must have an NVIDIA video card with CUDA installed on the system. This libra
|
|||||||
|
|
||||||
### Create environment
|
### Create environment
|
||||||
|
|
||||||
Nerfstudio requires `python >= 3.7`. We recommend using conda to manage dependencies. Make sure to install [Conda](https://docs.conda.io/en/latest/miniconda.html) before proceeding.
|
Nerfstudio requires `python >= 3.8`. We recommend using conda to manage dependencies. Make sure to install [Conda](https://docs.conda.io/en/latest/miniconda.html) before proceeding.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
conda create --name nerfstudio -y python=3.8
|
conda create --name nerfstudio -y python=3.8
|
||||||
@@ -168,7 +168,13 @@ It is possible to load a pretrained model by running
|
|||||||
ns-train nerfacto --data data/nerfstudio/poster --load-dir {outputs/.../nerfstudio_models}
|
ns-train nerfacto --data data/nerfstudio/poster --load-dir {outputs/.../nerfstudio_models}
|
||||||
```
|
```
|
||||||
|
|
||||||
This will automatically start training. If you do not want it to train, add `--viewer.start-train False` to your training command.
|
## Visualize existing run
|
||||||
|
|
||||||
|
Given a pretrained model checkpoint, you can start the viewer by running
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ns-viewer --load-config {outputs/.../config.yml}
|
||||||
|
```
|
||||||
|
|
||||||
## 3. Exporting Results
|
## 3. Exporting Results
|
||||||
|
|
||||||
@@ -230,9 +236,9 @@ Each model contains many parameters that can be changed, too many to list here.
|
|||||||
ns-train nerfacto --help
|
ns-train nerfacto --help
|
||||||
```
|
```
|
||||||
|
|
||||||
### Tensorboard / WandB
|
### Tensorboard / WandB / Viewer
|
||||||
|
|
||||||
We support three different methods to track training progress, using the viewer, [tensorboard](https://www.tensorflow.org/tensorboard), and [Weights and Biases](https://wandb.ai/site). You can specify which visualizer to use by appending `--vis {viewer, tensorboard, wandb}` to the training command. Note that only one may be used at a time. Additionally the viewer only works for methods that are fast (ie. nerfacto, instant-ngp), for slower methods like NeRF, use the other loggers.
|
We support three different methods to track training progress, using the viewer, [tensorboard](https://www.tensorflow.org/tensorboard), and [Weights and Biases](https://wandb.ai/site). You can specify which visualizer to use by appending `--vis {viewer, tensorboard, wandb, viewer+wandb, viewer+tensorboard}` to the training command. Simultaneously utilizing the viewer alongside wandb or tensorboard may cause stuttering issues during evaluation steps. The viewer only works for methods that are fast (ie. nerfacto, instant-ngp), for slower methods like NeRF, use the other loggers.
|
||||||
|
|
||||||
# Learn More
|
# Learn More
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ To launch training jobs automatically on each of these items, you can call:
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
||||||
./scripts/benchmarking/launch_train_blender.sh -m {METHOD_NAME} [-s] [-v {VIS}] [{GPU_LIST}]
|
./nerfstudio/scripts/benchmarking/launch_train_blender.sh -m {METHOD_NAME} [-s] [-v {VIS}] [{GPU_LIST}]
|
||||||
```
|
```
|
||||||
|
|
||||||
Simply replace the arguments in brackets with the correct arguments.
|
Simply replace the arguments in brackets with the correct arguments.
|
||||||
@@ -18,31 +18,31 @@ Simply replace the arguments in brackets with the correct arguments.
|
|||||||
- `-s`: Launch a single job per GPU.
|
- `-s`: Launch a single job per GPU.
|
||||||
- `-v {VIS}`: Use another visualization than wandb, which is the default. Only other option is tensorboard.
|
- `-v {VIS}`: Use another visualization than wandb, which is the default. Only other option is tensorboard.
|
||||||
- `{GPU_LIST}`: (optional) Specify the list of gpus you want to use on your machine space separated. for instance, if you want to use GPU's 0-3, you will need to pass in `0 1 2 3`. If left empty, the script will automatically find available GPU's and distribute training jobs on the available GPUs.
|
- `{GPU_LIST}`: (optional) Specify the list of gpus you want to use on your machine space separated. for instance, if you want to use GPU's 0-3, you will need to pass in `0 1 2 3`. If left empty, the script will automatically find available GPU's and distribute training jobs on the available GPUs.
|
||||||
|
|
||||||
:::{admonition} Tip
|
:::{admonition} Tip
|
||||||
:class: info
|
:class: info
|
||||||
|
|
||||||
To view all the arguments and annotations, you can run `./scripts/benchmarking/launch_train_blender.sh --help`
|
To view all the arguments and annotations, you can run `./nerfstudio/scripts/benchmarking/launch_train_blender.sh --help`
|
||||||
:::
|
:::
|
||||||
|
|
||||||
|
|
||||||
A full example would be:
|
A full example would be:
|
||||||
|
|
||||||
- Specifying gpus
|
- Specifying gpus
|
||||||
```bash
|
|
||||||
./scripts/benchmarking/launch_train_blender.sh -m nerfacto 0 1 2 3
|
```bash
|
||||||
```
|
./nerfstudio/scripts/benchmarking/launch_train_blender.sh -m nerfacto 0 1 2 3
|
||||||
|
```
|
||||||
|
|
||||||
- Automatically find available gpus
|
- Automatically find available gpus
|
||||||
```bash
|
```bash
|
||||||
./scripts/benchmarking/launch_train_blender.sh -m nerfacto
|
./nerfstudio/scripts/benchmarking/launch_train_blender.sh -m nerfacto
|
||||||
```
|
```
|
||||||
|
|
||||||
The script will automatically launch training on all of the items and save the checkpoints in an output directory with the experiment name and current timestamp.
|
The script will automatically launch training on all of the items and save the checkpoints in an output directory with the experiment name and current timestamp.
|
||||||
|
|
||||||
## Evaluating trained Blender models
|
## Evaluating trained Blender models
|
||||||
|
|
||||||
Once you have launched training, and training converges, you can test your method with `scripts/benchmarking/launch_eval_blender.sh`.
|
Once you have launched training, and training converges, you can test your method with `nerfstudio/scripts/benchmarking/launch_eval_blender.sh`.
|
||||||
|
|
||||||
Say we ran a benchmark on 08-10-2022 for `instant-ngp`. By default, the train script will save the benchmarks in the following format:
|
Say we ran a benchmark on 08-10-2022 for `instant-ngp`. By default, the train script will save the benchmarks in the following format:
|
||||||
|
|
||||||
@@ -65,7 +65,7 @@ If we wanted to run the benchmark on all the blender data for the above example,
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
||||||
./scripts/benchmarking/launch_eval_blender.sh -m instant-ngp -o outputs/ -t 2022-08-10_172517 [{GPU_LIST}]
|
./nerfstudio/scripts/benchmarking/launch_eval_blender.sh -m instant-ngp -o outputs/ -t 2022-08-10_172517 [{GPU_LIST}]
|
||||||
```
|
```
|
||||||
|
|
||||||
The flags used in the benchmarking script are defined as follows:
|
The flags used in the benchmarking script are defined as follows:
|
||||||
@@ -90,4 +90,4 @@ outputs
|
|||||||
:class: warning
|
:class: warning
|
||||||
|
|
||||||
Since we are running multiple backgrounded processes concurrently with this script, please note the terminal logs may be messy.
|
Since we are running multiple backgrounded processes concurrently with this script, please note the terminal logs may be messy.
|
||||||
:::
|
:::
|
||||||
@@ -70,6 +70,12 @@ finally run the following to register the method,
|
|||||||
pip install -e .
|
pip install -e .
|
||||||
```
|
```
|
||||||
|
|
||||||
|
When developing a new method you don't always want to install your code as a package.
|
||||||
|
Instead, you may use the `NERFSTUDIO_METHOD_CONFIGS` environment variable to temporarily register your custom method.
|
||||||
|
```
|
||||||
|
export NERFSTUDIO_METHOD_CONFIGS="my-method=my_method.my_config:MyMethod"
|
||||||
|
```
|
||||||
|
|
||||||
## Running custom method
|
## Running custom method
|
||||||
|
|
||||||
After registering your method you should be able to run the method with,
|
After registering your method you should be able to run the method with,
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ This Blender add-on allows for compositing with a Nerfstudio render as a backgro
|
|||||||
|
|
||||||
1. The add-on requires Blender 3.0 or newer, install Blender [here](https://www.blender.org/).
|
1. The add-on requires Blender 3.0 or newer, install Blender [here](https://www.blender.org/).
|
||||||
|
|
||||||
2. Download <a href="https://raw.githubusercontent.com/nerfstudio-project/nerfstudio/main/scripts/blender/nerfstudio_blender.py" download="nerfstudio_blender.py">Blender Add-on Script</a>
|
2. Download <a href="https://raw.githubusercontent.com/nerfstudio-project/nerfstudio/main/nerfstudio/scripts/blender/nerfstudio_blender.py" download="nerfstudio_blender.py">Blender Add-on Script</a>
|
||||||
|
|
||||||
3. Install and enable the add-on in Blender in `Edit → Preferences → Add-Ons`. The add-on will be visible in the Render Properties tab on the right panel.
|
3. Install and enable the add-on in Blender in `Edit → Preferences → Add-Ons`. The add-on will be visible in the Render Properties tab on the right panel.
|
||||||
<center>
|
<center>
|
||||||
@@ -136,34 +136,34 @@ You can composite NeRF objects into a scene with a NeRF background by rendering
|
|||||||
1. Import the background NeRF scene as a point cloud (or mesh, but point cloud is preferred for large scenes).
|
1. Import the background NeRF scene as a point cloud (or mesh, but point cloud is preferred for large scenes).
|
||||||
|
|
||||||
2. Export a cropped NeRF mesh of the NeRF object(s)
|
2. Export a cropped NeRF mesh of the NeRF object(s)
|
||||||
- Open the NeRF object from the Nerfstudio viewer and select "Crop Viewport" and accordingly adjust the Scale and Center values of the bounding box to crop the NeRF scene to around the bounds of the object of interest.
|
|
||||||
|
|
||||||
<center>
|
- Open the NeRF object from the Nerfstudio viewer and select "Crop Viewport" and accordingly adjust the Scale and Center values of the bounding box to crop the NeRF scene to around the bounds of the object of interest.
|
||||||
<img width="300" alt="image" src="https://user-images.githubusercontent.com/9502341/232264554-26357747-6f09-4084-9710-dabf60c61909.jpg">
|
|
||||||
</center>
|
|
||||||
|
|
||||||
- Copy over the scale and center values into the Export panel and export the NeRF object as a mesh (point cloud will also work but shadows can be rendered if the object is a mesh)
|
|
||||||
|
|
||||||
- Keep note of the scale and center values for the crop. This can be done by creating a new JSON camera path in the editor which will add a crop section towards the end of the file.
|
<center>
|
||||||
|
<img width="300" alt="image" src="https://user-images.githubusercontent.com/9502341/232264554-26357747-6f09-4084-9710-dabf60c61909.jpg">
|
||||||
|
</center>
|
||||||
|
|
||||||
<center>
|
- Copy over the scale and center values into the Export panel and export the NeRF object as a mesh (point cloud will also work but shadows can be rendered if the object is a mesh)
|
||||||
<img width="200" alt="image" src="https://user-images.githubusercontent.com/9502341/232264430-0b991e20-838f-4e06-9834-7d1d8c1d0042.png">
|
|
||||||
</center>
|
- Keep note of the scale and center values for the crop. This can be done by creating a new JSON camera path in the editor which will add a crop section towards the end of the file.
|
||||||
|
|
||||||
|
<center>
|
||||||
|
<img width="200" alt="image" src="https://user-images.githubusercontent.com/9502341/232264430-0b991e20-838f-4e06-9834-7d1d8c1d0042.png">
|
||||||
|
</center>
|
||||||
|
|
||||||
3. Import the NeRF object representation. Rescale and position the scene and NeRF object and background environment. You can also animate either of them.
|
3. Import the NeRF object representation. Rescale and position the scene and NeRF object and background environment. You can also animate either of them.
|
||||||
|
|
||||||
4. (Optional) To add shadows of the NeRF object(s)
|
4. (Optional) To add shadows of the NeRF object(s)
|
||||||
- Add a plane representing the ground of the environment. In object properties, select "Shadow Catcher" under Visibility. You may have to switch to the cycles renderer to see the shadow catcher option.
|
|
||||||
|
|
||||||
- In the object properties of the NeRF object, go to the Ray Visibility section and deselect the "Camera" option. This will hide the mesh in the Blender render, but keep its shadow.
|
- Add a plane representing the ground of the environment. In object properties, select "Shadow Catcher" under Visibility. You may have to switch to the cycles renderer to see the shadow catcher option.
|
||||||
|
|
||||||
|
|
||||||
<center>
|
- In the object properties of the NeRF object, go to the Ray Visibility section and deselect the "Camera" option. This will hide the mesh in the Blender render, but keep its shadow.
|
||||||
<img width="200" alt="image" src="https://user-images.githubusercontent.com/9502341/232265212-ca077af8-fb3a-491f-8d60-304cb9fae57e.png">
|
|
||||||
</center>
|
<center>
|
||||||
|
<img width="200" alt="image" src="https://user-images.githubusercontent.com/9502341/232265212-ca077af8-fb3a-491f-8d60-304cb9fae57e.png">
|
||||||
- Render the Blender animation with only the shadow of the object on the shadow catcher visible. Render with a transparent background by selecting "Transparent" under the Film Settings in the Render Properties.
|
</center>
|
||||||
|
|
||||||
|
- Render the Blender animation with only the shadow of the object on the shadow catcher visible. Render with a transparent background by selecting "Transparent" under the Film Settings in the Render Properties.
|
||||||
|
|
||||||
5. Go to the Nerfstudio Add-on in Render Properties and expand the "Nerfstudio Path Generator" tab in the panel. Use the object selector to select the NeRF environment representation. Then, select the file path for the output JSON camera path file. Click "Generate JSON file". The output JSON file is named `camera_path_blender.json`. It is recommended to rename this JSON file to keep track of the multiple camera paths that will be used to construct the full render.
|
5. Go to the Nerfstudio Add-on in Render Properties and expand the "Nerfstudio Path Generator" tab in the panel. Use the object selector to select the NeRF environment representation. Then, select the file path for the output JSON camera path file. Click "Generate JSON file". The output JSON file is named `camera_path_blender.json`. It is recommended to rename this JSON file to keep track of the multiple camera paths that will be used to construct the full render.
|
||||||
|
|
||||||
@@ -172,29 +172,32 @@ You can composite NeRF objects into a scene with a NeRF background by rendering
|
|||||||
7. Render the NeRF of the background environment using the generated camera path for the environment using the Nerfstudio in the command line or terminal.
|
7. Render the NeRF of the background environment using the generated camera path for the environment using the Nerfstudio in the command line or terminal.
|
||||||
|
|
||||||
8. Render the NeRF object
|
8. Render the NeRF object
|
||||||
- Open the recently generated blender Nerfstudio JSON camera path and add the crop parameters to the camera path. This section will be placed towards the end of the Blender Nerfstudio camera path after the `is_cycle` field. This can be done by copying over the crop section from the JSON camera path with the scene crop which was exported earlier. Alternatively, you can enter the crop values manually in this format.
|
|
||||||
<center>
|
|
||||||
<img width="200" alt="image" src="https://user-images.githubusercontent.com/9502341/232264689-d2e7747c-ce53-425b-810b-1b2954eceb62.png">
|
|
||||||
</center>
|
|
||||||
|
|
||||||
- Render the NeRF object using Nerfstudio and the edited camera path in the command line or terminal. This will be the RGB render.
|
- Open the recently generated blender Nerfstudio JSON camera path and add the crop parameters to the camera path. This section will be placed towards the end of the Blender Nerfstudio camera path after the `is_cycle` field. This can be done by copying over the crop section from the JSON camera path with the scene crop which was exported earlier. Alternatively, you can enter the crop values manually in this format.
|
||||||
|
<center>
|
||||||
|
<img width="200" alt="image" src="https://user-images.githubusercontent.com/9502341/232264689-d2e7747c-ce53-425b-810b-1b2954eceb62.png">
|
||||||
|
</center>
|
||||||
|
|
||||||
- Next, render the accumulation render as an alpha mask of the NeRF object by adding the command line argument `--rendered-output-names accumulation` to the render command.
|
- Render the NeRF object using Nerfstudio and the edited camera path in the command line or terminal. This will be the RGB render.
|
||||||
|
|
||||||
<center>
|
- Next, render the accumulation render as an alpha mask of the NeRF object by adding the command line argument `--rendered-output-names accumulation` to the render command.
|
||||||
<img width="450" alt="image" src="https://user-images.githubusercontent.com/9502341/232264813-195c970f-b194-4761-843b-983123f128f7.jpg">
|
|
||||||
</center>
|
<center>
|
||||||
|
<img width="450" alt="image" src="https://user-images.githubusercontent.com/9502341/232264813-195c970f-b194-4761-843b-983123f128f7.jpg">
|
||||||
|
</center>
|
||||||
|
|
||||||
9. Convert each of the Nerfstudio render videos into an image sequence of frames as PNG or JPG files. This will ensure that the frames will be aligned when compositing. You can convert the video mp4 to an image sequence by creating a Blender Video Editing file and rendering the mp4 as JPGs or PNGs.
|
9. Convert each of the Nerfstudio render videos into an image sequence of frames as PNG or JPG files. This will ensure that the frames will be aligned when compositing. You can convert the video mp4 to an image sequence by creating a Blender Video Editing file and rendering the mp4 as JPGs or PNGs.
|
||||||
|
|
||||||
10. Composite the NeRF renders in a video editing software such as Adobe Premiere Pro.
|
10. Composite the NeRF renders in a video editing software such as Adobe Premiere Pro.
|
||||||
|
|
||||||
- Place the render of the Nerfstudio background environment at the lowest layer, then place the shadow render of the NeRF object if created.
|
- Place the render of the Nerfstudio background environment at the lowest layer, then place the shadow render of the NeRF object if created.
|
||||||
|
|
||||||
- Place the RGB NeRF render of the NeRF object over the environment (and shadow if present) layers and then place the accumulation NeRF object render over the RGB NeRF object render.
|
- Place the RGB NeRF render of the NeRF object over the environment (and shadow if present) layers and then place the accumulation NeRF object render over the RGB NeRF object render.
|
||||||
|
|
||||||
- Apply a filter to use the accumulation render as an alpha mask. In Premiere Pro, apply the effect "Track Matte Key" to the RGB render and select the "Matte" as the video track of the accumulation render and under "Composite Using" select "Matte Luma".
|
- Apply a filter to use the accumulation render as an alpha mask. In Premiere Pro, apply the effect "Track Matte Key" to the RGB render and select the "Matte" as the video track of the accumulation render and under "Composite Using" select "Matte Luma".
|
||||||
|
|
||||||
### Additional Details
|
### Additional Details
|
||||||
|
|
||||||
- The RGB and accumulation renders will need to be rendered for each NeRF cropped object in the scene, but not for the NeRF environment if it is not cropped.
|
- The RGB and accumulation renders will need to be rendered for each NeRF cropped object in the scene, but not for the NeRF environment if it is not cropped.
|
||||||
- If you will composite a shadow layer, the quality of the exported mesh of the NeRF object should have enough fidelity to cast a shadow, but the texture doesn't need to be clear.
|
- If you will composite a shadow layer, the quality of the exported mesh of the NeRF object should have enough fidelity to cast a shadow, but the texture doesn't need to be clear.
|
||||||
- If motion tracking or compositing over real camera footage, you can add planes or cubes to represent walls or doorways as shadow catcher or holdout objects. This will composite the shadow layer over the NeRF environment and help create alpha masks.
|
- If motion tracking or compositing over real camera footage, you can add planes or cubes to represent walls or doorways as shadow catcher or holdout objects. This will composite the shadow layer over the NeRF environment and help create alpha masks.
|
||||||
@@ -202,6 +205,7 @@ You can composite NeRF objects into a scene with a NeRF background by rendering
|
|||||||
- A walkthrough of this section is included in the tutorial video.
|
- A walkthrough of this section is included in the tutorial video.
|
||||||
|
|
||||||
### Examples
|
### Examples
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img width="300" alt="image" src="https://user-images.githubusercontent.com/9502341/232274012-27fb912c-3d3e-47b2-bb6b-68abf8f0692a.gif">
|
<img width="300" alt="image" src="https://user-images.githubusercontent.com/9502341/232274012-27fb912c-3d3e-47b2-bb6b-68abf8f0692a.gif">
|
||||||
<img width="225" alt="image" src="https://user-images.githubusercontent.com/9502341/232274049-d03e9768-8905-4668-b41b-d8ad4f122829.gif">
|
<img width="225" alt="image" src="https://user-images.githubusercontent.com/9502341/232274049-d03e9768-8905-4668-b41b-d8ad4f122829.gif">
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ The following methods are supported in nerfstudio:
|
|||||||
Instruct-NeRF2NeRF<in2n.md>
|
Instruct-NeRF2NeRF<in2n.md>
|
||||||
LERF<lerf.md>
|
LERF<lerf.md>
|
||||||
Semantic NeRF-W<semantic_nerfw.md>
|
Semantic NeRF-W<semantic_nerfw.md>
|
||||||
|
Tetra-NeRF <tetranerf.md>
|
||||||
```
|
```
|
||||||
|
|
||||||
(own_method_docs)=
|
(own_method_docs)=
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Tetra-NeRF
|
||||||
|
|
||||||
|
<h4>Tetra-NeRF: Representing Neural Radiance Fields Using Tetrahedra</h4>
|
||||||
|
|
||||||
|
```{button-link} https://jkulhanek.com/tetra-nerf
|
||||||
|
:color: primary
|
||||||
|
:outline:
|
||||||
|
Paper Website
|
||||||
|
```
|
||||||
|
|
||||||
|
```{button-link} https://github.com/jkulhanek/tetra-nerf
|
||||||
|
:color: primary
|
||||||
|
:outline:
|
||||||
|
Code
|
||||||
|
```
|
||||||
|
|
||||||
|
<video id="teaser" muted autoplay playsinline loop controls width="100%">
|
||||||
|
<source id="mp4" src="https://jkulhanek.com/tetra-nerf/resources/intro-video.mp4" type="video/mp4">
|
||||||
|
</video>
|
||||||
|
|
||||||
|
**SfM input pointcloud is triangulated and resulting tetrahedra is used as the radiance field representation**
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
First, make sure to install the following:
|
||||||
|
```
|
||||||
|
CUDA (>=11.3)
|
||||||
|
PyTorch (>=1.12.1)
|
||||||
|
Nerfstudio (>=0.2.0)
|
||||||
|
OptiX (>=7.2, preferably 7.6)
|
||||||
|
CGAL
|
||||||
|
CMake (>=3.22.1)
|
||||||
|
```
|
||||||
|
Follow the [installation section](https://github.com/jkulhanek/tetra-nerf/blob/master/README.md#installation) in the tetra-nerf repository
|
||||||
|
|
||||||
|
Finally, you can install **Tetra-NeRF** by running:
|
||||||
|
```bash
|
||||||
|
pip install git+https://github.com/jkulhanek/tetra-nerf
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running Tetra-NeRF on custom data
|
||||||
|
Details for running Tetra-NeRF can be found [here](https://github.com/jkulhanek/tetra-nerf).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m tetranerf.scripts.process_images --path <data folder>
|
||||||
|
python -m tetranerf.scripts.triangulate --pointcloud <data folder>/sparse.ply --output <data folder>/sparse.th
|
||||||
|
ns-train tetra-nerf --pipeline.model.tetrahedra-path <data folder>/sparse.th minimal-parser --data <data folder>
|
||||||
|
```
|
||||||
|
|
||||||
|
Three following variants of Tetra-NeRF are provided:
|
||||||
|
|
||||||
|
| Method | Description | Memory | Quality |
|
||||||
|
| --------------------- | -------------------------------------- | ------- | ------- |
|
||||||
|
| `tetra-nerf-original` | Official implementation from the paper | ~18GB* | Good |
|
||||||
|
| `tetra-nerf` | Different sampler - faster and better | ~16GB* | Best |
|
||||||
|
|
||||||
|
*Depends on the size of the input pointcloud, estimate is given for a larger scene (1M points)
|
||||||
|
|
||||||
|
## Method
|
||||||
|
<br>
|
||||||
|
The input to Tetra-NeRF is a point cloud which is triangulated to get a set of tetrahedra used to represent the radiance field. Rays are sampled, and the field is queried. The barycentric interpolation is used to interpolate tetrahedra vertices, and the resulting features are passed to a shallow MLP to get the density and colours for volumetric rendering.<br>
|
||||||
|
|
||||||
|
[](https://jkulhanek.com/tetra-nerf/demo.html?scene=blender-lego-sparse)
|
||||||
|
[](https://jkulhanek.com/tetra-nerf/demo.html?scene=360-garden-sparse)
|
||||||
|
[](https://jkulhanek.com/tetra-nerf/demo.html?scene=360-bonsai-sparse)
|
||||||
|
[](https://jkulhanek.com/tetra-nerf/demo.html?scene=360-kitchen-dense)
|
||||||
|
|
||||||
|
|
||||||
|
## Existing checkpoints and predictions
|
||||||
|
For an easier comparisons with Tetra-NeRF, published checkpoints and predictions can be used:
|
||||||
|
|
||||||
|
| Dataset | Checkpoints | Predictions | Input tetrahedra |
|
||||||
|
| -------- | ----------- | ----------- | ---------------- |
|
||||||
|
| Mip-NeRF 360 (public scenes) | [download](https://data.ciirc.cvut.cz/public/projects/2023TetraNeRF/assets/mipnerf360-public-checkpoints.tar.gz) | [download](https://data.ciirc.cvut.cz/public/projects/2023TetraNeRF/assets/mipnerf360-public-predictions.tar.gz) | [download](https://data.ciirc.cvut.cz/public/projects/2023TetraNeRF/assets/mipnerf360-public-tetrahedra.tar.gz) |
|
||||||
|
| Blender | [download](https://data.ciirc.cvut.cz/public/projects/2023TetraNeRF/assets/blender-checkpoints.tar.gz) | [download](https://data.ciirc.cvut.cz/public/projects/2023TetraNeRF/assets/blender-predictions.tar.gz) | [download](https://data.ciirc.cvut.cz/public/projects/2023TetraNeRF/assets/blender-tetrahedra.tar.gz) |
|
||||||
|
| Tanks and Temples | [download](https://data.ciirc.cvut.cz/public/projects/2023TetraNeRF/assets/nsvf-tanks-and-temples-checkpoints.tar.gz) | [download](https://data.ciirc.cvut.cz/public/projects/2023TetraNeRF/assets/nsvf-tanks-and-temples-predictions.tar.gz) | [download](https://data.ciirc.cvut.cz/public/projects/2023TetraNeRF/assets/nsvf-tanks-and-temples-tetrahedra.tar.gz) |
|
||||||
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -259,6 +259,8 @@ ns-train nerfacto --data {output directory}
|
|||||||
|
|
||||||
## Metashape
|
## Metashape
|
||||||
|
|
||||||
|
All images must use the same sensor type (but multiple sensors are supported).
|
||||||
|
|
||||||
1. Align your images using Metashape. `File -> Workflow -> Align Photos...`
|
1. Align your images using Metashape. `File -> Workflow -> Align Photos...`
|
||||||
|
|
||||||
```{image} https://user-images.githubusercontent.com/3310961/203389662-12760210-2b52-49d4-ab21-4f23bfa4a2b3.png
|
```{image} https://user-images.githubusercontent.com/3310961/203389662-12760210-2b52-49d4-ab21-4f23bfa4a2b3.png
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ Poisson surface reconstruction gives the highest quality meshes. See the steps b
|
|||||||
> **Note:**
|
> **Note:**
|
||||||
> This will only work with a Model that computes or predicts normals, e.g., nerfacto.
|
> This will only work with a Model that computes or predicts normals, e.g., nerfacto.
|
||||||
|
|
||||||
|
|
||||||
1. Train nerfacto with network settings that predict normals.
|
1. Train nerfacto with network settings that predict normals.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -51,7 +50,7 @@ ns-export --help
|
|||||||
Say you want to simplify and/or smooth a mesh offline, and then you want to texture it with NeRF. You can do that with the following command. It will work for any mesh filetypes that [PyMeshLab](https://pymeshlab.readthedocs.io/en/latest/) can support, for example a `.ply`.
|
Say you want to simplify and/or smooth a mesh offline, and then you want to texture it with NeRF. You can do that with the following command. It will work for any mesh filetypes that [PyMeshLab](https://pymeshlab.readthedocs.io/en/latest/) can support, for example a `.ply`.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
python scripts/texture.py --load-config CONFIG.yml --input-mesh-filename FILENAME --output-dir OUTPUT_DIR
|
python nerfstudio/scripts/texture.py --load-config CONFIG.yml --input-mesh-filename FILENAME --output-dir OUTPUT_DIR
|
||||||
```
|
```
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
|
|||||||
@@ -38,8 +38,6 @@ It is possible to load a pretrained model by running
|
|||||||
ns-train nerfacto --data data/nerfstudio/poster --load-dir {outputs/.../nerfstudio_models}
|
ns-train nerfacto --data data/nerfstudio/poster --load-dir {outputs/.../nerfstudio_models}
|
||||||
```
|
```
|
||||||
|
|
||||||
This will automatically start training. If you do not want it to train, add `--viewer.start-train False` to your training command.
|
|
||||||
|
|
||||||
## Visualize existing run
|
## Visualize existing run
|
||||||
|
|
||||||
Given a pretrained model checkpoint, you can start the viewer by running
|
Given a pretrained model checkpoint, you can start the viewer by running
|
||||||
@@ -98,9 +96,9 @@ ns-train nerfacto <nerfacto optional args> nerfstudio-data --help
|
|||||||
|
|
||||||
Each script will have some other minor quirks (like the training script dataparser subcommand needing to come after the model subcommand), read up on them [here](../reference/cli/index.md).
|
Each script will have some other minor quirks (like the training script dataparser subcommand needing to come after the model subcommand), read up on them [here](../reference/cli/index.md).
|
||||||
|
|
||||||
## Tensorboard / WandB
|
## Tensorboard / WandB / Viewer
|
||||||
|
|
||||||
We support three different methods to track training progress, using the viewer, [tensorboard](https://www.tensorflow.org/tensorboard), and [Weights and Biases](https://wandb.ai/site). You can specify which visualizer to use by appending `--vis {viewer, tensorboard, wandb}` to the training command. Note that only one may be used at a time. Additionally the viewer only works for methods that are fast (ie. nerfacto, instant-ngp), for slower methods like NeRF, use the other loggers.
|
We support three different methods to track training progress, using the viewer, [tensorboard](https://www.tensorflow.org/tensorboard), and [Weights and Biases](https://wandb.ai/site). You can specify which visualizer to use by appending `--vis {viewer, tensorboard, wandb, viewer+wandb, viewer+tensorboard}` to the training command. Simultaneously utilizing the viewer alongside wandb or tensorboard may cause stuttering issues during evaluation steps. The viewer only works for methods that are fast (ie. nerfacto, instant-ngp), for slower methods like NeRF, use the other loggers.
|
||||||
|
|
||||||
## Evaluating Runs
|
## Evaluating Runs
|
||||||
|
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ Install CUDA 11.7. You can find CUDA download links [here](https://developer.nvi
|
|||||||
|
|
||||||
## Create environment
|
## Create environment
|
||||||
|
|
||||||
Nerfstudio requires `python >= 3.7`. We recommend using conda to manage dependencies. Make sure to install [Conda](https://docs.conda.io/en/latest/miniconda.html) before proceeding.
|
Nerfstudio requires `python >= 3.8`. We recommend using conda to manage dependencies. Make sure to install [Conda](https://docs.conda.io/en/latest/miniconda.html) before proceeding.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
conda create --name nerfstudio -y python=3.8
|
conda create --name nerfstudio -y python=3.8
|
||||||
|
|||||||
@@ -7,25 +7,4 @@ Base
|
|||||||
----------------
|
----------------
|
||||||
|
|
||||||
.. automodule:: nerfstudio.data.datamanagers.base_datamanager
|
.. automodule:: nerfstudio.data.datamanagers.base_datamanager
|
||||||
:members:
|
:members:
|
||||||
|
|
||||||
Depth Datamanager
|
|
||||||
-----------------
|
|
||||||
|
|
||||||
.. automodule:: nerfstudio.data.datamanagers.depth_datamanager
|
|
||||||
:members:
|
|
||||||
:show-inheritance:
|
|
||||||
|
|
||||||
SDF Datamanager
|
|
||||||
----------------
|
|
||||||
|
|
||||||
.. automodule:: nerfstudio.data.datamanagers.sdf_datamanager
|
|
||||||
:members:
|
|
||||||
:show-inheritance:
|
|
||||||
|
|
||||||
Semantic Datamanager
|
|
||||||
---------------------
|
|
||||||
|
|
||||||
.. automodule:: nerfstudio.data.datamanagers.semantic_datamanager
|
|
||||||
:members:
|
|
||||||
:show-inheritance:
|
|
||||||
+10
-10
@@ -6,16 +6,16 @@ We provide a command line interface for training your own NeRFs (no coding neces
|
|||||||
|
|
||||||
Here are the popular commands that we offer. If you've cloned the repo, you can also look at the [pyproject.toml file](https://github.com/nerfstudio-project/nerfstudio/blob/main/pyproject.toml) at the `[project.scripts]` section for details.
|
Here are the popular commands that we offer. If you've cloned the repo, you can also look at the [pyproject.toml file](https://github.com/nerfstudio-project/nerfstudio/blob/main/pyproject.toml) at the `[project.scripts]` section for details.
|
||||||
|
|
||||||
| Command | Description | Filename |
|
| Command | Description | Filename |
|
||||||
| ------------------------------------ | -------------------------------------- | ---------------------------------- |
|
| ------------------------------------ | -------------------------------------- | --------------------------------------------- |
|
||||||
| [ns-install-cli](ns_install_cli) | Install tab completion for all scripts | scripts/completions/install.py |
|
| [ns-install-cli](ns_install_cli) | Install tab completion for all scripts | nerfstudio/scripts/completions/install.py |
|
||||||
| [ns-process-data](ns_process_data) | Generate a dataset from your own data | scripts/process_data.py |
|
| [ns-process-data](ns_process_data) | Generate a dataset from your own data | nerfstudio/scripts/process_data.py |
|
||||||
| [ns-download-data](ns_download_data) | Download existing captures | scripts/downloads/download_data.py |
|
| [ns-download-data](ns_download_data) | Download existing captures | nerfstudio/scripts/downloads/download_data.py |
|
||||||
| [ns-train](ns_train) | Generate a NeRF | scripts/train.py |
|
| [ns-train](ns_train) | Generate a NeRF | nerfstudio/scripts/train.py |
|
||||||
| [ns-viewer](ns_viewer) | View a trained NeRF | scripts/viewer/run_viewer.py |
|
| [ns-viewer](ns_viewer) | View a trained NeRF | nerfstudio/scripts/viewer/run_viewer.py |
|
||||||
| [ns-eval](ns_eval) | Run evaluation metrics for your Model | scripts/eval.py |
|
| [ns-eval](ns_eval) | Run evaluation metrics for your Model | nerfstudio/scripts/eval.py |
|
||||||
| [ns-render](ns_render) | Render out a video of your NeRF | scripts/render.py |
|
| [ns-render](ns_render) | Render out a video of your NeRF | nerfstudio/scripts/render.py |
|
||||||
| [ns-export](ns_export) | Export a NeRF into other formats | scripts/exporter.py |
|
| [ns-export](ns_export) | Export a NeRF into other formats | nerfstudio/scripts/exporter.py |
|
||||||
|
|
||||||
```{toctree}
|
```{toctree}
|
||||||
:maxdepth: 1
|
:maxdepth: 1
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
```{eval-rst}
|
```{eval-rst}
|
||||||
.. argparse::
|
.. argparse::
|
||||||
:module: scripts.downloads.download_data
|
:module: nerfstudio.scripts.downloads.download_data
|
||||||
:func: get_parser_fn
|
:func: get_parser_fn
|
||||||
:prog: ns-download-data
|
:prog: ns-download-data
|
||||||
:nodefault:
|
:nodefault:
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
```{eval-rst}
|
```{eval-rst}
|
||||||
.. argparse::
|
.. argparse::
|
||||||
:module: scripts.eval
|
:module: nerfstudio.scripts.eval
|
||||||
:func: get_parser_fn
|
:func: get_parser_fn
|
||||||
:prog: ns-eval
|
:prog: ns-eval
|
||||||
:nodefault:
|
:nodefault:
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
```{eval-rst}
|
```{eval-rst}
|
||||||
.. argparse::
|
.. argparse::
|
||||||
:module: scripts.exporter
|
:module: nerfstudio.scripts.exporter
|
||||||
:func: get_parser_fn
|
:func: get_parser_fn
|
||||||
:prog: ns-export
|
:prog: ns-export
|
||||||
:nodefault:
|
:nodefault:
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
```{eval-rst}
|
```{eval-rst}
|
||||||
.. argparse::
|
.. argparse::
|
||||||
:module: scripts.completions.install
|
:module: nerfstudio.scripts.completions.install
|
||||||
:func: get_parser_fn
|
:func: get_parser_fn
|
||||||
:prog: ns-install-cli
|
:prog: ns-install-cli
|
||||||
:nodefault:
|
:nodefault:
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ You may also want to install [hloc](https://github.com/cvg/Hierarchical-Localiza
|
|||||||
|
|
||||||
```{eval-rst}
|
```{eval-rst}
|
||||||
.. argparse::
|
.. argparse::
|
||||||
:module: scripts.process_data
|
:module: nerfstudio.scripts.process_data
|
||||||
:func: get_parser_fn
|
:func: get_parser_fn
|
||||||
:prog: ns-process-data
|
:prog: ns-process-data
|
||||||
:nodefault:
|
:nodefault:
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ Make sure to have [FFmpeg](https://ffmpeg.org/download.html) installed.
|
|||||||
|
|
||||||
```{eval-rst}
|
```{eval-rst}
|
||||||
.. argparse::
|
.. argparse::
|
||||||
:module: scripts.render
|
:module: nerfstudio.scripts.render
|
||||||
:func: get_parser_fn
|
:func: get_parser_fn
|
||||||
:prog: ns-render
|
:prog: ns-render
|
||||||
:nodefault:
|
:nodefault:
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
```{eval-rst}
|
```{eval-rst}
|
||||||
.. argparse::
|
.. argparse::
|
||||||
:module: scripts.viewer.run_viewer
|
:module: nerfstudio.scripts.viewer.run_viewer
|
||||||
:func: get_parser_fn
|
:func: get_parser_fn
|
||||||
:prog: ns-viewer
|
:prog: ns-viewer
|
||||||
:nodefault:
|
:nodefault:
|
||||||
|
|||||||
@@ -7,13 +7,14 @@ Below, we document the contribution pipeline and good-to-knows for when you're r
|
|||||||
The project is set up for development in VSCode, we recommend using it if you plan to contribute.
|
The project is set up for development in VSCode, we recommend using it if you plan to contribute.
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Below are the various tooling features our team uses to maintain this codebase.
|
Below are the various tooling features our team uses to maintain this codebase.
|
||||||
|
|
||||||
| Tooling | Support |
|
| Tooling | Support |
|
||||||
| --------------- | ------------- |
|
| --------------- | ---------------------------------------------------------- |
|
||||||
| Linter | [Black](https://black.readthedocs.io/en/stable/) |
|
| Linter | [Black](https://black.readthedocs.io/en/stable/) |
|
||||||
| Testing | [PyTest](https://docs.pytest.org/en/7.1.x/) |
|
| Testing | [PyTest](https://docs.pytest.org/en/7.1.x/) |
|
||||||
| Docs | [Sphinx](https://www.sphinx-doc.org/en/master/) |
|
| Docs | [Sphinx](https://www.sphinx-doc.org/en/master/) |
|
||||||
| Docstring style | [Google](https://google.github.io/styleguide/pyguide.html) |
|
| Docstring style | [Google](https://google.github.io/styleguide/pyguide.html) |
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
@@ -53,8 +54,8 @@ conda install -c conda-forge pandoc
|
|||||||
|
|
||||||
:::{admonition} Attention
|
:::{admonition} Attention
|
||||||
:class: attention
|
:class: attention
|
||||||
In order to merge changes to the code base, all of these checks must be passing. If you pass these tests locally, you will likely pass on github servers as well (results in a green checkmark next to your commit).
|
In order to merge changes to the code base, all of these checks must be passing. If you pass these tests locally, you will likely pass on github servers as well (results in a green checkmark next to your commit).
|
||||||
:::
|
:::
|
||||||
|
|
||||||
3. Open pull request! 💌
|
3. Open pull request! 💌
|
||||||
|
|
||||||
@@ -65,7 +66,7 @@ conda install -c conda-forge pandoc
|
|||||||
Run the following to build the documentation:
|
Run the following to build the documentation:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python scripts/docs/build_docs.py
|
python nerfstudio/scripts/docs/build_docs.py
|
||||||
```
|
```
|
||||||
|
|
||||||
:::{admonition} Tip
|
:::{admonition} Tip
|
||||||
@@ -84,7 +85,7 @@ If you want the code to build on save you can use [sphinx autobuild](https://git
|
|||||||
:class: info
|
:class: info
|
||||||
|
|
||||||
If changes to the structure are made, the build files may be incorrect.
|
If changes to the structure are made, the build files may be incorrect.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install sphinx-autobuild
|
pip install sphinx-autobuild
|
||||||
|
|||||||
@@ -20,13 +20,13 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import functools
|
import functools
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Type, Union
|
from typing import Literal, Type, Union
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
import tyro
|
import tyro
|
||||||
from torch import nn
|
from torch import nn
|
||||||
from torchtyping import TensorType
|
from torchtyping import TensorType
|
||||||
from typing_extensions import Literal, assert_never
|
from typing_extensions import assert_never
|
||||||
|
|
||||||
from nerfstudio.cameras.lie_groups import exp_map_SE3, exp_map_SO3xR3
|
from nerfstudio.cameras.lie_groups import exp_map_SE3, exp_map_SO3xR3
|
||||||
from nerfstudio.configs.base_config import InstantiateConfig
|
from nerfstudio.configs.base_config import InstantiateConfig
|
||||||
|
|||||||
@@ -17,13 +17,12 @@ Camera transformation helper code.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import math
|
import math
|
||||||
from typing import List, Optional, Tuple
|
from typing import List, Literal, Optional, Tuple
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
from numpy.typing import ArrayLike
|
from numpy.typing import ArrayLike
|
||||||
from torchtyping import TensorType
|
from torchtyping import TensorType
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
_EPS = np.finfo(float).eps * 4.0
|
_EPS = np.finfo(float).eps * 4.0
|
||||||
|
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ Camera Models
|
|||||||
"""
|
"""
|
||||||
import base64
|
import base64
|
||||||
import math
|
import math
|
||||||
import os
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from enum import Enum, auto
|
from enum import Enum, auto
|
||||||
from typing import Dict, List, Optional, Tuple, Union
|
from typing import Dict, List, Optional, Tuple, Union
|
||||||
@@ -33,7 +32,6 @@ import nerfstudio.utils.poses as pose_utils
|
|||||||
from nerfstudio.cameras import camera_utils
|
from nerfstudio.cameras import camera_utils
|
||||||
from nerfstudio.cameras.rays import RayBundle
|
from nerfstudio.cameras.rays import RayBundle
|
||||||
from nerfstudio.data.scene_box import SceneBox
|
from nerfstudio.data.scene_box import SceneBox
|
||||||
from nerfstudio.utils.misc import strtobool
|
|
||||||
from nerfstudio.utils.tensor_dataclass import TensorDataclass
|
from nerfstudio.utils.tensor_dataclass import TensorDataclass
|
||||||
|
|
||||||
TORCH_DEVICE = Union[torch.device, str] # pylint: disable=invalid-name
|
TORCH_DEVICE = Union[torch.device, str] # pylint: disable=invalid-name
|
||||||
@@ -150,8 +148,6 @@ class Cameras(TensorDataclass):
|
|||||||
|
|
||||||
self.__post_init__() # This will do the dataclass post_init and broadcast all the tensors
|
self.__post_init__() # This will do the dataclass post_init and broadcast all the tensors
|
||||||
|
|
||||||
self._use_nerfacc = strtobool(os.environ.get("INTERSECT_WITH_NERFACC", "TRUE"))
|
|
||||||
|
|
||||||
def _init_get_fc_xy(self, fc_xy: Union[float, torch.Tensor], name: str) -> torch.Tensor:
|
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
|
Parses the input focal length / principle point x or y and returns a tensor of the correct shape
|
||||||
|
|||||||
@@ -21,9 +21,7 @@ from __future__ import annotations
|
|||||||
import warnings
|
import warnings
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, List, Optional, Tuple, Type
|
from typing import Any, List, Literal, Optional, Tuple, Type
|
||||||
|
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
# model instances
|
# model instances
|
||||||
from nerfstudio.utils import writer
|
from nerfstudio.utils import writer
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ from rich.console import Console
|
|||||||
CONSOLE = Console()
|
CONSOLE = Console()
|
||||||
# pylint: disable=import-outside-toplevel
|
# pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
|
||||||
# cannot use mutable types directly within dataclass; abstracting default factory calls
|
# cannot use mutable types directly within dataclass; abstracting default factory calls
|
||||||
def to_immutable_dict(d: Dict[str, Any]):
|
def to_immutable_dict(d: Dict[str, Any]):
|
||||||
"""Method to convert mutable dict to default factory dict
|
"""Method to convert mutable dict to default factory dict
|
||||||
|
|||||||
@@ -19,11 +19,10 @@ from __future__ import annotations
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, Literal, Optional
|
||||||
|
|
||||||
import yaml
|
import yaml
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.configs.base_config import (
|
from nerfstudio.configs.base_config import (
|
||||||
InstantiateConfig,
|
InstantiateConfig,
|
||||||
@@ -50,6 +49,8 @@ class ExperimentConfig(InstantiateConfig):
|
|||||||
"""Method name. Required to set in python or via cli"""
|
"""Method name. Required to set in python or via cli"""
|
||||||
experiment_name: Optional[str] = None
|
experiment_name: Optional[str] = None
|
||||||
"""Experiment name. If None, will automatically be set to dataset name"""
|
"""Experiment name. If None, will automatically be set to dataset name"""
|
||||||
|
project_name: Optional[str] = "nerfstudio-project"
|
||||||
|
"""Project name."""
|
||||||
timestamp: str = "{timestamp}"
|
timestamp: str = "{timestamp}"
|
||||||
"""Experiment timestamp."""
|
"""Experiment timestamp."""
|
||||||
machine: MachineConfig = MachineConfig()
|
machine: MachineConfig = MachineConfig()
|
||||||
|
|||||||
@@ -24,14 +24,11 @@ import tyro
|
|||||||
|
|
||||||
from nerfstudio.cameras.camera_optimizers import CameraOptimizerConfig
|
from nerfstudio.cameras.camera_optimizers import CameraOptimizerConfig
|
||||||
from nerfstudio.configs.base_config import ViewerConfig
|
from nerfstudio.configs.base_config import ViewerConfig
|
||||||
from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManagerConfig
|
from nerfstudio.data.datamanagers.base_datamanager import (
|
||||||
from nerfstudio.data.datamanagers.depth_datamanager import DepthDataManagerConfig
|
VanillaDataManager,
|
||||||
from nerfstudio.data.datamanagers.dreamfusion_datamanager import (
|
VanillaDataManagerConfig,
|
||||||
DreamFusionDataManagerConfig,
|
|
||||||
)
|
)
|
||||||
from nerfstudio.data.datamanagers.sdf_datamanager import SDFDataManagerConfig
|
from nerfstudio.data.datamanagers.dreamfusion_datamanager import DreamFusionDataManagerConfig
|
||||||
from nerfstudio.data.datamanagers.semantic_datamanager import SemanticDataManagerConfig
|
|
||||||
from nerfstudio.data.datamanagers.iterative_datamanager import IterativeDataManagerConfig
|
|
||||||
from nerfstudio.data.dataparsers.blender_dataparser import BlenderDataParserConfig
|
from nerfstudio.data.dataparsers.blender_dataparser import BlenderDataParserConfig
|
||||||
from nerfstudio.data.dataparsers.dnerf_dataparser import DNeRFDataParserConfig
|
from nerfstudio.data.dataparsers.dnerf_dataparser import DNeRFDataParserConfig
|
||||||
from nerfstudio.data.dataparsers.dycheck_dataparser import DycheckDataParserConfig
|
from nerfstudio.data.dataparsers.dycheck_dataparser import DycheckDataParserConfig
|
||||||
@@ -44,6 +41,9 @@ from nerfstudio.data.dataparsers.phototourism_dataparser import (
|
|||||||
)
|
)
|
||||||
from nerfstudio.data.dataparsers.sdfstudio_dataparser import SDFStudioDataParserConfig
|
from nerfstudio.data.dataparsers.sdfstudio_dataparser import SDFStudioDataParserConfig
|
||||||
from nerfstudio.data.dataparsers.sitcoms3d_dataparser import Sitcoms3DDataParserConfig
|
from nerfstudio.data.dataparsers.sitcoms3d_dataparser import Sitcoms3DDataParserConfig
|
||||||
|
from nerfstudio.data.datasets.depth_dataset import DepthDataset
|
||||||
|
from nerfstudio.data.datasets.sdf_dataset import SDFDataset
|
||||||
|
from nerfstudio.data.datasets.semantic_dataset import SemanticDataset
|
||||||
from nerfstudio.engine.optimizers import AdamOptimizerConfig, RAdamOptimizerConfig
|
from nerfstudio.engine.optimizers import AdamOptimizerConfig, RAdamOptimizerConfig
|
||||||
from nerfstudio.engine.schedulers import (
|
from nerfstudio.engine.schedulers import (
|
||||||
CosineDecaySchedulerConfig,
|
CosineDecaySchedulerConfig,
|
||||||
@@ -91,7 +91,8 @@ descriptions = {
|
|||||||
"dreamfusion": "Generative Text to NeRF model",
|
"dreamfusion": "Generative Text to NeRF model",
|
||||||
"nerfplayer-nerfacto": "NeRFPlayer with nerfacto backbone.",
|
"nerfplayer-nerfacto": "NeRFPlayer with nerfacto backbone.",
|
||||||
"nerfplayer-ngp": "NeRFPlayer with InstantNGP backbone.",
|
"nerfplayer-ngp": "NeRFPlayer with InstantNGP backbone.",
|
||||||
"neus": "Implementation of NeuS. (slow)"
|
"neus": "Implementation of NeuS. (slow)",
|
||||||
|
"neus-facto": "Implementation of NeuS-Facto. (slow)",
|
||||||
}
|
}
|
||||||
|
|
||||||
method_configs["nerfacto"] = TrainerConfig(
|
method_configs["nerfacto"] = TrainerConfig(
|
||||||
@@ -174,7 +175,8 @@ method_configs["depth-nerfacto"] = TrainerConfig(
|
|||||||
max_num_iterations=30000,
|
max_num_iterations=30000,
|
||||||
mixed_precision=True,
|
mixed_precision=True,
|
||||||
pipeline=VanillaPipelineConfig(
|
pipeline=VanillaPipelineConfig(
|
||||||
datamanager=DepthDataManagerConfig(
|
datamanager=VanillaDataManagerConfig(
|
||||||
|
_target=VanillaDataManager[DepthDataset],
|
||||||
dataparser=NerfstudioDataParserConfig(),
|
dataparser=NerfstudioDataParserConfig(),
|
||||||
train_num_rays_per_batch=4096,
|
train_num_rays_per_batch=4096,
|
||||||
eval_num_rays_per_batch=4096,
|
eval_num_rays_per_batch=4096,
|
||||||
@@ -320,8 +322,11 @@ method_configs["semantic-nerfw"] = TrainerConfig(
|
|||||||
max_num_iterations=30000,
|
max_num_iterations=30000,
|
||||||
mixed_precision=True,
|
mixed_precision=True,
|
||||||
pipeline=VanillaPipelineConfig(
|
pipeline=VanillaPipelineConfig(
|
||||||
datamanager=SemanticDataManagerConfig(
|
datamanager=VanillaDataManagerConfig(
|
||||||
dataparser=Sitcoms3DDataParserConfig(), train_num_rays_per_batch=4096, eval_num_rays_per_batch=8192
|
_target=VanillaDataManager[SemanticDataset],
|
||||||
|
dataparser=Sitcoms3DDataParserConfig(),
|
||||||
|
train_num_rays_per_batch=4096,
|
||||||
|
eval_num_rays_per_batch=8192,
|
||||||
),
|
),
|
||||||
model=SemanticNerfWModelConfig(eval_num_rays_per_chunk=1 << 16),
|
model=SemanticNerfWModelConfig(eval_num_rays_per_chunk=1 << 16),
|
||||||
),
|
),
|
||||||
@@ -371,7 +376,9 @@ method_configs["tensorf"] = TrainerConfig(
|
|||||||
train_num_rays_per_batch=4096,
|
train_num_rays_per_batch=4096,
|
||||||
eval_num_rays_per_batch=4096,
|
eval_num_rays_per_batch=4096,
|
||||||
),
|
),
|
||||||
model=TensoRFModelConfig(),
|
model=TensoRFModelConfig(
|
||||||
|
regularization="tv",
|
||||||
|
),
|
||||||
),
|
),
|
||||||
optimizers={
|
optimizers={
|
||||||
"fields": {
|
"fields": {
|
||||||
@@ -710,7 +717,8 @@ method_configs["dreamembed"] = TrainerConfig(
|
|||||||
method_configs["nerfplayer-nerfacto"] = TrainerConfig(
|
method_configs["nerfplayer-nerfacto"] = TrainerConfig(
|
||||||
method_name="nerfplayer-nerfacto",
|
method_name="nerfplayer-nerfacto",
|
||||||
pipeline=VanillaPipelineConfig(
|
pipeline=VanillaPipelineConfig(
|
||||||
datamanager=DepthDataManagerConfig(
|
datamanager=VanillaDataManagerConfig(
|
||||||
|
_target=VanillaDataManager[DepthDataset],
|
||||||
dataparser=DycheckDataParserConfig(),
|
dataparser=DycheckDataParserConfig(),
|
||||||
train_num_rays_per_batch=4096,
|
train_num_rays_per_batch=4096,
|
||||||
eval_num_rays_per_batch=4096,
|
eval_num_rays_per_batch=4096,
|
||||||
@@ -741,7 +749,11 @@ method_configs["nerfplayer-ngp"] = TrainerConfig(
|
|||||||
max_num_iterations=30000,
|
max_num_iterations=30000,
|
||||||
mixed_precision=True,
|
mixed_precision=True,
|
||||||
pipeline=DynamicBatchPipelineConfig(
|
pipeline=DynamicBatchPipelineConfig(
|
||||||
datamanager=DepthDataManagerConfig(dataparser=DycheckDataParserConfig(), train_num_rays_per_batch=8192),
|
datamanager=VanillaDataManagerConfig(
|
||||||
|
_target=VanillaDataManager[DepthDataset],
|
||||||
|
dataparser=DycheckDataParserConfig(),
|
||||||
|
train_num_rays_per_batch=8192,
|
||||||
|
),
|
||||||
model=NerfplayerNGPModelConfig(
|
model=NerfplayerNGPModelConfig(
|
||||||
eval_num_rays_per_chunk=8192,
|
eval_num_rays_per_chunk=8192,
|
||||||
grid_levels=1,
|
grid_levels=1,
|
||||||
@@ -770,7 +782,8 @@ method_configs["neus"] = TrainerConfig(
|
|||||||
max_num_iterations=100000,
|
max_num_iterations=100000,
|
||||||
mixed_precision=False,
|
mixed_precision=False,
|
||||||
pipeline=VanillaPipelineConfig(
|
pipeline=VanillaPipelineConfig(
|
||||||
datamanager=SDFDataManagerConfig(
|
datamanager=VanillaDataManagerConfig(
|
||||||
|
_target=VanillaDataManager[SDFDataset],
|
||||||
dataparser=SDFStudioDataParserConfig(),
|
dataparser=SDFStudioDataParserConfig(),
|
||||||
train_num_rays_per_batch=1024,
|
train_num_rays_per_batch=1024,
|
||||||
eval_num_rays_per_batch=1024,
|
eval_num_rays_per_batch=1024,
|
||||||
@@ -803,7 +816,8 @@ method_configs["neus-facto"] = TrainerConfig(
|
|||||||
max_num_iterations=20001,
|
max_num_iterations=20001,
|
||||||
mixed_precision=False,
|
mixed_precision=False,
|
||||||
pipeline=VanillaPipelineConfig(
|
pipeline=VanillaPipelineConfig(
|
||||||
datamanager=SDFDataManagerConfig(
|
datamanager=VanillaDataManagerConfig(
|
||||||
|
_target=VanillaDataManager[SDFDataset],
|
||||||
dataparser=SDFStudioDataParserConfig(),
|
dataparser=SDFStudioDataParserConfig(),
|
||||||
train_num_rays_per_batch=2048,
|
train_num_rays_per_batch=2048,
|
||||||
eval_num_rays_per_batch=2048,
|
eval_num_rays_per_batch=2048,
|
||||||
@@ -845,12 +859,12 @@ method_configs["neus-facto"] = TrainerConfig(
|
|||||||
)
|
)
|
||||||
|
|
||||||
external_methods, external_descriptions = discover_methods()
|
external_methods, external_descriptions = discover_methods()
|
||||||
method_configs.update(external_methods)
|
all_methods = {**method_configs, **external_methods}
|
||||||
descriptions.update(external_descriptions)
|
all_descriptions = {**descriptions, **external_descriptions}
|
||||||
|
|
||||||
AnnotatedBaseConfigUnion = tyro.conf.SuppressFixed[ # Don't show unparseable (fixed) arguments in helptext.
|
AnnotatedBaseConfigUnion = tyro.conf.SuppressFixed[ # Don't show unparseable (fixed) arguments in helptext.
|
||||||
tyro.conf.FlagConversionOff[
|
tyro.conf.FlagConversionOff[
|
||||||
tyro.extras.subcommand_type_from_defaults(defaults=method_configs, descriptions=descriptions)
|
tyro.extras.subcommand_type_from_defaults(defaults=all_methods, descriptions=all_descriptions)
|
||||||
]
|
]
|
||||||
]
|
]
|
||||||
"""Union[] type over config types, annotated with default instances for use with
|
"""Union[] type over config types, annotated with default instances for use with
|
||||||
|
|||||||
@@ -18,10 +18,11 @@ Datamanager.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import functools
|
||||||
from abc import abstractmethod
|
from abc import abstractmethod
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, Optional, Tuple, Type, Union
|
from typing import Any, Dict, Generic, List, Literal, Optional, Tuple, Type, Union
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
import tyro
|
import tyro
|
||||||
@@ -30,7 +31,7 @@ from torch import nn
|
|||||||
from torch.nn import Parameter
|
from torch.nn import Parameter
|
||||||
from torch.utils.data import Dataset
|
from torch.utils.data import Dataset
|
||||||
from torch.utils.data.distributed import DistributedSampler
|
from torch.utils.data.distributed import DistributedSampler
|
||||||
from typing_extensions import Literal
|
from typing_extensions import TypeVar
|
||||||
|
|
||||||
from nerfstudio.cameras.camera_optimizers import CameraOptimizerConfig
|
from nerfstudio.cameras.camera_optimizers import CameraOptimizerConfig
|
||||||
from nerfstudio.cameras.cameras import CameraType
|
from nerfstudio.cameras.cameras import CameraType
|
||||||
@@ -88,7 +89,7 @@ def variable_res_collate(batch: List[Dict]) -> Dict:
|
|||||||
image = data.pop("image")
|
image = data.pop("image")
|
||||||
mask = data.pop("mask", None)
|
mask = data.pop("mask", None)
|
||||||
images.append(image)
|
images.append(image)
|
||||||
if mask:
|
if mask is not None:
|
||||||
masks.append(mask)
|
masks.append(mask)
|
||||||
|
|
||||||
new_batch: dict = nerfstudio_collate(batch)
|
new_batch: dict = nerfstudio_collate(batch)
|
||||||
@@ -367,7 +368,10 @@ class VanillaDataManagerConfig(DataManagerConfig):
|
|||||||
"""Size of patch to sample from. If >1, patch-based sampling will be used."""
|
"""Size of patch to sample from. If >1, patch-based sampling will be used."""
|
||||||
|
|
||||||
|
|
||||||
class VanillaDataManager(DataManager): # pylint: disable=abstract-method
|
TDataset = TypeVar("TDataset", bound=InputDataset, default=InputDataset)
|
||||||
|
|
||||||
|
|
||||||
|
class VanillaDataManager(DataManager, Generic[TDataset]): # pylint: disable=abstract-method
|
||||||
"""Basic stored data manager implementation.
|
"""Basic stored data manager implementation.
|
||||||
|
|
||||||
This is pretty much a port over from our old dataloading utilities, and is a little jank
|
This is pretty much a port over from our old dataloading utilities, and is a little jank
|
||||||
@@ -381,8 +385,8 @@ class VanillaDataManager(DataManager): # pylint: disable=abstract-method
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
config: VanillaDataManagerConfig
|
config: VanillaDataManagerConfig
|
||||||
train_dataset: InputDataset
|
train_dataset: TDataset
|
||||||
eval_dataset: InputDataset
|
eval_dataset: TDataset
|
||||||
train_dataparser_outputs: DataparserOutputs
|
train_dataparser_outputs: DataparserOutputs
|
||||||
train_pixel_sampler: Optional[PixelSampler] = None
|
train_pixel_sampler: Optional[PixelSampler] = None
|
||||||
eval_pixel_sampler: Optional[PixelSampler] = None
|
eval_pixel_sampler: Optional[PixelSampler] = None
|
||||||
@@ -396,6 +400,7 @@ class VanillaDataManager(DataManager): # pylint: disable=abstract-method
|
|||||||
local_rank: int = 0,
|
local_rank: int = 0,
|
||||||
**kwargs, # pylint: disable=unused-argument
|
**kwargs, # pylint: disable=unused-argument
|
||||||
):
|
):
|
||||||
|
self.dataset_type: Type[TDataset] = kwargs.get("_dataset_type", TDataset.__default__)
|
||||||
self.config = config
|
self.config = config
|
||||||
self.device = device
|
self.device = device
|
||||||
self.world_size = world_size
|
self.world_size = world_size
|
||||||
@@ -426,22 +431,29 @@ class VanillaDataManager(DataManager): # pylint: disable=abstract-method
|
|||||||
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
def create_train_dataset(self) -> InputDataset:
|
def __class_getitem__(cls, item):
|
||||||
|
return type(
|
||||||
|
cls.__name__,
|
||||||
|
(cls,),
|
||||||
|
{"__module__": cls.__module__, "__init__": functools.partialmethod(cls.__init__, _dataset_type=item)},
|
||||||
|
)
|
||||||
|
|
||||||
|
def create_train_dataset(self) -> TDataset:
|
||||||
"""Sets up the data loaders for training"""
|
"""Sets up the data loaders for training"""
|
||||||
return InputDataset(
|
return self.dataset_type(
|
||||||
dataparser_outputs=self.train_dataparser_outputs,
|
dataparser_outputs=self.train_dataparser_outputs,
|
||||||
scale_factor=self.config.camera_res_scale_factor,
|
scale_factor=self.config.camera_res_scale_factor,
|
||||||
)
|
)
|
||||||
|
|
||||||
def create_eval_dataset(self) -> InputDataset:
|
def create_eval_dataset(self) -> TDataset:
|
||||||
"""Sets up the data loaders for evaluation"""
|
"""Sets up the data loaders for evaluation"""
|
||||||
return InputDataset(
|
return self.dataset_type(
|
||||||
dataparser_outputs=self.dataparser.get_dataparser_outputs(split=self.test_split),
|
dataparser_outputs=self.dataparser.get_dataparser_outputs(split=self.test_split),
|
||||||
scale_factor=self.config.camera_res_scale_factor,
|
scale_factor=self.config.camera_res_scale_factor,
|
||||||
)
|
)
|
||||||
|
|
||||||
def _get_pixel_sampler( # pylint: disable=no-self-use
|
def _get_pixel_sampler( # pylint: disable=no-self-use
|
||||||
self, dataset: InputDataset, *args: Any, **kwargs: Any
|
self, dataset: TDataset, *args: Any, **kwargs: Any
|
||||||
) -> PixelSampler:
|
) -> PixelSampler:
|
||||||
"""Infer pixel sampler to use."""
|
"""Infer pixel sampler to use."""
|
||||||
if self.config.patch_size > 1:
|
if self.config.patch_size > 1:
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
# 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.
|
|
||||||
|
|
||||||
"""
|
|
||||||
Depth datamanager.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from typing import Type
|
|
||||||
|
|
||||||
from nerfstudio.data.datamanagers import base_datamanager
|
|
||||||
from nerfstudio.data.datasets.depth_dataset import DepthDataset
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class DepthDataManagerConfig(base_datamanager.VanillaDataManagerConfig):
|
|
||||||
"""A depth datamanager - required to use with .setup()"""
|
|
||||||
|
|
||||||
_target: Type = field(default_factory=lambda: DepthDataManager)
|
|
||||||
|
|
||||||
|
|
||||||
class DepthDataManager(base_datamanager.VanillaDataManager): # pylint: disable=abstract-method
|
|
||||||
"""Data manager implementation for data that also requires processing depth data.
|
|
||||||
Args:
|
|
||||||
config: the DataManagerConfig used to instantiate class
|
|
||||||
"""
|
|
||||||
|
|
||||||
def create_train_dataset(self) -> DepthDataset:
|
|
||||||
self.train_dataparser_outputs = self.dataparser.get_dataparser_outputs(split="train")
|
|
||||||
return DepthDataset(
|
|
||||||
dataparser_outputs=self.train_dataparser_outputs,
|
|
||||||
)
|
|
||||||
|
|
||||||
def create_eval_dataset(self) -> DepthDataset:
|
|
||||||
return DepthDataset(
|
|
||||||
dataparser_outputs=self.dataparser.get_dataparser_outputs(split=self.test_split),
|
|
||||||
)
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
# 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.
|
|
||||||
|
|
||||||
"""
|
|
||||||
SDF datamanager.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from typing import Type
|
|
||||||
|
|
||||||
from nerfstudio.data.datamanagers import base_datamanager
|
|
||||||
from nerfstudio.data.datasets.sdf_dataset import SDFDataset
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class SDFDataManagerConfig(base_datamanager.VanillaDataManagerConfig):
|
|
||||||
"""A sdf datamanager - required to use with .setup()"""
|
|
||||||
|
|
||||||
_target: Type = field(default_factory=lambda: SDFDataManager)
|
|
||||||
|
|
||||||
|
|
||||||
class SDFDataManager(base_datamanager.VanillaDataManager): # pylint: disable=abstract-method
|
|
||||||
"""Data manager implementation for data that also requires processing sdf data.
|
|
||||||
Args:
|
|
||||||
config: the DataManagerConfig used to instantiate class
|
|
||||||
"""
|
|
||||||
|
|
||||||
def create_train_dataset(self) -> SDFDataset:
|
|
||||||
self.train_dataparser_outputs = self.dataparser.get_dataparser_outputs(split="train")
|
|
||||||
return SDFDataset(
|
|
||||||
dataparser_outputs=self.train_dataparser_outputs,
|
|
||||||
)
|
|
||||||
|
|
||||||
def create_eval_dataset(self) -> SDFDataset:
|
|
||||||
return SDFDataset(
|
|
||||||
dataparser_outputs=self.dataparser.get_dataparser_outputs(split=self.test_split),
|
|
||||||
)
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
# 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.
|
|
||||||
|
|
||||||
"""
|
|
||||||
Semantic datamanager.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from typing import Type
|
|
||||||
|
|
||||||
from nerfstudio.data.datamanagers.base_datamanager import (
|
|
||||||
VanillaDataManager,
|
|
||||||
VanillaDataManagerConfig,
|
|
||||||
)
|
|
||||||
from nerfstudio.data.datasets.semantic_dataset import SemanticDataset
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class SemanticDataManagerConfig(VanillaDataManagerConfig):
|
|
||||||
"""A semantic datamanager - required to use with .setup()"""
|
|
||||||
|
|
||||||
_target: Type = field(default_factory=lambda: SemanticDataManager)
|
|
||||||
|
|
||||||
|
|
||||||
class SemanticDataManager(VanillaDataManager): # pylint: disable=abstract-method
|
|
||||||
"""Data manager implementation for data that also requires processing semantic data.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
config: the DataManagerConfig used to instantiate class
|
|
||||||
"""
|
|
||||||
|
|
||||||
def create_train_dataset(self) -> SemanticDataset:
|
|
||||||
self.train_dataparser_outputs = self.dataparser.get_dataparser_outputs(split="train")
|
|
||||||
return SemanticDataset(
|
|
||||||
dataparser_outputs=self.train_dataparser_outputs,
|
|
||||||
scale_factor=self.config.camera_res_scale_factor,
|
|
||||||
)
|
|
||||||
|
|
||||||
def create_eval_dataset(self) -> SemanticDataset:
|
|
||||||
return SemanticDataset(
|
|
||||||
dataparser_outputs=self.dataparser.get_dataparser_outputs(split=self.test_split),
|
|
||||||
scale_factor=self.config.camera_res_scale_factor,
|
|
||||||
)
|
|
||||||
@@ -16,12 +16,11 @@
|
|||||||
import math
|
import math
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Type
|
from typing import Literal, Type
|
||||||
|
|
||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras import camera_utils
|
from nerfstudio.cameras import camera_utils
|
||||||
from nerfstudio.cameras.cameras import Cameras, CameraType
|
from nerfstudio.cameras.cameras import Cameras, CameraType
|
||||||
|
|||||||
@@ -20,11 +20,10 @@ import json
|
|||||||
from abc import abstractmethod
|
from abc import abstractmethod
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, Optional, Type
|
from typing import Any, Dict, List, Literal, Optional, Type
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
from torchtyping import TensorType
|
from torchtyping import TensorType
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
import nerfstudio.configs.base_config as cfg
|
import nerfstudio.configs.base_config as cfg
|
||||||
from nerfstudio.cameras.cameras import Cameras
|
from nerfstudio.cameras.cameras import Cameras
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ class Blender(DataParser):
|
|||||||
poses.append(np.array(frame["transform_matrix"]))
|
poses.append(np.array(frame["transform_matrix"]))
|
||||||
poses = np.array(poses).astype(np.float32)
|
poses = np.array(poses).astype(np.float32)
|
||||||
|
|
||||||
img_0 = imageio.imread(image_filenames[0])
|
img_0 = imageio.v2.imread(image_filenames[0])
|
||||||
image_height, image_width = img_0.shape[:2]
|
image_height, image_width = img_0.shape[:2]
|
||||||
camera_angle_x = float(meta["camera_angle_x"])
|
camera_angle_x = float(meta["camera_angle_x"])
|
||||||
focal_length = 0.5 * image_width / np.tan(0.5 * camera_angle_x)
|
focal_length = 0.5 * image_width / np.tan(0.5 * camera_angle_x)
|
||||||
|
|||||||
@@ -23,12 +23,11 @@ import glob
|
|||||||
import os
|
import os
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Tuple, Type
|
from typing import List, Literal, Tuple, Type
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras import camera_utils
|
from nerfstudio.cameras import camera_utils
|
||||||
from nerfstudio.cameras.cameras import Cameras, CameraType
|
from nerfstudio.cameras.cameras import Cameras, CameraType
|
||||||
|
|||||||
@@ -18,13 +18,12 @@ from __future__ import annotations
|
|||||||
import math
|
import math
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path, PurePath
|
from pathlib import Path, PurePath
|
||||||
from typing import Optional, Type
|
from typing import Literal, Optional, Type
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras import camera_utils
|
from nerfstudio.cameras import camera_utils
|
||||||
from nerfstudio.cameras.cameras import CAMERA_MODEL_TO_TYPE, Cameras, CameraType
|
from nerfstudio.cameras.cameras import CAMERA_MODEL_TO_TYPE, Cameras, CameraType
|
||||||
|
|||||||
@@ -17,13 +17,12 @@ import math
|
|||||||
import os
|
import os
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional, Tuple, Type
|
from typing import Literal, Optional, Tuple, Type
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pyquaternion
|
import pyquaternion
|
||||||
import torch
|
import torch
|
||||||
from nuscenes.nuscenes import NuScenes as NuScenesDatabase
|
from nuscenes.nuscenes import NuScenes as NuScenesDatabase
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.cameras import Cameras, CameraType
|
from nerfstudio.cameras.cameras import Cameras, CameraType
|
||||||
from nerfstudio.data.dataparsers.base_dataparser import (
|
from nerfstudio.data.dataparsers.base_dataparser import (
|
||||||
@@ -56,7 +55,7 @@ class NuScenesDataParserConfig(DataParserConfig):
|
|||||||
Each clip was recorded with a suite of sensors including 6 surround cameras.
|
Each clip was recorded with a suite of sensors including 6 surround cameras.
|
||||||
It also includes 3D cuboid annotations around objects.
|
It also includes 3D cuboid annotations around objects.
|
||||||
We optionally use these cuboids to mask dynamic objects by specifying the mask_dir flag.
|
We optionally use these cuboids to mask dynamic objects by specifying the mask_dir flag.
|
||||||
To create these masks use scripts/datasets/process_nuscenes_masks.py.
|
To create these masks use nerfstudio/scripts/datasets/process_nuscenes_masks.py.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
_target: Type = field(default_factory=lambda: NuScenes)
|
_target: Type = field(default_factory=lambda: NuScenes)
|
||||||
|
|||||||
@@ -18,12 +18,11 @@ from __future__ import annotations
|
|||||||
import math
|
import math
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Type
|
from typing import Literal, Type
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
from rich.progress import Console
|
from rich.progress import Console
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras import camera_utils
|
from nerfstudio.cameras import camera_utils
|
||||||
from nerfstudio.cameras.cameras import Cameras, CameraType
|
from nerfstudio.cameras.cameras import Cameras, CameraType
|
||||||
|
|||||||
@@ -16,12 +16,11 @@
|
|||||||
import math
|
import math
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Type
|
from typing import Literal, Type
|
||||||
|
|
||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras import camera_utils
|
from nerfstudio.cameras import camera_utils
|
||||||
from nerfstudio.cameras.cameras import Cameras, CameraType
|
from nerfstudio.cameras.cameras import Cameras, CameraType
|
||||||
|
|||||||
@@ -87,16 +87,17 @@ class SDFStudio(DataParser):
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
image_filename = self.config.data / frame["rgb_path"]
|
image_filename = self.config.data / frame["rgb_path"]
|
||||||
depth_filename = self.config.data / frame["mono_depth_path"]
|
depth_filename = frame.get("mono_depth_path")
|
||||||
normal_filename = self.config.data / frame["mono_normal_path"]
|
normal_filename = frame.get("mono_normal_path")
|
||||||
|
|
||||||
intrinsics = torch.tensor(frame["intrinsics"])
|
intrinsics = torch.tensor(frame["intrinsics"])
|
||||||
camtoworld = torch.tensor(frame["camtoworld"])
|
camtoworld = torch.tensor(frame["camtoworld"])
|
||||||
|
|
||||||
# append data
|
# append data
|
||||||
image_filenames.append(image_filename)
|
image_filenames.append(image_filename)
|
||||||
depth_filenames.append(depth_filename)
|
if depth_filename is not None and normal_filename is not None:
|
||||||
normal_filenames.append(normal_filename)
|
depth_filenames.append(self.config.data / depth_filename)
|
||||||
|
normal_filenames.append(self.config.data / normal_filename)
|
||||||
fx.append(intrinsics[0, 0])
|
fx.append(intrinsics[0, 0])
|
||||||
fy.append(intrinsics[1, 1])
|
fy.append(intrinsics[1, 1])
|
||||||
cx.append(intrinsics[0, 2])
|
cx.append(intrinsics[0, 2])
|
||||||
|
|||||||
@@ -65,7 +65,6 @@ class Sitcoms3D(DataParser):
|
|||||||
config: Sitcoms3DDataParserConfig
|
config: Sitcoms3DDataParserConfig
|
||||||
|
|
||||||
def _generate_dataparser_outputs(self, split="train"): # pylint: disable=unused-argument,too-many-statements
|
def _generate_dataparser_outputs(self, split="train"): # pylint: disable=unused-argument,too-many-statements
|
||||||
|
|
||||||
cameras_json = load_from_json(self.config.data / "cameras.json")
|
cameras_json = load_from_json(self.config.data / "cameras.json")
|
||||||
frames = cameras_json["frames"]
|
frames = cameras_json["frames"]
|
||||||
bbox = torch.tensor(cameras_json["bbox"])
|
bbox = torch.tensor(cameras_json["bbox"])
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ class PixelSampler: # pylint: disable=too-few-public-methods
|
|||||||
key: value[c, y, x] for key, value in batch.items() if key != "image_idx" and value is not None
|
key: value[c, y, x] for key, value in batch.items() if key != "image_idx" and value is not None
|
||||||
}
|
}
|
||||||
|
|
||||||
assert collated_batch["image"].shape == (num_rays_per_batch, 3), collated_batch["image"].shape
|
assert collated_batch["image"].shape[0] == num_rays_per_batch
|
||||||
|
|
||||||
# Needed to correct the random indices to their actual camera idx locations.
|
# Needed to correct the random indices to their actual camera idx locations.
|
||||||
indices[:, 0] = batch["image_idx"][c]
|
indices[:, 0] = batch["image_idx"][c]
|
||||||
@@ -137,7 +137,6 @@ class PixelSampler: # pylint: disable=too-few-public-methods
|
|||||||
if "mask" in batch:
|
if "mask" in batch:
|
||||||
num_rays_in_batch = num_rays_per_batch // num_images
|
num_rays_in_batch = num_rays_per_batch // num_images
|
||||||
for i in range(num_images):
|
for i in range(num_images):
|
||||||
|
|
||||||
image_height, image_width, _ = batch["image"][i].shape
|
image_height, image_width, _ = batch["image"][i].shape
|
||||||
|
|
||||||
if i == num_images - 1:
|
if i == num_images - 1:
|
||||||
@@ -172,7 +171,7 @@ class PixelSampler: # pylint: disable=too-few-public-methods
|
|||||||
|
|
||||||
collated_batch["image"] = torch.cat(all_images, dim=0)
|
collated_batch["image"] = torch.cat(all_images, dim=0)
|
||||||
|
|
||||||
assert collated_batch["image"].shape == (num_rays_per_batch, 3), collated_batch["image"].shape
|
assert collated_batch["image"].shape[0] == num_rays_per_batch
|
||||||
|
|
||||||
# Needed to correct the random indices to their actual camera idx locations.
|
# Needed to correct the random indices to their actual camera idx locations.
|
||||||
indices[:, 0] = batch["image_idx"][c]
|
indices[:, 0] = batch["image_idx"][c]
|
||||||
@@ -222,7 +221,6 @@ class EquirectangularPixelSampler(PixelSampler): # pylint: disable=too-few-publ
|
|||||||
mask: Optional[TensorType] = None,
|
mask: Optional[TensorType] = None,
|
||||||
device: Union[torch.device, str] = "cpu",
|
device: Union[torch.device, str] = "cpu",
|
||||||
) -> TensorType["batch_size", 3]:
|
) -> TensorType["batch_size", 3]:
|
||||||
|
|
||||||
if isinstance(mask, torch.Tensor):
|
if isinstance(mask, torch.Tensor):
|
||||||
# Note: if there is a mask, sampling reduces back to uniform sampling, which gives more
|
# Note: if there is a mask, sampling reduces back to uniform sampling, which gives more
|
||||||
# sampling weight to the poles of the image than the equators.
|
# sampling weight to the poles of the image than the equators.
|
||||||
@@ -230,7 +228,6 @@ class EquirectangularPixelSampler(PixelSampler): # pylint: disable=too-few-publ
|
|||||||
|
|
||||||
indices = super().sample_method(batch_size, num_images, image_height, image_width, mask=mask, device=device)
|
indices = super().sample_method(batch_size, num_images, image_height, image_width, mask=mask, device=device)
|
||||||
else:
|
else:
|
||||||
|
|
||||||
# We sample theta uniformly in [0, 2*pi]
|
# We sample theta uniformly in [0, 2*pi]
|
||||||
# We sample phi in [0, pi] according to the PDF f(phi) = sin(phi) / 2.
|
# We sample phi in [0, pi] according to the PDF f(phi) = sin(phi) / 2.
|
||||||
# This is done by inverse transform sampling.
|
# This is done by inverse transform sampling.
|
||||||
@@ -280,7 +277,6 @@ class PatchPixelSampler(PixelSampler): # pylint: disable=too-few-public-methods
|
|||||||
mask: Optional[TensorType] = None,
|
mask: Optional[TensorType] = None,
|
||||||
device: Union[torch.device, str] = "cpu",
|
device: Union[torch.device, str] = "cpu",
|
||||||
) -> TensorType["batch_size", 3]:
|
) -> TensorType["batch_size", 3]:
|
||||||
|
|
||||||
if mask:
|
if mask:
|
||||||
# Note: if there is a mask, sampling reduces back to uniform sampling
|
# Note: if there is a mask, sampling reduces back to uniform sampling
|
||||||
indices = super().sample_method(batch_size, num_images, image_height, image_width, mask=mask, device=device)
|
indices = super().sample_method(batch_size, num_images, image_height, image_width, mask=mask, device=device)
|
||||||
|
|||||||
@@ -225,30 +225,16 @@ class FixedIndicesEvalDataloader(EvalDataloader):
|
|||||||
|
|
||||||
class RandIndicesEvalDataloader(EvalDataloader):
|
class RandIndicesEvalDataloader(EvalDataloader):
|
||||||
"""Dataloader that returns random images.
|
"""Dataloader that returns random images.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
input_dataset: InputDataset to load data from
|
input_dataset: InputDataset to load data from
|
||||||
device: Device to load data to
|
device: Device to load data to
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
input_dataset: InputDataset,
|
|
||||||
device: Union[torch.device, str] = "cpu",
|
|
||||||
**kwargs,
|
|
||||||
):
|
|
||||||
super().__init__(input_dataset, device, **kwargs)
|
|
||||||
self.count = 0
|
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
self.count = 0
|
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def __next__(self):
|
def __next__(self):
|
||||||
if self.count < 1:
|
# choose a random image index
|
||||||
image_indices = range(self.cameras.size)
|
image_idx = random.randint(0, len(self.cameras) - 1)
|
||||||
image_idx = random.choice(image_indices)
|
ray_bundle, batch = self.get_data_from_image_idx(image_idx)
|
||||||
ray_bundle, batch = self.get_data_from_image_idx(image_idx)
|
return ray_bundle, batch
|
||||||
self.count += 1
|
|
||||||
return ray_bundle, batch
|
|
||||||
raise StopIteration
|
|
||||||
@@ -18,11 +18,10 @@
|
|||||||
|
|
||||||
from abc import abstractmethod
|
from abc import abstractmethod
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Optional, Tuple, Type
|
from typing import Literal, Optional, Tuple, Type
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from torch.optim import Optimizer, lr_scheduler
|
from torch.optim import Optimizer, lr_scheduler
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.configs.base_config import InstantiateConfig
|
from nerfstudio.configs.base_config import InstantiateConfig
|
||||||
|
|
||||||
|
|||||||
@@ -24,12 +24,14 @@ import time
|
|||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
from typing import Dict, List, Optional, Tuple, Type, Union
|
from typing import Dict, List, Literal, Optional, Tuple, Type, Union
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
|
from rich import box, style
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
|
from rich.panel import Panel
|
||||||
|
from rich.table import Table
|
||||||
from torch.cuda.amp.grad_scaler import GradScaler
|
from torch.cuda.amp.grad_scaler import GradScaler
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.configs.experiment_config import ExperimentConfig
|
from nerfstudio.configs.experiment_config import ExperimentConfig
|
||||||
from nerfstudio.engine.callbacks import (
|
from nerfstudio.engine.callbacks import (
|
||||||
@@ -86,6 +88,8 @@ class TrainerConfig(ExperimentConfig):
|
|||||||
"""Optionally specify model step to load from; if none, will find most recent model in load_dir."""
|
"""Optionally specify model step to load from; if none, will find most recent model in load_dir."""
|
||||||
load_config: Optional[Path] = None
|
load_config: Optional[Path] = None
|
||||||
"""Path to config YAML file."""
|
"""Path to config YAML file."""
|
||||||
|
load_checkpoint: Optional[Path] = None
|
||||||
|
"""Path to checkpoint file."""
|
||||||
log_gradients: bool = False
|
log_gradients: bool = False
|
||||||
"""Optionally log gradients during training"""
|
"""Optionally log gradients during training"""
|
||||||
|
|
||||||
@@ -184,7 +188,11 @@ class Trainer:
|
|||||||
# set up writers/profilers if enabled
|
# set up writers/profilers if enabled
|
||||||
writer_log_path = self.base_dir / self.config.logging.relative_log_dir
|
writer_log_path = self.base_dir / self.config.logging.relative_log_dir
|
||||||
writer.setup_event_writer(
|
writer.setup_event_writer(
|
||||||
self.config.is_wandb_enabled(), self.config.is_tensorboard_enabled(), log_dir=writer_log_path
|
self.config.is_wandb_enabled(),
|
||||||
|
self.config.is_tensorboard_enabled(),
|
||||||
|
log_dir=writer_log_path,
|
||||||
|
experiment_name=self.config.experiment_name,
|
||||||
|
project_name=self.config.project_name,
|
||||||
)
|
)
|
||||||
writer.setup_local_writer(
|
writer.setup_local_writer(
|
||||||
self.config.logging, max_iter=self.config.max_num_iterations, banner_messages=banner_messages
|
self.config.logging, max_iter=self.config.max_num_iterations, banner_messages=banner_messages
|
||||||
@@ -284,14 +292,18 @@ class Trainer:
|
|||||||
# write out any remaining events (e.g., total train time)
|
# write out any remaining events (e.g., total train time)
|
||||||
writer.write_out_storage()
|
writer.write_out_storage()
|
||||||
|
|
||||||
CONSOLE.rule()
|
table = Table(
|
||||||
CONSOLE.print("[bold green]:tada: :tada: :tada: Training Finished :tada: :tada: :tada:", justify="center")
|
title=None,
|
||||||
|
show_header=False,
|
||||||
|
box=box.MINIMAL,
|
||||||
|
title_style=style.Style(bold=True),
|
||||||
|
)
|
||||||
|
table.add_row("Config File", str(self.config.get_base_dir() / "config.yml"))
|
||||||
|
table.add_row("Checkpoint Directory", str(self.checkpoint_dir))
|
||||||
|
CONSOLE.print(Panel(table, title="[bold][green]:tada: Training Finished :tada:[/bold]", expand=False))
|
||||||
|
|
||||||
if not self.config.viewer.quit_on_train_completion:
|
if not self.config.viewer.quit_on_train_completion:
|
||||||
self.training_state = "completed"
|
|
||||||
self._train_complete_viewer()
|
self._train_complete_viewer()
|
||||||
CONSOLE.print("Use ctrl+c to quit", justify="center")
|
|
||||||
while True:
|
|
||||||
time.sleep(0.01)
|
|
||||||
|
|
||||||
@check_main_thread
|
@check_main_thread
|
||||||
def _check_viewer_warnings(self) -> None:
|
def _check_viewer_warnings(self) -> None:
|
||||||
@@ -336,11 +348,15 @@ class Trainer:
|
|||||||
def _train_complete_viewer(self) -> None:
|
def _train_complete_viewer(self) -> None:
|
||||||
"""Let the viewer know that the training is complete"""
|
"""Let the viewer know that the training is complete"""
|
||||||
assert self.viewer_state is not None
|
assert self.viewer_state is not None
|
||||||
|
self.training_state = "completed"
|
||||||
try:
|
try:
|
||||||
self.viewer_state.training_complete()
|
self.viewer_state.training_complete()
|
||||||
except RuntimeError:
|
except RuntimeError:
|
||||||
time.sleep(0.03) # sleep to allow buffer to reset
|
time.sleep(0.03) # sleep to allow buffer to reset
|
||||||
CONSOLE.log("Viewer failed. Continuing training.")
|
CONSOLE.log("Viewer failed. Continuing training.")
|
||||||
|
CONSOLE.print("Use ctrl+c to quit", justify="center")
|
||||||
|
while True:
|
||||||
|
time.sleep(0.01)
|
||||||
|
|
||||||
@check_viewer_enabled
|
@check_viewer_enabled
|
||||||
def _update_viewer_rays_per_sec(self, train_t: TimeWriter, vis_t: TimeWriter, step: int) -> None:
|
def _update_viewer_rays_per_sec(self, train_t: TimeWriter, vis_t: TimeWriter, step: int) -> None:
|
||||||
@@ -362,10 +378,11 @@ class Trainer:
|
|||||||
def _load_checkpoint(self) -> None:
|
def _load_checkpoint(self) -> None:
|
||||||
"""Helper function to load pipeline and optimizer from prespecified checkpoint"""
|
"""Helper function to load pipeline and optimizer from prespecified checkpoint"""
|
||||||
load_dir: Path = self.config.load_dir
|
load_dir: Path = self.config.load_dir
|
||||||
|
load_checkpoint: Path = self.config.load_checkpoint
|
||||||
if load_dir is not None:
|
if load_dir is not None:
|
||||||
load_step = self.config.load_step
|
load_step = self.config.load_step
|
||||||
if load_step is None:
|
if load_step is None:
|
||||||
print("Loading latest checkpoint from load_dir")
|
print("Loading latest Nerfstudio checkpoint from load_dir...")
|
||||||
# NOTE: this is specific to the checkpoint name format
|
# 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_step = sorted(int(x[x.find("-") + 1 : x.find(".")]) for x in os.listdir(load_dir))[-1]
|
||||||
load_path: Path = load_dir / f"step-{load_step:09d}.ckpt"
|
load_path: Path = load_dir / f"step-{load_step:09d}.ckpt"
|
||||||
@@ -376,9 +393,18 @@ class Trainer:
|
|||||||
self.pipeline.load_pipeline(loaded_state["pipeline"], loaded_state["step"])
|
self.pipeline.load_pipeline(loaded_state["pipeline"], loaded_state["step"])
|
||||||
self.optimizers.load_optimizers(loaded_state["optimizers"])
|
self.optimizers.load_optimizers(loaded_state["optimizers"])
|
||||||
self.grad_scaler.load_state_dict(loaded_state["scalers"])
|
self.grad_scaler.load_state_dict(loaded_state["scalers"])
|
||||||
CONSOLE.print(f"done loading checkpoint from {load_path}")
|
CONSOLE.print(f"Done loading Nerfstudio checkpoint from {load_path}")
|
||||||
|
elif load_checkpoint is not None:
|
||||||
|
assert load_checkpoint.exists(), f"Checkpoint {load_checkpoint} does not exist"
|
||||||
|
loaded_state = torch.load(load_checkpoint, map_location="cpu")
|
||||||
|
self._start_step = loaded_state["step"] + 1
|
||||||
|
# load the checkpoints for pipeline, optimizers, and gradient scalar
|
||||||
|
self.pipeline.load_pipeline(loaded_state["pipeline"], loaded_state["step"])
|
||||||
|
self.optimizers.load_optimizers(loaded_state["optimizers"])
|
||||||
|
self.grad_scaler.load_state_dict(loaded_state["scalers"])
|
||||||
|
CONSOLE.print(f"Done loading Nerfstudio checkpoint from {load_checkpoint}")
|
||||||
else:
|
else:
|
||||||
CONSOLE.print("No checkpoints to load, training from scratch")
|
CONSOLE.print("No Nerfstudio checkpoint to load, so training from scratch.")
|
||||||
|
|
||||||
@check_main_thread
|
@check_main_thread
|
||||||
def save_checkpoint(self, step: int) -> None:
|
def save_checkpoint(self, step: int) -> None:
|
||||||
@@ -438,8 +464,11 @@ class Trainer:
|
|||||||
|
|
||||||
metrics_dict["Gradients/Total"] = total_grad
|
metrics_dict["Gradients/Total"] = total_grad
|
||||||
|
|
||||||
|
scale = self.grad_scaler.get_scale()
|
||||||
self.grad_scaler.update()
|
self.grad_scaler.update()
|
||||||
self.optimizers.scheduler_step_all(step)
|
# If the gradient scaler is decreased, no optimization step is performed so we should not step the scheduler.
|
||||||
|
if scale <= self.grad_scaler.get_scale():
|
||||||
|
self.optimizers.scheduler_step_all(step)
|
||||||
|
|
||||||
# Merging loss and metrics dict into a single output.
|
# Merging loss and metrics dict into a single output.
|
||||||
return loss, loss_dict, metrics_dict
|
return loss, loss_dict, metrics_dict
|
||||||
|
|||||||
@@ -76,7 +76,6 @@ def evaluate_multiresolution_sdf(
|
|||||||
x_min: float,
|
x_min: float,
|
||||||
crop_n: int,
|
crop_n: int,
|
||||||
) -> TensorType["batch"]:
|
) -> TensorType["batch"]:
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Evaluate SDF values using a multi-resolution approach with a given point pyramid.
|
Evaluate SDF values using a multi-resolution approach with a given point pyramid.
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import math
|
import math
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional, Tuple, Union
|
from typing import Literal, Optional, Tuple, Union
|
||||||
|
|
||||||
import mediapy as media
|
import mediapy as media
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -30,7 +30,6 @@ import torch
|
|||||||
import xatlas
|
import xatlas
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from torchtyping import TensorType
|
from torchtyping import TensorType
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RayBundle
|
from nerfstudio.cameras.rays import RayBundle
|
||||||
from nerfstudio.exporter.exporter_utils import Mesh
|
from nerfstudio.exporter.exporter_utils import Mesh
|
||||||
|
|||||||
@@ -18,14 +18,13 @@ Encoding functions
|
|||||||
|
|
||||||
import itertools
|
import itertools
|
||||||
from abc import abstractmethod
|
from abc import abstractmethod
|
||||||
from typing import Optional, Sequence
|
from typing import Literal, Optional, Sequence
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
from torch import nn
|
from torch import nn
|
||||||
from torchtyping import TensorType
|
from torchtyping import TensorType
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.field_components.base_field_component import FieldComponent
|
from nerfstudio.field_components.base_field_component import FieldComponent
|
||||||
from nerfstudio.utils.math import components_from_spherical_harmonics, expected_sin
|
from nerfstudio.utils.math import components_from_spherical_harmonics, expected_sin
|
||||||
|
|||||||
@@ -61,7 +61,6 @@ class FieldHead(FieldComponent):
|
|||||||
in_dim: Optional[int] = None,
|
in_dim: Optional[int] = None,
|
||||||
activation: Optional[Union[nn.Module, Callable]] = None,
|
activation: Optional[Union[nn.Module, Callable]] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.out_dim = out_dim
|
self.out_dim = out_dim
|
||||||
self.activation = activation
|
self.activation = activation
|
||||||
@@ -133,7 +132,6 @@ class SHFieldHead(FieldHead):
|
|||||||
def __init__(
|
def __init__(
|
||||||
self, in_dim: Optional[int] = None, levels: int = 3, channels: int = 3, activation: Optional[nn.Module] = None
|
self, in_dim: Optional[int] = None, levels: int = 3, channels: int = 3, activation: Optional[nn.Module] = None
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
out_dim = channels * levels**2
|
out_dim = channels * levels**2
|
||||||
super().__init__(in_dim=in_dim, out_dim=out_dim, field_head_name=FieldHeadNames.SH, activation=activation)
|
super().__init__(in_dim=in_dim, out_dim=out_dim, field_head_name=FieldHeadNames.SH, activation=activation)
|
||||||
|
|
||||||
|
|||||||
@@ -46,7 +46,6 @@ class MLP(FieldComponent):
|
|||||||
activation: Optional[nn.Module] = nn.ReLU(),
|
activation: Optional[nn.Module] = nn.ReLU(),
|
||||||
out_activation: Optional[nn.Module] = None,
|
out_activation: Optional[nn.Module] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.in_dim = in_dim
|
self.in_dim = in_dim
|
||||||
assert self.in_dim > 0
|
assert self.in_dim > 0
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ class SceneContraction(SpatialDistortion):
|
|||||||
\\end{cases}
|
\\end{cases}
|
||||||
|
|
||||||
If the order is not specified, we use the Frobenius norm, this will contract the space to a sphere of
|
If the order is not specified, we use the Frobenius norm, this will contract the space to a sphere of
|
||||||
radius 1. If the order is L_inf (order=float("inf")), we will contract the space to a cube of side length 2.
|
radius 2. If the order is L_inf (order=float("inf")), we will contract the space to a cube of side length 4.
|
||||||
If using voxel based encodings such as the Hash encoder, we recommend using the L_inf norm.
|
If using voxel based encodings such as the Hash encoder, we recommend using the L_inf norm.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
|||||||
@@ -381,8 +381,8 @@ class TorchNerfactoField(Field):
|
|||||||
positions = self.spatial_distortion(positions)
|
positions = self.spatial_distortion(positions)
|
||||||
else:
|
else:
|
||||||
positions = ray_samples.frustums.get_positions()
|
positions = ray_samples.frustums.get_positions()
|
||||||
encoded_xyz = self.position_encoding(positions)
|
encoded_xyz = self.position_encoding(positions.view(-1, 3)).to(torch.float32)
|
||||||
base_mlp_out = self.mlp_base(encoded_xyz)
|
base_mlp_out = self.mlp_base(encoded_xyz).view(*ray_samples.frustums.shape, -1)
|
||||||
density = self.field_output_density(base_mlp_out)
|
density = self.field_output_density(base_mlp_out)
|
||||||
return density, base_mlp_out
|
return density, base_mlp_out
|
||||||
|
|
||||||
@@ -404,18 +404,20 @@ class TorchNerfactoField(Field):
|
|||||||
|
|
||||||
outputs = {}
|
outputs = {}
|
||||||
for field_head in self.field_heads:
|
for field_head in self.field_heads:
|
||||||
encoded_dir = self.direction_encoding(ray_samples.frustums.directions)
|
directions = shift_directions_for_tcnn(ray_samples.frustums.directions)
|
||||||
|
directions_flat = directions.view(-1, 3)
|
||||||
|
encoded_dir = self.direction_encoding(directions_flat)
|
||||||
mlp_out = self.mlp_head(
|
mlp_out = self.mlp_head(
|
||||||
torch.cat(
|
torch.cat(
|
||||||
[
|
[
|
||||||
encoded_dir,
|
encoded_dir.view(-1, self.direction_encoding.get_out_dim()),
|
||||||
density_embedding, # type:ignore
|
density_embedding.view(-1, self.mlp_base.get_out_dim()), # type:ignore
|
||||||
embedded_appearance.view(-1, self.appearance_embedding_dim),
|
embedded_appearance.view(-1, self.appearance_embedding_dim),
|
||||||
],
|
],
|
||||||
dim=-1, # type:ignore
|
dim=-1, # type:ignore
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
outputs[field_head.field_head_name] = field_head(mlp_out)
|
outputs[field_head.field_head_name] = field_head(mlp_out).view(*outputs_shape, -1).to(directions)
|
||||||
return outputs
|
return outputs
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ a signed distance function (SDF) for surface representation is used to help with
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Dict, Optional, Type
|
from typing import Dict, Literal, Optional, Type
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
@@ -26,7 +26,6 @@ import torch.nn.functional as F
|
|||||||
from torch import nn
|
from torch import nn
|
||||||
from torch.nn.parameter import Parameter
|
from torch.nn.parameter import Parameter
|
||||||
from torchtyping import TensorType
|
from torchtyping import TensorType
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RaySamples
|
from nerfstudio.cameras.rays import RaySamples
|
||||||
from nerfstudio.field_components.embedding import Embedding
|
from nerfstudio.field_components.embedding import Embedding
|
||||||
@@ -80,13 +79,13 @@ class SDFFieldConfig(FieldConfig):
|
|||||||
appearance_embedding_dim: int = 32
|
appearance_embedding_dim: int = 32
|
||||||
"""Dimension of appearance embedding"""
|
"""Dimension of appearance embedding"""
|
||||||
use_appearance_embedding: bool = False
|
use_appearance_embedding: bool = False
|
||||||
"""Dimension of appearance embedding"""
|
"""Whether to use appearance embedding"""
|
||||||
bias: float = 0.8
|
bias: float = 0.8
|
||||||
"""sphere size of geometric initializaion"""
|
"""Sphere size of geometric initialization"""
|
||||||
geometric_init: bool = True
|
geometric_init: bool = True
|
||||||
"""Whether to use geometric initialization"""
|
"""Whether to use geometric initialization"""
|
||||||
inside_outside: bool = True
|
inside_outside: bool = True
|
||||||
"""whether to revert signed distance value, set to True for indoor scene"""
|
"""Whether to revert signed distance value, set to True for indoor scene"""
|
||||||
weight_norm: bool = True
|
weight_norm: bool = True
|
||||||
"""Whether to use weight norm for linear layer"""
|
"""Whether to use weight norm for linear layer"""
|
||||||
use_grid_feature: bool = False
|
use_grid_feature: bool = False
|
||||||
@@ -257,8 +256,8 @@ class SDFField(Field):
|
|||||||
"""forward the geonetwork"""
|
"""forward the geonetwork"""
|
||||||
if self.use_grid_feature:
|
if self.use_grid_feature:
|
||||||
positions = self.spatial_distortion(inputs)
|
positions = self.spatial_distortion(inputs)
|
||||||
|
# map range [-2, 2] to [0, 1]
|
||||||
positions = (positions + 1.0) / 2.0
|
positions = (positions + 2.0) / 4.0
|
||||||
feature = self.encoding(positions)
|
feature = self.encoding(positions)
|
||||||
else:
|
else:
|
||||||
feature = torch.zeros_like(inputs[:, :1].repeat(1, self.encoding.n_output_dims))
|
feature = torch.zeros_like(inputs[:, :1].repeat(1, self.encoding.n_output_dims))
|
||||||
|
|||||||
@@ -16,11 +16,11 @@
|
|||||||
Collection of Losses.
|
Collection of Losses.
|
||||||
"""
|
"""
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
from typing import Dict, Literal
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
from torch import nn
|
from torch import nn
|
||||||
from torchtyping import TensorType
|
from torchtyping import TensorType
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RaySamples
|
from nerfstudio.cameras.rays import RaySamples
|
||||||
from nerfstudio.utils.math import masked_reduction, normalized_depth_scale_and_shift
|
from nerfstudio.utils.math import masked_reduction, normalized_depth_scale_and_shift
|
||||||
@@ -485,3 +485,57 @@ class ScaleAndShiftInvariantLoss(nn.Module):
|
|||||||
return self.__prediction_ssi
|
return self.__prediction_ssi
|
||||||
|
|
||||||
prediction_ssi = property(__get_prediction_ssi)
|
prediction_ssi = property(__get_prediction_ssi)
|
||||||
|
|
||||||
|
|
||||||
|
def tv_loss(grids: TensorType["grids", "feature_dim", "row", "column"]) -> TensorType[()]:
|
||||||
|
"""
|
||||||
|
https://github.com/apchenstu/TensoRF/blob/4ec894dc1341a2201fe13ae428631b58458f105d/utils.py#L139
|
||||||
|
|
||||||
|
Args:
|
||||||
|
grids: stacks of explicit feature grids (stacked at dim 0)
|
||||||
|
Returns:
|
||||||
|
average total variation loss for neighbor rows and columns.
|
||||||
|
"""
|
||||||
|
number_of_grids = grids.shape[0]
|
||||||
|
h_tv_count = grids[:, :, 1:, :].shape[1] * grids[:, :, 1:, :].shape[2] * grids[:, :, 1:, :].shape[3]
|
||||||
|
w_tv_count = grids[:, :, :, 1:].shape[1] * grids[:, :, :, 1:].shape[2] * grids[:, :, :, 1:].shape[3]
|
||||||
|
h_tv = torch.pow((grids[:, :, 1:, :] - grids[:, :, :-1, :]), 2).sum()
|
||||||
|
w_tv = torch.pow((grids[:, :, :, 1:] - grids[:, :, :, :-1]), 2).sum()
|
||||||
|
return 2 * (h_tv / h_tv_count + w_tv / w_tv_count) / number_of_grids
|
||||||
|
|
||||||
|
|
||||||
|
class _GradientScaler(torch.autograd.Function): # typing: ignore, pylint: disable=abstract-method
|
||||||
|
"""
|
||||||
|
Scale gradients by a constant factor.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def forward(ctx, value, scaling): # pylint: disable=arguments-differ
|
||||||
|
ctx.save_for_backward(scaling)
|
||||||
|
return value, scaling
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def backward(ctx, output_grad, grad_scaling): # pylint: disable=arguments-differ
|
||||||
|
(scaling,) = ctx.saved_tensors
|
||||||
|
return output_grad * scaling, grad_scaling
|
||||||
|
|
||||||
|
|
||||||
|
def scale_gradients_by_distance_squared(
|
||||||
|
field_outputs: Dict[str, torch.Tensor], ray_samples: RaySamples
|
||||||
|
) -> Dict[str, torch.Tensor]:
|
||||||
|
"""
|
||||||
|
Scale gradients by the ray distance to the pixel
|
||||||
|
as suggested in `Radiance Field Gradient Scaling for Unbiased Near-Camera Training` paper
|
||||||
|
|
||||||
|
Note: The scaling is applied on the interval of [0, 1] along the ray!
|
||||||
|
|
||||||
|
Example:
|
||||||
|
GradientLoss should be called right after obtaining the densities and colors from the field. ::
|
||||||
|
>>> field_outputs = scale_gradient_by_distance_squared(field_outputs, ray_samples)
|
||||||
|
"""
|
||||||
|
out = {}
|
||||||
|
ray_dist = (ray_samples.frustums.starts + ray_samples.frustums.ends) / 2
|
||||||
|
scaling = torch.square(ray_dist).clamp(0, 1)
|
||||||
|
for key, value in field_outputs.items():
|
||||||
|
out[key], _ = _GradientScaler.apply(value, scaling)
|
||||||
|
return out
|
||||||
@@ -384,7 +384,6 @@ class VolumetricSampler(Sampler):
|
|||||||
occupancy_grid: OccGridEstimator,
|
occupancy_grid: OccGridEstimator,
|
||||||
density_fn: Optional[Callable[[TensorType[..., 3]], TensorType[..., 1]]] = None,
|
density_fn: Optional[Callable[[TensorType[..., 3]], TensorType[..., 1]]] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
super().__init__()
|
super().__init__()
|
||||||
assert occupancy_grid is not None
|
assert occupancy_grid is not None
|
||||||
self.density_fn = density_fn
|
self.density_fn = density_fn
|
||||||
@@ -655,7 +654,6 @@ class NeuSSampler(Sampler):
|
|||||||
base_variance = self.base_variance
|
base_variance = self.base_variance
|
||||||
|
|
||||||
while total_iters < self.num_upsample_steps:
|
while total_iters < self.num_upsample_steps:
|
||||||
|
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
new_sdf = sdf_fn(new_samples)
|
new_sdf = sdf_fn(new_samples)
|
||||||
|
|
||||||
|
|||||||
@@ -28,13 +28,12 @@ Example:
|
|||||||
"""
|
"""
|
||||||
import contextlib
|
import contextlib
|
||||||
import math
|
import math
|
||||||
from typing import Generator, Optional, Union
|
from typing import Generator, Literal, Optional, Union
|
||||||
|
|
||||||
import nerfacc
|
import nerfacc
|
||||||
import torch
|
import torch
|
||||||
from torch import nn
|
from torch import nn
|
||||||
from torchtyping import TensorType
|
from torchtyping import TensorType
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RaySamples
|
from nerfstudio.cameras.rays import RaySamples
|
||||||
from nerfstudio.utils import colors
|
from nerfstudio.utils import colors
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ from __future__ import annotations
|
|||||||
|
|
||||||
from abc import abstractmethod
|
from abc import abstractmethod
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Dict, List, Tuple, Type
|
from typing import Dict, List, Literal, Tuple, Type
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
@@ -28,7 +28,6 @@ from torch.nn import Parameter
|
|||||||
from torchmetrics import PeakSignalNoiseRatio
|
from torchmetrics import PeakSignalNoiseRatio
|
||||||
from torchmetrics.functional import structural_similarity_index_measure
|
from torchmetrics.functional import structural_similarity_index_measure
|
||||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RayBundle
|
from nerfstudio.cameras.rays import RayBundle
|
||||||
from nerfstudio.field_components.encodings import NeRFEncoding
|
from nerfstudio.field_components.encodings import NeRFEncoding
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ Implementation of Instant NGP.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Dict, List, Optional, Tuple, Type
|
from typing import Dict, List, Literal, Optional, Tuple, Type
|
||||||
|
|
||||||
import nerfacc
|
import nerfacc
|
||||||
import torch
|
import torch
|
||||||
@@ -27,7 +27,6 @@ from torch.nn import Parameter
|
|||||||
from torchmetrics import PeakSignalNoiseRatio
|
from torchmetrics import PeakSignalNoiseRatio
|
||||||
from torchmetrics.functional import structural_similarity_index_measure
|
from torchmetrics.functional import structural_similarity_index_measure
|
||||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RayBundle
|
from nerfstudio.cameras.rays import RayBundle
|
||||||
from nerfstudio.engine.callbacks import (
|
from nerfstudio.engine.callbacks import (
|
||||||
@@ -233,7 +232,6 @@ class NGPModel(Model):
|
|||||||
def get_image_metrics_and_images(
|
def get_image_metrics_and_images(
|
||||||
self, outputs: Dict[str, torch.Tensor], batch: Dict[str, torch.Tensor]
|
self, outputs: Dict[str, torch.Tensor], batch: Dict[str, torch.Tensor]
|
||||||
) -> Tuple[Dict[str, float], Dict[str, torch.Tensor]]:
|
) -> Tuple[Dict[str, float], Dict[str, torch.Tensor]]:
|
||||||
|
|
||||||
image = batch["image"].to(self.device)
|
image = batch["image"].to(self.device)
|
||||||
rgb = outputs["rgb"]
|
rgb = outputs["rgb"]
|
||||||
acc = colormaps.apply_colormap(outputs["accumulation"])
|
acc = colormaps.apply_colormap(outputs["accumulation"])
|
||||||
|
|||||||
@@ -96,7 +96,6 @@ class MipNerfModel(Model):
|
|||||||
return param_groups
|
return param_groups
|
||||||
|
|
||||||
def get_outputs(self, ray_bundle: RayBundle):
|
def get_outputs(self, ray_bundle: RayBundle):
|
||||||
|
|
||||||
if self.field is None:
|
if self.field is None:
|
||||||
raise ValueError("populate_fields() must be called before get_outputs")
|
raise ValueError("populate_fields() must be called before get_outputs")
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ NeRF implementation that combines many recent advancements.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Dict, List, Tuple, Type
|
from typing import Dict, List, Literal, Tuple, Type
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
@@ -27,9 +27,8 @@ from torch.nn import Parameter
|
|||||||
from torchmetrics import PeakSignalNoiseRatio
|
from torchmetrics import PeakSignalNoiseRatio
|
||||||
from torchmetrics.functional import structural_similarity_index_measure
|
from torchmetrics.functional import structural_similarity_index_measure
|
||||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RayBundle
|
from nerfstudio.cameras.rays import RayBundle, RaySamples
|
||||||
from nerfstudio.engine.callbacks import (
|
from nerfstudio.engine.callbacks import (
|
||||||
TrainingCallback,
|
TrainingCallback,
|
||||||
TrainingCallbackAttributes,
|
TrainingCallbackAttributes,
|
||||||
@@ -45,6 +44,7 @@ from nerfstudio.model_components.losses import (
|
|||||||
interlevel_loss,
|
interlevel_loss,
|
||||||
orientation_loss,
|
orientation_loss,
|
||||||
pred_normal_loss,
|
pred_normal_loss,
|
||||||
|
scale_gradients_by_distance_squared,
|
||||||
)
|
)
|
||||||
from nerfstudio.model_components.ray_samplers import (
|
from nerfstudio.model_components.ray_samplers import (
|
||||||
ProposalNetworkSampler,
|
ProposalNetworkSampler,
|
||||||
@@ -128,6 +128,8 @@ class NerfactoModelConfig(ModelConfig):
|
|||||||
"""Whether to predict normals or not."""
|
"""Whether to predict normals or not."""
|
||||||
disable_scene_contraction: bool = False
|
disable_scene_contraction: bool = False
|
||||||
"""Whether to disable scene contraction or not."""
|
"""Whether to disable scene contraction or not."""
|
||||||
|
use_gradient_scaling: bool = False
|
||||||
|
"""Use gradient scaler where the gradients are lower for points closer to the camera."""
|
||||||
|
|
||||||
|
|
||||||
class NerfactoModel(Model):
|
class NerfactoModel(Model):
|
||||||
@@ -263,8 +265,12 @@ class NerfactoModel(Model):
|
|||||||
return callbacks
|
return callbacks
|
||||||
|
|
||||||
def get_outputs(self, ray_bundle: RayBundle):
|
def get_outputs(self, ray_bundle: RayBundle):
|
||||||
|
ray_samples: RaySamples
|
||||||
ray_samples, weights_list, ray_samples_list = self.proposal_sampler(ray_bundle, density_fns=self.density_fns)
|
ray_samples, weights_list, ray_samples_list = self.proposal_sampler(ray_bundle, density_fns=self.density_fns)
|
||||||
field_outputs = self.field(ray_samples, compute_normals=self.config.predict_normals)
|
field_outputs = self.field(ray_samples, compute_normals=self.config.predict_normals)
|
||||||
|
if self.config.use_gradient_scaling:
|
||||||
|
field_outputs = scale_gradients_by_distance_squared(field_outputs, ray_samples)
|
||||||
|
|
||||||
weights = ray_samples.get_weights(field_outputs[FieldHeadNames.DENSITY])
|
weights = ray_samples.get_weights(field_outputs[FieldHeadNames.DENSITY])
|
||||||
weights_list.append(weights)
|
weights_list.append(weights)
|
||||||
ray_samples_list.append(ray_samples)
|
ray_samples_list.append(ray_samples)
|
||||||
|
|||||||
@@ -20,14 +20,13 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import functools
|
import functools
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Dict, List, Type
|
from typing import Dict, List, Literal, Type
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
from torchmetrics import PeakSignalNoiseRatio
|
from torchmetrics import PeakSignalNoiseRatio
|
||||||
from torchmetrics.functional import structural_similarity_index_measure
|
from torchmetrics.functional import structural_similarity_index_measure
|
||||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RayBundle
|
from nerfstudio.cameras.rays import RayBundle
|
||||||
from nerfstudio.field_components.field_heads import FieldHeadNames
|
from nerfstudio.field_components.field_heads import FieldHeadNames
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ Implementation of NeRFPlayer (https://arxiv.org/abs/2210.15947) with InstantNGP
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import List, Type
|
from typing import List, Literal, Type
|
||||||
|
|
||||||
import nerfacc
|
import nerfacc
|
||||||
import torch
|
import torch
|
||||||
@@ -27,7 +27,6 @@ from torch.nn import Parameter
|
|||||||
from torchmetrics import PeakSignalNoiseRatio
|
from torchmetrics import PeakSignalNoiseRatio
|
||||||
from torchmetrics.functional import structural_similarity_index_measure
|
from torchmetrics.functional import structural_similarity_index_measure
|
||||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RayBundle
|
from nerfstudio.cameras.rays import RayBundle
|
||||||
from nerfstudio.engine.callbacks import (
|
from nerfstudio.engine.callbacks import (
|
||||||
|
|||||||
@@ -258,7 +258,6 @@ class SemanticNerfWModel(Model):
|
|||||||
def get_image_metrics_and_images(
|
def get_image_metrics_and_images(
|
||||||
self, outputs: Dict[str, torch.Tensor], batch: Dict[str, torch.Tensor]
|
self, outputs: Dict[str, torch.Tensor], batch: Dict[str, torch.Tensor]
|
||||||
) -> Tuple[Dict[str, float], Dict[str, torch.Tensor]]:
|
) -> Tuple[Dict[str, float], Dict[str, torch.Tensor]]:
|
||||||
|
|
||||||
image = batch["image"].to(self.device)
|
image = batch["image"].to(self.device)
|
||||||
rgb = outputs["rgb"]
|
rgb = outputs["rgb"]
|
||||||
rgb = torch.clamp(rgb, min=0, max=1)
|
rgb = torch.clamp(rgb, min=0, max=1)
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ TensorRF implementation.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Dict, List, Tuple, Type
|
from typing import Dict, List, Literal, Tuple, Type
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import torch
|
import torch
|
||||||
@@ -27,7 +27,6 @@ from torch.nn import Parameter
|
|||||||
from torchmetrics import PeakSignalNoiseRatio
|
from torchmetrics import PeakSignalNoiseRatio
|
||||||
from torchmetrics.functional import structural_similarity_index_measure
|
from torchmetrics.functional import structural_similarity_index_measure
|
||||||
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.cameras.rays import RayBundle
|
from nerfstudio.cameras.rays import RayBundle
|
||||||
from nerfstudio.configs.config_utils import to_immutable_dict
|
from nerfstudio.configs.config_utils import to_immutable_dict
|
||||||
@@ -44,7 +43,7 @@ from nerfstudio.field_components.encodings import (
|
|||||||
)
|
)
|
||||||
from nerfstudio.field_components.field_heads import FieldHeadNames
|
from nerfstudio.field_components.field_heads import FieldHeadNames
|
||||||
from nerfstudio.fields.tensorf_field import TensoRFField
|
from nerfstudio.fields.tensorf_field import TensoRFField
|
||||||
from nerfstudio.model_components.losses import MSELoss
|
from nerfstudio.model_components.losses import MSELoss, tv_loss
|
||||||
from nerfstudio.model_components.ray_samplers import PDFSampler, UniformSampler
|
from nerfstudio.model_components.ray_samplers import PDFSampler, UniformSampler
|
||||||
from nerfstudio.model_components.renderers import (
|
from nerfstudio.model_components.renderers import (
|
||||||
AccumulationRenderer,
|
AccumulationRenderer,
|
||||||
@@ -68,7 +67,14 @@ class TensoRFModelConfig(ModelConfig):
|
|||||||
"""final render resolution"""
|
"""final render resolution"""
|
||||||
upsampling_iters: Tuple[int, ...] = (2000, 3000, 4000, 5500, 7000)
|
upsampling_iters: Tuple[int, ...] = (2000, 3000, 4000, 5500, 7000)
|
||||||
"""specifies a list of iteration step numbers to perform upsampling"""
|
"""specifies a list of iteration step numbers to perform upsampling"""
|
||||||
loss_coefficients: Dict[str, float] = to_immutable_dict({"rgb_loss": 1.0})
|
loss_coefficients: Dict[str, float] = to_immutable_dict(
|
||||||
|
{
|
||||||
|
"rgb_loss": 1.0,
|
||||||
|
"tv_reg_density": 1e-3,
|
||||||
|
"tv_reg_color": 1e-4,
|
||||||
|
"l1_reg": 5e-4,
|
||||||
|
}
|
||||||
|
)
|
||||||
"""Loss specific weights."""
|
"""Loss specific weights."""
|
||||||
num_samples: int = 50
|
num_samples: int = 50
|
||||||
"""Number of samples in field evaluation"""
|
"""Number of samples in field evaluation"""
|
||||||
@@ -81,6 +87,8 @@ class TensoRFModelConfig(ModelConfig):
|
|||||||
appearance_dim: int = 27
|
appearance_dim: int = 27
|
||||||
"""Number of channels for color encoding"""
|
"""Number of channels for color encoding"""
|
||||||
tensorf_encoding: Literal["triplane", "vm", "cp"] = "vm"
|
tensorf_encoding: Literal["triplane", "vm", "cp"] = "vm"
|
||||||
|
regularization: Literal["none", "l1", "tv"] = "l1"
|
||||||
|
"""Regularization method used in tensorf paper"""
|
||||||
|
|
||||||
|
|
||||||
class TensoRFModel(Model):
|
class TensoRFModel(Model):
|
||||||
@@ -242,6 +250,10 @@ class TensoRFModel(Model):
|
|||||||
if self.config.enable_collider:
|
if self.config.enable_collider:
|
||||||
self.collider = AABBBoxCollider(scene_box=self.scene_box)
|
self.collider = AABBBoxCollider(scene_box=self.scene_box)
|
||||||
|
|
||||||
|
# regularizations
|
||||||
|
if self.config.tensorf_encoding == "cp" and self.config.regularization == "tv":
|
||||||
|
raise RuntimeError("TV reg not supported for CP decomposition")
|
||||||
|
|
||||||
def get_param_groups(self) -> Dict[str, List[Parameter]]:
|
def get_param_groups(self) -> Dict[str, List[Parameter]]:
|
||||||
param_groups = {}
|
param_groups = {}
|
||||||
|
|
||||||
@@ -296,6 +308,20 @@ class TensoRFModel(Model):
|
|||||||
rgb_loss = self.rgb_loss(image, outputs["rgb"])
|
rgb_loss = self.rgb_loss(image, outputs["rgb"])
|
||||||
|
|
||||||
loss_dict = {"rgb_loss": rgb_loss}
|
loss_dict = {"rgb_loss": rgb_loss}
|
||||||
|
|
||||||
|
if self.config.regularization == "l1":
|
||||||
|
l1_parameters = []
|
||||||
|
for parameter in self.field.density_encoding.parameters():
|
||||||
|
l1_parameters.append(parameter.view(-1))
|
||||||
|
loss_dict["l1_reg"] = torch.abs(torch.cat(l1_parameters)).mean()
|
||||||
|
elif self.config.regularization == "tv":
|
||||||
|
loss_dict["tv_reg_density"] = tv_loss(self.field.density_encoding.plane_coef)
|
||||||
|
loss_dict["tv_reg_color"] = tv_loss(self.field.color_encoding.plane_coef)
|
||||||
|
elif self.config.regularization == "none":
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Regularization {self.config.regularization} not supported")
|
||||||
|
|
||||||
loss_dict = misc.scale_dict(loss_dict, self.config.loss_coefficients)
|
loss_dict = misc.scale_dict(loss_dict, self.config.loss_coefficients)
|
||||||
return loss_dict
|
return loss_dict
|
||||||
|
|
||||||
|
|||||||
@@ -135,7 +135,6 @@ class NeRFModel(Model):
|
|||||||
return param_groups
|
return param_groups
|
||||||
|
|
||||||
def get_outputs(self, ray_bundle: RayBundle):
|
def get_outputs(self, ray_bundle: RayBundle):
|
||||||
|
|
||||||
if self.field_coarse is None or self.field_fine is None:
|
if self.field_coarse is None or self.field_fine is None:
|
||||||
raise ValueError("populate_fields() must be called before get_outputs")
|
raise ValueError("populate_fields() must be called before get_outputs")
|
||||||
|
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ import typing
|
|||||||
from abc import abstractmethod
|
from abc import abstractmethod
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from time import time
|
from time import time
|
||||||
from typing import Any, Dict, List, Mapping, Optional, Type, Union, cast
|
from typing import Any, Dict, List, Literal, Mapping, Optional, Type, Union, cast
|
||||||
|
|
||||||
import mediapy
|
import mediapy
|
||||||
import torch
|
import torch
|
||||||
@@ -37,7 +37,6 @@ from torch import nn
|
|||||||
from torch.cuda.amp.grad_scaler import GradScaler
|
from torch.cuda.amp.grad_scaler import GradScaler
|
||||||
from torch.nn import Parameter
|
from torch.nn import Parameter
|
||||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.configs import base_config as cfg
|
from nerfstudio.configs import base_config as cfg
|
||||||
from nerfstudio.data.datamanagers.base_datamanager import (
|
from nerfstudio.data.datamanagers.base_datamanager import (
|
||||||
|
|||||||
@@ -17,11 +17,9 @@ A pipeline that dynamically chooses the number of rays to sample.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from typing import Optional, Type
|
from typing import Literal, Type
|
||||||
|
|
||||||
import torch
|
import torch
|
||||||
from torch.cuda.amp.grad_scaler import GradScaler
|
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManager
|
from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManager
|
||||||
from nerfstudio.pipelines.base_pipeline import VanillaPipeline, VanillaPipelineConfig
|
from nerfstudio.pipelines.base_pipeline import VanillaPipeline, VanillaPipelineConfig
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
Module that keeps all registered plugins and allows for plugin discovery.
|
Module that keeps all registered plugins and allows for plugin discovery.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import importlib
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
import typing as t
|
import typing as t
|
||||||
|
|
||||||
@@ -34,6 +36,7 @@ CONSOLE = Console(width=120)
|
|||||||
def discover_methods() -> t.Tuple[t.Dict[str, TrainerConfig], t.Dict[str, str]]:
|
def discover_methods() -> t.Tuple[t.Dict[str, TrainerConfig], t.Dict[str, str]]:
|
||||||
"""
|
"""
|
||||||
Discovers all methods registered using the `nerfstudio.method_configs` entrypoint.
|
Discovers all methods registered using the `nerfstudio.method_configs` entrypoint.
|
||||||
|
And also methods in the NERFSTUDIO_METHOD_CONFIGS environment variable.
|
||||||
"""
|
"""
|
||||||
methods = {}
|
methods = {}
|
||||||
descriptions = {}
|
descriptions = {}
|
||||||
@@ -48,4 +51,22 @@ def discover_methods() -> t.Tuple[t.Dict[str, TrainerConfig], t.Dict[str, str]]:
|
|||||||
specification = t.cast(MethodSpecification, specification)
|
specification = t.cast(MethodSpecification, specification)
|
||||||
methods[specification.config.method_name] = specification.config
|
methods[specification.config.method_name] = specification.config
|
||||||
descriptions[specification.config.method_name] = specification.description
|
descriptions[specification.config.method_name] = specification.description
|
||||||
|
|
||||||
|
if "NERFSTUDIO_METHOD_CONFIGS" in os.environ:
|
||||||
|
try:
|
||||||
|
strings = os.environ["NERFSTUDIO_METHOD_CONFIGS"].split(",")
|
||||||
|
for definition in strings:
|
||||||
|
if not definition:
|
||||||
|
continue
|
||||||
|
name, path = definition.split("=")
|
||||||
|
CONSOLE.print(f"[bold green]Info: Loading method {name} from environment variable")
|
||||||
|
module, config_name = path.split(":")
|
||||||
|
method_config = getattr(importlib.import_module(module), config_name)
|
||||||
|
assert isinstance(method_config, MethodSpecification)
|
||||||
|
methods[name] = method_config.config
|
||||||
|
descriptions[name] = method_config.description
|
||||||
|
except Exception: # pylint: disable=broad-except
|
||||||
|
CONSOLE.print_exception()
|
||||||
|
CONSOLE.print("[bold red]Error: Could not load methods from environment variable NERFSTUDIO_METHOD_CONFIGS")
|
||||||
|
|
||||||
return methods, descriptions
|
return methods, descriptions
|
||||||
@@ -16,10 +16,9 @@
|
|||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Dict, List, Optional, Tuple
|
from typing import Dict, List, Literal, Optional, Tuple
|
||||||
|
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.process_data import colmap_utils, hloc_utils, process_data_utils
|
from nerfstudio.process_data import colmap_utils, hloc_utils, process_data_utils
|
||||||
from nerfstudio.process_data.base_converter_to_nerfstudio_dataset import (
|
from nerfstudio.process_data.base_converter_to_nerfstudio_dataset import (
|
||||||
@@ -182,7 +181,11 @@ class ColmapConverterToNerfstudioDataset(BaseConverterToNerfstudioDataset):
|
|||||||
"""
|
"""
|
||||||
self.absolute_colmap_path.mkdir(parents=True, exist_ok=True)
|
self.absolute_colmap_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
(sfm_tool, feature_type, matcher_type,) = process_data_utils.find_tool_feature_matcher_combination(
|
(
|
||||||
|
sfm_tool,
|
||||||
|
feature_type,
|
||||||
|
matcher_type,
|
||||||
|
) = process_data_utils.find_tool_feature_matcher_combination(
|
||||||
self.sfm_tool, self.feature_type, self.matcher_type
|
self.sfm_tool, self.feature_type, self.matcher_type
|
||||||
)
|
)
|
||||||
# check that sfm_tool is hloc if using refine_pixsfm
|
# check that sfm_tool is hloc if using refine_pixsfm
|
||||||
|
|||||||
@@ -13,12 +13,12 @@
|
|||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Tools supporting the execution of COLMAP and preparation of COLMAP-based datasets for nerstudio training.
|
Tools supporting the execution of COLMAP and preparation of COLMAP-based datasets for nerfstudio training.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, Literal, Optional
|
||||||
|
|
||||||
import appdirs
|
import appdirs
|
||||||
import cv2
|
import cv2
|
||||||
@@ -27,7 +27,6 @@ import requests
|
|||||||
import torch
|
import torch
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from rich.progress import track
|
from rich.progress import track
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
# TODO(1480) use pycolmap instead of colmap_parsing_utils
|
# TODO(1480) use pycolmap instead of colmap_parsing_utils
|
||||||
# import pycolmap
|
# import pycolmap
|
||||||
@@ -115,9 +114,7 @@ def run_colmap(
|
|||||||
colmap_version = get_colmap_version(colmap_cmd)
|
colmap_version = get_colmap_version(colmap_cmd)
|
||||||
|
|
||||||
colmap_database_path = colmap_dir / "database.db"
|
colmap_database_path = colmap_dir / "database.db"
|
||||||
if colmap_database_path.exists():
|
colmap_database_path.unlink(missing_ok=True)
|
||||||
# Can't use missing_ok argument because of Python 3.7 compatibility.
|
|
||||||
colmap_database_path.unlink()
|
|
||||||
|
|
||||||
# Feature extraction
|
# Feature extraction
|
||||||
feature_extractor_cmd = [
|
feature_extractor_cmd = [
|
||||||
|
|||||||
@@ -21,9 +21,9 @@ Requires hloc module from : https://github.com/cvg/Hierarchical-Localization
|
|||||||
|
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
from nerfstudio.process_data.process_data_utils import CameraModel
|
from nerfstudio.process_data.process_data_utils import CameraModel
|
||||||
|
|
||||||
|
|||||||
+1
@@ -56,6 +56,7 @@ class ImagesToNerfstudioDataset(ColmapConverterToNerfstudioDataset):
|
|||||||
self.data = equirect_utils.generate_planar_projections_from_equirectangular(
|
self.data = equirect_utils.generate_planar_projections_from_equirectangular(
|
||||||
self.data, pers_size, self.images_per_equirect, crop_factor=self.crop_factor
|
self.data, pers_size, self.images_per_equirect, crop_factor=self.crop_factor
|
||||||
)
|
)
|
||||||
|
self.camera_type = "perspective"
|
||||||
|
|
||||||
summary_log = []
|
summary_log = []
|
||||||
|
|
||||||
@@ -61,12 +61,17 @@ def metashape_to_json( # pylint: disable=too-many-statements
|
|||||||
if sensors is None:
|
if sensors is None:
|
||||||
raise ValueError("No sensors found")
|
raise ValueError("No sensors found")
|
||||||
|
|
||||||
calibrated_sensors = [sensor for sensor in sensors if sensor.find("calibration")]
|
calibrated_sensors = [
|
||||||
|
sensor for sensor in sensors if sensor.get("type") == "spherical" or sensor.find("calibration")
|
||||||
|
]
|
||||||
if not calibrated_sensors:
|
if not calibrated_sensors:
|
||||||
raise ValueError("No calibrated sensor found in Metashape XML")
|
raise ValueError("No calibrated sensor found in Metashape XML")
|
||||||
sensor_type = [s.get("type") for s in calibrated_sensors]
|
sensor_type = [s.get("type") for s in calibrated_sensors]
|
||||||
if sensor_type.count(sensor_type[0]) != len(sensor_type):
|
if sensor_type.count(sensor_type[0]) != len(sensor_type):
|
||||||
raise ValueError("All Metashape sensors do not have the same sensor type")
|
raise ValueError(
|
||||||
|
"All Metashape sensors do not have the same sensor type. "
|
||||||
|
"nerfstudio does not support per-frame camera_model."
|
||||||
|
)
|
||||||
data = {}
|
data = {}
|
||||||
if sensor_type[0] == "frame":
|
if sensor_type[0] == "frame":
|
||||||
data["camera_model"] = CAMERA_MODELS["perspective"].value
|
data["camera_model"] = CAMERA_MODELS["perspective"].value
|
||||||
@@ -87,46 +92,54 @@ def metashape_to_json( # pylint: disable=too-many-statements
|
|||||||
s["h"] = int(resolution.get("height")) # type: ignore
|
s["h"] = int(resolution.get("height")) # type: ignore
|
||||||
|
|
||||||
calib = sensor.find("calibration")
|
calib = sensor.find("calibration")
|
||||||
f = calib.find("f")
|
if calib is None:
|
||||||
if f is not None:
|
assert sensor_type[0] == "spherical", "Only spherical sensors should have no intrinsics"
|
||||||
|
s["fl_x"] = s["w"] / 2.0
|
||||||
|
s["fl_y"] = s["h"]
|
||||||
|
s["cx"] = s["w"] / 2.0
|
||||||
|
s["cy"] = s["h"] / 2.0
|
||||||
|
else:
|
||||||
|
f = calib.find("f")
|
||||||
|
assert f is not None, "Focal length not found in Metashape xml"
|
||||||
s["fl_x"] = s["fl_y"] = float(f.text) # type: ignore
|
s["fl_x"] = s["fl_y"] = float(f.text) # type: ignore
|
||||||
s["cx"] = _find_param(calib, "cx") + s["w"] / 2.0 # type: ignore
|
s["cx"] = _find_param(calib, "cx") + s["w"] / 2.0 # type: ignore
|
||||||
s["cy"] = _find_param(calib, "cy") + s["h"] / 2.0 # type: ignore
|
s["cy"] = _find_param(calib, "cy") + s["h"] / 2.0 # type: ignore
|
||||||
|
|
||||||
s["k1"] = _find_param(calib, "k1")
|
s["k1"] = _find_param(calib, "k1")
|
||||||
s["k2"] = _find_param(calib, "k2")
|
s["k2"] = _find_param(calib, "k2")
|
||||||
s["k3"] = _find_param(calib, "k3")
|
s["k3"] = _find_param(calib, "k3")
|
||||||
s["k4"] = _find_param(calib, "k4")
|
s["k4"] = _find_param(calib, "k4")
|
||||||
s["p1"] = _find_param(calib, "p1")
|
s["p1"] = _find_param(calib, "p1")
|
||||||
s["p2"] = _find_param(calib, "p2")
|
s["p2"] = _find_param(calib, "p2")
|
||||||
|
|
||||||
sensor_dict[sensor.get("id")] = s
|
sensor_dict[sensor.get("id")] = s
|
||||||
|
|
||||||
components = chunk.find("components")
|
components = chunk.find("components")
|
||||||
component_dict = {}
|
if components is not None:
|
||||||
for component in components:
|
component_dict = {}
|
||||||
transform = component.find("transform")
|
for component in components:
|
||||||
if transform is not None:
|
transform = component.find("transform")
|
||||||
rotation = transform.find("rotation")
|
if transform is not None:
|
||||||
if rotation is None:
|
rotation = transform.find("rotation")
|
||||||
r = np.eye(3)
|
if rotation is None:
|
||||||
else:
|
r = np.eye(3)
|
||||||
r = np.array([float(x) for x in rotation.text.split()]).reshape((3, 3))
|
else:
|
||||||
translation = transform.find("translation")
|
r = np.array([float(x) for x in rotation.text.split()]).reshape((3, 3))
|
||||||
if translation is None:
|
translation = transform.find("translation")
|
||||||
t = np.zeros(3)
|
if translation is None:
|
||||||
else:
|
t = np.zeros(3)
|
||||||
t = np.array([float(x) for x in translation.text.split()])
|
else:
|
||||||
scale = transform.find("scale")
|
t = np.array([float(x) for x in translation.text.split()])
|
||||||
if scale is None:
|
scale = transform.find("scale")
|
||||||
s = 1.0
|
if scale is None:
|
||||||
else:
|
s = 1.0
|
||||||
s = float(scale.text)
|
else:
|
||||||
|
s = float(scale.text)
|
||||||
|
|
||||||
m = np.eye(4)
|
m = np.eye(4)
|
||||||
m[:3, :3] = r
|
m[:3, :3] = r
|
||||||
m[:3, 3] = t / s
|
m[:3, 3] = t / s
|
||||||
component_dict[component.get("id")] = m
|
component_dict[component.get("id")] = m
|
||||||
|
|
||||||
frames = []
|
frames = []
|
||||||
cameras = chunk.find("cameras")
|
cameras = chunk.find("cameras")
|
||||||
@@ -159,9 +172,10 @@ def metashape_to_json( # pylint: disable=too-many-statements
|
|||||||
num_skipped += 1
|
num_skipped += 1
|
||||||
continue
|
continue
|
||||||
transform = np.array([float(x) for x in camera.find("transform").text.split()]).reshape((4, 4))
|
transform = np.array([float(x) for x in camera.find("transform").text.split()]).reshape((4, 4))
|
||||||
component_id = camera.get("component_id")
|
if components is not None:
|
||||||
if component_id in component_dict:
|
component_id = camera.get("component_id")
|
||||||
transform = component_dict[component_id] @ transform
|
if component_id in component_dict:
|
||||||
|
transform = component_dict[component_id] @ transform
|
||||||
transform = transform[[2, 0, 1, 3], :]
|
transform = transform[[2, 0, 1, 3], :]
|
||||||
transform[:, 1:3] *= -1
|
transform[:, 1:3] *= -1
|
||||||
frame["transform_matrix"] = transform.tolist()
|
frame["transform_matrix"] = transform.tolist()
|
||||||
|
|||||||
@@ -20,12 +20,11 @@ import shutil
|
|||||||
import sys
|
import sys
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import List, Optional, Tuple
|
from typing import List, Literal, Optional, OrderedDict, Tuple
|
||||||
|
|
||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from typing_extensions import Literal, OrderedDict
|
|
||||||
|
|
||||||
from nerfstudio.utils.rich_utils import status
|
from nerfstudio.utils.rich_utils import status
|
||||||
from nerfstudio.utils.scripts import run_command
|
from nerfstudio.utils.scripts import run_command
|
||||||
@@ -39,12 +38,13 @@ class CameraModel(Enum):
|
|||||||
|
|
||||||
OPENCV = "OPENCV"
|
OPENCV = "OPENCV"
|
||||||
OPENCV_FISHEYE = "OPENCV_FISHEYE"
|
OPENCV_FISHEYE = "OPENCV_FISHEYE"
|
||||||
|
EQUIRECTANGULAR = "EQUIRECTANGULAR"
|
||||||
|
|
||||||
|
|
||||||
CAMERA_MODELS = {
|
CAMERA_MODELS = {
|
||||||
"perspective": CameraModel.OPENCV,
|
"perspective": CameraModel.OPENCV,
|
||||||
"fisheye": CameraModel.OPENCV_FISHEYE,
|
"fisheye": CameraModel.OPENCV_FISHEYE,
|
||||||
"equirectangular": CameraModel.OPENCV,
|
"equirectangular": CameraModel.EQUIRECTANGULAR,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -91,6 +91,8 @@ class VideoToNerfstudioDataset(ColmapConverterToNerfstudioDataset):
|
|||||||
# remove the temp_images folder
|
# remove the temp_images folder
|
||||||
shutil.rmtree(self.output_dir / "temp_images", ignore_errors=True)
|
shutil.rmtree(self.output_dir / "temp_images", ignore_errors=True)
|
||||||
|
|
||||||
|
self.camera_type = "perspective"
|
||||||
|
|
||||||
# # Create mask
|
# # Create mask
|
||||||
mask_path = process_data_utils.save_mask(
|
mask_path = process_data_utils.save_mask(
|
||||||
image_dir=self.image_dir,
|
image_dir=self.image_dir,
|
||||||
|
|||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# 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.
|
||||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,13 @@
|
|||||||
|
# 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.
|
||||||
+20
-7
@@ -1,3 +1,17 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
nerfstudio_blender.py
|
nerfstudio_blender.py
|
||||||
"""
|
"""
|
||||||
@@ -141,7 +155,6 @@ class CreateJSONCameraPath(bpy.types.Operator):
|
|||||||
keyframe_list = []
|
keyframe_list = []
|
||||||
|
|
||||||
for i, transformed_camera_path_mat_val in enumerate(self.transformed_camera_path_mat):
|
for i, transformed_camera_path_mat_val in enumerate(self.transformed_camera_path_mat):
|
||||||
|
|
||||||
curr_properties = (
|
curr_properties = (
|
||||||
'[["FOV",'
|
'[["FOV",'
|
||||||
+ str(self.fov_list[i])
|
+ str(self.fov_list[i])
|
||||||
@@ -361,7 +374,7 @@ class NerfstudioBgPanel(bpy.types.Panel): # pylint: disable=too-few-public-meth
|
|||||||
self.layout.label(text="Camera path for Nerfstudio")
|
self.layout.label(text="Camera path for Nerfstudio")
|
||||||
|
|
||||||
col = self.layout.column()
|
col = self.layout.column()
|
||||||
for (prop_name, _) in INPUT_PROPERTIES:
|
for prop_name, _ in INPUT_PROPERTIES:
|
||||||
row = col.row()
|
row = col.row()
|
||||||
row.prop(context.scene, prop_name)
|
row.prop(context.scene, prop_name)
|
||||||
|
|
||||||
@@ -385,7 +398,7 @@ class NerfstudioInputPanel(bpy.types.Panel): # pylint: disable=too-few-public-m
|
|||||||
self.layout.label(text="Create Blender Camera From Nerfstudio JSON")
|
self.layout.label(text="Create Blender Camera From Nerfstudio JSON")
|
||||||
col = self.layout.column()
|
col = self.layout.column()
|
||||||
|
|
||||||
for (prop_name, _) in INPUT_PROPERTIES_NS_CAMERA:
|
for prop_name, _ in INPUT_PROPERTIES_NS_CAMERA:
|
||||||
row = col.row()
|
row = col.row()
|
||||||
row.prop(context.scene, prop_name)
|
row.prop(context.scene, prop_name)
|
||||||
|
|
||||||
@@ -425,10 +438,10 @@ OBJ_PROPERTIES = ["NeRF", "RenderCamera"]
|
|||||||
def register():
|
def register():
|
||||||
"""Register classes for UI panel."""
|
"""Register classes for UI panel."""
|
||||||
|
|
||||||
for (prop_name, prop_value) in INPUT_PROPERTIES:
|
for prop_name, prop_value in INPUT_PROPERTIES:
|
||||||
setattr(bpy.types.Scene, prop_name, prop_value)
|
setattr(bpy.types.Scene, prop_name, prop_value)
|
||||||
|
|
||||||
for (prop_name, prop_value) in INPUT_PROPERTIES_NS_CAMERA:
|
for prop_name, prop_value in INPUT_PROPERTIES_NS_CAMERA:
|
||||||
setattr(bpy.types.Scene, prop_name, prop_value)
|
setattr(bpy.types.Scene, prop_name, prop_value)
|
||||||
|
|
||||||
bpy.types.Scene.NeRF = bpy.props.PointerProperty(type=bpy.types.Object)
|
bpy.types.Scene.NeRF = bpy.props.PointerProperty(type=bpy.types.Object)
|
||||||
@@ -440,10 +453,10 @@ def register():
|
|||||||
def unregister():
|
def unregister():
|
||||||
"""Unregister classes for UI panel."""
|
"""Unregister classes for UI panel."""
|
||||||
|
|
||||||
for (prop_name, _) in INPUT_PROPERTIES:
|
for prop_name, _ in INPUT_PROPERTIES:
|
||||||
delattr(bpy.types.Scene, prop_name)
|
delattr(bpy.types.Scene, prop_name)
|
||||||
|
|
||||||
for (prop_name, _) in INPUT_PROPERTIES_NS_CAMERA:
|
for prop_name, _ in INPUT_PROPERTIES_NS_CAMERA:
|
||||||
delattr(bpy.types.Scene, prop_name)
|
delattr(bpy.types.Scene, prop_name)
|
||||||
|
|
||||||
del bpy.types.Scene.NeRF
|
del bpy.types.Scene.NeRF
|
||||||
File renamed without changes.
@@ -0,0 +1,13 @@
|
|||||||
|
# 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.
|
||||||
@@ -1,3 +1,17 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
"""Configuration script for setting up tab completion for nerfstudio in bash and zsh."""
|
"""Configuration script for setting up tab completion for nerfstudio in bash and zsh."""
|
||||||
|
|
||||||
@@ -10,13 +24,13 @@ import shutil
|
|||||||
import stat
|
import stat
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from typing import List, Optional, Union
|
from typing import List, Literal, Optional, Union
|
||||||
|
from typing import get_args as typing_get_args
|
||||||
|
|
||||||
import tyro
|
import tyro
|
||||||
from rich.console import Console
|
from rich.console import Console
|
||||||
from rich.prompt import Confirm
|
from rich.prompt import Confirm
|
||||||
from typing_extensions import Literal, assert_never
|
from typing_extensions import assert_never
|
||||||
from typing_extensions import get_args as typing_get_args
|
|
||||||
|
|
||||||
if sys.version_info < (3, 10):
|
if sys.version_info < (3, 10):
|
||||||
import importlib_metadata
|
import importlib_metadata
|
||||||
File renamed without changes.
File renamed without changes.
+15
-2
@@ -1,7 +1,21 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
import os
|
import os
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Tuple
|
from typing import Literal, Tuple
|
||||||
|
|
||||||
import cv2
|
import cv2
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -10,7 +24,6 @@ from nuscenes.nuscenes import NuScenes as NuScenesDatabase
|
|||||||
from nuscenes.utils.data_classes import Box
|
from nuscenes.utils.data_classes import Box
|
||||||
from nuscenes.utils.geometry_utils import BoxVisibility, view_points
|
from nuscenes.utils.geometry_utils import BoxVisibility, view_points
|
||||||
from tqdm import tqdm
|
from tqdm import tqdm
|
||||||
from typing_extensions import Literal
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# 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.
|
||||||
@@ -1,3 +1,17 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
"""Helper that add tags to notebooks based on cell comments."""
|
"""Helper that add tags to notebooks based on cell comments."""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
@@ -60,7 +74,8 @@ def main(check: bool = False):
|
|||||||
if incorrect_metadata:
|
if incorrect_metadata:
|
||||||
if check:
|
if check:
|
||||||
CONSOLE.print(
|
CONSOLE.print(
|
||||||
f"[bold yellow]{ipath} has incorrect metadata. Call `python scripts.docs.add_nb_tags.py` to add it."
|
f"[bold yellow]{ipath} has incorrect metadata. "
|
||||||
|
"Call `python nerfstudio.scripts.docs.add_nb_tags.py` to add it."
|
||||||
)
|
)
|
||||||
any_missing = True
|
any_missing = True
|
||||||
else:
|
else:
|
||||||
@@ -1,3 +1,17 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
"""Simple yaml debugger"""
|
"""Simple yaml debugger"""
|
||||||
import subprocess
|
import subprocess
|
||||||
@@ -32,7 +46,7 @@ def main(clean_cache: bool = False):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
CONSOLE.print("[green]Adding notebook documentation metadata")
|
CONSOLE.print("[green]Adding notebook documentation metadata")
|
||||||
run_command("python scripts/docs/add_nb_tags.py")
|
run_command("python nerfstudio/scripts/docs/add_nb_tags.py")
|
||||||
|
|
||||||
# Add checks for building documentation
|
# Add checks for building documentation
|
||||||
CONSOLE.print("[green]Building Documentation")
|
CONSOLE.print("[green]Building Documentation")
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# 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.
|
||||||
@@ -1,3 +1,17 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
"""Download datasets and specific captures from the datasets."""
|
"""Download datasets and specific captures from the datasets."""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -1,3 +1,17 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
"""
|
"""
|
||||||
eval.py
|
eval.py
|
||||||
@@ -1,3 +1,17 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
Script for exporting NeRF into other formats.
|
Script for exporting NeRF into other formats.
|
||||||
"""
|
"""
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# 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.
|
||||||
+14
@@ -1,3 +1,17 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
"""Trace Stable Diffusion UNet for speed improvement"""
|
"""Trace Stable Diffusion UNet for speed improvement"""
|
||||||
|
|
||||||
import functools
|
import functools
|
||||||
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user