Add files using upload-large-folder tool
Browse files- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/evaluation.rst +14 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/index.rst +10 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/models/feature_extractor/feature_extractor.rst +9 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/models/feature_extractor/index.rst +7 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/models/visualization/index.rst +6 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/tools.rst +64 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/blending.rst +9 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/camera_conversions.rst +9 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/compositing.rst +9 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/compositor.rst +9 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/index.rst +10 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/rasterize_points.rst +9 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/utils.rst +9 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/README.md +23 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/camera_position_optimization_with_differentiable_rendering.ipynb +587 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/dataloaders_ShapeNetCore_R2N2.ipynb +562 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/deform_source_mesh_to_target_mesh.ipynb +542 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/fit_simple_neural_radiance_field.ipynb +906 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/fit_textured_mesh.ipynb +962 -0
- project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/fit_textured_volume.ipynb +501 -0
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/evaluation.rst
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.implicitron.evaluation
|
| 2 |
+
================================
|
| 3 |
+
|
| 4 |
+
evaluation
|
| 5 |
+
|
| 6 |
+
.. automodule:: pytorch3d.implicitron.evaluation.evaluate_new_view_synthesis
|
| 7 |
+
:members:
|
| 8 |
+
:undoc-members:
|
| 9 |
+
:show-inheritance:
|
| 10 |
+
|
| 11 |
+
.. automodule:: pytorch3d.implicitron.evaluation.evaluator
|
| 12 |
+
:members:
|
| 13 |
+
:undoc-members:
|
| 14 |
+
:show-inheritance:
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/index.rst
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.implicitron
|
| 2 |
+
=====================
|
| 3 |
+
|
| 4 |
+
.. toctree::
|
| 5 |
+
|
| 6 |
+
models/index.rst
|
| 7 |
+
data_basics
|
| 8 |
+
datasets
|
| 9 |
+
evaluation
|
| 10 |
+
tools
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/models/feature_extractor/feature_extractor.rst
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.implicitron.models.feature_extractor.feature_extractor
|
| 2 |
+
================================================================
|
| 3 |
+
|
| 4 |
+
feature_extractor
|
| 5 |
+
|
| 6 |
+
.. automodule:: pytorch3d.implicitron.models.feature_extractor.feature_extractor
|
| 7 |
+
:members:
|
| 8 |
+
:undoc-members:
|
| 9 |
+
:show-inheritance:
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/models/feature_extractor/index.rst
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.implicitron.models.feature_extractor
|
| 2 |
+
==============================================
|
| 3 |
+
|
| 4 |
+
.. toctree::
|
| 5 |
+
|
| 6 |
+
feature_extractor
|
| 7 |
+
resnet_feature_extractor
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/models/visualization/index.rst
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.implicitron.models.visualization
|
| 2 |
+
==========================================
|
| 3 |
+
|
| 4 |
+
.. toctree::
|
| 5 |
+
|
| 6 |
+
render_flyaround
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/implicitron/tools.rst
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.implicitron.tools
|
| 2 |
+
===========================
|
| 3 |
+
|
| 4 |
+
Tools for implicitron
|
| 5 |
+
|
| 6 |
+
.. automodule:: pytorch3d.implicitron.tools.camera_utils
|
| 7 |
+
:members:
|
| 8 |
+
:undoc-members:
|
| 9 |
+
:show-inheritance:
|
| 10 |
+
|
| 11 |
+
.. automodule:: pytorch3d.implicitron.tools.circle_fitting
|
| 12 |
+
:members:
|
| 13 |
+
:undoc-members:
|
| 14 |
+
:show-inheritance:
|
| 15 |
+
|
| 16 |
+
.. automodule:: pytorch3d.implicitron.tools.config
|
| 17 |
+
:members:
|
| 18 |
+
:undoc-members:
|
| 19 |
+
:show-inheritance:
|
| 20 |
+
|
| 21 |
+
.. automodule:: pytorch3d.implicitron.tools.eval_video_trajectory
|
| 22 |
+
:members:
|
| 23 |
+
:undoc-members:
|
| 24 |
+
:show-inheritance:
|
| 25 |
+
|
| 26 |
+
.. automodule:: pytorch3d.implicitron.tools.image_utils
|
| 27 |
+
:members:
|
| 28 |
+
:undoc-members:
|
| 29 |
+
:show-inheritance:
|
| 30 |
+
|
| 31 |
+
.. automodule:: pytorch3d.implicitron.tools.metric_utils
|
| 32 |
+
:members:
|
| 33 |
+
:undoc-members:
|
| 34 |
+
:show-inheritance:
|
| 35 |
+
|
| 36 |
+
.. automodule:: pytorch3d.implicitron.tools.model_io
|
| 37 |
+
:members:
|
| 38 |
+
:undoc-members:
|
| 39 |
+
:show-inheritance:
|
| 40 |
+
|
| 41 |
+
.. automodule:: pytorch3d.implicitron.tools.point_cloud_utils
|
| 42 |
+
:members:
|
| 43 |
+
:undoc-members:
|
| 44 |
+
:show-inheritance:
|
| 45 |
+
|
| 46 |
+
.. automodule:: pytorch3d.implicitron.tools.rasterize_mc
|
| 47 |
+
:members:
|
| 48 |
+
:undoc-members:
|
| 49 |
+
:show-inheritance:
|
| 50 |
+
|
| 51 |
+
.. automodule:: pytorch3d.implicitron.tools.stats
|
| 52 |
+
:members:
|
| 53 |
+
:undoc-members:
|
| 54 |
+
:show-inheritance:
|
| 55 |
+
|
| 56 |
+
.. automodule:: pytorch3d.implicitron.tools.video_writer
|
| 57 |
+
:members:
|
| 58 |
+
:undoc-members:
|
| 59 |
+
:show-inheritance:
|
| 60 |
+
|
| 61 |
+
.. automodule:: pytorch3d.implicitron.tools.vis_utils
|
| 62 |
+
:members:
|
| 63 |
+
:undoc-members:
|
| 64 |
+
:show-inheritance:
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/blending.rst
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.renderer.blending
|
| 2 |
+
===========================
|
| 3 |
+
|
| 4 |
+
blending
|
| 5 |
+
|
| 6 |
+
.. automodule:: pytorch3d.renderer.blending
|
| 7 |
+
:members:
|
| 8 |
+
:undoc-members:
|
| 9 |
+
:show-inheritance:
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/camera_conversions.rst
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.renderer.camera_conversions
|
| 2 |
+
=====================================
|
| 3 |
+
|
| 4 |
+
camera_conversions
|
| 5 |
+
|
| 6 |
+
.. automodule:: pytorch3d.renderer.camera_conversions
|
| 7 |
+
:members:
|
| 8 |
+
:undoc-members:
|
| 9 |
+
:show-inheritance:
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/compositing.rst
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.renderer.compositing
|
| 2 |
+
==============================
|
| 3 |
+
|
| 4 |
+
compositing
|
| 5 |
+
|
| 6 |
+
.. automodule:: pytorch3d.renderer.compositing
|
| 7 |
+
:members:
|
| 8 |
+
:undoc-members:
|
| 9 |
+
:show-inheritance:
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/compositor.rst
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.renderer.points.compositor
|
| 2 |
+
====================================
|
| 3 |
+
|
| 4 |
+
compositor
|
| 5 |
+
|
| 6 |
+
.. automodule:: pytorch3d.renderer.points.compositor
|
| 7 |
+
:members:
|
| 8 |
+
:undoc-members:
|
| 9 |
+
:show-inheritance:
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/index.rst
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.renderer.points
|
| 2 |
+
=========================
|
| 3 |
+
|
| 4 |
+
.. toctree::
|
| 5 |
+
|
| 6 |
+
compositor
|
| 7 |
+
rasterize_points
|
| 8 |
+
rasterizer
|
| 9 |
+
renderer
|
| 10 |
+
pulsar/index
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/points/rasterize_points.rst
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.renderer.points.rasterize_points
|
| 2 |
+
==========================================
|
| 3 |
+
|
| 4 |
+
rasterize_points
|
| 5 |
+
|
| 6 |
+
.. automodule:: pytorch3d.renderer.points.rasterize_points
|
| 7 |
+
:members:
|
| 8 |
+
:undoc-members:
|
| 9 |
+
:show-inheritance:
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/modules/renderer/utils.rst
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pytorch3d.renderer.utils
|
| 2 |
+
========================
|
| 3 |
+
|
| 4 |
+
utils
|
| 5 |
+
|
| 6 |
+
.. automodule:: pytorch3d.renderer.utils
|
| 7 |
+
:members:
|
| 8 |
+
:undoc-members:
|
| 9 |
+
:show-inheritance:
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Tutorial notebooks
|
| 2 |
+
|
| 3 |
+
For current versions of the tutorials, which correspond to the latest release,
|
| 4 |
+
please look at this directory at the `stable` tag, namely at
|
| 5 |
+
https://github.com/facebookresearch/pytorch3d/tree/stable/docs/tutorials .
|
| 6 |
+
|
| 7 |
+
There are links at the project homepage for opening these directly in colab.
|
| 8 |
+
|
| 9 |
+
They install PyTorch3D from pip, which should work inside a GPU colab notebook.
|
| 10 |
+
If you need to install PyTorch3D from source inside colab, you can use
|
| 11 |
+
```
|
| 12 |
+
import os
|
| 13 |
+
!curl -LO https://github.com/NVIDIA/cub/archive/1.10.0.tar.gz
|
| 14 |
+
!tar xzf 1.10.0.tar.gz
|
| 15 |
+
os.environ["CUB_HOME"] = os.getcwd() + "/cub-1.10.0"
|
| 16 |
+
!pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'`
|
| 17 |
+
```
|
| 18 |
+
instead.
|
| 19 |
+
|
| 20 |
+
The versions of these tutorials on the main branch may need to use the latest
|
| 21 |
+
PyTorch3D from the main branch. You may be able to install this from source
|
| 22 |
+
with the same commands as above, but replacing the last line with
|
| 23 |
+
`!pip install 'git+https://github.com/facebookresearch/pytorch3d.git'`.
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/camera_position_optimization_with_differentiable_rendering.ipynb
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"metadata": {
|
| 7 |
+
"colab": {},
|
| 8 |
+
"colab_type": "code",
|
| 9 |
+
"id": "-P3OUvJirQdR"
|
| 10 |
+
},
|
| 11 |
+
"outputs": [],
|
| 12 |
+
"source": [
|
| 13 |
+
"# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
|
| 14 |
+
]
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"cell_type": "markdown",
|
| 18 |
+
"metadata": {
|
| 19 |
+
"colab_type": "text",
|
| 20 |
+
"id": "44lB2sH-rQdW"
|
| 21 |
+
},
|
| 22 |
+
"source": [
|
| 23 |
+
"# Camera position optimization using differentiable rendering\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"In this tutorial we will learn the [x, y, z] position of a camera given a reference image using differentiable rendering. \n",
|
| 26 |
+
"\n",
|
| 27 |
+
"We will first initialize a renderer with a starting position for the camera. We will then use this to generate an image, compute a loss with the reference image, and finally backpropagate through the entire pipeline to update the position of the camera. \n",
|
| 28 |
+
"\n",
|
| 29 |
+
"This tutorial shows how to:\n",
|
| 30 |
+
"- load a mesh from an `.obj` file\n",
|
| 31 |
+
"- initialize a `Camera`, `Shader` and `Renderer`,\n",
|
| 32 |
+
"- render a mesh\n",
|
| 33 |
+
"- set up an optimization loop with a loss function and optimizer\n"
|
| 34 |
+
]
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "markdown",
|
| 38 |
+
"metadata": {
|
| 39 |
+
"colab_type": "text",
|
| 40 |
+
"id": "AZGmIlmWrQdX"
|
| 41 |
+
},
|
| 42 |
+
"source": [
|
| 43 |
+
"## 0. Install and import modules"
|
| 44 |
+
]
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "markdown",
|
| 48 |
+
"metadata": {
|
| 49 |
+
"colab_type": "text",
|
| 50 |
+
"id": "qkX7DiM6rmeM"
|
| 51 |
+
},
|
| 52 |
+
"source": [
|
| 53 |
+
"Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
|
| 54 |
+
]
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"cell_type": "code",
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"metadata": {
|
| 60 |
+
"colab": {
|
| 61 |
+
"base_uri": "https://localhost:8080/",
|
| 62 |
+
"height": 717
|
| 63 |
+
},
|
| 64 |
+
"colab_type": "code",
|
| 65 |
+
"id": "sEVdNGFwripM",
|
| 66 |
+
"outputId": "27047061-a29b-4562-c164-c1288e24c266"
|
| 67 |
+
},
|
| 68 |
+
"outputs": [],
|
| 69 |
+
"source": [
|
| 70 |
+
"import os\n",
|
| 71 |
+
"import sys\n",
|
| 72 |
+
"import torch\n",
|
| 73 |
+
"import subprocess\n",
|
| 74 |
+
"need_pytorch3d=False\n",
|
| 75 |
+
"try:\n",
|
| 76 |
+
" import pytorch3d\n",
|
| 77 |
+
"except ModuleNotFoundError:\n",
|
| 78 |
+
" need_pytorch3d=True\n",
|
| 79 |
+
"if need_pytorch3d:\n",
|
| 80 |
+
" pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
|
| 81 |
+
" version_str=\"\".join([\n",
|
| 82 |
+
" f\"py3{sys.version_info.minor}_cu\",\n",
|
| 83 |
+
" torch.version.cuda.replace(\".\",\"\"),\n",
|
| 84 |
+
" f\"_pyt{pyt_version_str}\"\n",
|
| 85 |
+
" ])\n",
|
| 86 |
+
" !pip install iopath\n",
|
| 87 |
+
" if sys.platform.startswith(\"linux\"):\n",
|
| 88 |
+
" print(\"Trying to install wheel for PyTorch3D\")\n",
|
| 89 |
+
" !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
|
| 90 |
+
" pip_list = !pip freeze\n",
|
| 91 |
+
" need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
|
| 92 |
+
" if need_pytorch3d:\n",
|
| 93 |
+
" print(f\"failed to find/install wheel for {version_str}\")\n",
|
| 94 |
+
"if need_pytorch3d:\n",
|
| 95 |
+
" print(\"Installing PyTorch3D from source\")\n",
|
| 96 |
+
" !pip install ninja\n",
|
| 97 |
+
" !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
|
| 98 |
+
]
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"metadata": {
|
| 104 |
+
"colab": {},
|
| 105 |
+
"colab_type": "code",
|
| 106 |
+
"id": "w9mH5iVprQdZ"
|
| 107 |
+
},
|
| 108 |
+
"outputs": [],
|
| 109 |
+
"source": [
|
| 110 |
+
"import os\n",
|
| 111 |
+
"import torch\n",
|
| 112 |
+
"import numpy as np\n",
|
| 113 |
+
"from tqdm.notebook import tqdm\n",
|
| 114 |
+
"import imageio\n",
|
| 115 |
+
"import torch.nn as nn\n",
|
| 116 |
+
"import torch.nn.functional as F\n",
|
| 117 |
+
"import matplotlib.pyplot as plt\n",
|
| 118 |
+
"from skimage import img_as_ubyte\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# io utils\n",
|
| 121 |
+
"from pytorch3d.io import load_obj\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"# datastructures\n",
|
| 124 |
+
"from pytorch3d.structures import Meshes\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"# 3D transformations functions\n",
|
| 127 |
+
"from pytorch3d.transforms import Rotate, Translate\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"# rendering components\n",
|
| 130 |
+
"from pytorch3d.renderer import (\n",
|
| 131 |
+
" FoVPerspectiveCameras, look_at_view_transform, look_at_rotation, \n",
|
| 132 |
+
" RasterizationSettings, MeshRenderer, MeshRasterizer, BlendParams,\n",
|
| 133 |
+
" SoftSilhouetteShader, HardPhongShader, PointLights, TexturesVertex,\n",
|
| 134 |
+
")"
|
| 135 |
+
]
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "markdown",
|
| 139 |
+
"metadata": {
|
| 140 |
+
"colab_type": "text",
|
| 141 |
+
"id": "cpUf2UvirQdc"
|
| 142 |
+
},
|
| 143 |
+
"source": [
|
| 144 |
+
"## 1. Load the Obj\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"We will load an obj file and create a **Meshes** object. **Meshes** is a unique datastructure provided in PyTorch3D for working with **batches of meshes of different sizes**. It has several useful class methods which are used in the rendering pipeline. "
|
| 147 |
+
]
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "markdown",
|
| 151 |
+
"metadata": {
|
| 152 |
+
"colab_type": "text",
|
| 153 |
+
"id": "8d-oREfkrt_Z"
|
| 154 |
+
},
|
| 155 |
+
"source": [
|
| 156 |
+
"If you are running this notebook locally after cloning the PyTorch3D repository, the mesh will already be available. **If using Google Colab, fetch the mesh and save it at the path `data/`**:"
|
| 157 |
+
]
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"metadata": {
|
| 163 |
+
"colab": {
|
| 164 |
+
"base_uri": "https://localhost:8080/",
|
| 165 |
+
"height": 204
|
| 166 |
+
},
|
| 167 |
+
"colab_type": "code",
|
| 168 |
+
"id": "sD5KcLuJr0PL",
|
| 169 |
+
"outputId": "e65061fa-dbd5-4c06-b559-3592632983ee"
|
| 170 |
+
},
|
| 171 |
+
"outputs": [],
|
| 172 |
+
"source": [
|
| 173 |
+
"!mkdir -p data\n",
|
| 174 |
+
"!wget -P data https://dl.fbaipublicfiles.com/pytorch3d/data/teapot/teapot.obj"
|
| 175 |
+
]
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"metadata": {
|
| 181 |
+
"colab": {},
|
| 182 |
+
"colab_type": "code",
|
| 183 |
+
"id": "VWiPKnEIrQdd"
|
| 184 |
+
},
|
| 185 |
+
"outputs": [],
|
| 186 |
+
"source": [
|
| 187 |
+
"# Set the cuda device \n",
|
| 188 |
+
"if torch.cuda.is_available():\n",
|
| 189 |
+
" device = torch.device(\"cuda:0\")\n",
|
| 190 |
+
" torch.cuda.set_device(device)\n",
|
| 191 |
+
"else:\n",
|
| 192 |
+
" device = torch.device(\"cpu\")\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"# Load the obj and ignore the textures and materials.\n",
|
| 195 |
+
"verts, faces_idx, _ = load_obj(\"./data/teapot.obj\")\n",
|
| 196 |
+
"faces = faces_idx.verts_idx\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"# Initialize each vertex to be white in color.\n",
|
| 199 |
+
"verts_rgb = torch.ones_like(verts)[None] # (1, V, 3)\n",
|
| 200 |
+
"textures = TexturesVertex(verts_features=verts_rgb.to(device))\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"# Create a Meshes object for the teapot. Here we have only one mesh in the batch.\n",
|
| 203 |
+
"teapot_mesh = Meshes(\n",
|
| 204 |
+
" verts=[verts.to(device)], \n",
|
| 205 |
+
" faces=[faces.to(device)], \n",
|
| 206 |
+
" textures=textures\n",
|
| 207 |
+
")"
|
| 208 |
+
]
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "markdown",
|
| 212 |
+
"metadata": {
|
| 213 |
+
"colab_type": "text",
|
| 214 |
+
"id": "mgtGbQktrQdh"
|
| 215 |
+
},
|
| 216 |
+
"source": [
|
| 217 |
+
"\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"## 2. Optimization setup"
|
| 220 |
+
]
|
| 221 |
+
},
|
| 222 |
+
{
|
| 223 |
+
"cell_type": "markdown",
|
| 224 |
+
"metadata": {
|
| 225 |
+
"colab_type": "text",
|
| 226 |
+
"id": "Q6PzKD_NrQdi"
|
| 227 |
+
},
|
| 228 |
+
"source": [
|
| 229 |
+
"### Create a renderer\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"A **renderer** in PyTorch3D is composed of a **rasterizer** and a **shader** which each have a number of subcomponents such as a **camera** (orthographic/perspective). Here we initialize some of these components and use default values for the rest. \n",
|
| 232 |
+
"\n",
|
| 233 |
+
"For optimizing the camera position we will use a renderer which produces a **silhouette** of the object only and does not apply any **lighting** or **shading**. We will also initialize another renderer which applies full **Phong shading** and use this for visualizing the outputs. "
|
| 234 |
+
]
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"cell_type": "code",
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"metadata": {
|
| 240 |
+
"colab": {},
|
| 241 |
+
"colab_type": "code",
|
| 242 |
+
"id": "KPlby75GrQdj"
|
| 243 |
+
},
|
| 244 |
+
"outputs": [],
|
| 245 |
+
"source": [
|
| 246 |
+
"# Initialize a perspective camera.\n",
|
| 247 |
+
"cameras = FoVPerspectiveCameras(device=device)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"# To blend the 100 faces we set a few parameters which control the opacity and the sharpness of \n",
|
| 250 |
+
"# edges. Refer to blending.py for more details. \n",
|
| 251 |
+
"blend_params = BlendParams(sigma=1e-4, gamma=1e-4)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"# Define the settings for rasterization and shading. Here we set the output image to be of size\n",
|
| 254 |
+
"# 256x256. To form the blended image we use 100 faces for each pixel. We also set bin_size and max_faces_per_bin to None which ensure that \n",
|
| 255 |
+
"# the faster coarse-to-fine rasterization method is used. Refer to rasterize_meshes.py for \n",
|
| 256 |
+
"# explanations of these parameters. Refer to docs/notes/renderer.md for an explanation of \n",
|
| 257 |
+
"# the difference between naive and coarse-to-fine rasterization. \n",
|
| 258 |
+
"raster_settings = RasterizationSettings(\n",
|
| 259 |
+
" image_size=256, \n",
|
| 260 |
+
" blur_radius=np.log(1. / 1e-4 - 1.) * blend_params.sigma, \n",
|
| 261 |
+
" faces_per_pixel=100, \n",
|
| 262 |
+
")\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"# Create a silhouette mesh renderer by composing a rasterizer and a shader. \n",
|
| 265 |
+
"silhouette_renderer = MeshRenderer(\n",
|
| 266 |
+
" rasterizer=MeshRasterizer(\n",
|
| 267 |
+
" cameras=cameras, \n",
|
| 268 |
+
" raster_settings=raster_settings\n",
|
| 269 |
+
" ),\n",
|
| 270 |
+
" shader=SoftSilhouetteShader(blend_params=blend_params)\n",
|
| 271 |
+
")\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"# We will also create a Phong renderer. This is simpler and only needs to render one face per pixel.\n",
|
| 275 |
+
"raster_settings = RasterizationSettings(\n",
|
| 276 |
+
" image_size=256, \n",
|
| 277 |
+
" blur_radius=0.0, \n",
|
| 278 |
+
" faces_per_pixel=1, \n",
|
| 279 |
+
")\n",
|
| 280 |
+
"# We can add a point light in front of the object. \n",
|
| 281 |
+
"lights = PointLights(device=device, location=((2.0, 2.0, -2.0),))\n",
|
| 282 |
+
"phong_renderer = MeshRenderer(\n",
|
| 283 |
+
" rasterizer=MeshRasterizer(\n",
|
| 284 |
+
" cameras=cameras, \n",
|
| 285 |
+
" raster_settings=raster_settings\n",
|
| 286 |
+
" ),\n",
|
| 287 |
+
" shader=HardPhongShader(device=device, cameras=cameras, lights=lights)\n",
|
| 288 |
+
")"
|
| 289 |
+
]
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"cell_type": "markdown",
|
| 293 |
+
"metadata": {
|
| 294 |
+
"colab_type": "text",
|
| 295 |
+
"id": "osOy2OIJrQdn"
|
| 296 |
+
},
|
| 297 |
+
"source": [
|
| 298 |
+
"### Create a reference image\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"We will first position the teapot and generate an image. We use helper functions to rotate the teapot to a desired viewpoint. Then we can use the renderers to produce an image. Here we will use both renderers and visualize the silhouette and full shaded image. \n",
|
| 301 |
+
"\n",
|
| 302 |
+
"The world coordinate system is defined as +Y up, +X left and +Z in. The teapot in world coordinates has the spout pointing to the left. \n",
|
| 303 |
+
"\n",
|
| 304 |
+
"We defined a camera which is positioned on the positive z axis hence sees the spout to the right. "
|
| 305 |
+
]
|
| 306 |
+
},
|
| 307 |
+
{
|
| 308 |
+
"cell_type": "code",
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"metadata": {
|
| 311 |
+
"colab": {
|
| 312 |
+
"base_uri": "https://localhost:8080/",
|
| 313 |
+
"height": 305
|
| 314 |
+
},
|
| 315 |
+
"colab_type": "code",
|
| 316 |
+
"id": "EjJrW7qerQdo",
|
| 317 |
+
"outputId": "93545b65-269e-4719-f4a2-52cbc6c9c974"
|
| 318 |
+
},
|
| 319 |
+
"outputs": [],
|
| 320 |
+
"source": [
|
| 321 |
+
"# Select the viewpoint using spherical angles \n",
|
| 322 |
+
"distance = 3 # distance from camera to the object\n",
|
| 323 |
+
"elevation = 50.0 # angle of elevation in degrees\n",
|
| 324 |
+
"azimuth = 0.0 # No rotation so the camera is positioned on the +Z axis. \n",
|
| 325 |
+
"\n",
|
| 326 |
+
"# Get the position of the camera based on the spherical angles\n",
|
| 327 |
+
"R, T = look_at_view_transform(distance, elevation, azimuth, device=device)\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"# Render the teapot providing the values of R and T. \n",
|
| 330 |
+
"silhouette = silhouette_renderer(meshes_world=teapot_mesh, R=R, T=T)\n",
|
| 331 |
+
"image_ref = phong_renderer(meshes_world=teapot_mesh, R=R, T=T)\n",
|
| 332 |
+
"\n",
|
| 333 |
+
"silhouette = silhouette.cpu().numpy()\n",
|
| 334 |
+
"image_ref = image_ref.cpu().numpy()\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"plt.figure(figsize=(10, 10))\n",
|
| 337 |
+
"plt.subplot(1, 2, 1)\n",
|
| 338 |
+
"plt.imshow(silhouette.squeeze()[..., 3]) # only plot the alpha channel of the RGBA image\n",
|
| 339 |
+
"plt.grid(False)\n",
|
| 340 |
+
"plt.subplot(1, 2, 2)\n",
|
| 341 |
+
"plt.imshow(image_ref.squeeze())\n",
|
| 342 |
+
"plt.grid(False)"
|
| 343 |
+
]
|
| 344 |
+
},
|
| 345 |
+
{
|
| 346 |
+
"cell_type": "markdown",
|
| 347 |
+
"metadata": {
|
| 348 |
+
"colab_type": "text",
|
| 349 |
+
"id": "plBJwEslrQdt"
|
| 350 |
+
},
|
| 351 |
+
"source": [
|
| 352 |
+
"### Set up a basic model \n",
|
| 353 |
+
"\n",
|
| 354 |
+
"Here we create a simple model class and initialize a parameter for the camera position. "
|
| 355 |
+
]
|
| 356 |
+
},
|
| 357 |
+
{
|
| 358 |
+
"cell_type": "code",
|
| 359 |
+
"execution_count": null,
|
| 360 |
+
"metadata": {
|
| 361 |
+
"colab": {},
|
| 362 |
+
"colab_type": "code",
|
| 363 |
+
"id": "YBbP1-EDrQdu"
|
| 364 |
+
},
|
| 365 |
+
"outputs": [],
|
| 366 |
+
"source": [
|
| 367 |
+
"class Model(nn.Module):\n",
|
| 368 |
+
" def __init__(self, meshes, renderer, image_ref):\n",
|
| 369 |
+
" super().__init__()\n",
|
| 370 |
+
" self.meshes = meshes\n",
|
| 371 |
+
" self.device = meshes.device\n",
|
| 372 |
+
" self.renderer = renderer\n",
|
| 373 |
+
" \n",
|
| 374 |
+
" # Get the silhouette of the reference RGB image by finding all non-white pixel values. \n",
|
| 375 |
+
" image_ref = torch.from_numpy((image_ref[..., :3].max(-1) != 1).astype(np.float32))\n",
|
| 376 |
+
" self.register_buffer('image_ref', image_ref)\n",
|
| 377 |
+
" \n",
|
| 378 |
+
" # Create an optimizable parameter for the x, y, z position of the camera. \n",
|
| 379 |
+
" self.camera_position = nn.Parameter(\n",
|
| 380 |
+
" torch.from_numpy(np.array([3.0, 6.9, +2.5], dtype=np.float32)).to(meshes.device))\n",
|
| 381 |
+
"\n",
|
| 382 |
+
" def forward(self):\n",
|
| 383 |
+
" \n",
|
| 384 |
+
" # Render the image using the updated camera position. Based on the new position of the \n",
|
| 385 |
+
" # camera we calculate the rotation and translation matrices\n",
|
| 386 |
+
" R = look_at_rotation(self.camera_position[None, :], device=self.device) # (1, 3, 3)\n",
|
| 387 |
+
" T = -torch.bmm(R.transpose(1, 2), self.camera_position[None, :, None])[:, :, 0] # (1, 3)\n",
|
| 388 |
+
" \n",
|
| 389 |
+
" image = self.renderer(meshes_world=self.meshes.clone(), R=R, T=T)\n",
|
| 390 |
+
" \n",
|
| 391 |
+
" # Calculate the silhouette loss\n",
|
| 392 |
+
" loss = torch.sum((image[..., 3] - self.image_ref) ** 2)\n",
|
| 393 |
+
" return loss, image\n",
|
| 394 |
+
" "
|
| 395 |
+
]
|
| 396 |
+
},
|
| 397 |
+
{
|
| 398 |
+
"cell_type": "markdown",
|
| 399 |
+
"metadata": {
|
| 400 |
+
"colab_type": "text",
|
| 401 |
+
"id": "qCGLSJtfrQdy"
|
| 402 |
+
},
|
| 403 |
+
"source": [
|
| 404 |
+
"## 3. Initialize the model and optimizer\n",
|
| 405 |
+
"\n",
|
| 406 |
+
"Now we can create an instance of the **model** above and set up an **optimizer** for the camera position parameter. "
|
| 407 |
+
]
|
| 408 |
+
},
|
| 409 |
+
{
|
| 410 |
+
"cell_type": "code",
|
| 411 |
+
"execution_count": null,
|
| 412 |
+
"metadata": {
|
| 413 |
+
"colab": {},
|
| 414 |
+
"colab_type": "code",
|
| 415 |
+
"id": "srZPBU7_rQdz"
|
| 416 |
+
},
|
| 417 |
+
"outputs": [],
|
| 418 |
+
"source": [
|
| 419 |
+
"# We will save images periodically and compose them into a GIF.\n",
|
| 420 |
+
"filename_output = \"./teapot_optimization_demo.gif\"\n",
|
| 421 |
+
"writer = imageio.get_writer(filename_output, mode='I', duration=0.3)\n",
|
| 422 |
+
"\n",
|
| 423 |
+
"# Initialize a model using the renderer, mesh and reference image\n",
|
| 424 |
+
"model = Model(meshes=teapot_mesh, renderer=silhouette_renderer, image_ref=image_ref).to(device)\n",
|
| 425 |
+
"\n",
|
| 426 |
+
"# Create an optimizer. Here we are using Adam and we pass in the parameters of the model\n",
|
| 427 |
+
"optimizer = torch.optim.Adam(model.parameters(), lr=0.05)"
|
| 428 |
+
]
|
| 429 |
+
},
|
| 430 |
+
{
|
| 431 |
+
"cell_type": "markdown",
|
| 432 |
+
"metadata": {
|
| 433 |
+
"colab_type": "text",
|
| 434 |
+
"id": "dvTLnrWorQd2"
|
| 435 |
+
},
|
| 436 |
+
"source": [
|
| 437 |
+
"### Visualize the starting position and the reference position"
|
| 438 |
+
]
|
| 439 |
+
},
|
| 440 |
+
{
|
| 441 |
+
"cell_type": "code",
|
| 442 |
+
"execution_count": null,
|
| 443 |
+
"metadata": {
|
| 444 |
+
"colab": {
|
| 445 |
+
"base_uri": "https://localhost:8080/",
|
| 446 |
+
"height": 335
|
| 447 |
+
},
|
| 448 |
+
"colab_type": "code",
|
| 449 |
+
"id": "qyRXpP3mrQd3",
|
| 450 |
+
"outputId": "47ecb12a-e68c-47f5-92fc-821a7a9bd661"
|
| 451 |
+
},
|
| 452 |
+
"outputs": [],
|
| 453 |
+
"source": [
|
| 454 |
+
"plt.figure(figsize=(10, 10))\n",
|
| 455 |
+
"\n",
|
| 456 |
+
"_, image_init = model()\n",
|
| 457 |
+
"plt.subplot(1, 2, 1)\n",
|
| 458 |
+
"plt.imshow(image_init.detach().squeeze().cpu().numpy()[..., 3])\n",
|
| 459 |
+
"plt.grid(False)\n",
|
| 460 |
+
"plt.title(\"Starting position\")\n",
|
| 461 |
+
"\n",
|
| 462 |
+
"plt.subplot(1, 2, 2)\n",
|
| 463 |
+
"plt.imshow(model.image_ref.cpu().numpy().squeeze())\n",
|
| 464 |
+
"plt.grid(False)\n",
|
| 465 |
+
"plt.title(\"Reference silhouette\");\n"
|
| 466 |
+
]
|
| 467 |
+
},
|
| 468 |
+
{
|
| 469 |
+
"cell_type": "markdown",
|
| 470 |
+
"metadata": {
|
| 471 |
+
"colab_type": "text",
|
| 472 |
+
"id": "aGJu7h-lrQd5"
|
| 473 |
+
},
|
| 474 |
+
"source": [
|
| 475 |
+
"## 4. Run the optimization \n",
|
| 476 |
+
"\n",
|
| 477 |
+
"We run several iterations of the forward and backward pass and save outputs every 10 iterations. When this has finished take a look at `./teapot_optimization_demo.gif` for a cool gif of the optimization process!"
|
| 478 |
+
]
|
| 479 |
+
},
|
| 480 |
+
{
|
| 481 |
+
"cell_type": "code",
|
| 482 |
+
"execution_count": null,
|
| 483 |
+
"metadata": {
|
| 484 |
+
"colab": {
|
| 485 |
+
"base_uri": "https://localhost:8080/",
|
| 486 |
+
"height": 1000,
|
| 487 |
+
"referenced_widgets": [
|
| 488 |
+
"79d7fc84b5564206ab64b2759474da04",
|
| 489 |
+
"02acadb61c3949fcaeab177fd184c388",
|
| 490 |
+
"efd9860908c64bfe9d47118be4734648",
|
| 491 |
+
"f8df7c6efb7d47f5be760a39b4bdbcf8",
|
| 492 |
+
"d8a109658c364a00ab4d298112dac6db",
|
| 493 |
+
"2d05db82cc99482bb3d62b6d4e5b1a98",
|
| 494 |
+
"c621d425e2c8426c8cd4f9136d392af1",
|
| 495 |
+
"3df8063f307040ebb8ff8e2f26ccf729"
|
| 496 |
+
]
|
| 497 |
+
},
|
| 498 |
+
"colab_type": "code",
|
| 499 |
+
"id": "HvnK5VI5rQd6",
|
| 500 |
+
"outputId": "4019c697-3fc6-4c7b-cdfe-225633cc0d60"
|
| 501 |
+
},
|
| 502 |
+
"outputs": [],
|
| 503 |
+
"source": [
|
| 504 |
+
"loop = tqdm(range(200))\n",
|
| 505 |
+
"for i in loop:\n",
|
| 506 |
+
" optimizer.zero_grad()\n",
|
| 507 |
+
" loss, _ = model()\n",
|
| 508 |
+
" loss.backward()\n",
|
| 509 |
+
" optimizer.step()\n",
|
| 510 |
+
" \n",
|
| 511 |
+
" loop.set_description('Optimizing (loss %.4f)' % loss.data)\n",
|
| 512 |
+
" \n",
|
| 513 |
+
" if loss.item() < 200:\n",
|
| 514 |
+
" break\n",
|
| 515 |
+
" \n",
|
| 516 |
+
" # Save outputs to create a GIF. \n",
|
| 517 |
+
" if i % 10 == 0:\n",
|
| 518 |
+
" R = look_at_rotation(model.camera_position[None, :], device=model.device)\n",
|
| 519 |
+
" T = -torch.bmm(R.transpose(1, 2), model.camera_position[None, :, None])[:, :, 0] # (1, 3)\n",
|
| 520 |
+
" image = phong_renderer(meshes_world=model.meshes.clone(), R=R, T=T)\n",
|
| 521 |
+
" image = image[0, ..., :3].detach().squeeze().cpu().numpy()\n",
|
| 522 |
+
" image = img_as_ubyte(image)\n",
|
| 523 |
+
" writer.append_data(image)\n",
|
| 524 |
+
" \n",
|
| 525 |
+
" plt.figure()\n",
|
| 526 |
+
" plt.imshow(image[..., :3])\n",
|
| 527 |
+
" plt.title(\"iter: %d, loss: %0.2f\" % (i, loss.data))\n",
|
| 528 |
+
" plt.axis(\"off\")\n",
|
| 529 |
+
" \n",
|
| 530 |
+
"writer.close()"
|
| 531 |
+
]
|
| 532 |
+
},
|
| 533 |
+
{
|
| 534 |
+
"cell_type": "markdown",
|
| 535 |
+
"metadata": {
|
| 536 |
+
"colab_type": "text",
|
| 537 |
+
"id": "mWj80P_SsPTN"
|
| 538 |
+
},
|
| 539 |
+
"source": [
|
| 540 |
+
"## 5. Conclusion \n",
|
| 541 |
+
"\n",
|
| 542 |
+
"In this tutorial we learnt how to **load** a mesh from an obj file, initialize a PyTorch3D datastructure called **Meshes**, set up an **Renderer** consisting of a **Rasterizer** and a **Shader**, set up an optimization loop including a **Model** and a **loss function**, and run the optimization. "
|
| 543 |
+
]
|
| 544 |
+
}
|
| 545 |
+
],
|
| 546 |
+
"metadata": {
|
| 547 |
+
"accelerator": "GPU",
|
| 548 |
+
"anp_metadata": {
|
| 549 |
+
"path": "fbsource/fbcode/vision/fair/pytorch3d/docs/tutorials/camera_position_optimization_with_differentiable_rendering.ipynb"
|
| 550 |
+
},
|
| 551 |
+
"bento_stylesheets": {
|
| 552 |
+
"bento/extensions/flow/main.css": true,
|
| 553 |
+
"bento/extensions/kernel_selector/main.css": true,
|
| 554 |
+
"bento/extensions/kernel_ui/main.css": true,
|
| 555 |
+
"bento/extensions/new_kernel/main.css": true,
|
| 556 |
+
"bento/extensions/system_usage/main.css": true,
|
| 557 |
+
"bento/extensions/theme/main.css": true
|
| 558 |
+
},
|
| 559 |
+
"colab": {
|
| 560 |
+
"name": "camera_position_optimization_with_differentiable_rendering.ipynb",
|
| 561 |
+
"provenance": [],
|
| 562 |
+
"toc_visible": true
|
| 563 |
+
},
|
| 564 |
+
"disseminate_notebook_info": {
|
| 565 |
+
"backup_notebook_id": "1062179640844868"
|
| 566 |
+
},
|
| 567 |
+
"kernelspec": {
|
| 568 |
+
"display_name": "pytorch3d (local)",
|
| 569 |
+
"language": "python",
|
| 570 |
+
"name": "pytorch3d_local"
|
| 571 |
+
},
|
| 572 |
+
"language_info": {
|
| 573 |
+
"codemirror_mode": {
|
| 574 |
+
"name": "ipython",
|
| 575 |
+
"version": 3
|
| 576 |
+
},
|
| 577 |
+
"file_extension": ".py",
|
| 578 |
+
"mimetype": "text/x-python",
|
| 579 |
+
"name": "python",
|
| 580 |
+
"nbconvert_exporter": "python",
|
| 581 |
+
"pygments_lexer": "ipython3",
|
| 582 |
+
"version": "3.7.5+"
|
| 583 |
+
}
|
| 584 |
+
},
|
| 585 |
+
"nbformat": 4,
|
| 586 |
+
"nbformat_minor": 1
|
| 587 |
+
}
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/dataloaders_ShapeNetCore_R2N2.ipynb
ADDED
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"outputs": [],
|
| 8 |
+
"source": [
|
| 9 |
+
"# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
|
| 10 |
+
]
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "markdown",
|
| 14 |
+
"metadata": {},
|
| 15 |
+
"source": [
|
| 16 |
+
"# Dataloaders for ShapeNetCore and R2N2\n",
|
| 17 |
+
"This tutorial shows how to:\n",
|
| 18 |
+
"- Load models from ShapeNetCore and R2N2 using PyTorch3D's data loaders.\n",
|
| 19 |
+
"- Pass the loaded datasets to `torch.utils.data.DataLoader`.\n",
|
| 20 |
+
"- Render ShapeNetCore models with PyTorch3D's renderer.\n",
|
| 21 |
+
"- Render R2N2 models with the same orientations as the original renderings in the dataset.\n",
|
| 22 |
+
"- Visualize R2N2 model voxels."
|
| 23 |
+
]
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "markdown",
|
| 27 |
+
"metadata": {},
|
| 28 |
+
"source": [
|
| 29 |
+
"## 0. Install and import modules"
|
| 30 |
+
]
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "markdown",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
|
| 37 |
+
]
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"outputs": [],
|
| 44 |
+
"source": [
|
| 45 |
+
"import os\n",
|
| 46 |
+
"import sys\n",
|
| 47 |
+
"import torch\n",
|
| 48 |
+
"import subprocess\n",
|
| 49 |
+
"need_pytorch3d=False\n",
|
| 50 |
+
"try:\n",
|
| 51 |
+
" import pytorch3d\n",
|
| 52 |
+
"except ModuleNotFoundError:\n",
|
| 53 |
+
" need_pytorch3d=True\n",
|
| 54 |
+
"if need_pytorch3d:\n",
|
| 55 |
+
" pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
|
| 56 |
+
" version_str=\"\".join([\n",
|
| 57 |
+
" f\"py3{sys.version_info.minor}_cu\",\n",
|
| 58 |
+
" torch.version.cuda.replace(\".\",\"\"),\n",
|
| 59 |
+
" f\"_pyt{pyt_version_str}\"\n",
|
| 60 |
+
" ])\n",
|
| 61 |
+
" !pip install iopath\n",
|
| 62 |
+
" if sys.platform.startswith(\"linux\"):\n",
|
| 63 |
+
" print(\"Trying to install wheel for PyTorch3D\")\n",
|
| 64 |
+
" !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
|
| 65 |
+
" pip_list = !pip freeze\n",
|
| 66 |
+
" need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
|
| 67 |
+
" if need_pytorch3d:\n",
|
| 68 |
+
" print(f\"failed to find/install wheel for {version_str}\")\n",
|
| 69 |
+
"if need_pytorch3d:\n",
|
| 70 |
+
" print(\"Installing PyTorch3D from source\")\n",
|
| 71 |
+
" !pip install ninja\n",
|
| 72 |
+
" !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
|
| 73 |
+
]
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"outputs": [],
|
| 80 |
+
"source": [
|
| 81 |
+
"import numpy as np\n",
|
| 82 |
+
"import torch\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"from pytorch3d.datasets import (\n",
|
| 85 |
+
" R2N2,\n",
|
| 86 |
+
" ShapeNetCore,\n",
|
| 87 |
+
" collate_batched_meshes,\n",
|
| 88 |
+
" render_cubified_voxels,\n",
|
| 89 |
+
")\n",
|
| 90 |
+
"from pytorch3d.renderer import (\n",
|
| 91 |
+
" OpenGLPerspectiveCameras,\n",
|
| 92 |
+
" PointLights,\n",
|
| 93 |
+
" RasterizationSettings,\n",
|
| 94 |
+
" TexturesVertex,\n",
|
| 95 |
+
" look_at_view_transform,\n",
|
| 96 |
+
")\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"from pytorch3d.structures import Meshes\n",
|
| 99 |
+
"from torch.utils.data import DataLoader\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"# add path for demo utils functions \n",
|
| 102 |
+
"import sys\n",
|
| 103 |
+
"import os\n",
|
| 104 |
+
"sys.path.append(os.path.abspath(''))"
|
| 105 |
+
]
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "markdown",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"If using **Google Colab**, fetch the utils file for plotting image grids:"
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"outputs": [],
|
| 119 |
+
"source": [
|
| 120 |
+
"!wget https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/docs/tutorials/utils/plot_image_grid.py\n",
|
| 121 |
+
"from plot_image_grid import image_grid"
|
| 122 |
+
]
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "markdown",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"OR if running locally uncomment and run the following cell:"
|
| 129 |
+
]
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"outputs": [],
|
| 136 |
+
"source": [
|
| 137 |
+
"# from utils import image_grid"
|
| 138 |
+
]
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "markdown",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"## 1. Load the datasets"
|
| 145 |
+
]
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "markdown",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"If you haven't already downloaded the ShapeNetCore dataset, first do that following the instructions here: https://www.shapenet.org/. ShapeNetCore is a subset of the ShapeNet dataset. In PyTorch3D we support both version 1 (57 categories) and version 2 (55 categories).\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"Then modify `SHAPENET_PATH` below to you local path to the ShapeNetCore dataset folder. "
|
| 154 |
+
]
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"execution_count": null,
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"outputs": [],
|
| 161 |
+
"source": [
|
| 162 |
+
"# Setup\n",
|
| 163 |
+
"if torch.cuda.is_available():\n",
|
| 164 |
+
" device = torch.device(\"cuda:0\")\n",
|
| 165 |
+
" torch.cuda.set_device(device)\n",
|
| 166 |
+
"else:\n",
|
| 167 |
+
" device = torch.device(\"cpu\")\n",
|
| 168 |
+
" \n",
|
| 169 |
+
"SHAPENET_PATH = \"\"\n",
|
| 170 |
+
"shapenet_dataset = ShapeNetCore(SHAPENET_PATH)"
|
| 171 |
+
]
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "markdown",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"The R2N2 dataset can be downloaded using the instructions here: http://3d-r2n2.stanford.edu/. Look at the links for `ShapeNetRendering` and `ShapeNetVox32`. The R2N2 dataset contains 13 categories that are a subset of the ShapeNetCore v.1\n",
|
| 178 |
+
"dataset. The R2N2 dataset also contains its own 24 renderings of each object and voxelized models.\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"Then modify `R2N2_PATH` and `SPLITS_PATH` below to your local R2N2 dataset folder path and splits file path respectively. Here we will load the `train` split of R2N2 and ask the voxels of each model to be returned."
|
| 181 |
+
]
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"metadata": {},
|
| 187 |
+
"outputs": [],
|
| 188 |
+
"source": [
|
| 189 |
+
"R2N2_PATH = \"\"\n",
|
| 190 |
+
"SPLITS_PATH = \"None\"\n",
|
| 191 |
+
"r2n2_dataset = R2N2(\"train\", SHAPENET_PATH, R2N2_PATH, SPLITS_PATH, return_voxels=True)"
|
| 192 |
+
]
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "markdown",
|
| 196 |
+
"metadata": {},
|
| 197 |
+
"source": [
|
| 198 |
+
"We can retrieve a model by indexing into the loaded dataset. For both ShapeNetCore and R2N2, we can examine the category this model belongs to (in the form of a synset id, equivalent to wnid described in ImageNet's API: http://image-net.org/download-API), its model id, and its vertices and faces."
|
| 199 |
+
]
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"cell_type": "code",
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"metadata": {},
|
| 205 |
+
"outputs": [],
|
| 206 |
+
"source": [
|
| 207 |
+
"shapenet_model = shapenet_dataset[6]\n",
|
| 208 |
+
"print(\"This model belongs to the category \" + shapenet_model[\"synset_id\"] + \".\")\n",
|
| 209 |
+
"print(\"This model has model id \" + shapenet_model[\"model_id\"] + \".\")\n",
|
| 210 |
+
"model_verts, model_faces = shapenet_model[\"verts\"], shapenet_model[\"faces\"]"
|
| 211 |
+
]
|
| 212 |
+
},
|
| 213 |
+
{
|
| 214 |
+
"cell_type": "markdown",
|
| 215 |
+
"metadata": {},
|
| 216 |
+
"source": [
|
| 217 |
+
"We can use its vertices and faces to form a `Meshes` object which is a PyTorch3D datastructure for working with batched meshes."
|
| 218 |
+
]
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "code",
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"outputs": [],
|
| 225 |
+
"source": [
|
| 226 |
+
"model_textures = TexturesVertex(verts_features=torch.ones_like(model_verts, device=device)[None])\n",
|
| 227 |
+
"shapenet_model_mesh = Meshes(\n",
|
| 228 |
+
" verts=[model_verts.to(device)], \n",
|
| 229 |
+
" faces=[model_faces.to(device)],\n",
|
| 230 |
+
" textures=model_textures\n",
|
| 231 |
+
")"
|
| 232 |
+
]
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"cell_type": "markdown",
|
| 236 |
+
"metadata": {},
|
| 237 |
+
"source": [
|
| 238 |
+
"With R2N2, we can further examine R2N2's original renderings. For instance, if we would like to see the second and third views of the eleventh objects in the R2N2 dataset, we can do the following:"
|
| 239 |
+
]
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"outputs": [],
|
| 246 |
+
"source": [
|
| 247 |
+
"r2n2_renderings = r2n2_dataset[10,[1,2]]\n",
|
| 248 |
+
"image_grid(r2n2_renderings.numpy(), rows=1, cols=2, rgb=True)"
|
| 249 |
+
]
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "markdown",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"## 2. Use the datasets with `torch.utils.data.DataLoader`"
|
| 256 |
+
]
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "markdown",
|
| 260 |
+
"metadata": {},
|
| 261 |
+
"source": [
|
| 262 |
+
"Training deep learning models, usually requires passing in batches of inputs. The `torch.utils.data.DataLoader` from PyTorch helps us do this. PyTorch3D provides a function `collate_batched_meshes` to group the input meshes into a single `Meshes` object which represents the batch. The `Meshes` datastructure can then be used directly by other PyTorch3D ops which might be part of the deep learning model (e.g. `graph_conv`).\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"For R2N2, if all the models in the batch have the same number of views, the views, rotation matrices, translation matrices, intrinsic matrices and voxels will also be stacked into batched tensors.\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"**NOTE**: All models in the `val` split of R2N2 have 24 views, but there are 8 models that split their 24 views between `train` and `test` splits, in which case `collate_batched_meshes` will only be able to join the matrices, views and voxels as lists. However, this can be avoided by loading only one view of each model by setting `return_all_views = False`."
|
| 267 |
+
]
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"cell_type": "code",
|
| 271 |
+
"execution_count": null,
|
| 272 |
+
"metadata": {},
|
| 273 |
+
"outputs": [],
|
| 274 |
+
"source": [
|
| 275 |
+
"batch_size = 12\n",
|
| 276 |
+
"r2n2_single_view = R2N2(\"train\", SHAPENET_PATH, R2N2_PATH, SPLITS_PATH, return_all_views=False, return_voxels=True)\n",
|
| 277 |
+
"r2n2_loader = DataLoader(r2n2_single_view, batch_size=batch_size, collate_fn=collate_batched_meshes)"
|
| 278 |
+
]
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "markdown",
|
| 282 |
+
"metadata": {},
|
| 283 |
+
"source": [
|
| 284 |
+
"Let's visualize all the views (one for each model) in the batch:"
|
| 285 |
+
]
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"cell_type": "code",
|
| 289 |
+
"execution_count": null,
|
| 290 |
+
"metadata": {},
|
| 291 |
+
"outputs": [],
|
| 292 |
+
"source": [
|
| 293 |
+
"it = iter(r2n2_loader)\n",
|
| 294 |
+
"r2n2_batch = next(it)\n",
|
| 295 |
+
"batch_renderings = r2n2_batch[\"images\"] # (N, V, H, W, 3), and in this case V is 1.\n",
|
| 296 |
+
"image_grid(batch_renderings.squeeze().numpy(), rows=3, cols=4, rgb=True)"
|
| 297 |
+
]
|
| 298 |
+
},
|
| 299 |
+
{
|
| 300 |
+
"cell_type": "markdown",
|
| 301 |
+
"metadata": {},
|
| 302 |
+
"source": [
|
| 303 |
+
"## 3. Render ShapeNetCore models with PyTorch3D's differentiable renderer"
|
| 304 |
+
]
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"cell_type": "markdown",
|
| 308 |
+
"metadata": {},
|
| 309 |
+
"source": [
|
| 310 |
+
"Both `ShapeNetCore` and `R2N2` dataloaders have customized `render` functions that support rendering models by specifying their model ids, categories or indices using PyTorch3D's differentiable renderer implementation."
|
| 311 |
+
]
|
| 312 |
+
},
|
| 313 |
+
{
|
| 314 |
+
"cell_type": "code",
|
| 315 |
+
"execution_count": null,
|
| 316 |
+
"metadata": {},
|
| 317 |
+
"outputs": [],
|
| 318 |
+
"source": [
|
| 319 |
+
"# Rendering settings.\n",
|
| 320 |
+
"R, T = look_at_view_transform(1.0, 1.0, 90)\n",
|
| 321 |
+
"cameras = OpenGLPerspectiveCameras(R=R, T=T, device=device)\n",
|
| 322 |
+
"raster_settings = RasterizationSettings(image_size=512)\n",
|
| 323 |
+
"lights = PointLights(location=torch.tensor([0.0, 1.0, -2.0], device=device)[None],device=device)"
|
| 324 |
+
]
|
| 325 |
+
},
|
| 326 |
+
{
|
| 327 |
+
"cell_type": "markdown",
|
| 328 |
+
"metadata": {},
|
| 329 |
+
"source": [
|
| 330 |
+
"First we will try to render three models by their model ids:"
|
| 331 |
+
]
|
| 332 |
+
},
|
| 333 |
+
{
|
| 334 |
+
"cell_type": "code",
|
| 335 |
+
"execution_count": null,
|
| 336 |
+
"metadata": {},
|
| 337 |
+
"outputs": [],
|
| 338 |
+
"source": [
|
| 339 |
+
"images_by_model_ids = shapenet_dataset.render(\n",
|
| 340 |
+
" model_ids=[\n",
|
| 341 |
+
" \"13394ca47c89f91525a3aaf903a41c90\",\n",
|
| 342 |
+
" \"14755c2ee8e693aba508f621166382b0\",\n",
|
| 343 |
+
" \"156c4207af6d2c8f1fdc97905708b8ea\",\n",
|
| 344 |
+
" ],\n",
|
| 345 |
+
" device=device,\n",
|
| 346 |
+
" cameras=cameras,\n",
|
| 347 |
+
" raster_settings=raster_settings,\n",
|
| 348 |
+
" lights=lights,\n",
|
| 349 |
+
")\n",
|
| 350 |
+
"image_grid(images_by_model_ids.cpu().numpy(), rows=1, cols=3, rgb=True)"
|
| 351 |
+
]
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "markdown",
|
| 355 |
+
"metadata": {},
|
| 356 |
+
"source": [
|
| 357 |
+
"Suppose we would like to render the first three models in the dataset, we can render models by their indices:"
|
| 358 |
+
]
|
| 359 |
+
},
|
| 360 |
+
{
|
| 361 |
+
"cell_type": "code",
|
| 362 |
+
"execution_count": null,
|
| 363 |
+
"metadata": {},
|
| 364 |
+
"outputs": [],
|
| 365 |
+
"source": [
|
| 366 |
+
"images_by_idxs = shapenet_dataset.render(\n",
|
| 367 |
+
" idxs=list(range(3)),\n",
|
| 368 |
+
" device=device,\n",
|
| 369 |
+
" cameras=cameras,\n",
|
| 370 |
+
" raster_settings=raster_settings,\n",
|
| 371 |
+
" lights=lights,\n",
|
| 372 |
+
")\n",
|
| 373 |
+
"image_grid(images_by_idxs.cpu().numpy(), rows=1, cols=3, rgb=True)"
|
| 374 |
+
]
|
| 375 |
+
},
|
| 376 |
+
{
|
| 377 |
+
"cell_type": "markdown",
|
| 378 |
+
"metadata": {},
|
| 379 |
+
"source": [
|
| 380 |
+
"Alternatively, if we are not interested in any particular models but would like see random models from some specific categories, we can do that by specifying `categories` and `sample_nums`. For example, if we would like to render 2 models from the category \"faucet\" and 3 models from the category \"chair\", we can do the following:"
|
| 381 |
+
]
|
| 382 |
+
},
|
| 383 |
+
{
|
| 384 |
+
"cell_type": "code",
|
| 385 |
+
"execution_count": null,
|
| 386 |
+
"metadata": {},
|
| 387 |
+
"outputs": [],
|
| 388 |
+
"source": [
|
| 389 |
+
"images_by_categories = shapenet_dataset.render(\n",
|
| 390 |
+
" categories=[\"faucet\", \"chair\"],\n",
|
| 391 |
+
" sample_nums=[2, 3],\n",
|
| 392 |
+
" device=device,\n",
|
| 393 |
+
" cameras=cameras,\n",
|
| 394 |
+
" raster_settings=raster_settings,\n",
|
| 395 |
+
" lights=lights,\n",
|
| 396 |
+
")\n",
|
| 397 |
+
"image_grid(images_by_categories.cpu().numpy(), rows=1, cols=5, rgb=True)"
|
| 398 |
+
]
|
| 399 |
+
},
|
| 400 |
+
{
|
| 401 |
+
"cell_type": "markdown",
|
| 402 |
+
"metadata": {},
|
| 403 |
+
"source": [
|
| 404 |
+
"If we are not interested in any particular categories and just would like to render some random models from the whole dataset, we can set the number of models to be rendered in `sample_nums` and not specify any `categories`:"
|
| 405 |
+
]
|
| 406 |
+
},
|
| 407 |
+
{
|
| 408 |
+
"cell_type": "code",
|
| 409 |
+
"execution_count": null,
|
| 410 |
+
"metadata": {},
|
| 411 |
+
"outputs": [],
|
| 412 |
+
"source": [
|
| 413 |
+
"random_model_images = shapenet_dataset.render(\n",
|
| 414 |
+
" sample_nums=[5],\n",
|
| 415 |
+
" device=device,\n",
|
| 416 |
+
" cameras=cameras,\n",
|
| 417 |
+
" raster_settings=raster_settings,\n",
|
| 418 |
+
" lights=lights,\n",
|
| 419 |
+
")\n",
|
| 420 |
+
"image_grid(random_model_images.cpu().numpy(), rows=1, cols=5, rgb=True)"
|
| 421 |
+
]
|
| 422 |
+
},
|
| 423 |
+
{
|
| 424 |
+
"cell_type": "markdown",
|
| 425 |
+
"metadata": {},
|
| 426 |
+
"source": [
|
| 427 |
+
"## 4. Render R2N2 models with the same orientations as the original renderings in the dataset"
|
| 428 |
+
]
|
| 429 |
+
},
|
| 430 |
+
{
|
| 431 |
+
"cell_type": "markdown",
|
| 432 |
+
"metadata": {},
|
| 433 |
+
"source": [
|
| 434 |
+
"We can render R2N2 models the same way as we rendered ShapeNetCore models above. In addition, we can also render R2N2 models with the same orientations as the original renderings in the dataset. For this we will use R2N2's customized `render` function and a different type of PyTorch3D camera called `BlenderCamera`."
|
| 435 |
+
]
|
| 436 |
+
},
|
| 437 |
+
{
|
| 438 |
+
"cell_type": "markdown",
|
| 439 |
+
"metadata": {},
|
| 440 |
+
"source": [
|
| 441 |
+
"In this example, we will render the seventh model with the same orientations as its second and third views. First we will retrieve R2N2's original renderings to compare with the result."
|
| 442 |
+
]
|
| 443 |
+
},
|
| 444 |
+
{
|
| 445 |
+
"cell_type": "code",
|
| 446 |
+
"execution_count": null,
|
| 447 |
+
"metadata": {},
|
| 448 |
+
"outputs": [],
|
| 449 |
+
"source": [
|
| 450 |
+
"original_rendering = r2n2_dataset[6,[1,2]][\"images\"]\n",
|
| 451 |
+
"image_grid(original_rendering.numpy(), rows=1, cols=2, rgb=True)"
|
| 452 |
+
]
|
| 453 |
+
},
|
| 454 |
+
{
|
| 455 |
+
"cell_type": "markdown",
|
| 456 |
+
"metadata": {},
|
| 457 |
+
"source": [
|
| 458 |
+
"Next, we will visualize PyTorch3D's renderings:"
|
| 459 |
+
]
|
| 460 |
+
},
|
| 461 |
+
{
|
| 462 |
+
"cell_type": "code",
|
| 463 |
+
"execution_count": null,
|
| 464 |
+
"metadata": {},
|
| 465 |
+
"outputs": [],
|
| 466 |
+
"source": [
|
| 467 |
+
"r2n2_oriented_images = r2n2_dataset.render(\n",
|
| 468 |
+
" idxs=[6],\n",
|
| 469 |
+
" view_idxs=[1,2],\n",
|
| 470 |
+
" device=device,\n",
|
| 471 |
+
" raster_settings=raster_settings,\n",
|
| 472 |
+
" lights=lights,\n",
|
| 473 |
+
")\n",
|
| 474 |
+
"image_grid(r2n2_oriented_images.cpu().numpy(), rows=1, cols=2, rgb=True)"
|
| 475 |
+
]
|
| 476 |
+
},
|
| 477 |
+
{
|
| 478 |
+
"cell_type": "markdown",
|
| 479 |
+
"metadata": {},
|
| 480 |
+
"source": [
|
| 481 |
+
"## 5. Visualize R2N2 models' voxels"
|
| 482 |
+
]
|
| 483 |
+
},
|
| 484 |
+
{
|
| 485 |
+
"cell_type": "markdown",
|
| 486 |
+
"metadata": {},
|
| 487 |
+
"source": [
|
| 488 |
+
"R2N2 dataloader also returns models' voxels. We can visualize them by utilizing R2N2's `render_vox_to_mesh` function. This will cubify the voxels to a Meshes object, which will then be rendered."
|
| 489 |
+
]
|
| 490 |
+
},
|
| 491 |
+
{
|
| 492 |
+
"cell_type": "markdown",
|
| 493 |
+
"metadata": {},
|
| 494 |
+
"source": [
|
| 495 |
+
"In this example we will visualize the tenth model in the dataset with the same orientation of its second and third views. First we will retrieve R2N2's original renderings to compare with the result."
|
| 496 |
+
]
|
| 497 |
+
},
|
| 498 |
+
{
|
| 499 |
+
"cell_type": "code",
|
| 500 |
+
"execution_count": null,
|
| 501 |
+
"metadata": {},
|
| 502 |
+
"outputs": [],
|
| 503 |
+
"source": [
|
| 504 |
+
"r2n2_model = r2n2_dataset[9,[1,2]]\n",
|
| 505 |
+
"original_rendering = r2n2_model[\"images\"]\n",
|
| 506 |
+
"image_grid(original_rendering.numpy(), rows=1, cols=2, rgb=True)"
|
| 507 |
+
]
|
| 508 |
+
},
|
| 509 |
+
{
|
| 510 |
+
"cell_type": "markdown",
|
| 511 |
+
"metadata": {},
|
| 512 |
+
"source": [
|
| 513 |
+
"Next, we will pass the voxels to `render_vox_to_mesh`:"
|
| 514 |
+
]
|
| 515 |
+
},
|
| 516 |
+
{
|
| 517 |
+
"cell_type": "code",
|
| 518 |
+
"execution_count": null,
|
| 519 |
+
"metadata": {},
|
| 520 |
+
"outputs": [],
|
| 521 |
+
"source": [
|
| 522 |
+
"vox_render = render_cubified_voxels(r2n2_model[\"voxels\"], device=device)\n",
|
| 523 |
+
"image_grid(vox_render.cpu().numpy(), rows=1, cols=2, rgb=True)"
|
| 524 |
+
]
|
| 525 |
+
}
|
| 526 |
+
],
|
| 527 |
+
"metadata": {
|
| 528 |
+
"anp_metadata": {
|
| 529 |
+
"path": "fbsource/fbcode/vision/fair/pytorch3d/docs/tutorials/Dataloaders_ShapeNetCore_R2N2.ipynb"
|
| 530 |
+
},
|
| 531 |
+
"bento_stylesheets": {
|
| 532 |
+
"bento/extensions/flow/main.css": true,
|
| 533 |
+
"bento/extensions/kernel_selector/main.css": true,
|
| 534 |
+
"bento/extensions/kernel_ui/main.css": true,
|
| 535 |
+
"bento/extensions/new_kernel/main.css": true,
|
| 536 |
+
"bento/extensions/system_usage/main.css": true,
|
| 537 |
+
"bento/extensions/theme/main.css": true
|
| 538 |
+
},
|
| 539 |
+
"disseminate_notebook_info": {
|
| 540 |
+
"backup_notebook_id": "669429066983805"
|
| 541 |
+
},
|
| 542 |
+
"kernelspec": {
|
| 543 |
+
"display_name": "intro_to_cv",
|
| 544 |
+
"language": "python",
|
| 545 |
+
"name": "bento_kernel_intro_to_cv"
|
| 546 |
+
},
|
| 547 |
+
"language_info": {
|
| 548 |
+
"codemirror_mode": {
|
| 549 |
+
"name": "ipython",
|
| 550 |
+
"version": 3
|
| 551 |
+
},
|
| 552 |
+
"file_extension": ".py",
|
| 553 |
+
"mimetype": "text/x-python",
|
| 554 |
+
"name": "python",
|
| 555 |
+
"nbconvert_exporter": "python",
|
| 556 |
+
"pygments_lexer": "ipython3",
|
| 557 |
+
"version": "3.7.5+"
|
| 558 |
+
}
|
| 559 |
+
},
|
| 560 |
+
"nbformat": 4,
|
| 561 |
+
"nbformat_minor": 2
|
| 562 |
+
}
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/deform_source_mesh_to_target_mesh.ipynb
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"metadata": {
|
| 7 |
+
"colab": {},
|
| 8 |
+
"colab_type": "code",
|
| 9 |
+
"id": "nF07sDgJWHQy"
|
| 10 |
+
},
|
| 11 |
+
"outputs": [],
|
| 12 |
+
"source": [
|
| 13 |
+
"# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
|
| 14 |
+
]
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"cell_type": "markdown",
|
| 18 |
+
"metadata": {
|
| 19 |
+
"colab_type": "text",
|
| 20 |
+
"id": "BRcOouCyWHQ2"
|
| 21 |
+
},
|
| 22 |
+
"source": [
|
| 23 |
+
"# Deform a source mesh to form a target mesh using 3D loss functions"
|
| 24 |
+
]
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "markdown",
|
| 28 |
+
"metadata": {
|
| 29 |
+
"colab_type": "text",
|
| 30 |
+
"id": "HfwwW9HqtuvQ"
|
| 31 |
+
},
|
| 32 |
+
"source": [
|
| 33 |
+
"In this tutorial, we learn to deform an initial generic shape (e.g. sphere) to fit a target shape.\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"We will cover: \n",
|
| 36 |
+
"\n",
|
| 37 |
+
"- How to **load a mesh** from an `.obj` file\n",
|
| 38 |
+
"- How to use the PyTorch3D **Meshes** datastructure\n",
|
| 39 |
+
"- How to use 4 different PyTorch3D **mesh loss functions**\n",
|
| 40 |
+
"- How to set up an **optimization loop**\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"Starting from a sphere mesh, we learn the offset to each vertex in the mesh such that\n",
|
| 44 |
+
"the predicted mesh is closer to the target mesh at each optimization step. To achieve this we minimize:\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"+ `chamfer_distance`, the distance between the predicted (deformed) and target mesh, defined as the chamfer distance between the set of pointclouds resulting from **differentiably sampling points** from their surfaces. \n",
|
| 47 |
+
"\n",
|
| 48 |
+
"However, solely minimizing the chamfer distance between the predicted and the target mesh will lead to a non-smooth shape (verify this by setting `w_chamfer=1.0` and all other weights to `0.0`). \n",
|
| 49 |
+
"\n",
|
| 50 |
+
"We enforce smoothness by adding **shape regularizers** to the objective. Namely, we add:\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"+ `mesh_edge_length`, which minimizes the length of the edges in the predicted mesh.\n",
|
| 53 |
+
"+ `mesh_normal_consistency`, which enforces consistency across the normals of neighboring faces.\n",
|
| 54 |
+
"+ `mesh_laplacian_smoothing`, which is the laplacian regularizer."
|
| 55 |
+
]
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "markdown",
|
| 59 |
+
"metadata": {
|
| 60 |
+
"colab_type": "text",
|
| 61 |
+
"id": "P-h1ji4dWHQ5"
|
| 62 |
+
},
|
| 63 |
+
"source": [
|
| 64 |
+
"## 0. Install and Import modules"
|
| 65 |
+
]
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "markdown",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
|
| 72 |
+
]
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"cell_type": "code",
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"metadata": {
|
| 78 |
+
"colab": {},
|
| 79 |
+
"colab_type": "code",
|
| 80 |
+
"id": "_qkuyhyTeRyM"
|
| 81 |
+
},
|
| 82 |
+
"outputs": [],
|
| 83 |
+
"source": [
|
| 84 |
+
"import os\n",
|
| 85 |
+
"import sys\n",
|
| 86 |
+
"import torch\n",
|
| 87 |
+
"import subprocess\n",
|
| 88 |
+
"need_pytorch3d=False\n",
|
| 89 |
+
"try:\n",
|
| 90 |
+
" import pytorch3d\n",
|
| 91 |
+
"except ModuleNotFoundError:\n",
|
| 92 |
+
" need_pytorch3d=True\n",
|
| 93 |
+
"if need_pytorch3d:\n",
|
| 94 |
+
" pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
|
| 95 |
+
" version_str=\"\".join([\n",
|
| 96 |
+
" f\"py3{sys.version_info.minor}_cu\",\n",
|
| 97 |
+
" torch.version.cuda.replace(\".\",\"\"),\n",
|
| 98 |
+
" f\"_pyt{pyt_version_str}\"\n",
|
| 99 |
+
" ])\n",
|
| 100 |
+
" !pip install iopath\n",
|
| 101 |
+
" if sys.platform.startswith(\"linux\"):\n",
|
| 102 |
+
" print(\"Trying to install wheel for PyTorch3D\")\n",
|
| 103 |
+
" !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
|
| 104 |
+
" pip_list = !pip freeze\n",
|
| 105 |
+
" need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
|
| 106 |
+
" if need_pytorch3d:\n",
|
| 107 |
+
" print(f\"failed to find/install wheel for {version_str}\")\n",
|
| 108 |
+
"if need_pytorch3d:\n",
|
| 109 |
+
" print(\"Installing PyTorch3D from source\")\n",
|
| 110 |
+
" !pip install ninja\n",
|
| 111 |
+
" !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
|
| 112 |
+
]
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"metadata": {
|
| 118 |
+
"colab": {},
|
| 119 |
+
"colab_type": "code",
|
| 120 |
+
"id": "ylbZGXYBtuvB"
|
| 121 |
+
},
|
| 122 |
+
"outputs": [],
|
| 123 |
+
"source": [
|
| 124 |
+
"import os\n",
|
| 125 |
+
"import torch\n",
|
| 126 |
+
"from pytorch3d.io import load_obj, save_obj\n",
|
| 127 |
+
"from pytorch3d.structures import Meshes\n",
|
| 128 |
+
"from pytorch3d.utils import ico_sphere\n",
|
| 129 |
+
"from pytorch3d.ops import sample_points_from_meshes\n",
|
| 130 |
+
"from pytorch3d.loss import (\n",
|
| 131 |
+
" chamfer_distance, \n",
|
| 132 |
+
" mesh_edge_loss, \n",
|
| 133 |
+
" mesh_laplacian_smoothing, \n",
|
| 134 |
+
" mesh_normal_consistency,\n",
|
| 135 |
+
")\n",
|
| 136 |
+
"import numpy as np\n",
|
| 137 |
+
"from tqdm.notebook import tqdm\n",
|
| 138 |
+
"%matplotlib notebook \n",
|
| 139 |
+
"from mpl_toolkits.mplot3d import Axes3D\n",
|
| 140 |
+
"import matplotlib.pyplot as plt\n",
|
| 141 |
+
"import matplotlib as mpl\n",
|
| 142 |
+
"mpl.rcParams['savefig.dpi'] = 80\n",
|
| 143 |
+
"mpl.rcParams['figure.dpi'] = 80\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"# Set the device\n",
|
| 146 |
+
"if torch.cuda.is_available():\n",
|
| 147 |
+
" device = torch.device(\"cuda:0\")\n",
|
| 148 |
+
"else:\n",
|
| 149 |
+
" device = torch.device(\"cpu\")\n",
|
| 150 |
+
" print(\"WARNING: CPU only, this will be slow!\")"
|
| 151 |
+
]
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "markdown",
|
| 155 |
+
"metadata": {
|
| 156 |
+
"colab_type": "text",
|
| 157 |
+
"id": "yT1JTXu1WHQ_"
|
| 158 |
+
},
|
| 159 |
+
"source": [
|
| 160 |
+
"## 1. Load an obj file and create a Meshes object"
|
| 161 |
+
]
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "markdown",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"Download the target 3D model of a dolphin. It will be saved locally as a file called `dolphin.obj`."
|
| 168 |
+
]
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"metadata": {
|
| 174 |
+
"colab": {
|
| 175 |
+
"base_uri": "https://localhost:8080/",
|
| 176 |
+
"height": 204
|
| 177 |
+
},
|
| 178 |
+
"colab_type": "code",
|
| 179 |
+
"id": "oFNkB6nQWZSw",
|
| 180 |
+
"outputId": "c1bbe6e2-a4ea-4113-d53d-1cb1ece130f1"
|
| 181 |
+
},
|
| 182 |
+
"outputs": [],
|
| 183 |
+
"source": [
|
| 184 |
+
"!wget https://dl.fbaipublicfiles.com/pytorch3d/data/dolphin/dolphin.obj"
|
| 185 |
+
]
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"metadata": {
|
| 191 |
+
"colab": {},
|
| 192 |
+
"colab_type": "code",
|
| 193 |
+
"id": "dz0imH-ltuvS"
|
| 194 |
+
},
|
| 195 |
+
"outputs": [],
|
| 196 |
+
"source": [
|
| 197 |
+
"# Load the dolphin mesh.\n",
|
| 198 |
+
"trg_obj = 'dolphin.obj'"
|
| 199 |
+
]
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"cell_type": "code",
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"metadata": {
|
| 205 |
+
"colab": {},
|
| 206 |
+
"colab_type": "code",
|
| 207 |
+
"id": "rbyRhI8ituvW"
|
| 208 |
+
},
|
| 209 |
+
"outputs": [],
|
| 210 |
+
"source": [
|
| 211 |
+
"# We read the target 3D model using load_obj\n",
|
| 212 |
+
"verts, faces, aux = load_obj(trg_obj)\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"# verts is a FloatTensor of shape (V, 3) where V is the number of vertices in the mesh\n",
|
| 215 |
+
"# faces is an object which contains the following LongTensors: verts_idx, normals_idx and textures_idx\n",
|
| 216 |
+
"# For this tutorial, normals and textures are ignored.\n",
|
| 217 |
+
"faces_idx = faces.verts_idx.to(device)\n",
|
| 218 |
+
"verts = verts.to(device)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"# We scale normalize and center the target mesh to fit in a sphere of radius 1 centered at (0,0,0). \n",
|
| 221 |
+
"# (scale, center) will be used to bring the predicted mesh to its original center and scale\n",
|
| 222 |
+
"# Note that normalizing the target mesh, speeds up the optimization but is not necessary!\n",
|
| 223 |
+
"center = verts.mean(0)\n",
|
| 224 |
+
"verts = verts - center\n",
|
| 225 |
+
"scale = max(verts.abs().max(0)[0])\n",
|
| 226 |
+
"verts = verts / scale\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"# We construct a Meshes structure for the target mesh\n",
|
| 229 |
+
"trg_mesh = Meshes(verts=[verts], faces=[faces_idx])"
|
| 230 |
+
]
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"execution_count": null,
|
| 235 |
+
"metadata": {
|
| 236 |
+
"colab": {},
|
| 237 |
+
"colab_type": "code",
|
| 238 |
+
"id": "6BxDTpB2WHRH"
|
| 239 |
+
},
|
| 240 |
+
"outputs": [],
|
| 241 |
+
"source": [
|
| 242 |
+
"# We initialize the source shape to be a sphere of radius 1\n",
|
| 243 |
+
"src_mesh = ico_sphere(4, device)"
|
| 244 |
+
]
|
| 245 |
+
},
|
| 246 |
+
{
|
| 247 |
+
"cell_type": "markdown",
|
| 248 |
+
"metadata": {
|
| 249 |
+
"colab_type": "text",
|
| 250 |
+
"id": "dYWDl4VGWHRK"
|
| 251 |
+
},
|
| 252 |
+
"source": [
|
| 253 |
+
"## 2. Visualize the source and target meshes"
|
| 254 |
+
]
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"cell_type": "code",
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"metadata": {
|
| 260 |
+
"colab": {},
|
| 261 |
+
"colab_type": "code",
|
| 262 |
+
"id": "482YycLHWHRL"
|
| 263 |
+
},
|
| 264 |
+
"outputs": [],
|
| 265 |
+
"source": [
|
| 266 |
+
"def plot_pointcloud(mesh, title=\"\"):\n",
|
| 267 |
+
" # Sample points uniformly from the surface of the mesh.\n",
|
| 268 |
+
" points = sample_points_from_meshes(mesh, 5000)\n",
|
| 269 |
+
" x, y, z = points.clone().detach().cpu().squeeze().unbind(1) \n",
|
| 270 |
+
" fig = plt.figure(figsize=(5, 5))\n",
|
| 271 |
+
" ax = fig.add_subplot(111, projection='3d')\n",
|
| 272 |
+
" ax.scatter3D(x, z, -y)\n",
|
| 273 |
+
" ax.set_xlabel('x')\n",
|
| 274 |
+
" ax.set_ylabel('z')\n",
|
| 275 |
+
" ax.set_zlabel('y')\n",
|
| 276 |
+
" ax.set_title(title)\n",
|
| 277 |
+
" ax.view_init(190, 30)\n",
|
| 278 |
+
" plt.show()"
|
| 279 |
+
]
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"cell_type": "code",
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"metadata": {
|
| 285 |
+
"colab": {
|
| 286 |
+
"base_uri": "https://localhost:8080/",
|
| 287 |
+
"height": 765
|
| 288 |
+
},
|
| 289 |
+
"colab_type": "code",
|
| 290 |
+
"id": "UoGcflJ_WHRO",
|
| 291 |
+
"outputId": "b9a2d699-2c68-4696-9dff-d30eea7a0fb0"
|
| 292 |
+
},
|
| 293 |
+
"outputs": [],
|
| 294 |
+
"source": [
|
| 295 |
+
"# %matplotlib notebook\n",
|
| 296 |
+
"plot_pointcloud(trg_mesh, \"Target mesh\")\n",
|
| 297 |
+
"plot_pointcloud(src_mesh, \"Source mesh\")"
|
| 298 |
+
]
|
| 299 |
+
},
|
| 300 |
+
{
|
| 301 |
+
"cell_type": "markdown",
|
| 302 |
+
"metadata": {
|
| 303 |
+
"colab_type": "text",
|
| 304 |
+
"id": "8uzMiTUSWHRS"
|
| 305 |
+
},
|
| 306 |
+
"source": [
|
| 307 |
+
"## 3. Optimization loop "
|
| 308 |
+
]
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"execution_count": null,
|
| 313 |
+
"metadata": {
|
| 314 |
+
"colab": {},
|
| 315 |
+
"colab_type": "code",
|
| 316 |
+
"id": "Sc-3M17Ltuvh"
|
| 317 |
+
},
|
| 318 |
+
"outputs": [],
|
| 319 |
+
"source": [
|
| 320 |
+
"# We will learn to deform the source mesh by offsetting its vertices\n",
|
| 321 |
+
"# The shape of the deform parameters is equal to the total number of vertices in src_mesh\n",
|
| 322 |
+
"deform_verts = torch.full(src_mesh.verts_packed().shape, 0.0, device=device, requires_grad=True)"
|
| 323 |
+
]
|
| 324 |
+
},
|
| 325 |
+
{
|
| 326 |
+
"cell_type": "code",
|
| 327 |
+
"execution_count": null,
|
| 328 |
+
"metadata": {
|
| 329 |
+
"colab": {},
|
| 330 |
+
"colab_type": "code",
|
| 331 |
+
"id": "0BtSUfMYtuvl"
|
| 332 |
+
},
|
| 333 |
+
"outputs": [],
|
| 334 |
+
"source": [
|
| 335 |
+
"# The optimizer\n",
|
| 336 |
+
"optimizer = torch.optim.SGD([deform_verts], lr=1.0, momentum=0.9)"
|
| 337 |
+
]
|
| 338 |
+
},
|
| 339 |
+
{
|
| 340 |
+
"cell_type": "code",
|
| 341 |
+
"execution_count": null,
|
| 342 |
+
"metadata": {
|
| 343 |
+
"colab": {
|
| 344 |
+
"base_uri": "https://localhost:8080/",
|
| 345 |
+
"height": 1000,
|
| 346 |
+
"referenced_widgets": [
|
| 347 |
+
"12fdcbc799cc4da899d889d0399616c2",
|
| 348 |
+
"0bd231c2134e4127a3756807317d6aae",
|
| 349 |
+
"23804ad243d44cecbff89ab0b7f40c7e",
|
| 350 |
+
"be25dd06faf04bf29733cc16deefb189",
|
| 351 |
+
"283601ac2fe54ecc8716aed8842a5dd2",
|
| 352 |
+
"6e2ff75105a74afbb4ed3fafd414e16f",
|
| 353 |
+
"5462de8f68be408d98a6a495e630f448",
|
| 354 |
+
"6e1e9eb164434a06b7b1bc73e4eb4fcd"
|
| 355 |
+
]
|
| 356 |
+
},
|
| 357 |
+
"colab_type": "code",
|
| 358 |
+
"id": "9DAjqI9Atuvp",
|
| 359 |
+
"outputId": "d59e959b-8616-40fe-aec4-5b09b27e325f"
|
| 360 |
+
},
|
| 361 |
+
"outputs": [],
|
| 362 |
+
"source": [
|
| 363 |
+
"# Number of optimization steps\n",
|
| 364 |
+
"Niter = 2000\n",
|
| 365 |
+
"# Weight for the chamfer loss\n",
|
| 366 |
+
"w_chamfer = 1.0 \n",
|
| 367 |
+
"# Weight for mesh edge loss\n",
|
| 368 |
+
"w_edge = 1.0 \n",
|
| 369 |
+
"# Weight for mesh normal consistency\n",
|
| 370 |
+
"w_normal = 0.01 \n",
|
| 371 |
+
"# Weight for mesh laplacian smoothing\n",
|
| 372 |
+
"w_laplacian = 0.1 \n",
|
| 373 |
+
"# Plot period for the losses\n",
|
| 374 |
+
"plot_period = 250\n",
|
| 375 |
+
"loop = tqdm(range(Niter))\n",
|
| 376 |
+
"\n",
|
| 377 |
+
"chamfer_losses = []\n",
|
| 378 |
+
"laplacian_losses = []\n",
|
| 379 |
+
"edge_losses = []\n",
|
| 380 |
+
"normal_losses = []\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"%matplotlib inline\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"for i in loop:\n",
|
| 385 |
+
" # Initialize optimizer\n",
|
| 386 |
+
" optimizer.zero_grad()\n",
|
| 387 |
+
" \n",
|
| 388 |
+
" # Deform the mesh\n",
|
| 389 |
+
" new_src_mesh = src_mesh.offset_verts(deform_verts)\n",
|
| 390 |
+
" \n",
|
| 391 |
+
" # We sample 5k points from the surface of each mesh \n",
|
| 392 |
+
" sample_trg = sample_points_from_meshes(trg_mesh, 5000)\n",
|
| 393 |
+
" sample_src = sample_points_from_meshes(new_src_mesh, 5000)\n",
|
| 394 |
+
" \n",
|
| 395 |
+
" # We compare the two sets of pointclouds by computing (a) the chamfer loss\n",
|
| 396 |
+
" loss_chamfer, _ = chamfer_distance(sample_trg, sample_src)\n",
|
| 397 |
+
" \n",
|
| 398 |
+
" # and (b) the edge length of the predicted mesh\n",
|
| 399 |
+
" loss_edge = mesh_edge_loss(new_src_mesh)\n",
|
| 400 |
+
" \n",
|
| 401 |
+
" # mesh normal consistency\n",
|
| 402 |
+
" loss_normal = mesh_normal_consistency(new_src_mesh)\n",
|
| 403 |
+
" \n",
|
| 404 |
+
" # mesh laplacian smoothing\n",
|
| 405 |
+
" loss_laplacian = mesh_laplacian_smoothing(new_src_mesh, method=\"uniform\")\n",
|
| 406 |
+
" \n",
|
| 407 |
+
" # Weighted sum of the losses\n",
|
| 408 |
+
" loss = loss_chamfer * w_chamfer + loss_edge * w_edge + loss_normal * w_normal + loss_laplacian * w_laplacian\n",
|
| 409 |
+
" \n",
|
| 410 |
+
" # Print the losses\n",
|
| 411 |
+
" loop.set_description('total_loss = %.6f' % loss)\n",
|
| 412 |
+
" \n",
|
| 413 |
+
" # Save the losses for plotting\n",
|
| 414 |
+
" chamfer_losses.append(float(loss_chamfer.detach().cpu()))\n",
|
| 415 |
+
" edge_losses.append(float(loss_edge.detach().cpu()))\n",
|
| 416 |
+
" normal_losses.append(float(loss_normal.detach().cpu()))\n",
|
| 417 |
+
" laplacian_losses.append(float(loss_laplacian.detach().cpu()))\n",
|
| 418 |
+
" \n",
|
| 419 |
+
" # Plot mesh\n",
|
| 420 |
+
" if i % plot_period == 0:\n",
|
| 421 |
+
" plot_pointcloud(new_src_mesh, title=\"iter: %d\" % i)\n",
|
| 422 |
+
" \n",
|
| 423 |
+
" # Optimization step\n",
|
| 424 |
+
" loss.backward()\n",
|
| 425 |
+
" optimizer.step()\n"
|
| 426 |
+
]
|
| 427 |
+
},
|
| 428 |
+
{
|
| 429 |
+
"cell_type": "markdown",
|
| 430 |
+
"metadata": {
|
| 431 |
+
"colab_type": "text",
|
| 432 |
+
"id": "VGcZsvWBWHRc"
|
| 433 |
+
},
|
| 434 |
+
"source": [
|
| 435 |
+
"## 4. Visualize the loss"
|
| 436 |
+
]
|
| 437 |
+
},
|
| 438 |
+
{
|
| 439 |
+
"cell_type": "code",
|
| 440 |
+
"execution_count": null,
|
| 441 |
+
"metadata": {
|
| 442 |
+
"colab": {
|
| 443 |
+
"base_uri": "https://localhost:8080/",
|
| 444 |
+
"height": 374
|
| 445 |
+
},
|
| 446 |
+
"colab_type": "code",
|
| 447 |
+
"id": "baXvAo1yWHRd",
|
| 448 |
+
"outputId": "11ebe2ad-4352-4492-bd67-e6a3c95adc85"
|
| 449 |
+
},
|
| 450 |
+
"outputs": [],
|
| 451 |
+
"source": [
|
| 452 |
+
"fig = plt.figure(figsize=(13, 5))\n",
|
| 453 |
+
"ax = fig.gca()\n",
|
| 454 |
+
"ax.plot(chamfer_losses, label=\"chamfer loss\")\n",
|
| 455 |
+
"ax.plot(edge_losses, label=\"edge loss\")\n",
|
| 456 |
+
"ax.plot(normal_losses, label=\"normal loss\")\n",
|
| 457 |
+
"ax.plot(laplacian_losses, label=\"laplacian loss\")\n",
|
| 458 |
+
"ax.legend(fontsize=\"16\")\n",
|
| 459 |
+
"ax.set_xlabel(\"Iteration\", fontsize=\"16\")\n",
|
| 460 |
+
"ax.set_ylabel(\"Loss\", fontsize=\"16\")\n",
|
| 461 |
+
"ax.set_title(\"Loss vs iterations\", fontsize=\"16\");"
|
| 462 |
+
]
|
| 463 |
+
},
|
| 464 |
+
{
|
| 465 |
+
"cell_type": "markdown",
|
| 466 |
+
"metadata": {
|
| 467 |
+
"colab_type": "text",
|
| 468 |
+
"id": "Y9vSKErDWHRg"
|
| 469 |
+
},
|
| 470 |
+
"source": [
|
| 471 |
+
"## 5. Save the predicted mesh"
|
| 472 |
+
]
|
| 473 |
+
},
|
| 474 |
+
{
|
| 475 |
+
"cell_type": "code",
|
| 476 |
+
"execution_count": null,
|
| 477 |
+
"metadata": {
|
| 478 |
+
"colab": {},
|
| 479 |
+
"colab_type": "code",
|
| 480 |
+
"id": "krikJzrLtuvw"
|
| 481 |
+
},
|
| 482 |
+
"outputs": [],
|
| 483 |
+
"source": [
|
| 484 |
+
"# Fetch the verts and faces of the final predicted mesh\n",
|
| 485 |
+
"final_verts, final_faces = new_src_mesh.get_mesh_verts_faces(0)\n",
|
| 486 |
+
"\n",
|
| 487 |
+
"# Scale normalize back to the original target size\n",
|
| 488 |
+
"final_verts = final_verts * scale + center\n",
|
| 489 |
+
"\n",
|
| 490 |
+
"# Store the predicted mesh using save_obj\n",
|
| 491 |
+
"final_obj = 'final_model.obj'\n",
|
| 492 |
+
"save_obj(final_obj, final_verts, final_faces)"
|
| 493 |
+
]
|
| 494 |
+
},
|
| 495 |
+
{
|
| 496 |
+
"cell_type": "markdown",
|
| 497 |
+
"metadata": {
|
| 498 |
+
"colab_type": "text",
|
| 499 |
+
"id": "quR1DVAcWHRk"
|
| 500 |
+
},
|
| 501 |
+
"source": [
|
| 502 |
+
"## 6. Conclusion \n",
|
| 503 |
+
"\n",
|
| 504 |
+
"In this tutorial we learnt how to load a mesh from an obj file, initialize a PyTorch3D datastructure called **Meshes**, set up an optimization loop and use four different PyTorch3D mesh loss functions. "
|
| 505 |
+
]
|
| 506 |
+
}
|
| 507 |
+
],
|
| 508 |
+
"metadata": {
|
| 509 |
+
"accelerator": "GPU",
|
| 510 |
+
"bento_stylesheets": {
|
| 511 |
+
"bento/extensions/flow/main.css": true,
|
| 512 |
+
"bento/extensions/kernel_selector/main.css": true,
|
| 513 |
+
"bento/extensions/kernel_ui/main.css": true,
|
| 514 |
+
"bento/extensions/new_kernel/main.css": true,
|
| 515 |
+
"bento/extensions/system_usage/main.css": true,
|
| 516 |
+
"bento/extensions/theme/main.css": true
|
| 517 |
+
},
|
| 518 |
+
"colab": {
|
| 519 |
+
"name": "deform_source_mesh_to_target_mesh.ipynb",
|
| 520 |
+
"provenance": []
|
| 521 |
+
},
|
| 522 |
+
"kernelspec": {
|
| 523 |
+
"display_name": "Python 3",
|
| 524 |
+
"language": "python",
|
| 525 |
+
"name": "python3"
|
| 526 |
+
},
|
| 527 |
+
"language_info": {
|
| 528 |
+
"codemirror_mode": {
|
| 529 |
+
"name": "ipython",
|
| 530 |
+
"version": 3
|
| 531 |
+
},
|
| 532 |
+
"file_extension": ".py",
|
| 533 |
+
"mimetype": "text/x-python",
|
| 534 |
+
"name": "python",
|
| 535 |
+
"nbconvert_exporter": "python",
|
| 536 |
+
"pygments_lexer": "ipython3",
|
| 537 |
+
"version": "3.7.6"
|
| 538 |
+
}
|
| 539 |
+
},
|
| 540 |
+
"nbformat": 4,
|
| 541 |
+
"nbformat_minor": 1
|
| 542 |
+
}
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/fit_simple_neural_radiance_field.ipynb
ADDED
|
@@ -0,0 +1,906 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "markdown",
|
| 14 |
+
"metadata": {},
|
| 15 |
+
"source": [
|
| 16 |
+
"# Fit a simple Neural Radiance Field via raymarching\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"This tutorial shows how to fit Neural Radiance Field given a set of views of a scene using differentiable implicit function rendering.\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"More specifically, this tutorial will explain how to:\n",
|
| 21 |
+
"1. Create a differentiable implicit function renderer with either image-grid or Monte Carlo ray sampling.\n",
|
| 22 |
+
"2. Create an Implicit model of a scene.\n",
|
| 23 |
+
"3. Fit the implicit function (Neural Radiance Field) based on input images using the differentiable implicit renderer. \n",
|
| 24 |
+
"4. Visualize the learnt implicit function.\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"Note that the presented implicit model is a simplified version of NeRF:<br>\n",
|
| 27 |
+
"_Ben Mildenhall, Pratul P. Srinivasan, Matthew Tancik, Jonathan T. Barron, Ravi Ramamoorthi, Ren Ng: NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis, ECCV 2020._\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"The simplifications include:\n",
|
| 30 |
+
"* *Ray sampling*: This notebook does not perform stratified ray sampling but rather ray sampling at equidistant depths.\n",
|
| 31 |
+
"* *Rendering*: We do a single rendering pass, as opposed to the original implementation that does a coarse and fine rendering pass.\n",
|
| 32 |
+
"* *Architecture*: Our network is shallower which allows for faster optimization possibly at the cost of surface details.\n",
|
| 33 |
+
"* *Mask loss*: Since our observations include segmentation masks, we also optimize a silhouette loss that forces rays to either get fully absorbed inside the volume, or to completely pass through it.\n"
|
| 34 |
+
]
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "markdown",
|
| 38 |
+
"metadata": {},
|
| 39 |
+
"source": [
|
| 40 |
+
"## 0. Install and Import modules\n",
|
| 41 |
+
"Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
|
| 42 |
+
]
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"execution_count": null,
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"outputs": [],
|
| 49 |
+
"source": [
|
| 50 |
+
"import os\n",
|
| 51 |
+
"import sys\n",
|
| 52 |
+
"import torch\n",
|
| 53 |
+
"import subprocess\n",
|
| 54 |
+
"need_pytorch3d=False\n",
|
| 55 |
+
"try:\n",
|
| 56 |
+
" import pytorch3d\n",
|
| 57 |
+
"except ModuleNotFoundError:\n",
|
| 58 |
+
" need_pytorch3d=True\n",
|
| 59 |
+
"if need_pytorch3d:\n",
|
| 60 |
+
" pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
|
| 61 |
+
" version_str=\"\".join([\n",
|
| 62 |
+
" f\"py3{sys.version_info.minor}_cu\",\n",
|
| 63 |
+
" torch.version.cuda.replace(\".\",\"\"),\n",
|
| 64 |
+
" f\"_pyt{pyt_version_str}\"\n",
|
| 65 |
+
" ])\n",
|
| 66 |
+
" !pip install iopath\n",
|
| 67 |
+
" if sys.platform.startswith(\"linux\"):\n",
|
| 68 |
+
" print(\"Trying to install wheel for PyTorch3D\")\n",
|
| 69 |
+
" !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
|
| 70 |
+
" pip_list = !pip freeze\n",
|
| 71 |
+
" need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
|
| 72 |
+
" if need_pytorch3d:\n",
|
| 73 |
+
" print(f\"failed to find/install wheel for {version_str}\")\n",
|
| 74 |
+
"if need_pytorch3d:\n",
|
| 75 |
+
" print(\"Installing PyTorch3D from source\")\n",
|
| 76 |
+
" !pip install ninja\n",
|
| 77 |
+
" !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
|
| 78 |
+
]
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"outputs": [],
|
| 85 |
+
"source": [
|
| 86 |
+
"# %matplotlib inline\n",
|
| 87 |
+
"# %matplotlib notebook\n",
|
| 88 |
+
"import os\n",
|
| 89 |
+
"import sys\n",
|
| 90 |
+
"import time\n",
|
| 91 |
+
"import json\n",
|
| 92 |
+
"import glob\n",
|
| 93 |
+
"import torch\n",
|
| 94 |
+
"import math\n",
|
| 95 |
+
"import matplotlib.pyplot as plt\n",
|
| 96 |
+
"import numpy as np\n",
|
| 97 |
+
"from PIL import Image\n",
|
| 98 |
+
"from IPython import display\n",
|
| 99 |
+
"from tqdm.notebook import tqdm\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"# Data structures and functions for rendering\n",
|
| 102 |
+
"from pytorch3d.structures import Volumes\n",
|
| 103 |
+
"from pytorch3d.transforms import so3_exp_map\n",
|
| 104 |
+
"from pytorch3d.renderer import (\n",
|
| 105 |
+
" FoVPerspectiveCameras, \n",
|
| 106 |
+
" NDCMultinomialRaysampler,\n",
|
| 107 |
+
" MonteCarloRaysampler,\n",
|
| 108 |
+
" EmissionAbsorptionRaymarcher,\n",
|
| 109 |
+
" ImplicitRenderer,\n",
|
| 110 |
+
" RayBundle,\n",
|
| 111 |
+
" ray_bundle_to_ray_points,\n",
|
| 112 |
+
")\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"# obtain the utilized device\n",
|
| 115 |
+
"if torch.cuda.is_available():\n",
|
| 116 |
+
" device = torch.device(\"cuda:0\")\n",
|
| 117 |
+
" torch.cuda.set_device(device)\n",
|
| 118 |
+
"else:\n",
|
| 119 |
+
" print(\n",
|
| 120 |
+
" 'Please note that NeRF is a resource-demanding method.'\n",
|
| 121 |
+
" + ' Running this notebook on CPU will be extremely slow.'\n",
|
| 122 |
+
" + ' We recommend running the example on a GPU'\n",
|
| 123 |
+
" + ' with at least 10 GB of memory.'\n",
|
| 124 |
+
" )\n",
|
| 125 |
+
" device = torch.device(\"cpu\")"
|
| 126 |
+
]
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"outputs": [],
|
| 133 |
+
"source": [
|
| 134 |
+
"!wget https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/docs/tutorials/utils/plot_image_grid.py\n",
|
| 135 |
+
"!wget https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/docs/tutorials/utils/generate_cow_renders.py\n",
|
| 136 |
+
"from plot_image_grid import image_grid\n",
|
| 137 |
+
"from generate_cow_renders import generate_cow_renders"
|
| 138 |
+
]
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "markdown",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"OR if running locally uncomment and run the following cell:"
|
| 145 |
+
]
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"outputs": [],
|
| 152 |
+
"source": [
|
| 153 |
+
"# from utils.generate_cow_renders import generate_cow_renders\n",
|
| 154 |
+
"# from utils import image_grid"
|
| 155 |
+
]
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "markdown",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"## 1. Generate images of the scene and masks\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"The following cell generates our training data.\n",
|
| 164 |
+
"It renders the cow mesh from the `fit_textured_mesh.ipynb` tutorial from several viewpoints and returns:\n",
|
| 165 |
+
"1. A batch of image and silhouette tensors that are produced by the cow mesh renderer.\n",
|
| 166 |
+
"2. A set of cameras corresponding to each render.\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"Note: For the purpose of this tutorial, which aims at explaining the details of implicit rendering, we do not explain how the mesh rendering, implemented in the `generate_cow_renders` function, works. Please refer to `fit_textured_mesh.ipynb` for a detailed explanation of mesh rendering."
|
| 169 |
+
]
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"outputs": [],
|
| 176 |
+
"source": [
|
| 177 |
+
"target_cameras, target_images, target_silhouettes = generate_cow_renders(num_views=40, azimuth_range=180)\n",
|
| 178 |
+
"print(f'Generated {len(target_images)} images/silhouettes/cameras.')"
|
| 179 |
+
]
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"cell_type": "markdown",
|
| 183 |
+
"metadata": {},
|
| 184 |
+
"source": [
|
| 185 |
+
"## 2. Initialize the implicit renderer\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"The following initializes an implicit renderer that emits a ray from each pixel of a target image and samples a set of uniformly-spaced points along the ray. At each ray-point, the corresponding density and color value is obtained by querying the corresponding location in the neural model of the scene (the model is described & instantiated in a later cell).\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"The renderer is composed of a *raymarcher* and a *raysampler*.\n",
|
| 190 |
+
"- The *raysampler* is responsible for emitting rays from image pixels and sampling the points along them. Here, we use two different raysamplers:\n",
|
| 191 |
+
" - `MonteCarloRaysampler` is used to generate rays from a random subset of pixels of the image plane. The random subsampling of pixels is carried out during **training** to decrease the memory consumption of the implicit model.\n",
|
| 192 |
+
" - `NDCMultinomialRaysampler` which follows the standard PyTorch3D coordinate grid convention (+X from right to left; +Y from bottom to top; +Z away from the user). In combination with the implicit model of the scene, `NDCMultinomialRaysampler` consumes a large amount of memory and, hence, is only used for visualizing the results of the training at **test** time.\n",
|
| 193 |
+
"- The *raymarcher* takes the densities and colors sampled along each ray and renders each ray into a color and an opacity value of the ray's source pixel. Here we use the `EmissionAbsorptionRaymarcher` which implements the standard Emission-Absorption raymarching algorithm."
|
| 194 |
+
]
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"cell_type": "code",
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"outputs": [],
|
| 201 |
+
"source": [
|
| 202 |
+
"# render_size describes the size of both sides of the \n",
|
| 203 |
+
"# rendered images in pixels. Since an advantage of \n",
|
| 204 |
+
"# Neural Radiance Fields are high quality renders\n",
|
| 205 |
+
"# with a significant amount of details, we render\n",
|
| 206 |
+
"# the implicit function at double the size of \n",
|
| 207 |
+
"# target images.\n",
|
| 208 |
+
"render_size = target_images.shape[1] * 2\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"# Our rendered scene is centered around (0,0,0) \n",
|
| 211 |
+
"# and is enclosed inside a bounding box\n",
|
| 212 |
+
"# whose side is roughly equal to 3.0 (world units).\n",
|
| 213 |
+
"volume_extent_world = 3.0\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"# 1) Instantiate the raysamplers.\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"# Here, NDCMultinomialRaysampler generates a rectangular image\n",
|
| 218 |
+
"# grid of rays whose coordinates follow the PyTorch3D\n",
|
| 219 |
+
"# coordinate conventions.\n",
|
| 220 |
+
"raysampler_grid = NDCMultinomialRaysampler(\n",
|
| 221 |
+
" image_height=render_size,\n",
|
| 222 |
+
" image_width=render_size,\n",
|
| 223 |
+
" n_pts_per_ray=128,\n",
|
| 224 |
+
" min_depth=0.1,\n",
|
| 225 |
+
" max_depth=volume_extent_world,\n",
|
| 226 |
+
")\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"# MonteCarloRaysampler generates a random subset \n",
|
| 229 |
+
"# of `n_rays_per_image` rays emitted from the image plane.\n",
|
| 230 |
+
"raysampler_mc = MonteCarloRaysampler(\n",
|
| 231 |
+
" min_x = -1.0,\n",
|
| 232 |
+
" max_x = 1.0,\n",
|
| 233 |
+
" min_y = -1.0,\n",
|
| 234 |
+
" max_y = 1.0,\n",
|
| 235 |
+
" n_rays_per_image=750,\n",
|
| 236 |
+
" n_pts_per_ray=128,\n",
|
| 237 |
+
" min_depth=0.1,\n",
|
| 238 |
+
" max_depth=volume_extent_world,\n",
|
| 239 |
+
")\n",
|
| 240 |
+
"\n",
|
| 241 |
+
"# 2) Instantiate the raymarcher.\n",
|
| 242 |
+
"# Here, we use the standard EmissionAbsorptionRaymarcher \n",
|
| 243 |
+
"# which marches along each ray in order to render\n",
|
| 244 |
+
"# the ray into a single 3D color vector \n",
|
| 245 |
+
"# and an opacity scalar.\n",
|
| 246 |
+
"raymarcher = EmissionAbsorptionRaymarcher()\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"# Finally, instantiate the implicit renders\n",
|
| 249 |
+
"# for both raysamplers.\n",
|
| 250 |
+
"renderer_grid = ImplicitRenderer(\n",
|
| 251 |
+
" raysampler=raysampler_grid, raymarcher=raymarcher,\n",
|
| 252 |
+
")\n",
|
| 253 |
+
"renderer_mc = ImplicitRenderer(\n",
|
| 254 |
+
" raysampler=raysampler_mc, raymarcher=raymarcher,\n",
|
| 255 |
+
")"
|
| 256 |
+
]
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "markdown",
|
| 260 |
+
"metadata": {},
|
| 261 |
+
"source": [
|
| 262 |
+
"## 3. Define the neural radiance field model\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"In this cell we define the `NeuralRadianceField` module, which specifies a continuous field of colors and opacities over the 3D domain of the scene.\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"The `forward` function of `NeuralRadianceField` (NeRF) receives as input a set of tensors that parametrize a bundle of rendering rays. The ray bundle is later converted to 3D ray points in the world coordinates of the scene. Each 3D point is then mapped to a harmonic representation using the `HarmonicEmbedding` layer (defined in the next cell). The harmonic embeddings then enter the _color_ and _opacity_ branches of the NeRF model in order to label each ray point with a 3D vector and a 1D scalar ranging in [0-1] which define the point's RGB color and opacity respectively.\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"Since NeRF has a large memory footprint, we also implement the `NeuralRadianceField.forward_batched` method. The method splits the input rays into batches and executes the `forward` function for each batch separately in a for loop. This lets us render a large set of rays without running out of GPU memory. Standardly, `forward_batched` would be used to render rays emitted from all pixels of an image in order to produce a full-sized render of a scene.\n"
|
| 269 |
+
]
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"cell_type": "code",
|
| 273 |
+
"execution_count": null,
|
| 274 |
+
"metadata": {},
|
| 275 |
+
"outputs": [],
|
| 276 |
+
"source": [
|
| 277 |
+
"class HarmonicEmbedding(torch.nn.Module):\n",
|
| 278 |
+
" def __init__(self, n_harmonic_functions=60, omega0=0.1):\n",
|
| 279 |
+
" \"\"\"\n",
|
| 280 |
+
" Given an input tensor `x` of shape [minibatch, ... , dim],\n",
|
| 281 |
+
" the harmonic embedding layer converts each feature\n",
|
| 282 |
+
" in `x` into a series of harmonic features `embedding`\n",
|
| 283 |
+
" as follows:\n",
|
| 284 |
+
" embedding[..., i*dim:(i+1)*dim] = [\n",
|
| 285 |
+
" sin(x[..., i]),\n",
|
| 286 |
+
" sin(2*x[..., i]),\n",
|
| 287 |
+
" sin(4*x[..., i]),\n",
|
| 288 |
+
" ...\n",
|
| 289 |
+
" sin(2**(self.n_harmonic_functions-1) * x[..., i]),\n",
|
| 290 |
+
" cos(x[..., i]),\n",
|
| 291 |
+
" cos(2*x[..., i]),\n",
|
| 292 |
+
" cos(4*x[..., i]),\n",
|
| 293 |
+
" ...\n",
|
| 294 |
+
" cos(2**(self.n_harmonic_functions-1) * x[..., i])\n",
|
| 295 |
+
" ]\n",
|
| 296 |
+
" \n",
|
| 297 |
+
" Note that `x` is also premultiplied by `omega0` before\n",
|
| 298 |
+
" evaluating the harmonic functions.\n",
|
| 299 |
+
" \"\"\"\n",
|
| 300 |
+
" super().__init__()\n",
|
| 301 |
+
" self.register_buffer(\n",
|
| 302 |
+
" 'frequencies',\n",
|
| 303 |
+
" omega0 * (2.0 ** torch.arange(n_harmonic_functions)),\n",
|
| 304 |
+
" )\n",
|
| 305 |
+
" def forward(self, x):\n",
|
| 306 |
+
" \"\"\"\n",
|
| 307 |
+
" Args:\n",
|
| 308 |
+
" x: tensor of shape [..., dim]\n",
|
| 309 |
+
" Returns:\n",
|
| 310 |
+
" embedding: a harmonic embedding of `x`\n",
|
| 311 |
+
" of shape [..., n_harmonic_functions * dim * 2]\n",
|
| 312 |
+
" \"\"\"\n",
|
| 313 |
+
" embed = (x[..., None] * self.frequencies).view(*x.shape[:-1], -1)\n",
|
| 314 |
+
" return torch.cat((embed.sin(), embed.cos()), dim=-1)\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"class NeuralRadianceField(torch.nn.Module):\n",
|
| 318 |
+
" def __init__(self, n_harmonic_functions=60, n_hidden_neurons=256):\n",
|
| 319 |
+
" super().__init__()\n",
|
| 320 |
+
" \"\"\"\n",
|
| 321 |
+
" Args:\n",
|
| 322 |
+
" n_harmonic_functions: The number of harmonic functions\n",
|
| 323 |
+
" used to form the harmonic embedding of each point.\n",
|
| 324 |
+
" n_hidden_neurons: The number of hidden units in the\n",
|
| 325 |
+
" fully connected layers of the MLPs of the model.\n",
|
| 326 |
+
" \"\"\"\n",
|
| 327 |
+
" \n",
|
| 328 |
+
" # The harmonic embedding layer converts input 3D coordinates\n",
|
| 329 |
+
" # to a representation that is more suitable for\n",
|
| 330 |
+
" # processing with a deep neural network.\n",
|
| 331 |
+
" self.harmonic_embedding = HarmonicEmbedding(n_harmonic_functions)\n",
|
| 332 |
+
" \n",
|
| 333 |
+
" # The dimension of the harmonic embedding.\n",
|
| 334 |
+
" embedding_dim = n_harmonic_functions * 2 * 3\n",
|
| 335 |
+
" \n",
|
| 336 |
+
" # self.mlp is a simple 2-layer multi-layer perceptron\n",
|
| 337 |
+
" # which converts the input per-point harmonic embeddings\n",
|
| 338 |
+
" # to a latent representation.\n",
|
| 339 |
+
" # Not that we use Softplus activations instead of ReLU.\n",
|
| 340 |
+
" self.mlp = torch.nn.Sequential(\n",
|
| 341 |
+
" torch.nn.Linear(embedding_dim, n_hidden_neurons),\n",
|
| 342 |
+
" torch.nn.Softplus(beta=10.0),\n",
|
| 343 |
+
" torch.nn.Linear(n_hidden_neurons, n_hidden_neurons),\n",
|
| 344 |
+
" torch.nn.Softplus(beta=10.0),\n",
|
| 345 |
+
" ) \n",
|
| 346 |
+
" \n",
|
| 347 |
+
" # Given features predicted by self.mlp, self.color_layer\n",
|
| 348 |
+
" # is responsible for predicting a 3-D per-point vector\n",
|
| 349 |
+
" # that represents the RGB color of the point.\n",
|
| 350 |
+
" self.color_layer = torch.nn.Sequential(\n",
|
| 351 |
+
" torch.nn.Linear(n_hidden_neurons + embedding_dim, n_hidden_neurons),\n",
|
| 352 |
+
" torch.nn.Softplus(beta=10.0),\n",
|
| 353 |
+
" torch.nn.Linear(n_hidden_neurons, 3),\n",
|
| 354 |
+
" torch.nn.Sigmoid(),\n",
|
| 355 |
+
" # To ensure that the colors correctly range between [0-1],\n",
|
| 356 |
+
" # the layer is terminated with a sigmoid layer.\n",
|
| 357 |
+
" ) \n",
|
| 358 |
+
" \n",
|
| 359 |
+
" # The density layer converts the features of self.mlp\n",
|
| 360 |
+
" # to a 1D density value representing the raw opacity\n",
|
| 361 |
+
" # of each point.\n",
|
| 362 |
+
" self.density_layer = torch.nn.Sequential(\n",
|
| 363 |
+
" torch.nn.Linear(n_hidden_neurons, 1),\n",
|
| 364 |
+
" torch.nn.Softplus(beta=10.0),\n",
|
| 365 |
+
" # Sofplus activation ensures that the raw opacity\n",
|
| 366 |
+
" # is a non-negative number.\n",
|
| 367 |
+
" )\n",
|
| 368 |
+
" \n",
|
| 369 |
+
" # We set the bias of the density layer to -1.5\n",
|
| 370 |
+
" # in order to initialize the opacities of the\n",
|
| 371 |
+
" # ray points to values close to 0. \n",
|
| 372 |
+
" # This is a crucial detail for ensuring convergence\n",
|
| 373 |
+
" # of the model.\n",
|
| 374 |
+
" self.density_layer[0].bias.data[0] = -1.5 \n",
|
| 375 |
+
" \n",
|
| 376 |
+
" def _get_densities(self, features):\n",
|
| 377 |
+
" \"\"\"\n",
|
| 378 |
+
" This function takes `features` predicted by `self.mlp`\n",
|
| 379 |
+
" and converts them to `raw_densities` with `self.density_layer`.\n",
|
| 380 |
+
" `raw_densities` are later mapped to [0-1] range with\n",
|
| 381 |
+
" 1 - inverse exponential of `raw_densities`.\n",
|
| 382 |
+
" \"\"\"\n",
|
| 383 |
+
" raw_densities = self.density_layer(features)\n",
|
| 384 |
+
" return 1 - (-raw_densities).exp()\n",
|
| 385 |
+
" \n",
|
| 386 |
+
" def _get_colors(self, features, rays_directions):\n",
|
| 387 |
+
" \"\"\"\n",
|
| 388 |
+
" This function takes per-point `features` predicted by `self.mlp`\n",
|
| 389 |
+
" and evaluates the color model in order to attach to each\n",
|
| 390 |
+
" point a 3D vector of its RGB color.\n",
|
| 391 |
+
" \n",
|
| 392 |
+
" In order to represent viewpoint dependent effects,\n",
|
| 393 |
+
" before evaluating `self.color_layer`, `NeuralRadianceField`\n",
|
| 394 |
+
" concatenates to the `features` a harmonic embedding\n",
|
| 395 |
+
" of `ray_directions`, which are per-point directions \n",
|
| 396 |
+
" of point rays expressed as 3D l2-normalized vectors\n",
|
| 397 |
+
" in world coordinates.\n",
|
| 398 |
+
" \"\"\"\n",
|
| 399 |
+
" spatial_size = features.shape[:-1]\n",
|
| 400 |
+
" \n",
|
| 401 |
+
" # Normalize the ray_directions to unit l2 norm.\n",
|
| 402 |
+
" rays_directions_normed = torch.nn.functional.normalize(\n",
|
| 403 |
+
" rays_directions, dim=-1\n",
|
| 404 |
+
" )\n",
|
| 405 |
+
" \n",
|
| 406 |
+
" # Obtain the harmonic embedding of the normalized ray directions.\n",
|
| 407 |
+
" rays_embedding = self.harmonic_embedding(\n",
|
| 408 |
+
" rays_directions_normed\n",
|
| 409 |
+
" )\n",
|
| 410 |
+
" \n",
|
| 411 |
+
" # Expand the ray directions tensor so that its spatial size\n",
|
| 412 |
+
" # is equal to the size of features.\n",
|
| 413 |
+
" rays_embedding_expand = rays_embedding[..., None, :].expand(\n",
|
| 414 |
+
" *spatial_size, rays_embedding.shape[-1]\n",
|
| 415 |
+
" )\n",
|
| 416 |
+
" \n",
|
| 417 |
+
" # Concatenate ray direction embeddings with \n",
|
| 418 |
+
" # features and evaluate the color model.\n",
|
| 419 |
+
" color_layer_input = torch.cat(\n",
|
| 420 |
+
" (features, rays_embedding_expand),\n",
|
| 421 |
+
" dim=-1\n",
|
| 422 |
+
" )\n",
|
| 423 |
+
" return self.color_layer(color_layer_input)\n",
|
| 424 |
+
" \n",
|
| 425 |
+
" \n",
|
| 426 |
+
" def forward(\n",
|
| 427 |
+
" self, \n",
|
| 428 |
+
" ray_bundle: RayBundle,\n",
|
| 429 |
+
" **kwargs,\n",
|
| 430 |
+
" ):\n",
|
| 431 |
+
" \"\"\"\n",
|
| 432 |
+
" The forward function accepts the parametrizations of\n",
|
| 433 |
+
" 3D points sampled along projection rays. The forward\n",
|
| 434 |
+
" pass is responsible for attaching a 3D vector\n",
|
| 435 |
+
" and a 1D scalar representing the point's \n",
|
| 436 |
+
" RGB color and opacity respectively.\n",
|
| 437 |
+
" \n",
|
| 438 |
+
" Args:\n",
|
| 439 |
+
" ray_bundle: A RayBundle object containing the following variables:\n",
|
| 440 |
+
" origins: A tensor of shape `(minibatch, ..., 3)` denoting the\n",
|
| 441 |
+
" origins of the sampling rays in world coords.\n",
|
| 442 |
+
" directions: A tensor of shape `(minibatch, ..., 3)`\n",
|
| 443 |
+
" containing the direction vectors of sampling rays in world coords.\n",
|
| 444 |
+
" lengths: A tensor of shape `(minibatch, ..., num_points_per_ray)`\n",
|
| 445 |
+
" containing the lengths at which the rays are sampled.\n",
|
| 446 |
+
"\n",
|
| 447 |
+
" Returns:\n",
|
| 448 |
+
" rays_densities: A tensor of shape `(minibatch, ..., num_points_per_ray, 1)`\n",
|
| 449 |
+
" denoting the opacity of each ray point.\n",
|
| 450 |
+
" rays_colors: A tensor of shape `(minibatch, ..., num_points_per_ray, 3)`\n",
|
| 451 |
+
" denoting the color of each ray point.\n",
|
| 452 |
+
" \"\"\"\n",
|
| 453 |
+
" # We first convert the ray parametrizations to world\n",
|
| 454 |
+
" # coordinates with `ray_bundle_to_ray_points`.\n",
|
| 455 |
+
" rays_points_world = ray_bundle_to_ray_points(ray_bundle)\n",
|
| 456 |
+
" # rays_points_world.shape = [minibatch x ... x 3]\n",
|
| 457 |
+
" \n",
|
| 458 |
+
" # For each 3D world coordinate, we obtain its harmonic embedding.\n",
|
| 459 |
+
" embeds = self.harmonic_embedding(\n",
|
| 460 |
+
" rays_points_world\n",
|
| 461 |
+
" )\n",
|
| 462 |
+
" # embeds.shape = [minibatch x ... x self.n_harmonic_functions*6]\n",
|
| 463 |
+
" \n",
|
| 464 |
+
" # self.mlp maps each harmonic embedding to a latent feature space.\n",
|
| 465 |
+
" features = self.mlp(embeds)\n",
|
| 466 |
+
" # features.shape = [minibatch x ... x n_hidden_neurons]\n",
|
| 467 |
+
" \n",
|
| 468 |
+
" # Finally, given the per-point features, \n",
|
| 469 |
+
" # execute the density and color branches.\n",
|
| 470 |
+
" \n",
|
| 471 |
+
" rays_densities = self._get_densities(features)\n",
|
| 472 |
+
" # rays_densities.shape = [minibatch x ... x 1]\n",
|
| 473 |
+
"\n",
|
| 474 |
+
" rays_colors = self._get_colors(features, ray_bundle.directions)\n",
|
| 475 |
+
" # rays_colors.shape = [minibatch x ... x 3]\n",
|
| 476 |
+
" \n",
|
| 477 |
+
" return rays_densities, rays_colors\n",
|
| 478 |
+
" \n",
|
| 479 |
+
" def batched_forward(\n",
|
| 480 |
+
" self, \n",
|
| 481 |
+
" ray_bundle: RayBundle,\n",
|
| 482 |
+
" n_batches: int = 16,\n",
|
| 483 |
+
" **kwargs, \n",
|
| 484 |
+
" ):\n",
|
| 485 |
+
" \"\"\"\n",
|
| 486 |
+
" This function is used to allow for memory efficient processing\n",
|
| 487 |
+
" of input rays. The input rays are first split to `n_batches`\n",
|
| 488 |
+
" chunks and passed through the `self.forward` function one at a time\n",
|
| 489 |
+
" in a for loop. Combined with disabling PyTorch gradient caching\n",
|
| 490 |
+
" (`torch.no_grad()`), this allows for rendering large batches\n",
|
| 491 |
+
" of rays that do not all fit into GPU memory in a single forward pass.\n",
|
| 492 |
+
" In our case, batched_forward is used to export a fully-sized render\n",
|
| 493 |
+
" of the radiance field for visualization purposes.\n",
|
| 494 |
+
" \n",
|
| 495 |
+
" Args:\n",
|
| 496 |
+
" ray_bundle: A RayBundle object containing the following variables:\n",
|
| 497 |
+
" origins: A tensor of shape `(minibatch, ..., 3)` denoting the\n",
|
| 498 |
+
" origins of the sampling rays in world coords.\n",
|
| 499 |
+
" directions: A tensor of shape `(minibatch, ..., 3)`\n",
|
| 500 |
+
" containing the direction vectors of sampling rays in world coords.\n",
|
| 501 |
+
" lengths: A tensor of shape `(minibatch, ..., num_points_per_ray)`\n",
|
| 502 |
+
" containing the lengths at which the rays are sampled.\n",
|
| 503 |
+
" n_batches: Specifies the number of batches the input rays are split into.\n",
|
| 504 |
+
" The larger the number of batches, the smaller the memory footprint\n",
|
| 505 |
+
" and the lower the processing speed.\n",
|
| 506 |
+
"\n",
|
| 507 |
+
" Returns:\n",
|
| 508 |
+
" rays_densities: A tensor of shape `(minibatch, ..., num_points_per_ray, 1)`\n",
|
| 509 |
+
" denoting the opacity of each ray point.\n",
|
| 510 |
+
" rays_colors: A tensor of shape `(minibatch, ..., num_points_per_ray, 3)`\n",
|
| 511 |
+
" denoting the color of each ray point.\n",
|
| 512 |
+
"\n",
|
| 513 |
+
" \"\"\"\n",
|
| 514 |
+
"\n",
|
| 515 |
+
" # Parse out shapes needed for tensor reshaping in this function.\n",
|
| 516 |
+
" n_pts_per_ray = ray_bundle.lengths.shape[-1] \n",
|
| 517 |
+
" spatial_size = [*ray_bundle.origins.shape[:-1], n_pts_per_ray]\n",
|
| 518 |
+
"\n",
|
| 519 |
+
" # Split the rays to `n_batches` batches.\n",
|
| 520 |
+
" tot_samples = ray_bundle.origins.shape[:-1].numel()\n",
|
| 521 |
+
" batches = torch.chunk(torch.arange(tot_samples), n_batches)\n",
|
| 522 |
+
"\n",
|
| 523 |
+
" # For each batch, execute the standard forward pass.\n",
|
| 524 |
+
" batch_outputs = [\n",
|
| 525 |
+
" self.forward(\n",
|
| 526 |
+
" RayBundle(\n",
|
| 527 |
+
" origins=ray_bundle.origins.view(-1, 3)[batch_idx],\n",
|
| 528 |
+
" directions=ray_bundle.directions.view(-1, 3)[batch_idx],\n",
|
| 529 |
+
" lengths=ray_bundle.lengths.view(-1, n_pts_per_ray)[batch_idx],\n",
|
| 530 |
+
" xys=None,\n",
|
| 531 |
+
" )\n",
|
| 532 |
+
" ) for batch_idx in batches\n",
|
| 533 |
+
" ]\n",
|
| 534 |
+
" \n",
|
| 535 |
+
" # Concatenate the per-batch rays_densities and rays_colors\n",
|
| 536 |
+
" # and reshape according to the sizes of the inputs.\n",
|
| 537 |
+
" rays_densities, rays_colors = [\n",
|
| 538 |
+
" torch.cat(\n",
|
| 539 |
+
" [batch_output[output_i] for batch_output in batch_outputs], dim=0\n",
|
| 540 |
+
" ).view(*spatial_size, -1) for output_i in (0, 1)\n",
|
| 541 |
+
" ]\n",
|
| 542 |
+
" return rays_densities, rays_colors"
|
| 543 |
+
]
|
| 544 |
+
},
|
| 545 |
+
{
|
| 546 |
+
"cell_type": "markdown",
|
| 547 |
+
"metadata": {},
|
| 548 |
+
"source": [
|
| 549 |
+
"## 4. Helper functions\n",
|
| 550 |
+
"\n",
|
| 551 |
+
"In this function we define functions that help with the Neural Radiance Field optimization."
|
| 552 |
+
]
|
| 553 |
+
},
|
| 554 |
+
{
|
| 555 |
+
"cell_type": "code",
|
| 556 |
+
"execution_count": null,
|
| 557 |
+
"metadata": {},
|
| 558 |
+
"outputs": [],
|
| 559 |
+
"source": [
|
| 560 |
+
"def huber(x, y, scaling=0.1):\n",
|
| 561 |
+
" \"\"\"\n",
|
| 562 |
+
" A helper function for evaluating the smooth L1 (huber) loss\n",
|
| 563 |
+
" between the rendered silhouettes and colors.\n",
|
| 564 |
+
" \"\"\"\n",
|
| 565 |
+
" diff_sq = (x - y) ** 2\n",
|
| 566 |
+
" loss = ((1 + diff_sq / (scaling**2)).clamp(1e-4).sqrt() - 1) * float(scaling)\n",
|
| 567 |
+
" return loss\n",
|
| 568 |
+
"\n",
|
| 569 |
+
"def sample_images_at_mc_locs(target_images, sampled_rays_xy):\n",
|
| 570 |
+
" \"\"\"\n",
|
| 571 |
+
" Given a set of Monte Carlo pixel locations `sampled_rays_xy`,\n",
|
| 572 |
+
" this method samples the tensor `target_images` at the\n",
|
| 573 |
+
" respective 2D locations.\n",
|
| 574 |
+
" \n",
|
| 575 |
+
" This function is used in order to extract the colors from\n",
|
| 576 |
+
" ground truth images that correspond to the colors\n",
|
| 577 |
+
" rendered using `MonteCarloRaysampler`.\n",
|
| 578 |
+
" \"\"\"\n",
|
| 579 |
+
" ba = target_images.shape[0]\n",
|
| 580 |
+
" dim = target_images.shape[-1]\n",
|
| 581 |
+
" spatial_size = sampled_rays_xy.shape[1:-1]\n",
|
| 582 |
+
" # In order to sample target_images, we utilize\n",
|
| 583 |
+
" # the grid_sample function which implements a\n",
|
| 584 |
+
" # bilinear image sampler.\n",
|
| 585 |
+
" # Note that we have to invert the sign of the \n",
|
| 586 |
+
" # sampled ray positions to convert the NDC xy locations\n",
|
| 587 |
+
" # of the MonteCarloRaysampler to the coordinate\n",
|
| 588 |
+
" # convention of grid_sample.\n",
|
| 589 |
+
" images_sampled = torch.nn.functional.grid_sample(\n",
|
| 590 |
+
" target_images.permute(0, 3, 1, 2), \n",
|
| 591 |
+
" -sampled_rays_xy.view(ba, -1, 1, 2), # note the sign inversion\n",
|
| 592 |
+
" align_corners=True\n",
|
| 593 |
+
" )\n",
|
| 594 |
+
" return images_sampled.permute(0, 2, 3, 1).view(\n",
|
| 595 |
+
" ba, *spatial_size, dim\n",
|
| 596 |
+
" )\n",
|
| 597 |
+
"\n",
|
| 598 |
+
"def show_full_render(\n",
|
| 599 |
+
" neural_radiance_field, camera,\n",
|
| 600 |
+
" target_image, target_silhouette,\n",
|
| 601 |
+
" loss_history_color, loss_history_sil,\n",
|
| 602 |
+
"):\n",
|
| 603 |
+
" \"\"\"\n",
|
| 604 |
+
" This is a helper function for visualizing the\n",
|
| 605 |
+
" intermediate results of the learning. \n",
|
| 606 |
+
" \n",
|
| 607 |
+
" Since the `NeuralRadianceField` suffers from\n",
|
| 608 |
+
" a large memory footprint, which does not let us\n",
|
| 609 |
+
" render the full image grid in a single forward pass,\n",
|
| 610 |
+
" we utilize the `NeuralRadianceField.batched_forward`\n",
|
| 611 |
+
" function in combination with disabling the gradient caching.\n",
|
| 612 |
+
" This chunks the set of emitted rays to batches and \n",
|
| 613 |
+
" evaluates the implicit function on one batch at a time\n",
|
| 614 |
+
" to prevent GPU memory overflow.\n",
|
| 615 |
+
" \"\"\"\n",
|
| 616 |
+
" \n",
|
| 617 |
+
" # Prevent gradient caching.\n",
|
| 618 |
+
" with torch.no_grad():\n",
|
| 619 |
+
" # Render using the grid renderer and the\n",
|
| 620 |
+
" # batched_forward function of neural_radiance_field.\n",
|
| 621 |
+
" rendered_image_silhouette, _ = renderer_grid(\n",
|
| 622 |
+
" cameras=camera, \n",
|
| 623 |
+
" volumetric_function=neural_radiance_field.batched_forward\n",
|
| 624 |
+
" )\n",
|
| 625 |
+
" # Split the rendering result to a silhouette render\n",
|
| 626 |
+
" # and the image render.\n",
|
| 627 |
+
" rendered_image, rendered_silhouette = (\n",
|
| 628 |
+
" rendered_image_silhouette[0].split([3, 1], dim=-1)\n",
|
| 629 |
+
" )\n",
|
| 630 |
+
" \n",
|
| 631 |
+
" # Generate plots.\n",
|
| 632 |
+
" fig, ax = plt.subplots(2, 3, figsize=(15, 10))\n",
|
| 633 |
+
" ax = ax.ravel()\n",
|
| 634 |
+
" clamp_and_detach = lambda x: x.clamp(0.0, 1.0).cpu().detach().numpy()\n",
|
| 635 |
+
" ax[0].plot(list(range(len(loss_history_color))), loss_history_color, linewidth=1)\n",
|
| 636 |
+
" ax[1].imshow(clamp_and_detach(rendered_image))\n",
|
| 637 |
+
" ax[2].imshow(clamp_and_detach(rendered_silhouette[..., 0]))\n",
|
| 638 |
+
" ax[3].plot(list(range(len(loss_history_sil))), loss_history_sil, linewidth=1)\n",
|
| 639 |
+
" ax[4].imshow(clamp_and_detach(target_image))\n",
|
| 640 |
+
" ax[5].imshow(clamp_and_detach(target_silhouette))\n",
|
| 641 |
+
" for ax_, title_ in zip(\n",
|
| 642 |
+
" ax,\n",
|
| 643 |
+
" (\n",
|
| 644 |
+
" \"loss color\", \"rendered image\", \"rendered silhouette\",\n",
|
| 645 |
+
" \"loss silhouette\", \"target image\", \"target silhouette\",\n",
|
| 646 |
+
" )\n",
|
| 647 |
+
" ):\n",
|
| 648 |
+
" if not title_.startswith('loss'):\n",
|
| 649 |
+
" ax_.grid(\"off\")\n",
|
| 650 |
+
" ax_.axis(\"off\")\n",
|
| 651 |
+
" ax_.set_title(title_)\n",
|
| 652 |
+
" fig.canvas.draw(); fig.show()\n",
|
| 653 |
+
" display.clear_output(wait=True)\n",
|
| 654 |
+
" display.display(fig)\n",
|
| 655 |
+
" return fig\n"
|
| 656 |
+
]
|
| 657 |
+
},
|
| 658 |
+
{
|
| 659 |
+
"cell_type": "markdown",
|
| 660 |
+
"metadata": {},
|
| 661 |
+
"source": [
|
| 662 |
+
"## 5. Fit the radiance field\n",
|
| 663 |
+
"\n",
|
| 664 |
+
"Here we carry out the radiance field fitting with differentiable rendering.\n",
|
| 665 |
+
"\n",
|
| 666 |
+
"In order to fit the radiance field, we render it from the viewpoints of the `target_cameras`\n",
|
| 667 |
+
"and compare the resulting renders with the observed `target_images` and `target_silhouettes`.\n",
|
| 668 |
+
"\n",
|
| 669 |
+
"The comparison is done by evaluating the mean huber (smooth-l1) error between corresponding\n",
|
| 670 |
+
"pairs of `target_images`/`rendered_images` and `target_silhouettes`/`rendered_silhouettes`.\n",
|
| 671 |
+
"\n",
|
| 672 |
+
"Since we use the `MonteCarloRaysampler`, the outputs of the training renderer `renderer_mc`\n",
|
| 673 |
+
"are colors of pixels that are randomly sampled from the image plane, not a lattice of pixels forming\n",
|
| 674 |
+
"a valid image. Thus, in order to compare the rendered colors with the ground truth, we \n",
|
| 675 |
+
"utilize the random MonteCarlo pixel locations to sample the ground truth images/silhouettes\n",
|
| 676 |
+
"`target_silhouettes`/`rendered_silhouettes` at the xy locations corresponding to the render\n",
|
| 677 |
+
"locations. This is done with the helper function `sample_images_at_mc_locs`, which is\n",
|
| 678 |
+
"described in the previous cell."
|
| 679 |
+
]
|
| 680 |
+
},
|
| 681 |
+
{
|
| 682 |
+
"cell_type": "code",
|
| 683 |
+
"execution_count": null,
|
| 684 |
+
"metadata": {},
|
| 685 |
+
"outputs": [],
|
| 686 |
+
"source": [
|
| 687 |
+
"# First move all relevant variables to the correct device.\n",
|
| 688 |
+
"renderer_grid = renderer_grid.to(device)\n",
|
| 689 |
+
"renderer_mc = renderer_mc.to(device)\n",
|
| 690 |
+
"target_cameras = target_cameras.to(device)\n",
|
| 691 |
+
"target_images = target_images.to(device)\n",
|
| 692 |
+
"target_silhouettes = target_silhouettes.to(device)\n",
|
| 693 |
+
"\n",
|
| 694 |
+
"# Set the seed for reproducibility\n",
|
| 695 |
+
"torch.manual_seed(1)\n",
|
| 696 |
+
"\n",
|
| 697 |
+
"# Instantiate the radiance field model.\n",
|
| 698 |
+
"neural_radiance_field = NeuralRadianceField().to(device)\n",
|
| 699 |
+
"\n",
|
| 700 |
+
"# Instantiate the Adam optimizer. We set its master learning rate to 1e-3.\n",
|
| 701 |
+
"lr = 1e-3\n",
|
| 702 |
+
"optimizer = torch.optim.Adam(neural_radiance_field.parameters(), lr=lr)\n",
|
| 703 |
+
"\n",
|
| 704 |
+
"# We sample 6 random cameras in a minibatch. Each camera\n",
|
| 705 |
+
"# emits raysampler_mc.n_pts_per_image rays.\n",
|
| 706 |
+
"batch_size = 6\n",
|
| 707 |
+
"\n",
|
| 708 |
+
"# 3000 iterations take ~20 min on a Tesla M40 and lead to\n",
|
| 709 |
+
"# reasonably sharp results. However, for the best possible\n",
|
| 710 |
+
"# results, we recommend setting n_iter=20000.\n",
|
| 711 |
+
"n_iter = 3000\n",
|
| 712 |
+
"\n",
|
| 713 |
+
"# Init the loss history buffers.\n",
|
| 714 |
+
"loss_history_color, loss_history_sil = [], []\n",
|
| 715 |
+
"\n",
|
| 716 |
+
"# The main optimization loop.\n",
|
| 717 |
+
"for iteration in range(n_iter): \n",
|
| 718 |
+
" # In case we reached the last 75% of iterations,\n",
|
| 719 |
+
" # decrease the learning rate of the optimizer 10-fold.\n",
|
| 720 |
+
" if iteration == round(n_iter * 0.75):\n",
|
| 721 |
+
" print('Decreasing LR 10-fold ...')\n",
|
| 722 |
+
" optimizer = torch.optim.Adam(\n",
|
| 723 |
+
" neural_radiance_field.parameters(), lr=lr * 0.1\n",
|
| 724 |
+
" )\n",
|
| 725 |
+
" \n",
|
| 726 |
+
" # Zero the optimizer gradient.\n",
|
| 727 |
+
" optimizer.zero_grad()\n",
|
| 728 |
+
" \n",
|
| 729 |
+
" # Sample random batch indices.\n",
|
| 730 |
+
" batch_idx = torch.randperm(len(target_cameras))[:batch_size]\n",
|
| 731 |
+
" \n",
|
| 732 |
+
" # Sample the minibatch of cameras.\n",
|
| 733 |
+
" batch_cameras = FoVPerspectiveCameras(\n",
|
| 734 |
+
" R = target_cameras.R[batch_idx], \n",
|
| 735 |
+
" T = target_cameras.T[batch_idx], \n",
|
| 736 |
+
" znear = target_cameras.znear[batch_idx],\n",
|
| 737 |
+
" zfar = target_cameras.zfar[batch_idx],\n",
|
| 738 |
+
" aspect_ratio = target_cameras.aspect_ratio[batch_idx],\n",
|
| 739 |
+
" fov = target_cameras.fov[batch_idx],\n",
|
| 740 |
+
" device = device,\n",
|
| 741 |
+
" )\n",
|
| 742 |
+
" \n",
|
| 743 |
+
" # Evaluate the nerf model.\n",
|
| 744 |
+
" rendered_images_silhouettes, sampled_rays = renderer_mc(\n",
|
| 745 |
+
" cameras=batch_cameras, \n",
|
| 746 |
+
" volumetric_function=neural_radiance_field\n",
|
| 747 |
+
" )\n",
|
| 748 |
+
" rendered_images, rendered_silhouettes = (\n",
|
| 749 |
+
" rendered_images_silhouettes.split([3, 1], dim=-1)\n",
|
| 750 |
+
" )\n",
|
| 751 |
+
" \n",
|
| 752 |
+
" # Compute the silhouette error as the mean huber\n",
|
| 753 |
+
" # loss between the predicted masks and the\n",
|
| 754 |
+
" # sampled target silhouettes.\n",
|
| 755 |
+
" silhouettes_at_rays = sample_images_at_mc_locs(\n",
|
| 756 |
+
" target_silhouettes[batch_idx, ..., None], \n",
|
| 757 |
+
" sampled_rays.xys\n",
|
| 758 |
+
" )\n",
|
| 759 |
+
" sil_err = huber(\n",
|
| 760 |
+
" rendered_silhouettes, \n",
|
| 761 |
+
" silhouettes_at_rays,\n",
|
| 762 |
+
" ).abs().mean()\n",
|
| 763 |
+
"\n",
|
| 764 |
+
" # Compute the color error as the mean huber\n",
|
| 765 |
+
" # loss between the rendered colors and the\n",
|
| 766 |
+
" # sampled target images.\n",
|
| 767 |
+
" colors_at_rays = sample_images_at_mc_locs(\n",
|
| 768 |
+
" target_images[batch_idx], \n",
|
| 769 |
+
" sampled_rays.xys\n",
|
| 770 |
+
" )\n",
|
| 771 |
+
" color_err = huber(\n",
|
| 772 |
+
" rendered_images, \n",
|
| 773 |
+
" colors_at_rays,\n",
|
| 774 |
+
" ).abs().mean()\n",
|
| 775 |
+
" \n",
|
| 776 |
+
" # The optimization loss is a simple\n",
|
| 777 |
+
" # sum of the color and silhouette errors.\n",
|
| 778 |
+
" loss = color_err + sil_err\n",
|
| 779 |
+
" \n",
|
| 780 |
+
" # Log the loss history.\n",
|
| 781 |
+
" loss_history_color.append(float(color_err))\n",
|
| 782 |
+
" loss_history_sil.append(float(sil_err))\n",
|
| 783 |
+
" \n",
|
| 784 |
+
" # Every 10 iterations, print the current values of the losses.\n",
|
| 785 |
+
" if iteration % 10 == 0:\n",
|
| 786 |
+
" print(\n",
|
| 787 |
+
" f'Iteration {iteration:05d}:'\n",
|
| 788 |
+
" + f' loss color = {float(color_err):1.2e}'\n",
|
| 789 |
+
" + f' loss silhouette = {float(sil_err):1.2e}'\n",
|
| 790 |
+
" )\n",
|
| 791 |
+
" \n",
|
| 792 |
+
" # Take the optimization step.\n",
|
| 793 |
+
" loss.backward()\n",
|
| 794 |
+
" optimizer.step()\n",
|
| 795 |
+
" \n",
|
| 796 |
+
" # Visualize the full renders every 100 iterations.\n",
|
| 797 |
+
" if iteration % 100 == 0:\n",
|
| 798 |
+
" show_idx = torch.randperm(len(target_cameras))[:1]\n",
|
| 799 |
+
" show_full_render(\n",
|
| 800 |
+
" neural_radiance_field,\n",
|
| 801 |
+
" FoVPerspectiveCameras(\n",
|
| 802 |
+
" R = target_cameras.R[show_idx], \n",
|
| 803 |
+
" T = target_cameras.T[show_idx], \n",
|
| 804 |
+
" znear = target_cameras.znear[show_idx],\n",
|
| 805 |
+
" zfar = target_cameras.zfar[show_idx],\n",
|
| 806 |
+
" aspect_ratio = target_cameras.aspect_ratio[show_idx],\n",
|
| 807 |
+
" fov = target_cameras.fov[show_idx],\n",
|
| 808 |
+
" device = device,\n",
|
| 809 |
+
" ), \n",
|
| 810 |
+
" target_images[show_idx][0],\n",
|
| 811 |
+
" target_silhouettes[show_idx][0],\n",
|
| 812 |
+
" loss_history_color,\n",
|
| 813 |
+
" loss_history_sil,\n",
|
| 814 |
+
" )"
|
| 815 |
+
]
|
| 816 |
+
},
|
| 817 |
+
{
|
| 818 |
+
"cell_type": "markdown",
|
| 819 |
+
"metadata": {},
|
| 820 |
+
"source": [
|
| 821 |
+
"## 6. Visualizing the optimized neural radiance field\n",
|
| 822 |
+
"\n",
|
| 823 |
+
"Finally, we visualize the neural radiance field by rendering from multiple viewpoints that rotate around the volume's y-axis."
|
| 824 |
+
]
|
| 825 |
+
},
|
| 826 |
+
{
|
| 827 |
+
"cell_type": "code",
|
| 828 |
+
"execution_count": null,
|
| 829 |
+
"metadata": {},
|
| 830 |
+
"outputs": [],
|
| 831 |
+
"source": [
|
| 832 |
+
"def generate_rotating_nerf(neural_radiance_field, n_frames = 50):\n",
|
| 833 |
+
" logRs = torch.zeros(n_frames, 3, device=device)\n",
|
| 834 |
+
" logRs[:, 1] = torch.linspace(-3.14, 3.14, n_frames, device=device)\n",
|
| 835 |
+
" Rs = so3_exp_map(logRs)\n",
|
| 836 |
+
" Ts = torch.zeros(n_frames, 3, device=device)\n",
|
| 837 |
+
" Ts[:, 2] = 2.7\n",
|
| 838 |
+
" frames = []\n",
|
| 839 |
+
" print('Rendering rotating NeRF ...')\n",
|
| 840 |
+
" for R, T in zip(tqdm(Rs), Ts):\n",
|
| 841 |
+
" camera = FoVPerspectiveCameras(\n",
|
| 842 |
+
" R=R[None], \n",
|
| 843 |
+
" T=T[None], \n",
|
| 844 |
+
" znear=target_cameras.znear[0],\n",
|
| 845 |
+
" zfar=target_cameras.zfar[0],\n",
|
| 846 |
+
" aspect_ratio=target_cameras.aspect_ratio[0],\n",
|
| 847 |
+
" fov=target_cameras.fov[0],\n",
|
| 848 |
+
" device=device,\n",
|
| 849 |
+
" )\n",
|
| 850 |
+
" # Note that we again render with `NDCMultinomialRaysampler`\n",
|
| 851 |
+
" # and the batched_forward function of neural_radiance_field.\n",
|
| 852 |
+
" frames.append(\n",
|
| 853 |
+
" renderer_grid(\n",
|
| 854 |
+
" cameras=camera, \n",
|
| 855 |
+
" volumetric_function=neural_radiance_field.batched_forward,\n",
|
| 856 |
+
" )[0][..., :3]\n",
|
| 857 |
+
" )\n",
|
| 858 |
+
" return torch.cat(frames)\n",
|
| 859 |
+
" \n",
|
| 860 |
+
"with torch.no_grad():\n",
|
| 861 |
+
" rotating_nerf_frames = generate_rotating_nerf(neural_radiance_field, n_frames=3*5)\n",
|
| 862 |
+
" \n",
|
| 863 |
+
"image_grid(rotating_nerf_frames.clamp(0., 1.).cpu().numpy(), rows=3, cols=5, rgb=True, fill=True)\n",
|
| 864 |
+
"plt.show()"
|
| 865 |
+
]
|
| 866 |
+
},
|
| 867 |
+
{
|
| 868 |
+
"cell_type": "markdown",
|
| 869 |
+
"metadata": {},
|
| 870 |
+
"source": [
|
| 871 |
+
"## 7. Conclusion\n",
|
| 872 |
+
"\n",
|
| 873 |
+
"In this tutorial, we have shown how to optimize an implicit representation of a scene such that the renders of the scene from known viewpoints match the observed images for each viewpoint. The rendering was carried out using the PyTorch3D's implicit function renderer composed of either a `MonteCarloRaysampler` or `NDCMultinomialRaysampler`, and an `EmissionAbsorptionRaymarcher`."
|
| 874 |
+
]
|
| 875 |
+
}
|
| 876 |
+
],
|
| 877 |
+
"metadata": {
|
| 878 |
+
"bento_stylesheets": {
|
| 879 |
+
"bento/extensions/flow/main.css": true,
|
| 880 |
+
"bento/extensions/kernel_selector/main.css": true,
|
| 881 |
+
"bento/extensions/kernel_ui/main.css": true,
|
| 882 |
+
"bento/extensions/new_kernel/main.css": true,
|
| 883 |
+
"bento/extensions/system_usage/main.css": true,
|
| 884 |
+
"bento/extensions/theme/main.css": true
|
| 885 |
+
},
|
| 886 |
+
"kernelspec": {
|
| 887 |
+
"display_name": "pytorch3d_etc (local)",
|
| 888 |
+
"language": "python",
|
| 889 |
+
"name": "pytorch3d_etc_local"
|
| 890 |
+
},
|
| 891 |
+
"language_info": {
|
| 892 |
+
"codemirror_mode": {
|
| 893 |
+
"name": "ipython",
|
| 894 |
+
"version": 3
|
| 895 |
+
},
|
| 896 |
+
"file_extension": ".py",
|
| 897 |
+
"mimetype": "text/x-python",
|
| 898 |
+
"name": "python",
|
| 899 |
+
"nbconvert_exporter": "python",
|
| 900 |
+
"pygments_lexer": "ipython3",
|
| 901 |
+
"version": "3.7.5+"
|
| 902 |
+
}
|
| 903 |
+
},
|
| 904 |
+
"nbformat": 4,
|
| 905 |
+
"nbformat_minor": 2
|
| 906 |
+
}
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/fit_textured_mesh.ipynb
ADDED
|
@@ -0,0 +1,962 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"metadata": {
|
| 7 |
+
"colab": {},
|
| 8 |
+
"colab_type": "code",
|
| 9 |
+
"id": "_Ip8kp4TfBLZ"
|
| 10 |
+
},
|
| 11 |
+
"outputs": [],
|
| 12 |
+
"source": [
|
| 13 |
+
"# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
|
| 14 |
+
]
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"cell_type": "markdown",
|
| 18 |
+
"metadata": {
|
| 19 |
+
"colab_type": "text",
|
| 20 |
+
"id": "kuXHJv44fBLe"
|
| 21 |
+
},
|
| 22 |
+
"source": [
|
| 23 |
+
"# Fit a mesh via rendering\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"This tutorial shows how to:\n",
|
| 26 |
+
"- Load a mesh and textures from an `.obj` file. \n",
|
| 27 |
+
"- Create a synthetic dataset by rendering a textured mesh from multiple viewpoints\n",
|
| 28 |
+
"- Fit a mesh to the observed synthetic images using differential silhouette rendering\n",
|
| 29 |
+
"- Fit a mesh and its textures using differential textured rendering"
|
| 30 |
+
]
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "markdown",
|
| 34 |
+
"metadata": {
|
| 35 |
+
"colab_type": "text",
|
| 36 |
+
"id": "Bnj3THhzfBLf"
|
| 37 |
+
},
|
| 38 |
+
"source": [
|
| 39 |
+
"## 0. Install and Import modules"
|
| 40 |
+
]
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "markdown",
|
| 44 |
+
"metadata": {
|
| 45 |
+
"colab_type": "text",
|
| 46 |
+
"id": "okLalbR_g7NS"
|
| 47 |
+
},
|
| 48 |
+
"source": [
|
| 49 |
+
"Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
|
| 50 |
+
]
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"metadata": {
|
| 56 |
+
"colab": {},
|
| 57 |
+
"colab_type": "code",
|
| 58 |
+
"id": "musUWTglgxSB"
|
| 59 |
+
},
|
| 60 |
+
"outputs": [],
|
| 61 |
+
"source": [
|
| 62 |
+
"import os\n",
|
| 63 |
+
"import sys\n",
|
| 64 |
+
"import torch\n",
|
| 65 |
+
"import subprocess\n",
|
| 66 |
+
"need_pytorch3d=False\n",
|
| 67 |
+
"try:\n",
|
| 68 |
+
" import pytorch3d\n",
|
| 69 |
+
"except ModuleNotFoundError:\n",
|
| 70 |
+
" need_pytorch3d=True\n",
|
| 71 |
+
"if need_pytorch3d:\n",
|
| 72 |
+
" pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
|
| 73 |
+
" version_str=\"\".join([\n",
|
| 74 |
+
" f\"py3{sys.version_info.minor}_cu\",\n",
|
| 75 |
+
" torch.version.cuda.replace(\".\",\"\"),\n",
|
| 76 |
+
" f\"_pyt{pyt_version_str}\"\n",
|
| 77 |
+
" ])\n",
|
| 78 |
+
" !pip install iopath\n",
|
| 79 |
+
" if sys.platform.startswith(\"linux\"):\n",
|
| 80 |
+
" print(\"Trying to install wheel for PyTorch3D\")\n",
|
| 81 |
+
" !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
|
| 82 |
+
" pip_list = !pip freeze\n",
|
| 83 |
+
" need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
|
| 84 |
+
" if need_pytorch3d:\n",
|
| 85 |
+
" print(f\"failed to find/install wheel for {version_str}\")\n",
|
| 86 |
+
"if need_pytorch3d:\n",
|
| 87 |
+
" print(\"Installing PyTorch3D from source\")\n",
|
| 88 |
+
" !pip install ninja\n",
|
| 89 |
+
" !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
|
| 90 |
+
]
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"metadata": {
|
| 96 |
+
"colab": {},
|
| 97 |
+
"colab_type": "code",
|
| 98 |
+
"id": "nX99zdoffBLg"
|
| 99 |
+
},
|
| 100 |
+
"outputs": [],
|
| 101 |
+
"source": [
|
| 102 |
+
"import os\n",
|
| 103 |
+
"import torch\n",
|
| 104 |
+
"import matplotlib.pyplot as plt\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"from pytorch3d.utils import ico_sphere\n",
|
| 107 |
+
"import numpy as np\n",
|
| 108 |
+
"from tqdm.notebook import tqdm\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"# Util function for loading meshes\n",
|
| 111 |
+
"from pytorch3d.io import load_objs_as_meshes, save_obj\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"from pytorch3d.loss import (\n",
|
| 114 |
+
" chamfer_distance, \n",
|
| 115 |
+
" mesh_edge_loss, \n",
|
| 116 |
+
" mesh_laplacian_smoothing, \n",
|
| 117 |
+
" mesh_normal_consistency,\n",
|
| 118 |
+
")\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# Data structures and functions for rendering\n",
|
| 121 |
+
"from pytorch3d.structures import Meshes\n",
|
| 122 |
+
"from pytorch3d.renderer import (\n",
|
| 123 |
+
" look_at_view_transform,\n",
|
| 124 |
+
" FoVPerspectiveCameras, \n",
|
| 125 |
+
" PointLights, \n",
|
| 126 |
+
" DirectionalLights, \n",
|
| 127 |
+
" Materials, \n",
|
| 128 |
+
" RasterizationSettings, \n",
|
| 129 |
+
" MeshRenderer, \n",
|
| 130 |
+
" MeshRasterizer, \n",
|
| 131 |
+
" SoftPhongShader,\n",
|
| 132 |
+
" SoftSilhouetteShader,\n",
|
| 133 |
+
" SoftPhongShader,\n",
|
| 134 |
+
" TexturesVertex\n",
|
| 135 |
+
")\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"# add path for demo utils functions \n",
|
| 138 |
+
"import sys\n",
|
| 139 |
+
"import os\n",
|
| 140 |
+
"sys.path.append(os.path.abspath(''))"
|
| 141 |
+
]
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "markdown",
|
| 145 |
+
"metadata": {
|
| 146 |
+
"colab_type": "text",
|
| 147 |
+
"id": "Lxmehq6Zhrzv"
|
| 148 |
+
},
|
| 149 |
+
"source": [
|
| 150 |
+
"If using **Google Colab**, fetch the utils file for plotting image grids:"
|
| 151 |
+
]
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"execution_count": null,
|
| 156 |
+
"metadata": {
|
| 157 |
+
"colab": {},
|
| 158 |
+
"colab_type": "code",
|
| 159 |
+
"id": "HZozr3Pmho-5"
|
| 160 |
+
},
|
| 161 |
+
"outputs": [],
|
| 162 |
+
"source": [
|
| 163 |
+
"!wget https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/docs/tutorials/utils/plot_image_grid.py\n",
|
| 164 |
+
"from plot_image_grid import image_grid"
|
| 165 |
+
]
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "markdown",
|
| 169 |
+
"metadata": {
|
| 170 |
+
"colab_type": "text",
|
| 171 |
+
"id": "g4B62MzYiJUM"
|
| 172 |
+
},
|
| 173 |
+
"source": [
|
| 174 |
+
"OR if running **locally** uncomment and run the following cell:"
|
| 175 |
+
]
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"metadata": {
|
| 181 |
+
"colab": {},
|
| 182 |
+
"colab_type": "code",
|
| 183 |
+
"id": "paJ4Im8ahl7O"
|
| 184 |
+
},
|
| 185 |
+
"outputs": [],
|
| 186 |
+
"source": [
|
| 187 |
+
"# from utils.plot_image_grid import image_grid"
|
| 188 |
+
]
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"cell_type": "markdown",
|
| 192 |
+
"metadata": {
|
| 193 |
+
"colab_type": "text",
|
| 194 |
+
"collapsed": true,
|
| 195 |
+
"id": "5jGq772XfBLk"
|
| 196 |
+
},
|
| 197 |
+
"source": [
|
| 198 |
+
"### 1. Load a mesh and texture file\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"Load an `.obj` file and its associated `.mtl` file and create a **Textures** and **Meshes** object. \n",
|
| 201 |
+
"\n",
|
| 202 |
+
"**Meshes** is a unique datastructure provided in PyTorch3D for working with batches of meshes of different sizes. \n",
|
| 203 |
+
"\n",
|
| 204 |
+
"**TexturesVertex** is an auxiliary datastructure for storing vertex rgb texture information about meshes. \n",
|
| 205 |
+
"\n",
|
| 206 |
+
"**Meshes** has several class methods which are used throughout the rendering pipeline."
|
| 207 |
+
]
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "markdown",
|
| 211 |
+
"metadata": {
|
| 212 |
+
"colab_type": "text",
|
| 213 |
+
"id": "a8eU4zo5jd_H"
|
| 214 |
+
},
|
| 215 |
+
"source": [
|
| 216 |
+
"If running this notebook using **Google Colab**, run the following cell to fetch the mesh obj and texture files and save it at the path `data/cow_mesh`:\n",
|
| 217 |
+
"If running locally, the data is already available at the correct path. "
|
| 218 |
+
]
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "code",
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"metadata": {
|
| 224 |
+
"colab": {},
|
| 225 |
+
"colab_type": "code",
|
| 226 |
+
"id": "tTm0cVuOjb1W"
|
| 227 |
+
},
|
| 228 |
+
"outputs": [],
|
| 229 |
+
"source": [
|
| 230 |
+
"!mkdir -p data/cow_mesh\n",
|
| 231 |
+
"!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.obj\n",
|
| 232 |
+
"!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow.mtl\n",
|
| 233 |
+
"!wget -P data/cow_mesh https://dl.fbaipublicfiles.com/pytorch3d/data/cow_mesh/cow_texture.png"
|
| 234 |
+
]
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"cell_type": "code",
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"metadata": {
|
| 240 |
+
"colab": {},
|
| 241 |
+
"colab_type": "code",
|
| 242 |
+
"id": "gi5Kd0GafBLl"
|
| 243 |
+
},
|
| 244 |
+
"outputs": [],
|
| 245 |
+
"source": [
|
| 246 |
+
"# Setup\n",
|
| 247 |
+
"if torch.cuda.is_available():\n",
|
| 248 |
+
" device = torch.device(\"cuda:0\")\n",
|
| 249 |
+
" torch.cuda.set_device(device)\n",
|
| 250 |
+
"else:\n",
|
| 251 |
+
" device = torch.device(\"cpu\")\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"# Set paths\n",
|
| 254 |
+
"DATA_DIR = \"./data\"\n",
|
| 255 |
+
"obj_filename = os.path.join(DATA_DIR, \"cow_mesh/cow.obj\")\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"# Load obj file\n",
|
| 258 |
+
"mesh = load_objs_as_meshes([obj_filename], device=device)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"# We scale normalize and center the target mesh to fit in a sphere of radius 1 \n",
|
| 261 |
+
"# centered at (0,0,0). (scale, center) will be used to bring the predicted mesh \n",
|
| 262 |
+
"# to its original center and scale. Note that normalizing the target mesh, \n",
|
| 263 |
+
"# speeds up the optimization but is not necessary!\n",
|
| 264 |
+
"verts = mesh.verts_packed()\n",
|
| 265 |
+
"N = verts.shape[0]\n",
|
| 266 |
+
"center = verts.mean(0)\n",
|
| 267 |
+
"scale = max((verts - center).abs().max(0)[0])\n",
|
| 268 |
+
"mesh.offset_verts_(-center)\n",
|
| 269 |
+
"mesh.scale_verts_((1.0 / float(scale)));"
|
| 270 |
+
]
|
| 271 |
+
},
|
| 272 |
+
{
|
| 273 |
+
"cell_type": "markdown",
|
| 274 |
+
"metadata": {
|
| 275 |
+
"colab_type": "text",
|
| 276 |
+
"id": "17c4xmtyfBMH"
|
| 277 |
+
},
|
| 278 |
+
"source": [
|
| 279 |
+
"## 2. Dataset Creation\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"We sample different camera positions that encode multiple viewpoints of the cow. We create a renderer with a shader that performs texture map interpolation. We render a synthetic dataset of images of the textured cow mesh from multiple viewpoints.\n"
|
| 282 |
+
]
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"cell_type": "code",
|
| 286 |
+
"execution_count": null,
|
| 287 |
+
"metadata": {
|
| 288 |
+
"colab": {},
|
| 289 |
+
"colab_type": "code",
|
| 290 |
+
"id": "CDQKebNNfBMI"
|
| 291 |
+
},
|
| 292 |
+
"outputs": [],
|
| 293 |
+
"source": [
|
| 294 |
+
"# the number of different viewpoints from which we want to render the mesh.\n",
|
| 295 |
+
"num_views = 20\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"# Get a batch of viewing angles. \n",
|
| 298 |
+
"elev = torch.linspace(0, 360, num_views)\n",
|
| 299 |
+
"azim = torch.linspace(-180, 180, num_views)\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"# Place a point light in front of the object. As mentioned above, the front of \n",
|
| 302 |
+
"# the cow is facing the -z direction. \n",
|
| 303 |
+
"lights = PointLights(device=device, location=[[0.0, 0.0, -3.0]])\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"# Initialize an OpenGL perspective camera that represents a batch of different \n",
|
| 306 |
+
"# viewing angles. All the cameras helper methods support mixed type inputs and \n",
|
| 307 |
+
"# broadcasting. So we can view the camera from the a distance of dist=2.7, and \n",
|
| 308 |
+
"# then specify elevation and azimuth angles for each viewpoint as tensors. \n",
|
| 309 |
+
"R, T = look_at_view_transform(dist=2.7, elev=elev, azim=azim)\n",
|
| 310 |
+
"cameras = FoVPerspectiveCameras(device=device, R=R, T=T)\n",
|
| 311 |
+
"\n",
|
| 312 |
+
"# We arbitrarily choose one particular view that will be used to visualize \n",
|
| 313 |
+
"# results\n",
|
| 314 |
+
"camera = FoVPerspectiveCameras(device=device, R=R[None, 1, ...], \n",
|
| 315 |
+
" T=T[None, 1, ...]) \n",
|
| 316 |
+
"\n",
|
| 317 |
+
"# Define the settings for rasterization and shading. Here we set the output \n",
|
| 318 |
+
"# image to be of size 128X128. As we are rendering images for visualization \n",
|
| 319 |
+
"# purposes only we will set faces_per_pixel=1 and blur_radius=0.0. Refer to \n",
|
| 320 |
+
"# rasterize_meshes.py for explanations of these parameters. We also leave \n",
|
| 321 |
+
"# bin_size and max_faces_per_bin to their default values of None, which sets \n",
|
| 322 |
+
"# their values using heuristics and ensures that the faster coarse-to-fine \n",
|
| 323 |
+
"# rasterization method is used. Refer to docs/notes/renderer.md for an \n",
|
| 324 |
+
"# explanation of the difference between naive and coarse-to-fine rasterization. \n",
|
| 325 |
+
"raster_settings = RasterizationSettings(\n",
|
| 326 |
+
" image_size=128, \n",
|
| 327 |
+
" blur_radius=0.0, \n",
|
| 328 |
+
" faces_per_pixel=1, \n",
|
| 329 |
+
")\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"# Create a Phong renderer by composing a rasterizer and a shader. The textured \n",
|
| 332 |
+
"# Phong shader will interpolate the texture uv coordinates for each vertex, \n",
|
| 333 |
+
"# sample from a texture image and apply the Phong lighting model\n",
|
| 334 |
+
"renderer = MeshRenderer(\n",
|
| 335 |
+
" rasterizer=MeshRasterizer(\n",
|
| 336 |
+
" cameras=camera, \n",
|
| 337 |
+
" raster_settings=raster_settings\n",
|
| 338 |
+
" ),\n",
|
| 339 |
+
" shader=SoftPhongShader(\n",
|
| 340 |
+
" device=device, \n",
|
| 341 |
+
" cameras=camera,\n",
|
| 342 |
+
" lights=lights\n",
|
| 343 |
+
" )\n",
|
| 344 |
+
")\n",
|
| 345 |
+
"\n",
|
| 346 |
+
"# Create a batch of meshes by repeating the cow mesh and associated textures. \n",
|
| 347 |
+
"# Meshes has a useful `extend` method which allows us do this very easily. \n",
|
| 348 |
+
"# This also extends the textures. \n",
|
| 349 |
+
"meshes = mesh.extend(num_views)\n",
|
| 350 |
+
"\n",
|
| 351 |
+
"# Render the cow mesh from each viewing angle\n",
|
| 352 |
+
"target_images = renderer(meshes, cameras=cameras, lights=lights)\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"# Our multi-view cow dataset will be represented by these 2 lists of tensors,\n",
|
| 355 |
+
"# each of length num_views.\n",
|
| 356 |
+
"target_rgb = [target_images[i, ..., :3] for i in range(num_views)]\n",
|
| 357 |
+
"target_cameras = [FoVPerspectiveCameras(device=device, R=R[None, i, ...], \n",
|
| 358 |
+
" T=T[None, i, ...]) for i in range(num_views)]"
|
| 359 |
+
]
|
| 360 |
+
},
|
| 361 |
+
{
|
| 362 |
+
"cell_type": "markdown",
|
| 363 |
+
"metadata": {
|
| 364 |
+
"colab_type": "text",
|
| 365 |
+
"id": "TppB4PVmR1Rc"
|
| 366 |
+
},
|
| 367 |
+
"source": [
|
| 368 |
+
"Visualize the dataset:"
|
| 369 |
+
]
|
| 370 |
+
},
|
| 371 |
+
{
|
| 372 |
+
"cell_type": "code",
|
| 373 |
+
"execution_count": null,
|
| 374 |
+
"metadata": {
|
| 375 |
+
"colab": {},
|
| 376 |
+
"colab_type": "code",
|
| 377 |
+
"id": "HHE0CnbVR1Rd"
|
| 378 |
+
},
|
| 379 |
+
"outputs": [],
|
| 380 |
+
"source": [
|
| 381 |
+
"# RGB images\n",
|
| 382 |
+
"image_grid(target_images.cpu().numpy(), rows=4, cols=5, rgb=True)\n",
|
| 383 |
+
"plt.show()"
|
| 384 |
+
]
|
| 385 |
+
},
|
| 386 |
+
{
|
| 387 |
+
"cell_type": "markdown",
|
| 388 |
+
"metadata": {
|
| 389 |
+
"colab_type": "text",
|
| 390 |
+
"id": "gOb4rYx65E8z"
|
| 391 |
+
},
|
| 392 |
+
"source": [
|
| 393 |
+
"Later in this tutorial, we will fit a mesh to the rendered RGB images, as well as to just images of just the cow silhouette. For the latter case, we will render a dataset of silhouette images. Most shaders in PyTorch3D will output an alpha channel along with the RGB image as a 4th channel in an RGBA image. The alpha channel encodes the probability that each pixel belongs to the foreground of the object. We construct a soft silhouette shader to render this alpha channel."
|
| 394 |
+
]
|
| 395 |
+
},
|
| 396 |
+
{
|
| 397 |
+
"cell_type": "code",
|
| 398 |
+
"execution_count": null,
|
| 399 |
+
"metadata": {
|
| 400 |
+
"colab": {},
|
| 401 |
+
"colab_type": "code",
|
| 402 |
+
"id": "iP_g-nwX4exM"
|
| 403 |
+
},
|
| 404 |
+
"outputs": [],
|
| 405 |
+
"source": [
|
| 406 |
+
"# Rasterization settings for silhouette rendering \n",
|
| 407 |
+
"sigma = 1e-4\n",
|
| 408 |
+
"raster_settings_silhouette = RasterizationSettings(\n",
|
| 409 |
+
" image_size=128, \n",
|
| 410 |
+
" blur_radius=np.log(1. / 1e-4 - 1.)*sigma, \n",
|
| 411 |
+
" faces_per_pixel=50, \n",
|
| 412 |
+
")\n",
|
| 413 |
+
"\n",
|
| 414 |
+
"# Silhouette renderer \n",
|
| 415 |
+
"renderer_silhouette = MeshRenderer(\n",
|
| 416 |
+
" rasterizer=MeshRasterizer(\n",
|
| 417 |
+
" cameras=camera, \n",
|
| 418 |
+
" raster_settings=raster_settings_silhouette\n",
|
| 419 |
+
" ),\n",
|
| 420 |
+
" shader=SoftSilhouetteShader()\n",
|
| 421 |
+
")\n",
|
| 422 |
+
"\n",
|
| 423 |
+
"# Render silhouette images. The 3rd channel of the rendering output is \n",
|
| 424 |
+
"# the alpha/silhouette channel\n",
|
| 425 |
+
"silhouette_images = renderer_silhouette(meshes, cameras=cameras, lights=lights)\n",
|
| 426 |
+
"target_silhouette = [silhouette_images[i, ..., 3] for i in range(num_views)]\n",
|
| 427 |
+
"\n",
|
| 428 |
+
"# Visualize silhouette images\n",
|
| 429 |
+
"image_grid(silhouette_images.cpu().numpy(), rows=4, cols=5, rgb=False)\n",
|
| 430 |
+
"plt.show()"
|
| 431 |
+
]
|
| 432 |
+
},
|
| 433 |
+
{
|
| 434 |
+
"cell_type": "markdown",
|
| 435 |
+
"metadata": {
|
| 436 |
+
"colab_type": "text",
|
| 437 |
+
"id": "t3qphI1ElUb5"
|
| 438 |
+
},
|
| 439 |
+
"source": [
|
| 440 |
+
"## 3. Mesh prediction via silhouette rendering\n",
|
| 441 |
+
"In the previous section, we created a dataset of images of multiple viewpoints of a cow. In this section, we predict a mesh by observing those target images without any knowledge of the ground truth cow mesh. We assume we know the position of the cameras and lighting.\n",
|
| 442 |
+
"\n",
|
| 443 |
+
"We first define some helper functions to visualize the results of our mesh prediction:"
|
| 444 |
+
]
|
| 445 |
+
},
|
| 446 |
+
{
|
| 447 |
+
"cell_type": "code",
|
| 448 |
+
"execution_count": null,
|
| 449 |
+
"metadata": {
|
| 450 |
+
"colab": {},
|
| 451 |
+
"colab_type": "code",
|
| 452 |
+
"id": "eeWYHROrR1Rh"
|
| 453 |
+
},
|
| 454 |
+
"outputs": [],
|
| 455 |
+
"source": [
|
| 456 |
+
"# Show a visualization comparing the rendered predicted mesh to the ground truth \n",
|
| 457 |
+
"# mesh\n",
|
| 458 |
+
"def visualize_prediction(predicted_mesh, renderer=renderer_silhouette, \n",
|
| 459 |
+
" target_image=target_rgb[1], title='', \n",
|
| 460 |
+
" silhouette=False):\n",
|
| 461 |
+
" inds = 3 if silhouette else range(3)\n",
|
| 462 |
+
" with torch.no_grad():\n",
|
| 463 |
+
" predicted_images = renderer(predicted_mesh)\n",
|
| 464 |
+
" plt.figure(figsize=(20, 10))\n",
|
| 465 |
+
" plt.subplot(1, 2, 1)\n",
|
| 466 |
+
" plt.imshow(predicted_images[0, ..., inds].cpu().detach().numpy())\n",
|
| 467 |
+
"\n",
|
| 468 |
+
" plt.subplot(1, 2, 2)\n",
|
| 469 |
+
" plt.imshow(target_image.cpu().detach().numpy())\n",
|
| 470 |
+
" plt.title(title)\n",
|
| 471 |
+
" plt.axis(\"off\")\n",
|
| 472 |
+
"\n",
|
| 473 |
+
"# Plot losses as a function of optimization iteration\n",
|
| 474 |
+
"def plot_losses(losses):\n",
|
| 475 |
+
" fig = plt.figure(figsize=(13, 5))\n",
|
| 476 |
+
" ax = fig.gca()\n",
|
| 477 |
+
" for k, l in losses.items():\n",
|
| 478 |
+
" ax.plot(l['values'], label=k + \" loss\")\n",
|
| 479 |
+
" ax.legend(fontsize=\"16\")\n",
|
| 480 |
+
" ax.set_xlabel(\"Iteration\", fontsize=\"16\")\n",
|
| 481 |
+
" ax.set_ylabel(\"Loss\", fontsize=\"16\")\n",
|
| 482 |
+
" ax.set_title(\"Loss vs iterations\", fontsize=\"16\")"
|
| 483 |
+
]
|
| 484 |
+
},
|
| 485 |
+
{
|
| 486 |
+
"cell_type": "markdown",
|
| 487 |
+
"metadata": {
|
| 488 |
+
"colab_type": "text",
|
| 489 |
+
"id": "PpsvBpuMR1Ri"
|
| 490 |
+
},
|
| 491 |
+
"source": [
|
| 492 |
+
"Starting from a sphere mesh, we will learn offsets of each vertex such that the predicted mesh silhouette is more similar to the target silhouette image at each optimization step. We begin by loading our initial sphere mesh:"
|
| 493 |
+
]
|
| 494 |
+
},
|
| 495 |
+
{
|
| 496 |
+
"cell_type": "code",
|
| 497 |
+
"execution_count": null,
|
| 498 |
+
"metadata": {
|
| 499 |
+
"colab": {},
|
| 500 |
+
"colab_type": "code",
|
| 501 |
+
"id": "i989ARH1R1Rj"
|
| 502 |
+
},
|
| 503 |
+
"outputs": [],
|
| 504 |
+
"source": [
|
| 505 |
+
"# We initialize the source shape to be a sphere of radius 1. \n",
|
| 506 |
+
"src_mesh = ico_sphere(4, device)"
|
| 507 |
+
]
|
| 508 |
+
},
|
| 509 |
+
{
|
| 510 |
+
"cell_type": "markdown",
|
| 511 |
+
"metadata": {
|
| 512 |
+
"colab_type": "text",
|
| 513 |
+
"id": "f5xVtgLNDvC5"
|
| 514 |
+
},
|
| 515 |
+
"source": [
|
| 516 |
+
"We create a new differentiable renderer for rendering the silhouette of our predicted mesh:"
|
| 517 |
+
]
|
| 518 |
+
},
|
| 519 |
+
{
|
| 520 |
+
"cell_type": "code",
|
| 521 |
+
"execution_count": null,
|
| 522 |
+
"metadata": {
|
| 523 |
+
"colab": {},
|
| 524 |
+
"colab_type": "code",
|
| 525 |
+
"id": "sXfjzgG4DsDJ"
|
| 526 |
+
},
|
| 527 |
+
"outputs": [],
|
| 528 |
+
"source": [
|
| 529 |
+
"# Rasterization settings for differentiable rendering, where the blur_radius\n",
|
| 530 |
+
"# initialization is based on Liu et al, 'Soft Rasterizer: A Differentiable \n",
|
| 531 |
+
"# Renderer for Image-based 3D Reasoning', ICCV 2019\n",
|
| 532 |
+
"sigma = 1e-4\n",
|
| 533 |
+
"raster_settings_soft = RasterizationSettings(\n",
|
| 534 |
+
" image_size=128, \n",
|
| 535 |
+
" blur_radius=np.log(1. / 1e-4 - 1.)*sigma, \n",
|
| 536 |
+
" faces_per_pixel=50, \n",
|
| 537 |
+
")\n",
|
| 538 |
+
"\n",
|
| 539 |
+
"# Silhouette renderer \n",
|
| 540 |
+
"renderer_silhouette = MeshRenderer(\n",
|
| 541 |
+
" rasterizer=MeshRasterizer(\n",
|
| 542 |
+
" cameras=camera, \n",
|
| 543 |
+
" raster_settings=raster_settings_soft\n",
|
| 544 |
+
" ),\n",
|
| 545 |
+
" shader=SoftSilhouetteShader()\n",
|
| 546 |
+
")"
|
| 547 |
+
]
|
| 548 |
+
},
|
| 549 |
+
{
|
| 550 |
+
"cell_type": "markdown",
|
| 551 |
+
"metadata": {
|
| 552 |
+
"colab_type": "text",
|
| 553 |
+
"id": "SGJKbCB6R1Rk"
|
| 554 |
+
},
|
| 555 |
+
"source": [
|
| 556 |
+
"We initialize settings, losses, and the optimizer that will be used to iteratively fit our mesh to the target silhouettes:"
|
| 557 |
+
]
|
| 558 |
+
},
|
| 559 |
+
{
|
| 560 |
+
"cell_type": "code",
|
| 561 |
+
"execution_count": null,
|
| 562 |
+
"metadata": {
|
| 563 |
+
"colab": {},
|
| 564 |
+
"colab_type": "code",
|
| 565 |
+
"id": "0sLrKv_MEULh"
|
| 566 |
+
},
|
| 567 |
+
"outputs": [],
|
| 568 |
+
"source": [
|
| 569 |
+
"# Number of views to optimize over in each SGD iteration\n",
|
| 570 |
+
"num_views_per_iteration = 2\n",
|
| 571 |
+
"# Number of optimization steps\n",
|
| 572 |
+
"Niter = 2000\n",
|
| 573 |
+
"# Plot period for the losses\n",
|
| 574 |
+
"plot_period = 250\n",
|
| 575 |
+
"\n",
|
| 576 |
+
"%matplotlib inline\n",
|
| 577 |
+
"\n",
|
| 578 |
+
"# Optimize using rendered silhouette image loss, mesh edge loss, mesh normal \n",
|
| 579 |
+
"# consistency, and mesh laplacian smoothing\n",
|
| 580 |
+
"losses = {\"silhouette\": {\"weight\": 1.0, \"values\": []},\n",
|
| 581 |
+
" \"edge\": {\"weight\": 1.0, \"values\": []},\n",
|
| 582 |
+
" \"normal\": {\"weight\": 0.01, \"values\": []},\n",
|
| 583 |
+
" \"laplacian\": {\"weight\": 1.0, \"values\": []},\n",
|
| 584 |
+
" }\n",
|
| 585 |
+
"\n",
|
| 586 |
+
"# Losses to smooth / regularize the mesh shape\n",
|
| 587 |
+
"def update_mesh_shape_prior_losses(mesh, loss):\n",
|
| 588 |
+
" # and (b) the edge length of the predicted mesh\n",
|
| 589 |
+
" loss[\"edge\"] = mesh_edge_loss(mesh)\n",
|
| 590 |
+
" \n",
|
| 591 |
+
" # mesh normal consistency\n",
|
| 592 |
+
" loss[\"normal\"] = mesh_normal_consistency(mesh)\n",
|
| 593 |
+
" \n",
|
| 594 |
+
" # mesh laplacian smoothing\n",
|
| 595 |
+
" loss[\"laplacian\"] = mesh_laplacian_smoothing(mesh, method=\"uniform\")\n",
|
| 596 |
+
"\n",
|
| 597 |
+
"# We will learn to deform the source mesh by offsetting its vertices\n",
|
| 598 |
+
"# The shape of the deform parameters is equal to the total number of vertices in\n",
|
| 599 |
+
"# src_mesh\n",
|
| 600 |
+
"verts_shape = src_mesh.verts_packed().shape\n",
|
| 601 |
+
"deform_verts = torch.full(verts_shape, 0.0, device=device, requires_grad=True)\n",
|
| 602 |
+
"\n",
|
| 603 |
+
"# The optimizer\n",
|
| 604 |
+
"optimizer = torch.optim.SGD([deform_verts], lr=1.0, momentum=0.9)"
|
| 605 |
+
]
|
| 606 |
+
},
|
| 607 |
+
{
|
| 608 |
+
"cell_type": "markdown",
|
| 609 |
+
"metadata": {
|
| 610 |
+
"colab_type": "text",
|
| 611 |
+
"id": "QLc9zK8lEqFS"
|
| 612 |
+
},
|
| 613 |
+
"source": [
|
| 614 |
+
"We write an optimization loop to iteratively refine our predicted mesh from the sphere mesh into a mesh that matches the silhouettes of the target images:"
|
| 615 |
+
]
|
| 616 |
+
},
|
| 617 |
+
{
|
| 618 |
+
"cell_type": "code",
|
| 619 |
+
"execution_count": null,
|
| 620 |
+
"metadata": {
|
| 621 |
+
"colab": {},
|
| 622 |
+
"colab_type": "code",
|
| 623 |
+
"id": "gCfepfOoR1Rl"
|
| 624 |
+
},
|
| 625 |
+
"outputs": [],
|
| 626 |
+
"source": [
|
| 627 |
+
"loop = tqdm(range(Niter))\n",
|
| 628 |
+
"\n",
|
| 629 |
+
"for i in loop:\n",
|
| 630 |
+
" # Initialize optimizer\n",
|
| 631 |
+
" optimizer.zero_grad()\n",
|
| 632 |
+
" \n",
|
| 633 |
+
" # Deform the mesh\n",
|
| 634 |
+
" new_src_mesh = src_mesh.offset_verts(deform_verts)\n",
|
| 635 |
+
" \n",
|
| 636 |
+
" # Losses to smooth /regularize the mesh shape\n",
|
| 637 |
+
" loss = {k: torch.tensor(0.0, device=device) for k in losses}\n",
|
| 638 |
+
" update_mesh_shape_prior_losses(new_src_mesh, loss)\n",
|
| 639 |
+
" \n",
|
| 640 |
+
" # Compute the average silhouette loss over two random views, as the average \n",
|
| 641 |
+
" # squared L2 distance between the predicted silhouette and the target \n",
|
| 642 |
+
" # silhouette from our dataset\n",
|
| 643 |
+
" for j in np.random.permutation(num_views).tolist()[:num_views_per_iteration]:\n",
|
| 644 |
+
" images_predicted = renderer_silhouette(new_src_mesh, cameras=target_cameras[j], lights=lights)\n",
|
| 645 |
+
" predicted_silhouette = images_predicted[..., 3]\n",
|
| 646 |
+
" loss_silhouette = ((predicted_silhouette - target_silhouette[j]) ** 2).mean()\n",
|
| 647 |
+
" loss[\"silhouette\"] += loss_silhouette / num_views_per_iteration\n",
|
| 648 |
+
" \n",
|
| 649 |
+
" # Weighted sum of the losses\n",
|
| 650 |
+
" sum_loss = torch.tensor(0.0, device=device)\n",
|
| 651 |
+
" for k, l in loss.items():\n",
|
| 652 |
+
" sum_loss += l * losses[k][\"weight\"]\n",
|
| 653 |
+
" losses[k][\"values\"].append(float(l.detach().cpu()))\n",
|
| 654 |
+
"\n",
|
| 655 |
+
" \n",
|
| 656 |
+
" # Print the losses\n",
|
| 657 |
+
" loop.set_description(\"total_loss = %.6f\" % sum_loss)\n",
|
| 658 |
+
" \n",
|
| 659 |
+
" # Plot mesh\n",
|
| 660 |
+
" if i % plot_period == 0:\n",
|
| 661 |
+
" visualize_prediction(new_src_mesh, title=\"iter: %d\" % i, silhouette=True,\n",
|
| 662 |
+
" target_image=target_silhouette[1])\n",
|
| 663 |
+
" \n",
|
| 664 |
+
" # Optimization step\n",
|
| 665 |
+
" sum_loss.backward()\n",
|
| 666 |
+
" optimizer.step()"
|
| 667 |
+
]
|
| 668 |
+
},
|
| 669 |
+
{
|
| 670 |
+
"cell_type": "code",
|
| 671 |
+
"execution_count": null,
|
| 672 |
+
"metadata": {
|
| 673 |
+
"colab": {},
|
| 674 |
+
"colab_type": "code",
|
| 675 |
+
"id": "CX4huayKR1Rm",
|
| 676 |
+
"scrolled": true
|
| 677 |
+
},
|
| 678 |
+
"outputs": [],
|
| 679 |
+
"source": [
|
| 680 |
+
"visualize_prediction(new_src_mesh, silhouette=True, \n",
|
| 681 |
+
" target_image=target_silhouette[1])\n",
|
| 682 |
+
"plot_losses(losses)"
|
| 683 |
+
]
|
| 684 |
+
},
|
| 685 |
+
{
|
| 686 |
+
"cell_type": "markdown",
|
| 687 |
+
"metadata": {
|
| 688 |
+
"colab_type": "text",
|
| 689 |
+
"id": "XJDsJQmrR1Ro"
|
| 690 |
+
},
|
| 691 |
+
"source": [
|
| 692 |
+
"## 3. Mesh and texture prediction via textured rendering\n",
|
| 693 |
+
"We can predict both the mesh and its texture if we add an additional loss based on the comparing a predicted rendered RGB image to the target image. As before, we start with a sphere mesh. We learn both translational offsets and RGB texture colors for each vertex in the sphere mesh. Since our loss is based on rendered RGB pixel values instead of just the silhouette, we use a **SoftPhongShader** instead of a **SoftSilhouetteShader**."
|
| 694 |
+
]
|
| 695 |
+
},
|
| 696 |
+
{
|
| 697 |
+
"cell_type": "code",
|
| 698 |
+
"execution_count": null,
|
| 699 |
+
"metadata": {
|
| 700 |
+
"colab": {},
|
| 701 |
+
"colab_type": "code",
|
| 702 |
+
"id": "aZObyIt9R1Ro"
|
| 703 |
+
},
|
| 704 |
+
"outputs": [],
|
| 705 |
+
"source": [
|
| 706 |
+
"# Rasterization settings for differentiable rendering, where the blur_radius\n",
|
| 707 |
+
"# initialization is based on Liu et al, 'Soft Rasterizer: A Differentiable \n",
|
| 708 |
+
"# Renderer for Image-based 3D Reasoning', ICCV 2019\n",
|
| 709 |
+
"sigma = 1e-4\n",
|
| 710 |
+
"raster_settings_soft = RasterizationSettings(\n",
|
| 711 |
+
" image_size=128, \n",
|
| 712 |
+
" blur_radius=np.log(1. / 1e-4 - 1.)*sigma, \n",
|
| 713 |
+
" faces_per_pixel=50, \n",
|
| 714 |
+
" perspective_correct=False, \n",
|
| 715 |
+
")\n",
|
| 716 |
+
"\n",
|
| 717 |
+
"# Differentiable soft renderer using per vertex RGB colors for texture\n",
|
| 718 |
+
"renderer_textured = MeshRenderer(\n",
|
| 719 |
+
" rasterizer=MeshRasterizer(\n",
|
| 720 |
+
" cameras=camera, \n",
|
| 721 |
+
" raster_settings=raster_settings_soft\n",
|
| 722 |
+
" ),\n",
|
| 723 |
+
" shader=SoftPhongShader(device=device, \n",
|
| 724 |
+
" cameras=camera,\n",
|
| 725 |
+
" lights=lights)\n",
|
| 726 |
+
")"
|
| 727 |
+
]
|
| 728 |
+
},
|
| 729 |
+
{
|
| 730 |
+
"cell_type": "markdown",
|
| 731 |
+
"metadata": {
|
| 732 |
+
"colab_type": "text",
|
| 733 |
+
"id": "NM7gJux8GMQX"
|
| 734 |
+
},
|
| 735 |
+
"source": [
|
| 736 |
+
"We initialize settings, losses, and the optimizer that will be used to iteratively fit our mesh to the target RGB images:"
|
| 737 |
+
]
|
| 738 |
+
},
|
| 739 |
+
{
|
| 740 |
+
"cell_type": "code",
|
| 741 |
+
"execution_count": null,
|
| 742 |
+
"metadata": {
|
| 743 |
+
"colab": {},
|
| 744 |
+
"colab_type": "code",
|
| 745 |
+
"id": "BS6LAQquF3wq"
|
| 746 |
+
},
|
| 747 |
+
"outputs": [],
|
| 748 |
+
"source": [
|
| 749 |
+
"# Number of views to optimize over in each SGD iteration\n",
|
| 750 |
+
"num_views_per_iteration = 2\n",
|
| 751 |
+
"# Number of optimization steps\n",
|
| 752 |
+
"Niter = 2000\n",
|
| 753 |
+
"# Plot period for the losses\n",
|
| 754 |
+
"plot_period = 250\n",
|
| 755 |
+
"\n",
|
| 756 |
+
"%matplotlib inline\n",
|
| 757 |
+
"\n",
|
| 758 |
+
"# Optimize using rendered RGB image loss, rendered silhouette image loss, mesh \n",
|
| 759 |
+
"# edge loss, mesh normal consistency, and mesh laplacian smoothing\n",
|
| 760 |
+
"losses = {\"rgb\": {\"weight\": 1.0, \"values\": []},\n",
|
| 761 |
+
" \"silhouette\": {\"weight\": 1.0, \"values\": []},\n",
|
| 762 |
+
" \"edge\": {\"weight\": 1.0, \"values\": []},\n",
|
| 763 |
+
" \"normal\": {\"weight\": 0.01, \"values\": []},\n",
|
| 764 |
+
" \"laplacian\": {\"weight\": 1.0, \"values\": []},\n",
|
| 765 |
+
" }\n",
|
| 766 |
+
"\n",
|
| 767 |
+
"# We will learn to deform the source mesh by offsetting its vertices\n",
|
| 768 |
+
"# The shape of the deform parameters is equal to the total number of vertices in \n",
|
| 769 |
+
"# src_mesh\n",
|
| 770 |
+
"verts_shape = src_mesh.verts_packed().shape\n",
|
| 771 |
+
"deform_verts = torch.full(verts_shape, 0.0, device=device, requires_grad=True)\n",
|
| 772 |
+
"\n",
|
| 773 |
+
"# We will also learn per vertex colors for our sphere mesh that define texture \n",
|
| 774 |
+
"# of the mesh\n",
|
| 775 |
+
"sphere_verts_rgb = torch.full([1, verts_shape[0], 3], 0.5, device=device, requires_grad=True)\n",
|
| 776 |
+
"\n",
|
| 777 |
+
"# The optimizer\n",
|
| 778 |
+
"optimizer = torch.optim.SGD([deform_verts, sphere_verts_rgb], lr=1.0, momentum=0.9)"
|
| 779 |
+
]
|
| 780 |
+
},
|
| 781 |
+
{
|
| 782 |
+
"cell_type": "markdown",
|
| 783 |
+
"metadata": {
|
| 784 |
+
"colab_type": "text",
|
| 785 |
+
"id": "tzIAycuUR1Rq"
|
| 786 |
+
},
|
| 787 |
+
"source": [
|
| 788 |
+
"We write an optimization loop to iteratively refine our predicted mesh and its vertex colors from the sphere mesh into a mesh that matches the target images:"
|
| 789 |
+
]
|
| 790 |
+
},
|
| 791 |
+
{
|
| 792 |
+
"cell_type": "code",
|
| 793 |
+
"execution_count": null,
|
| 794 |
+
"metadata": {
|
| 795 |
+
"colab": {},
|
| 796 |
+
"colab_type": "code",
|
| 797 |
+
"id": "EKEH2p8-R1Rr"
|
| 798 |
+
},
|
| 799 |
+
"outputs": [],
|
| 800 |
+
"source": [
|
| 801 |
+
"loop = tqdm(range(Niter))\n",
|
| 802 |
+
"\n",
|
| 803 |
+
"for i in loop:\n",
|
| 804 |
+
" # Initialize optimizer\n",
|
| 805 |
+
" optimizer.zero_grad()\n",
|
| 806 |
+
" \n",
|
| 807 |
+
" # Deform the mesh\n",
|
| 808 |
+
" new_src_mesh = src_mesh.offset_verts(deform_verts)\n",
|
| 809 |
+
" \n",
|
| 810 |
+
" # Add per vertex colors to texture the mesh\n",
|
| 811 |
+
" new_src_mesh.textures = TexturesVertex(verts_features=sphere_verts_rgb) \n",
|
| 812 |
+
" \n",
|
| 813 |
+
" # Losses to smooth /regularize the mesh shape\n",
|
| 814 |
+
" loss = {k: torch.tensor(0.0, device=device) for k in losses}\n",
|
| 815 |
+
" update_mesh_shape_prior_losses(new_src_mesh, loss)\n",
|
| 816 |
+
" \n",
|
| 817 |
+
" # Randomly select two views to optimize over in this iteration. Compared\n",
|
| 818 |
+
" # to using just one view, this helps resolve ambiguities between updating\n",
|
| 819 |
+
" # mesh shape vs. updating mesh texture\n",
|
| 820 |
+
" for j in np.random.permutation(num_views).tolist()[:num_views_per_iteration]:\n",
|
| 821 |
+
" images_predicted = renderer_textured(new_src_mesh, cameras=target_cameras[j], lights=lights)\n",
|
| 822 |
+
"\n",
|
| 823 |
+
" # Squared L2 distance between the predicted silhouette and the target \n",
|
| 824 |
+
" # silhouette from our dataset\n",
|
| 825 |
+
" predicted_silhouette = images_predicted[..., 3]\n",
|
| 826 |
+
" loss_silhouette = ((predicted_silhouette - target_silhouette[j]) ** 2).mean()\n",
|
| 827 |
+
" loss[\"silhouette\"] += loss_silhouette / num_views_per_iteration\n",
|
| 828 |
+
" \n",
|
| 829 |
+
" # Squared L2 distance between the predicted RGB image and the target \n",
|
| 830 |
+
" # image from our dataset\n",
|
| 831 |
+
" predicted_rgb = images_predicted[..., :3]\n",
|
| 832 |
+
" loss_rgb = ((predicted_rgb - target_rgb[j]) ** 2).mean()\n",
|
| 833 |
+
" loss[\"rgb\"] += loss_rgb / num_views_per_iteration\n",
|
| 834 |
+
" \n",
|
| 835 |
+
" # Weighted sum of the losses\n",
|
| 836 |
+
" sum_loss = torch.tensor(0.0, device=device)\n",
|
| 837 |
+
" for k, l in loss.items():\n",
|
| 838 |
+
" sum_loss += l * losses[k][\"weight\"]\n",
|
| 839 |
+
" losses[k][\"values\"].append(float(l.detach().cpu()))\n",
|
| 840 |
+
" \n",
|
| 841 |
+
" # Print the losses\n",
|
| 842 |
+
" loop.set_description(\"total_loss = %.6f\" % sum_loss)\n",
|
| 843 |
+
" \n",
|
| 844 |
+
" # Plot mesh\n",
|
| 845 |
+
" if i % plot_period == 0:\n",
|
| 846 |
+
" visualize_prediction(new_src_mesh, renderer=renderer_textured, title=\"iter: %d\" % i, silhouette=False)\n",
|
| 847 |
+
" \n",
|
| 848 |
+
" # Optimization step\n",
|
| 849 |
+
" sum_loss.backward()\n",
|
| 850 |
+
" optimizer.step()\n"
|
| 851 |
+
]
|
| 852 |
+
},
|
| 853 |
+
{
|
| 854 |
+
"cell_type": "code",
|
| 855 |
+
"execution_count": null,
|
| 856 |
+
"metadata": {
|
| 857 |
+
"colab": {},
|
| 858 |
+
"colab_type": "code",
|
| 859 |
+
"id": "2qTcHO4rR1Rs",
|
| 860 |
+
"scrolled": true
|
| 861 |
+
},
|
| 862 |
+
"outputs": [],
|
| 863 |
+
"source": [
|
| 864 |
+
"visualize_prediction(new_src_mesh, renderer=renderer_textured, silhouette=False)\n",
|
| 865 |
+
"plot_losses(losses)"
|
| 866 |
+
]
|
| 867 |
+
},
|
| 868 |
+
{
|
| 869 |
+
"cell_type": "markdown",
|
| 870 |
+
"metadata": {
|
| 871 |
+
"colab_type": "text",
|
| 872 |
+
"id": "akBOm_xcNUms"
|
| 873 |
+
},
|
| 874 |
+
"source": [
|
| 875 |
+
"Save the final predicted mesh:"
|
| 876 |
+
]
|
| 877 |
+
},
|
| 878 |
+
{
|
| 879 |
+
"cell_type": "markdown",
|
| 880 |
+
"metadata": {
|
| 881 |
+
"colab_type": "text",
|
| 882 |
+
"id": "dXoIsGyhxRyK"
|
| 883 |
+
},
|
| 884 |
+
"source": [
|
| 885 |
+
"## 4. Save the final predicted mesh"
|
| 886 |
+
]
|
| 887 |
+
},
|
| 888 |
+
{
|
| 889 |
+
"cell_type": "code",
|
| 890 |
+
"execution_count": null,
|
| 891 |
+
"metadata": {
|
| 892 |
+
"colab": {},
|
| 893 |
+
"colab_type": "code",
|
| 894 |
+
"id": "OQGhV-psKna8"
|
| 895 |
+
},
|
| 896 |
+
"outputs": [],
|
| 897 |
+
"source": [
|
| 898 |
+
"# Fetch the verts and faces of the final predicted mesh\n",
|
| 899 |
+
"final_verts, final_faces = new_src_mesh.get_mesh_verts_faces(0)\n",
|
| 900 |
+
"\n",
|
| 901 |
+
"# Scale normalize back to the original target size\n",
|
| 902 |
+
"final_verts = final_verts * scale + center\n",
|
| 903 |
+
"\n",
|
| 904 |
+
"# Store the predicted mesh using save_obj\n",
|
| 905 |
+
"final_obj = os.path.join('./', 'final_model.obj')\n",
|
| 906 |
+
"save_obj(final_obj, final_verts, final_faces)"
|
| 907 |
+
]
|
| 908 |
+
},
|
| 909 |
+
{
|
| 910 |
+
"cell_type": "markdown",
|
| 911 |
+
"metadata": {
|
| 912 |
+
"colab_type": "text",
|
| 913 |
+
"id": "MtKYp0B6R1Ru"
|
| 914 |
+
},
|
| 915 |
+
"source": [
|
| 916 |
+
"## 5. Conclusion\n",
|
| 917 |
+
"In this tutorial, we learned how to load a textured mesh from an obj file, create a synthetic dataset by rendering the mesh from multiple viewpoints. We showed how to set up an optimization loop to fit a mesh to the observed dataset images based on a rendered silhouette loss. We then augmented this optimization loop with an additional loss based on rendered RGB images, which allowed us to predict both a mesh and its texture."
|
| 918 |
+
]
|
| 919 |
+
}
|
| 920 |
+
],
|
| 921 |
+
"metadata": {
|
| 922 |
+
"accelerator": "GPU",
|
| 923 |
+
"anp_metadata": {
|
| 924 |
+
"path": "fbsource/fbcode/vision/fair/pytorch3d/docs/tutorials/fit_textured_mesh.ipynb"
|
| 925 |
+
},
|
| 926 |
+
"bento_stylesheets": {
|
| 927 |
+
"bento/extensions/flow/main.css": true,
|
| 928 |
+
"bento/extensions/kernel_selector/main.css": true,
|
| 929 |
+
"bento/extensions/kernel_ui/main.css": true,
|
| 930 |
+
"bento/extensions/new_kernel/main.css": true,
|
| 931 |
+
"bento/extensions/system_usage/main.css": true,
|
| 932 |
+
"bento/extensions/theme/main.css": true
|
| 933 |
+
},
|
| 934 |
+
"colab": {
|
| 935 |
+
"name": "fit_textured_mesh.ipynb",
|
| 936 |
+
"provenance": [],
|
| 937 |
+
"toc_visible": true
|
| 938 |
+
},
|
| 939 |
+
"disseminate_notebook_info": {
|
| 940 |
+
"backup_notebook_id": "781874812352022"
|
| 941 |
+
},
|
| 942 |
+
"kernelspec": {
|
| 943 |
+
"display_name": "intro_to_cv",
|
| 944 |
+
"language": "python",
|
| 945 |
+
"name": "bento_kernel_intro_to_cv"
|
| 946 |
+
},
|
| 947 |
+
"language_info": {
|
| 948 |
+
"codemirror_mode": {
|
| 949 |
+
"name": "ipython",
|
| 950 |
+
"version": 3
|
| 951 |
+
},
|
| 952 |
+
"file_extension": ".py",
|
| 953 |
+
"mimetype": "text/x-python",
|
| 954 |
+
"name": "python",
|
| 955 |
+
"nbconvert_exporter": "python",
|
| 956 |
+
"pygments_lexer": "ipython3",
|
| 957 |
+
"version": "3.7.5+"
|
| 958 |
+
}
|
| 959 |
+
},
|
| 960 |
+
"nbformat": 4,
|
| 961 |
+
"nbformat_minor": 1
|
| 962 |
+
}
|
project/ManiSkill3/src/maniskill2_benchmark/cfdp_experiment/cfdp/extern/pytorch3d/docs/tutorials/fit_textured_volume.ipynb
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"execution_count": null,
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"outputs": [],
|
| 8 |
+
"source": [
|
| 9 |
+
"# Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved."
|
| 10 |
+
]
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "markdown",
|
| 14 |
+
"metadata": {},
|
| 15 |
+
"source": [
|
| 16 |
+
"# Fit a volume via raymarching\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"This tutorial shows how to fit a volume given a set of views of a scene using differentiable volumetric rendering.\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"More specifically, this tutorial will explain how to:\n",
|
| 21 |
+
"1. Create a differentiable volumetric renderer.\n",
|
| 22 |
+
"2. Create a Volumetric model (including how to use the `Volumes` class).\n",
|
| 23 |
+
"3. Fit the volume based on the images using the differentiable volumetric renderer. \n",
|
| 24 |
+
"4. Visualize the predicted volume."
|
| 25 |
+
]
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "markdown",
|
| 29 |
+
"metadata": {},
|
| 30 |
+
"source": [
|
| 31 |
+
"## 0. Install and Import modules\n",
|
| 32 |
+
"Ensure `torch` and `torchvision` are installed. If `pytorch3d` is not installed, install it using the following cell:"
|
| 33 |
+
]
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"metadata": {},
|
| 39 |
+
"outputs": [],
|
| 40 |
+
"source": [
|
| 41 |
+
"import os\n",
|
| 42 |
+
"import sys\n",
|
| 43 |
+
"import torch\n",
|
| 44 |
+
"import subprocess\n",
|
| 45 |
+
"need_pytorch3d=False\n",
|
| 46 |
+
"try:\n",
|
| 47 |
+
" import pytorch3d\n",
|
| 48 |
+
"except ModuleNotFoundError:\n",
|
| 49 |
+
" need_pytorch3d=True\n",
|
| 50 |
+
"if need_pytorch3d:\n",
|
| 51 |
+
" pyt_version_str=torch.__version__.split(\"+\")[0].replace(\".\", \"\")\n",
|
| 52 |
+
" version_str=\"\".join([\n",
|
| 53 |
+
" f\"py3{sys.version_info.minor}_cu\",\n",
|
| 54 |
+
" torch.version.cuda.replace(\".\",\"\"),\n",
|
| 55 |
+
" f\"_pyt{pyt_version_str}\"\n",
|
| 56 |
+
" ])\n",
|
| 57 |
+
" !pip install iopath\n",
|
| 58 |
+
" if sys.platform.startswith(\"linux\"):\n",
|
| 59 |
+
" print(\"Trying to install wheel for PyTorch3D\")\n",
|
| 60 |
+
" !pip install --no-index --no-cache-dir pytorch3d -f https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/{version_str}/download.html\n",
|
| 61 |
+
" pip_list = !pip freeze\n",
|
| 62 |
+
" need_pytorch3d = not any(i.startswith(\"pytorch3d==\") for i in pip_list)\n",
|
| 63 |
+
" if need_pytorch3d:\n",
|
| 64 |
+
" print(f\"failed to find/install wheel for {version_str}\")\n",
|
| 65 |
+
"if need_pytorch3d:\n",
|
| 66 |
+
" print(\"Installing PyTorch3D from source\")\n",
|
| 67 |
+
" !pip install ninja\n",
|
| 68 |
+
" !pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'"
|
| 69 |
+
]
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"outputs": [],
|
| 76 |
+
"source": [
|
| 77 |
+
"import os\n",
|
| 78 |
+
"import sys\n",
|
| 79 |
+
"import time\n",
|
| 80 |
+
"import json\n",
|
| 81 |
+
"import glob\n",
|
| 82 |
+
"import torch\n",
|
| 83 |
+
"import math\n",
|
| 84 |
+
"from tqdm.notebook import tqdm\n",
|
| 85 |
+
"import matplotlib.pyplot as plt\n",
|
| 86 |
+
"import numpy as np\n",
|
| 87 |
+
"from PIL import Image\n",
|
| 88 |
+
"from IPython import display\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"# Data structures and functions for rendering\n",
|
| 91 |
+
"from pytorch3d.structures import Volumes\n",
|
| 92 |
+
"from pytorch3d.renderer import (\n",
|
| 93 |
+
" FoVPerspectiveCameras, \n",
|
| 94 |
+
" VolumeRenderer,\n",
|
| 95 |
+
" NDCMultinomialRaysampler,\n",
|
| 96 |
+
" EmissionAbsorptionRaymarcher\n",
|
| 97 |
+
")\n",
|
| 98 |
+
"from pytorch3d.transforms import so3_exp_map\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"# obtain the utilized device\n",
|
| 101 |
+
"if torch.cuda.is_available():\n",
|
| 102 |
+
" device = torch.device(\"cuda:0\")\n",
|
| 103 |
+
" torch.cuda.set_device(device)\n",
|
| 104 |
+
"else:\n",
|
| 105 |
+
" device = torch.device(\"cpu\")"
|
| 106 |
+
]
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"outputs": [],
|
| 113 |
+
"source": [
|
| 114 |
+
"!wget https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/docs/tutorials/utils/plot_image_grid.py\n",
|
| 115 |
+
"!wget https://raw.githubusercontent.com/facebookresearch/pytorch3d/main/docs/tutorials/utils/generate_cow_renders.py\n",
|
| 116 |
+
"from plot_image_grid import image_grid\n",
|
| 117 |
+
"from generate_cow_renders import generate_cow_renders"
|
| 118 |
+
]
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "markdown",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"OR if running locally uncomment and run the following cell:"
|
| 125 |
+
]
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"outputs": [],
|
| 132 |
+
"source": [
|
| 133 |
+
"# from utils.generate_cow_renders import generate_cow_renders\n",
|
| 134 |
+
"# from utils import image_grid"
|
| 135 |
+
]
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "markdown",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"## 1. Generate images of the scene and masks\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"The following cell generates our training data.\n",
|
| 144 |
+
"It renders the cow mesh from the `fit_textured_mesh.ipynb` tutorial from several viewpoints and returns:\n",
|
| 145 |
+
"1. A batch of image and silhouette tensors that are produced by the cow mesh renderer.\n",
|
| 146 |
+
"2. A set of cameras corresponding to each render.\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"Note: For the purpose of this tutorial, which aims at explaining the details of volumetric rendering, we do not explain how the mesh rendering, implemented in the `generate_cow_renders` function, works. Please refer to `fit_textured_mesh.ipynb` for a detailed explanation of mesh rendering."
|
| 149 |
+
]
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"cell_type": "code",
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"outputs": [],
|
| 156 |
+
"source": [
|
| 157 |
+
"target_cameras, target_images, target_silhouettes = generate_cow_renders(num_views=40)\n",
|
| 158 |
+
"print(f'Generated {len(target_images)} images/silhouettes/cameras.')"
|
| 159 |
+
]
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "markdown",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"## 2. Initialize the volumetric renderer\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"The following initializes a volumetric renderer that emits a ray from each pixel of a target image and samples a set of uniformly-spaced points along the ray. At each ray-point, the corresponding density and color value is obtained by querying the corresponding location in the volumetric model of the scene (the model is described & instantiated in a later cell).\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"The renderer is composed of a *raymarcher* and a *raysampler*.\n",
|
| 170 |
+
"- The *raysampler* is responsible for emitting rays from image pixels and sampling the points along them. Here, we use the `NDCMultinomialRaysampler` which follows the standard PyTorch3D coordinate grid convention (+X from right to left; +Y from bottom to top; +Z away from the user).\n",
|
| 171 |
+
"- The *raymarcher* takes the densities and colors sampled along each ray and renders each ray into a color and an opacity value of the ray's source pixel. Here we use the `EmissionAbsorptionRaymarcher` which implements the standard Emission-Absorption raymarching algorithm."
|
| 172 |
+
]
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"outputs": [],
|
| 179 |
+
"source": [
|
| 180 |
+
"# render_size describes the size of both sides of the \n",
|
| 181 |
+
"# rendered images in pixels. We set this to the same size\n",
|
| 182 |
+
"# as the target images. I.e. we render at the same\n",
|
| 183 |
+
"# size as the ground truth images.\n",
|
| 184 |
+
"render_size = target_images.shape[1]\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"# Our rendered scene is centered around (0,0,0) \n",
|
| 187 |
+
"# and is enclosed inside a bounding box\n",
|
| 188 |
+
"# whose side is roughly equal to 3.0 (world units).\n",
|
| 189 |
+
"volume_extent_world = 3.0\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"# 1) Instantiate the raysampler.\n",
|
| 192 |
+
"# Here, NDCMultinomialRaysampler generates a rectangular image\n",
|
| 193 |
+
"# grid of rays whose coordinates follow the PyTorch3D\n",
|
| 194 |
+
"# coordinate conventions.\n",
|
| 195 |
+
"# Since we use a volume of size 128^3, we sample n_pts_per_ray=150,\n",
|
| 196 |
+
"# which roughly corresponds to a one ray-point per voxel.\n",
|
| 197 |
+
"# We further set the min_depth=0.1 since there is no surface within\n",
|
| 198 |
+
"# 0.1 units of any camera plane.\n",
|
| 199 |
+
"raysampler = NDCMultinomialRaysampler(\n",
|
| 200 |
+
" image_width=render_size,\n",
|
| 201 |
+
" image_height=render_size,\n",
|
| 202 |
+
" n_pts_per_ray=150,\n",
|
| 203 |
+
" min_depth=0.1,\n",
|
| 204 |
+
" max_depth=volume_extent_world,\n",
|
| 205 |
+
")\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"\n",
|
| 208 |
+
"# 2) Instantiate the raymarcher.\n",
|
| 209 |
+
"# Here, we use the standard EmissionAbsorptionRaymarcher \n",
|
| 210 |
+
"# which marches along each ray in order to render\n",
|
| 211 |
+
"# each ray into a single 3D color vector \n",
|
| 212 |
+
"# and an opacity scalar.\n",
|
| 213 |
+
"raymarcher = EmissionAbsorptionRaymarcher()\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"# Finally, instantiate the volumetric render\n",
|
| 216 |
+
"# with the raysampler and raymarcher objects.\n",
|
| 217 |
+
"renderer = VolumeRenderer(\n",
|
| 218 |
+
" raysampler=raysampler, raymarcher=raymarcher,\n",
|
| 219 |
+
")"
|
| 220 |
+
]
|
| 221 |
+
},
|
| 222 |
+
{
|
| 223 |
+
"cell_type": "markdown",
|
| 224 |
+
"metadata": {},
|
| 225 |
+
"source": [
|
| 226 |
+
"## 3. Initialize the volumetric model\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"Next we instantiate a volumetric model of the scene. This quantizes the 3D space to cubical voxels, where each voxel is described with a 3D vector representing the voxel's RGB color and a density scalar which describes the opacity of the voxel (ranging between [0-1], the higher the more opaque).\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"In order to ensure the range of densities and colors is between [0-1], we represent both volume colors and densities in the logarithmic space. During the forward function of the model, the log-space values are passed through the sigmoid function to bring the log-space values to the correct range.\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"Additionally, `VolumeModel` contains the renderer object. This object stays unaltered throughout the optimization.\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"In this cell we also define the `huber` loss function which computes the discrepancy between the rendered colors and masks."
|
| 235 |
+
]
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"outputs": [],
|
| 242 |
+
"source": [
|
| 243 |
+
"class VolumeModel(torch.nn.Module):\n",
|
| 244 |
+
" def __init__(self, renderer, volume_size=[64] * 3, voxel_size=0.1):\n",
|
| 245 |
+
" super().__init__()\n",
|
| 246 |
+
" # After evaluating torch.sigmoid(self.log_colors), we get \n",
|
| 247 |
+
" # densities close to zero.\n",
|
| 248 |
+
" self.log_densities = torch.nn.Parameter(-4.0 * torch.ones(1, *volume_size))\n",
|
| 249 |
+
" # After evaluating torch.sigmoid(self.log_colors), we get \n",
|
| 250 |
+
" # a neutral gray color everywhere.\n",
|
| 251 |
+
" self.log_colors = torch.nn.Parameter(torch.zeros(3, *volume_size))\n",
|
| 252 |
+
" self._voxel_size = voxel_size\n",
|
| 253 |
+
" # Store the renderer module as well.\n",
|
| 254 |
+
" self._renderer = renderer\n",
|
| 255 |
+
" \n",
|
| 256 |
+
" def forward(self, cameras):\n",
|
| 257 |
+
" batch_size = cameras.R.shape[0]\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" # Convert the log-space values to the densities/colors\n",
|
| 260 |
+
" densities = torch.sigmoid(self.log_densities)\n",
|
| 261 |
+
" colors = torch.sigmoid(self.log_colors)\n",
|
| 262 |
+
" \n",
|
| 263 |
+
" # Instantiate the Volumes object, making sure\n",
|
| 264 |
+
" # the densities and colors are correctly\n",
|
| 265 |
+
" # expanded batch_size-times.\n",
|
| 266 |
+
" volumes = Volumes(\n",
|
| 267 |
+
" densities = densities[None].expand(\n",
|
| 268 |
+
" batch_size, *self.log_densities.shape),\n",
|
| 269 |
+
" features = colors[None].expand(\n",
|
| 270 |
+
" batch_size, *self.log_colors.shape),\n",
|
| 271 |
+
" voxel_size=self._voxel_size,\n",
|
| 272 |
+
" )\n",
|
| 273 |
+
" \n",
|
| 274 |
+
" # Given cameras and volumes, run the renderer\n",
|
| 275 |
+
" # and return only the first output value \n",
|
| 276 |
+
" # (the 2nd output is a representation of the sampled\n",
|
| 277 |
+
" # rays which can be omitted for our purpose).\n",
|
| 278 |
+
" return self._renderer(cameras=cameras, volumes=volumes)[0]\n",
|
| 279 |
+
" \n",
|
| 280 |
+
"# A helper function for evaluating the smooth L1 (huber) loss\n",
|
| 281 |
+
"# between the rendered silhouettes and colors.\n",
|
| 282 |
+
"def huber(x, y, scaling=0.1):\n",
|
| 283 |
+
" diff_sq = (x - y) ** 2\n",
|
| 284 |
+
" loss = ((1 + diff_sq / (scaling**2)).clamp(1e-4).sqrt() - 1) * float(scaling)\n",
|
| 285 |
+
" return loss"
|
| 286 |
+
]
|
| 287 |
+
},
|
| 288 |
+
{
|
| 289 |
+
"cell_type": "markdown",
|
| 290 |
+
"metadata": {},
|
| 291 |
+
"source": [
|
| 292 |
+
"## 4. Fit the volume\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"Here we carry out the volume fitting with differentiable rendering.\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"In order to fit the volume, we render it from the viewpoints of the `target_cameras`\n",
|
| 297 |
+
"and compare the resulting renders with the observed `target_images` and `target_silhouettes`.\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"The comparison is done by evaluating the mean huber (smooth-l1) error between corresponding\n",
|
| 300 |
+
"pairs of `target_images`/`rendered_images` and `target_silhouettes`/`rendered_silhouettes`."
|
| 301 |
+
]
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"execution_count": null,
|
| 306 |
+
"metadata": {},
|
| 307 |
+
"outputs": [],
|
| 308 |
+
"source": [
|
| 309 |
+
"# First move all relevant variables to the correct device.\n",
|
| 310 |
+
"target_cameras = target_cameras.to(device)\n",
|
| 311 |
+
"target_images = target_images.to(device)\n",
|
| 312 |
+
"target_silhouettes = target_silhouettes.to(device)\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"# Instantiate the volumetric model.\n",
|
| 315 |
+
"# We use a cubical volume with the size of \n",
|
| 316 |
+
"# one side = 128. The size of each voxel of the volume \n",
|
| 317 |
+
"# is set to volume_extent_world / volume_size s.t. the\n",
|
| 318 |
+
"# volume represents the space enclosed in a 3D bounding box\n",
|
| 319 |
+
"# centered at (0, 0, 0) with the size of each side equal to 3.\n",
|
| 320 |
+
"volume_size = 128\n",
|
| 321 |
+
"volume_model = VolumeModel(\n",
|
| 322 |
+
" renderer,\n",
|
| 323 |
+
" volume_size=[volume_size] * 3, \n",
|
| 324 |
+
" voxel_size = volume_extent_world / volume_size,\n",
|
| 325 |
+
").to(device)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"# Instantiate the Adam optimizer. We set its master learning rate to 0.1.\n",
|
| 328 |
+
"lr = 0.1\n",
|
| 329 |
+
"optimizer = torch.optim.Adam(volume_model.parameters(), lr=lr)\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"# We do 300 Adam iterations and sample 10 random images in each minibatch.\n",
|
| 332 |
+
"batch_size = 10\n",
|
| 333 |
+
"n_iter = 300\n",
|
| 334 |
+
"for iteration in range(n_iter):\n",
|
| 335 |
+
"\n",
|
| 336 |
+
" # In case we reached the last 75% of iterations,\n",
|
| 337 |
+
" # decrease the learning rate of the optimizer 10-fold.\n",
|
| 338 |
+
" if iteration == round(n_iter * 0.75):\n",
|
| 339 |
+
" print('Decreasing LR 10-fold ...')\n",
|
| 340 |
+
" optimizer = torch.optim.Adam(\n",
|
| 341 |
+
" volume_model.parameters(), lr=lr * 0.1\n",
|
| 342 |
+
" )\n",
|
| 343 |
+
" \n",
|
| 344 |
+
" # Zero the optimizer gradient.\n",
|
| 345 |
+
" optimizer.zero_grad()\n",
|
| 346 |
+
" \n",
|
| 347 |
+
" # Sample random batch indices.\n",
|
| 348 |
+
" batch_idx = torch.randperm(len(target_cameras))[:batch_size]\n",
|
| 349 |
+
" \n",
|
| 350 |
+
" # Sample the minibatch of cameras.\n",
|
| 351 |
+
" batch_cameras = FoVPerspectiveCameras(\n",
|
| 352 |
+
" R = target_cameras.R[batch_idx], \n",
|
| 353 |
+
" T = target_cameras.T[batch_idx], \n",
|
| 354 |
+
" znear = target_cameras.znear[batch_idx],\n",
|
| 355 |
+
" zfar = target_cameras.zfar[batch_idx],\n",
|
| 356 |
+
" aspect_ratio = target_cameras.aspect_ratio[batch_idx],\n",
|
| 357 |
+
" fov = target_cameras.fov[batch_idx],\n",
|
| 358 |
+
" device = device,\n",
|
| 359 |
+
" )\n",
|
| 360 |
+
" \n",
|
| 361 |
+
" # Evaluate the volumetric model.\n",
|
| 362 |
+
" rendered_images, rendered_silhouettes = volume_model(\n",
|
| 363 |
+
" batch_cameras\n",
|
| 364 |
+
" ).split([3, 1], dim=-1)\n",
|
| 365 |
+
" \n",
|
| 366 |
+
" # Compute the silhouette error as the mean huber\n",
|
| 367 |
+
" # loss between the predicted masks and the\n",
|
| 368 |
+
" # target silhouettes.\n",
|
| 369 |
+
" sil_err = huber(\n",
|
| 370 |
+
" rendered_silhouettes[..., 0], target_silhouettes[batch_idx],\n",
|
| 371 |
+
" ).abs().mean()\n",
|
| 372 |
+
"\n",
|
| 373 |
+
" # Compute the color error as the mean huber\n",
|
| 374 |
+
" # loss between the rendered colors and the\n",
|
| 375 |
+
" # target ground truth images.\n",
|
| 376 |
+
" color_err = huber(\n",
|
| 377 |
+
" rendered_images, target_images[batch_idx],\n",
|
| 378 |
+
" ).abs().mean()\n",
|
| 379 |
+
" \n",
|
| 380 |
+
" # The optimization loss is a simple\n",
|
| 381 |
+
" # sum of the color and silhouette errors.\n",
|
| 382 |
+
" loss = color_err + sil_err \n",
|
| 383 |
+
" \n",
|
| 384 |
+
" # Print the current values of the losses.\n",
|
| 385 |
+
" if iteration % 10 == 0:\n",
|
| 386 |
+
" print(\n",
|
| 387 |
+
" f'Iteration {iteration:05d}:'\n",
|
| 388 |
+
" + f' color_err = {float(color_err):1.2e}'\n",
|
| 389 |
+
" + f' mask_err = {float(sil_err):1.2e}'\n",
|
| 390 |
+
" )\n",
|
| 391 |
+
" \n",
|
| 392 |
+
" # Take the optimization step.\n",
|
| 393 |
+
" loss.backward()\n",
|
| 394 |
+
" optimizer.step()\n",
|
| 395 |
+
" \n",
|
| 396 |
+
" # Visualize the renders every 40 iterations.\n",
|
| 397 |
+
" if iteration % 40 == 0:\n",
|
| 398 |
+
" # Visualize only a single randomly selected element of the batch.\n",
|
| 399 |
+
" im_show_idx = int(torch.randint(low=0, high=batch_size, size=(1,)))\n",
|
| 400 |
+
" fig, ax = plt.subplots(2, 2, figsize=(10, 10))\n",
|
| 401 |
+
" ax = ax.ravel()\n",
|
| 402 |
+
" clamp_and_detach = lambda x: x.clamp(0.0, 1.0).cpu().detach().numpy()\n",
|
| 403 |
+
" ax[0].imshow(clamp_and_detach(rendered_images[im_show_idx]))\n",
|
| 404 |
+
" ax[1].imshow(clamp_and_detach(target_images[batch_idx[im_show_idx], ..., :3]))\n",
|
| 405 |
+
" ax[2].imshow(clamp_and_detach(rendered_silhouettes[im_show_idx, ..., 0]))\n",
|
| 406 |
+
" ax[3].imshow(clamp_and_detach(target_silhouettes[batch_idx[im_show_idx]]))\n",
|
| 407 |
+
" for ax_, title_ in zip(\n",
|
| 408 |
+
" ax, \n",
|
| 409 |
+
" (\"rendered image\", \"target image\", \"rendered silhouette\", \"target silhouette\")\n",
|
| 410 |
+
" ):\n",
|
| 411 |
+
" ax_.grid(\"off\")\n",
|
| 412 |
+
" ax_.axis(\"off\")\n",
|
| 413 |
+
" ax_.set_title(title_)\n",
|
| 414 |
+
" fig.canvas.draw(); fig.show()\n",
|
| 415 |
+
" display.clear_output(wait=True)\n",
|
| 416 |
+
" display.display(fig)"
|
| 417 |
+
]
|
| 418 |
+
},
|
| 419 |
+
{
|
| 420 |
+
"cell_type": "markdown",
|
| 421 |
+
"metadata": {},
|
| 422 |
+
"source": [
|
| 423 |
+
"## 5. Visualizing the optimized volume\n",
|
| 424 |
+
"\n",
|
| 425 |
+
"Finally, we visualize the optimized volume by rendering from multiple viewpoints that rotate around the volume's y-axis."
|
| 426 |
+
]
|
| 427 |
+
},
|
| 428 |
+
{
|
| 429 |
+
"cell_type": "code",
|
| 430 |
+
"execution_count": null,
|
| 431 |
+
"metadata": {},
|
| 432 |
+
"outputs": [],
|
| 433 |
+
"source": [
|
| 434 |
+
"def generate_rotating_volume(volume_model, n_frames = 50):\n",
|
| 435 |
+
" logRs = torch.zeros(n_frames, 3, device=device)\n",
|
| 436 |
+
" logRs[:, 1] = torch.linspace(0.0, 2.0 * 3.14, n_frames, device=device)\n",
|
| 437 |
+
" Rs = so3_exp_map(logRs)\n",
|
| 438 |
+
" Ts = torch.zeros(n_frames, 3, device=device)\n",
|
| 439 |
+
" Ts[:, 2] = 2.7\n",
|
| 440 |
+
" frames = []\n",
|
| 441 |
+
" print('Generating rotating volume ...')\n",
|
| 442 |
+
" for R, T in zip(tqdm(Rs), Ts):\n",
|
| 443 |
+
" camera = FoVPerspectiveCameras(\n",
|
| 444 |
+
" R=R[None], \n",
|
| 445 |
+
" T=T[None], \n",
|
| 446 |
+
" znear = target_cameras.znear[0],\n",
|
| 447 |
+
" zfar = target_cameras.zfar[0],\n",
|
| 448 |
+
" aspect_ratio = target_cameras.aspect_ratio[0],\n",
|
| 449 |
+
" fov = target_cameras.fov[0],\n",
|
| 450 |
+
" device=device,\n",
|
| 451 |
+
" )\n",
|
| 452 |
+
" frames.append(volume_model(camera)[..., :3].clamp(0.0, 1.0))\n",
|
| 453 |
+
" return torch.cat(frames)\n",
|
| 454 |
+
" \n",
|
| 455 |
+
"with torch.no_grad():\n",
|
| 456 |
+
" rotating_volume_frames = generate_rotating_volume(volume_model, n_frames=7*4)\n",
|
| 457 |
+
"\n",
|
| 458 |
+
"image_grid(rotating_volume_frames.clamp(0., 1.).cpu().numpy(), rows=4, cols=7, rgb=True, fill=True)\n",
|
| 459 |
+
"plt.show()"
|
| 460 |
+
]
|
| 461 |
+
},
|
| 462 |
+
{
|
| 463 |
+
"cell_type": "markdown",
|
| 464 |
+
"metadata": {},
|
| 465 |
+
"source": [
|
| 466 |
+
"## 6. Conclusion\n",
|
| 467 |
+
"\n",
|
| 468 |
+
"In this tutorial, we have shown how to optimize a 3D volumetric representation of a scene such that the renders of the volume from known viewpoints match the observed images for each viewpoint. The rendering was carried out using the PyTorch3D's volumetric renderer composed of an `NDCMultinomialRaysampler` and an `EmissionAbsorptionRaymarcher`."
|
| 469 |
+
]
|
| 470 |
+
}
|
| 471 |
+
],
|
| 472 |
+
"metadata": {
|
| 473 |
+
"bento_stylesheets": {
|
| 474 |
+
"bento/extensions/flow/main.css": true,
|
| 475 |
+
"bento/extensions/kernel_selector/main.css": true,
|
| 476 |
+
"bento/extensions/kernel_ui/main.css": true,
|
| 477 |
+
"bento/extensions/new_kernel/main.css": true,
|
| 478 |
+
"bento/extensions/system_usage/main.css": true,
|
| 479 |
+
"bento/extensions/theme/main.css": true
|
| 480 |
+
},
|
| 481 |
+
"kernelspec": {
|
| 482 |
+
"display_name": "pytorch3d_etc (local)",
|
| 483 |
+
"language": "python",
|
| 484 |
+
"name": "pytorch3d_etc_local"
|
| 485 |
+
},
|
| 486 |
+
"language_info": {
|
| 487 |
+
"codemirror_mode": {
|
| 488 |
+
"name": "ipython",
|
| 489 |
+
"version": 3
|
| 490 |
+
},
|
| 491 |
+
"file_extension": ".py",
|
| 492 |
+
"mimetype": "text/x-python",
|
| 493 |
+
"name": "python",
|
| 494 |
+
"nbconvert_exporter": "python",
|
| 495 |
+
"pygments_lexer": "ipython3",
|
| 496 |
+
"version": "3.7.5+"
|
| 497 |
+
}
|
| 498 |
+
},
|
| 499 |
+
"nbformat": 4,
|
| 500 |
+
"nbformat_minor": 2
|
| 501 |
+
}
|