[ICCV 2023] Make-It-3D: High-Fidelity 3D Creation from A Single Image with Diffusion Prior
update DPT
junshutangf7a8def5a206
diff --git a/DPT/.gitignore b/DPT/.gitignorenew file mode 100644index 0000000..534fed2--- /dev/null+++ b/DPT/.gitignore@@ -0,0 +1,111 @@+# Byte-compiled / optimized / DLL files+__pycache__/+*.py[cod]+*$py.class++# C extensions+*.so++# Distribution / packaging+.Python+build/+develop-eggs/+dist/+downloads/+eggs/+.eggs/+lib/+lib64/+parts/+sdist/+var/+wheels/+*.egg-info/+.installed.cfg+*.egg+MANIFEST++# PyInstaller+# Usually these files are written by a python script from a template+# before PyInstaller builds the exe, so as to inject date/other infos into it.+*.manifest+*.spec++# Installer logs+pip-log.txt+pip-delete-this-directory.txt++# Unit test / coverage reports+htmlcov/+.tox/+.coverage+.coverage.*+.cache+nosetests.xml+coverage.xml+*.cover+.hypothesis/+.pytest_cache/++# Translations+*.mo+*.pot++# Django stuff:+*.log+local_settings.py+db.sqlite3++# Flask stuff:+instance/+.webassets-cache++# Scrapy stuff:+.scrapy++# Sphinx documentation+docs/_build/++# PyBuilder+target/++# Jupyter Notebook+.ipynb_checkpoints++# pyenv+.python-version++# celery beat schedule file+celerybeat-schedule++# SageMath parsed files+*.sage.py++# Environments+.env+.venv+env/+venv/+ENV/+env.bak/+venv.bak/++# Spyder project settings+.spyderproject+.spyproject++# Rope project settings+.ropeproject++# mkdocs documentation+/site++# mypy+.mypy_cache/++*.png+*.pfm+*.jpg+*.jpeg+*.pt+.DS_Storediff --git a/DPT/EVALUATION.md b/DPT/EVALUATION.mdnew file mode 100644index 0000000..fc2427f--- /dev/null+++ b/DPT/EVALUATION.md@@ -0,0 +1,60 @@+### Genral-purpose models+The general-purpose models are affine-invariant and as such need a pre-alignment step before an error can be computed.++Sample code for NYUv2 can be found here:+https://gist.github.com/ranftlr/a1c7a24ebb24ce0e2f2ace5bce917022++Sample code for KITTI can be found here:+https://gist.github.com/ranftlr/45f4c7ddeb1bbb88d606bc600cab6c8d+++### KITTI+* Remove images from `/input/` and `/output_monodepth/` folders+* Download `kitti_eval_dataset.zip` https://drive.google.com/file/d/1GbfMGuwg2VS06Vl75-_tB5FDj9EOrjl0/view?usp=sharing and unzip it in the `/input/` folder (or follow this repository https://github.com/cogaplex-bts/bts to get RGB and Depth images from list [eigen_test_files_with_gt.txt](https://github.com/cogaplex-bts/bts/blob/master/train_test_inputs/eigen_test_files_with_gt.txt) )+* Download [dpt_hybrid_kitti-cb926ef4.pt](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid_kitti-cb926ef4.pt) model and place it in the `/weights/` folder+* Download [eval_with_pngs.py](https://raw.githubusercontent.com/cogaplex-bts/bts/5a55542ebbe849eb85b5ce9592365225b93d8b28/utils/eval_with_pngs.py) in the root folder+* `python run_monodepth.py --model_type dpt_hybrid_kitti --kitti_crop --absolute_depth`+* `python ./eval_with_pngs.py --pred_path ./output_monodepth/ --gt_path ./input/gt/ --dataset kitti --min_depth_eval 1e-3 --max_depth_eval 80 --garg_crop --do_kb_crop`++Result:+```+Evaluating 697 files+GT files reading done+45 GT files missing+Computing errors+ d1, d2, d3, AbsRel, SqRel, RMSE, RMSElog, SILog, log10+ 0.959, 0.995, 0.999, 0.062, 0.222, 2.575, 0.092, 8.282, 0.027+Done.+```++----++### NYUv2+* Remove images from `/input/` and `/output_monodepth/` folders+* Download `nyu_eval_dataset.zip` https://drive.google.com/file/d/1b37uu-bqTZcSwokGkHIOEXuuBdfo80HI/view?usp=sharing and unzip it in the `/input/` folder (or follow this repository https://github.com/cogaplex-bts/bts to get RGB and Depth images from list [nyudepthv2_test_files_with_gt.txt](https://github.com/cogaplex-bts/bts/blob/master/train_test_inputs/nyudepthv2_test_files_with_gt.txt) )+* Download [dpt_hybrid_nyu-2ce69ec7.pt](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid_nyu-2ce69ec7.pt) model (**or a new model** that is fine-tuned with slightly different hyperparameters [dpt_hybrid_nyu_new-217f207d.pt](https://drive.google.com/file/d/1Nxv2OiqhAMosBL2a3pflamTW39dMjaSp/view?usp=sharing) ) and place it in the `/weights/` folder+* Download [eval_with_pngs.py](https://raw.githubusercontent.com/cogaplex-bts/bts/5a55542ebbe849eb85b5ce9592365225b93d8b28/utils/eval_with_pngs.py) in the root folder+* `python run_monodepth.py --model_type dpt_hybrid_nyu --absolute_depth`+(or **for new model** `python run_monodepth.py --model_type dpt_hybrid_nyu --absolute_depth --model_weights weights/dpt_hybrid_nyu_new-217f207d.pt` )+* `python ./eval_with_pngs.py --pred_path ./output_monodepth/ --gt_path ./input/gt/ --dataset nyu --max_depth_eval 10 --eigen_crop`++Result (old model) - **from paper**:+```+Evaluating 654 files+GT files reading done+0 GT files missing+Computing errors+ d1, d2, d3, AbsRel, SqRel, RMSE, RMSElog, SILog, log10+ 0.904, 0.988, 0.998, 0.109, 0.054, 0.357, 0.129, 9.521, 0.045+Done.+```++Result (new model):+```+GT files reading done+697 GT files missing+Computing errors+ d1, d2, d3, AbsRel, SqRel, RMSE, RMSElog, SILog, log10+ 0.905, 0.988, 0.998, 0.109, 0.055, 0.357, 0.129, 9.427, 0.045+Done.+```diff --git a/DPT/LICENSE b/DPT/LICENSEnew file mode 100644index 0000000..4396e96--- /dev/null+++ b/DPT/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2021 Intel ISL (Intel Intelligent Systems Lab)++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/DPT/README.md b/DPT/README.mdnew file mode 100644index 0000000..70d78e8--- /dev/null+++ b/DPT/README.md@@ -0,0 +1,97 @@+## Vision Transformers for Dense Prediction++This repository contains code and models for our [paper](https://arxiv.org/abs/2103.13413):++> Vision Transformers for Dense Prediction+> René Ranftl, Alexey Bochkovskiy, Vladlen Koltun+++### Changelog+* [March 2021] Initial release of inference code and models++### Setup++1) Download the model weights and place them in the `weights` folder:+++Monodepth:+- [dpt_hybrid-midas-501f0c75.pt](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-midas-501f0c75.pt), [Mirror](https://drive.google.com/file/d/1dgcJEYYw1F8qirXhZxgNK8dWWz_8gZBD/view?usp=sharing)+- [dpt_large-midas-2f21e586.pt](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt), [Mirror](https://drive.google.com/file/d/1vnuhoMc6caF-buQQ4hK0CeiMk9SjwB-G/view?usp=sharing)++Segmentation:+ - [dpt_hybrid-ade20k-53898607.pt](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid-ade20k-53898607.pt), [Mirror](https://drive.google.com/file/d/1zKIAMbltJ3kpGLMh6wjsq65_k5XQ7_9m/view?usp=sharing)+ - [dpt_large-ade20k-b12dca68.pt](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-ade20k-b12dca68.pt), [Mirror](https://drive.google.com/file/d/1foDpUM7CdS8Zl6GPdkrJaAOjskb7hHe-/view?usp=sharing)++2) Set up dependencies:++ ```shell+ pip install -r requirements.txt+ ```++ The code was tested with Python 3.7, PyTorch 1.8.0, OpenCV 4.5.1, and timm 0.4.5++### Usage++1) Place one or more input images in the folder `input`.++2) Run a monocular depth estimation model:++ ```shell+ python run_monodepth.py+ ```++ Or run a semantic segmentation model:++ ```shell+ python run_segmentation.py+ ```++3) The results are written to the folder `output_monodepth` and `output_semseg`, respectively.++Use the flag `-t` to switch between different models. Possible options are `dpt_hybrid` (default) and `dpt_large`.+++**Additional models:**++- Monodepth finetuned on KITTI: [dpt_hybrid_kitti-cb926ef4.pt](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid_kitti-cb926ef4.pt) [Mirror](https://drive.google.com/file/d/1-oJpORoJEdxj4LTV-Pc17iB-smp-khcX/view?usp=sharing)+- Monodepth finetuned on NYUv2: [dpt_hybrid_nyu-2ce69ec7.pt](https://github.com/intel-isl/DPT/releases/download/1_0/dpt_hybrid_nyu-2ce69ec7.pt) [Mirror](https\://drive.google.com/file/d/1NjiFw1Z9lUAfTPZu4uQ9gourVwvmd58O/view?usp=sharing)++Run with++```shell+python run_monodepth -t [dpt_hybrid_kitti|dpt_hybrid_nyu]+```++### Evaluation++Hints on how to evaluate monodepth models can be found here: https://github.com/intel-isl/DPT/blob/main/EVALUATION.md+++### Citation++Please cite our papers if you use this code or any of the models.+```+@article{Ranftl2021,+ author = {Ren\'{e} Ranftl and Alexey Bochkovskiy and Vladlen Koltun},+ title = {Vision Transformers for Dense Prediction},+ journal = {ArXiv preprint},+ year = {2021},+}+```++```+@article{Ranftl2020,+ author = {Ren\'{e} Ranftl and Katrin Lasinger and David Hafner and Konrad Schindler and Vladlen Koltun},+ title = {Towards Robust Monocular Depth Estimation: Mixing Datasets for Zero-shot Cross-dataset Transfer},+ journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence (TPAMI)},+ year = {2020},+}+```++### Acknowledgements++Our work builds on and uses code from [timm](https://github.com/rwightman/pytorch-image-models) and [PyTorch-Encoding](https://github.com/zhanghang1989/PyTorch-Encoding). We'd like to thank the authors for making these libraries available.++### License++MIT Licensediff --git a/DPT/dpt/__init__.py b/DPT/dpt/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/DPT/dpt/base_model.py b/DPT/dpt/base_model.pynew file mode 100644index 0000000..5c2e0e9--- /dev/null+++ b/DPT/dpt/base_model.py@@ -0,0 +1,16 @@+import torch+++class BaseModel(torch.nn.Module):+ def load(self, path):+ """Load model from file.++ Args:+ path (str): file path+ """+ parameters = torch.load(path, map_location=torch.device("cpu"))++ if "optimizer" in parameters:+ parameters = parameters["model"]++ self.load_state_dict(parameters)diff --git a/DPT/dpt/blocks.py b/DPT/dpt/blocks.pynew file mode 100644index 0000000..46b3fe3--- /dev/null+++ b/DPT/dpt/blocks.py@@ -0,0 +1,383 @@+import torch+import torch.nn as nn++from .vit import (+ _make_pretrained_vitb_rn50_384,+ _make_pretrained_vitl16_384,+ _make_pretrained_vitb16_384,+ forward_vit,+)+++def _make_encoder(+ backbone,+ features,+ use_pretrained,+ groups=1,+ expand=False,+ exportable=True,+ hooks=None,+ use_vit_only=False,+ use_readout="ignore",+ enable_attention_hooks=False,+):+ if backbone == "vitl16_384":+ pretrained = _make_pretrained_vitl16_384(+ use_pretrained,+ hooks=hooks,+ use_readout=use_readout,+ enable_attention_hooks=enable_attention_hooks,+ )+ scratch = _make_scratch(+ [256, 512, 1024, 1024], features, groups=groups, expand=expand+ ) # ViT-L/16 - 85.0% Top1 (backbone)+ elif backbone == "vitb_rn50_384":+ pretrained = _make_pretrained_vitb_rn50_384(+ use_pretrained,+ hooks=hooks,+ use_vit_only=use_vit_only,+ use_readout=use_readout,+ enable_attention_hooks=enable_attention_hooks,+ )+ scratch = _make_scratch(+ [256, 512, 768, 768], features, groups=groups, expand=expand+ ) # ViT-H/16 - 85.0% Top1 (backbone)+ elif backbone == "vitb16_384":+ pretrained = _make_pretrained_vitb16_384(+ use_pretrained,+ hooks=hooks,+ use_readout=use_readout,+ enable_attention_hooks=enable_attention_hooks,+ )+ scratch = _make_scratch(+ [96, 192, 384, 768], features, groups=groups, expand=expand+ ) # ViT-B/16 - 84.6% Top1 (backbone)+ elif backbone == "resnext101_wsl":+ pretrained = _make_pretrained_resnext101_wsl(use_pretrained)+ scratch = _make_scratch(+ [256, 512, 1024, 2048], features, groups=groups, expand=expand+ ) # efficientnet_lite3+ else:+ print(f"Backbone '{backbone}' not implemented")+ assert False++ return pretrained, scratch+++def _make_scratch(in_shape, out_shape, groups=1, expand=False):+ scratch = nn.Module()++ out_shape1 = out_shape+ out_shape2 = out_shape+ out_shape3 = out_shape+ out_shape4 = out_shape+ if expand == True:+ out_shape1 = out_shape+ out_shape2 = out_shape * 2+ out_shape3 = out_shape * 4+ out_shape4 = out_shape * 8++ scratch.layer1_rn = nn.Conv2d(+ in_shape[0],+ out_shape1,+ kernel_size=3,+ stride=1,+ padding=1,+ bias=False,+ groups=groups,+ )+ scratch.layer2_rn = nn.Conv2d(+ in_shape[1],+ out_shape2,+ kernel_size=3,+ stride=1,+ padding=1,+ bias=False,+ groups=groups,+ )+ scratch.layer3_rn = nn.Conv2d(+ in_shape[2],+ out_shape3,+ kernel_size=3,+ stride=1,+ padding=1,+ bias=False,+ groups=groups,+ )+ scratch.layer4_rn = nn.Conv2d(+ in_shape[3],+ out_shape4,+ kernel_size=3,+ stride=1,+ padding=1,+ bias=False,+ groups=groups,+ )++ return scratch+++def _make_resnet_backbone(resnet):+ pretrained = nn.Module()+ pretrained.layer1 = nn.Sequential(+ resnet.conv1, resnet.bn1, resnet.relu, resnet.maxpool, resnet.layer1+ )++ pretrained.layer2 = resnet.layer2+ pretrained.layer3 = resnet.layer3+ pretrained.layer4 = resnet.layer4++ return pretrained+++def _make_pretrained_resnext101_wsl(use_pretrained):+ resnet = torch.hub.load("facebookresearch/WSL-Images", "resnext101_32x8d_wsl")+ return _make_resnet_backbone(resnet)+++class Interpolate(nn.Module):+ """Interpolation module."""++ def __init__(self, scale_factor, mode, align_corners=False):+ """Init.++ Args:+ scale_factor (float): scaling+ mode (str): interpolation mode+ """+ super(Interpolate, self).__init__()++ self.interp = nn.functional.interpolate+ self.scale_factor = scale_factor+ self.mode = mode+ self.align_corners = align_corners++ def forward(self, x):+ """Forward pass.++ Args:+ x (tensor): input++ Returns:+ tensor: interpolated data+ """++ x = self.interp(+ x,+ scale_factor=self.scale_factor,+ mode=self.mode,+ align_corners=self.align_corners,+ )++ return x+++class ResidualConvUnit(nn.Module):+ """Residual convolution module."""++ def __init__(self, features):+ """Init.++ Args:+ features (int): number of features+ """+ super().__init__()++ self.conv1 = nn.Conv2d(+ features, features, kernel_size=3, stride=1, padding=1, bias=True+ )++ self.conv2 = nn.Conv2d(+ features, features, kernel_size=3, stride=1, padding=1, bias=True+ )++ self.relu = nn.ReLU(inplace=True)++ def forward(self, x):+ """Forward pass.++ Args:+ x (tensor): input++ Returns:+ tensor: output+ """+ out = self.relu(x)+ out = self.conv1(out)+ out = self.relu(out)+ out = self.conv2(out)++ return out + x+++class FeatureFusionBlock(nn.Module):+ """Feature fusion block."""++ def __init__(self, features):+ """Init.++ Args:+ features (int): number of features+ """+ super(FeatureFusionBlock, self).__init__()++ self.resConfUnit1 = ResidualConvUnit(features)+ self.resConfUnit2 = ResidualConvUnit(features)++ def forward(self, *xs):+ """Forward pass.++ Returns:+ tensor: output+ """+ output = xs[0]++ if len(xs) == 2:+ output += self.resConfUnit1(xs[1])++ output = self.resConfUnit2(output)++ output = nn.functional.interpolate(+ output, scale_factor=2, mode="bilinear", align_corners=True+ )++ return output+++class ResidualConvUnit_custom(nn.Module):+ """Residual convolution module."""++ def __init__(self, features, activation, bn):+ """Init.++ Args:+ features (int): number of features+ """+ super().__init__()++ self.bn = bn++ self.groups = 1++ self.conv1 = nn.Conv2d(+ features,+ features,+ kernel_size=3,+ stride=1,+ padding=1,+ bias=not self.bn,+ groups=self.groups,+ )++ self.conv2 = nn.Conv2d(+ features,+ features,+ kernel_size=3,+ stride=1,+ padding=1,+ bias=not self.bn,+ groups=self.groups,+ )++ if self.bn == True:+ self.bn1 = nn.BatchNorm2d(features)+ self.bn2 = nn.BatchNorm2d(features)++ self.activation = activation++ self.skip_add = nn.quantized.FloatFunctional()++ def forward(self, x):+ """Forward pass.++ Args:+ x (tensor): input++ Returns:+ tensor: output+ """++ out = self.activation(x)+ out = self.conv1(out)+ if self.bn == True:+ out = self.bn1(out)++ out = self.activation(out)+ out = self.conv2(out)+ if self.bn == True:+ out = self.bn2(out)++ if self.groups > 1:+ out = self.conv_merge(out)++ return self.skip_add.add(out, x)++ # return out + x+++class FeatureFusionBlock_custom(nn.Module):+ """Feature fusion block."""++ def __init__(+ self,+ features,+ activation,+ deconv=False,+ bn=False,+ expand=False,+ align_corners=True,+ ):+ """Init.++ Args:+ features (int): number of features+ """+ super(FeatureFusionBlock_custom, self).__init__()++ self.deconv = deconv+ self.align_corners = align_corners++ self.groups = 1++ self.expand = expand+ out_features = features+ if self.expand == True:+ out_features = features // 2++ self.out_conv = nn.Conv2d(+ features,+ out_features,+ kernel_size=1,+ stride=1,+ padding=0,+ bias=True,+ groups=1,+ )++ self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn)+ self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn)++ self.skip_add = nn.quantized.FloatFunctional()++ def forward(self, *xs):+ """Forward pass.++ Returns:+ tensor: output+ """+ output = xs[0]++ if len(xs) == 2:+ res = self.resConfUnit1(xs[1])+ output = self.skip_add.add(output, res)+ # output += res++ output = self.resConfUnit2(output)++ output = nn.functional.interpolate(+ output, scale_factor=2, mode="bilinear", align_corners=self.align_corners+ )++ output = self.out_conv(output)++ return outputdiff --git a/DPT/dpt/midas_net.py b/DPT/dpt/midas_net.pynew file mode 100644index 0000000..34d6d7e--- /dev/null+++ b/DPT/dpt/midas_net.py@@ -0,0 +1,77 @@+"""MidashNet: Network for monocular depth estimation trained by mixing several datasets.+This file contains code that is adapted from+https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py+"""+import torch+import torch.nn as nn++from .base_model import BaseModel+from .blocks import FeatureFusionBlock, Interpolate, _make_encoder+++class MidasNet_large(BaseModel):+ """Network for monocular depth estimation."""++ def __init__(self, path=None, features=256, non_negative=True):+ """Init.++ Args:+ path (str, optional): Path to saved model. Defaults to None.+ features (int, optional): Number of features. Defaults to 256.+ backbone (str, optional): Backbone network for encoder. Defaults to resnet50+ """+ print("Loading weights: ", path)++ super(MidasNet_large, self).__init__()++ use_pretrained = False if path is None else True++ self.pretrained, self.scratch = _make_encoder(+ backbone="resnext101_wsl", features=features, use_pretrained=use_pretrained+ )++ self.scratch.refinenet4 = FeatureFusionBlock(features)+ self.scratch.refinenet3 = FeatureFusionBlock(features)+ self.scratch.refinenet2 = FeatureFusionBlock(features)+ self.scratch.refinenet1 = FeatureFusionBlock(features)++ self.scratch.output_conv = nn.Sequential(+ nn.Conv2d(features, 128, kernel_size=3, stride=1, padding=1),+ Interpolate(scale_factor=2, mode="bilinear"),+ nn.Conv2d(128, 32, kernel_size=3, stride=1, padding=1),+ nn.ReLU(True),+ nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),+ nn.ReLU(True) if non_negative else nn.Identity(),+ )++ if path:+ self.load(path)++ def forward(self, x):+ """Forward pass.++ Args:+ x (tensor): input data (image)++ Returns:+ tensor: depth+ """++ layer_1 = self.pretrained.layer1(x)+ layer_2 = self.pretrained.layer2(layer_1)+ layer_3 = self.pretrained.layer3(layer_2)+ layer_4 = self.pretrained.layer4(layer_3)++ layer_1_rn = self.scratch.layer1_rn(layer_1)+ layer_2_rn = self.scratch.layer2_rn(layer_2)+ layer_3_rn = self.scratch.layer3_rn(layer_3)+ layer_4_rn = self.scratch.layer4_rn(layer_4)++ path_4 = self.scratch.refinenet4(layer_4_rn)+ path_3 = self.scratch.refinenet3(path_4, layer_3_rn)+ path_2 = self.scratch.refinenet2(path_3, layer_2_rn)+ path_1 = self.scratch.refinenet1(path_2, layer_1_rn)++ out = self.scratch.output_conv(path_1)++ return torch.squeeze(out, dim=1)diff --git a/DPT/dpt/models.py b/DPT/dpt/models.pynew file mode 100644index 0000000..f0c142f--- /dev/null+++ b/DPT/dpt/models.py@@ -0,0 +1,153 @@+import torch+import torch.nn as nn+import torch.nn.functional as F++from .base_model import BaseModel+from .blocks import (+ FeatureFusionBlock,+ FeatureFusionBlock_custom,+ Interpolate,+ _make_encoder,+ forward_vit,+)+++def _make_fusion_block(features, use_bn):+ return FeatureFusionBlock_custom(+ features,+ nn.ReLU(False),+ deconv=False,+ bn=use_bn,+ expand=False,+ align_corners=True,+ )+++class DPT(BaseModel):+ def __init__(+ self,+ head,+ features=256,+ backbone="vitb_rn50_384",+ readout="project",+ channels_last=False,+ use_bn=False,+ enable_attention_hooks=False,+ ):++ super(DPT, self).__init__()++ self.channels_last = channels_last++ hooks = {+ "vitb_rn50_384": [0, 1, 8, 11],+ "vitb16_384": [2, 5, 8, 11],+ "vitl16_384": [5, 11, 17, 23],+ }++ # Instantiate backbone and reassemble blocks+ self.pretrained, self.scratch = _make_encoder(+ backbone,+ features,+ False, # Set to true of you want to train from scratch, uses ImageNet weights+ groups=1,+ expand=False,+ exportable=False,+ hooks=hooks[backbone],+ use_readout=readout,+ enable_attention_hooks=enable_attention_hooks,+ )++ self.scratch.refinenet1 = _make_fusion_block(features, use_bn)+ self.scratch.refinenet2 = _make_fusion_block(features, use_bn)+ self.scratch.refinenet3 = _make_fusion_block(features, use_bn)+ self.scratch.refinenet4 = _make_fusion_block(features, use_bn)++ self.scratch.output_conv = head++ def forward(self, x):+ if self.channels_last == True:+ x.contiguous(memory_format=torch.channels_last)++ layer_1, layer_2, layer_3, layer_4 = forward_vit(self.pretrained, x)++ layer_1_rn = self.scratch.layer1_rn(layer_1)+ layer_2_rn = self.scratch.layer2_rn(layer_2)+ layer_3_rn = self.scratch.layer3_rn(layer_3)+ layer_4_rn = self.scratch.layer4_rn(layer_4)++ path_4 = self.scratch.refinenet4(layer_4_rn)+ path_3 = self.scratch.refinenet3(path_4, layer_3_rn)+ path_2 = self.scratch.refinenet2(path_3, layer_2_rn)+ path_1 = self.scratch.refinenet1(path_2, layer_1_rn)++ out = self.scratch.output_conv(path_1)++ return out+++class DPTDepthModel(DPT):+ def __init__(+ self, path=None, non_negative=True, scale=1.0, shift=0.0, invert=False, **kwargs+ ):+ features = kwargs["features"] if "features" in kwargs else 256++ self.scale = scale+ self.shift = shift+ self.invert = invert++ head = nn.Sequential(+ nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1),+ Interpolate(scale_factor=2, mode="bilinear", align_corners=True),+ nn.Conv2d(features // 2, 32, kernel_size=3, stride=1, padding=1),+ nn.ReLU(True),+ nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),+ nn.ReLU(True) if non_negative else nn.Identity(),+ nn.Identity(),+ )++ super().__init__(head, **kwargs)++ if path is not None:+ self.load(path)++ def forward(self, x):+ inv_depth = super().forward(x).squeeze(dim=1)++ if self.invert:+ depth = self.scale * inv_depth + self.shift+ depth[depth < 1e-8] = 1e-8+ depth = 1.0 / depth+ return depth+ else:+ return inv_depth+++class DPTSegmentationModel(DPT):+ def __init__(self, num_classes, path=None, **kwargs):++ features = kwargs["features"] if "features" in kwargs else 256++ kwargs["use_bn"] = True++ head = nn.Sequential(+ nn.Conv2d(features, features, kernel_size=3, padding=1, bias=False),+ nn.BatchNorm2d(features),+ nn.ReLU(True),+ nn.Dropout(0.1, False),+ nn.Conv2d(features, num_classes, kernel_size=1),+ Interpolate(scale_factor=2, mode="bilinear", align_corners=True),+ )++ super().__init__(head, **kwargs)++ self.auxlayer = nn.Sequential(+ nn.Conv2d(features, features, kernel_size=3, padding=1, bias=False),+ nn.BatchNorm2d(features),+ nn.ReLU(True),+ nn.Dropout(0.1, False),+ nn.Conv2d(features, num_classes, kernel_size=1),+ )++ if path is not None:+ self.load(path)diff --git a/DPT/dpt/transforms.py b/DPT/dpt/transforms.pynew file mode 100644index 0000000..399adbc--- /dev/null+++ b/DPT/dpt/transforms.py@@ -0,0 +1,231 @@+import numpy as np+import cv2+import math+++def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA):+ """Rezise the sample to ensure the given size. Keeps aspect ratio.++ Args:+ sample (dict): sample+ size (tuple): image size++ Returns:+ tuple: new size+ """+ shape = list(sample["disparity"].shape)++ if shape[0] >= size[0] and shape[1] >= size[1]:+ return sample++ scale = [0, 0]+ scale[0] = size[0] / shape[0]+ scale[1] = size[1] / shape[1]++ scale = max(scale)++ shape[0] = math.ceil(scale * shape[0])+ shape[1] = math.ceil(scale * shape[1])++ # resize+ sample["image"] = cv2.resize(+ sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method+ )++ sample["disparity"] = cv2.resize(+ sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST+ )+ sample["mask"] = cv2.resize(+ sample["mask"].astype(np.float32),+ tuple(shape[::-1]),+ interpolation=cv2.INTER_NEAREST,+ )+ sample["mask"] = sample["mask"].astype(bool)++ return tuple(shape)+++class Resize(object):+ """Resize sample to given size (width, height)."""++ def __init__(+ self,+ width,+ height,+ resize_target=True,+ keep_aspect_ratio=False,+ ensure_multiple_of=1,+ resize_method="lower_bound",+ image_interpolation_method=cv2.INTER_AREA,+ ):+ """Init.++ Args:+ width (int): desired output width+ height (int): desired output height+ resize_target (bool, optional):+ True: Resize the full sample (image, mask, target).+ False: Resize image only.+ Defaults to True.+ keep_aspect_ratio (bool, optional):+ True: Keep the aspect ratio of the input sample.+ Output sample might not have the given width and height, and+ resize behaviour depends on the parameter 'resize_method'.+ Defaults to False.+ ensure_multiple_of (int, optional):+ Output width and height is constrained to be multiple of this parameter.+ Defaults to 1.+ resize_method (str, optional):+ "lower_bound": Output will be at least as large as the given size.+ "upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)+ "minimal": Scale as least as possible. (Output size might be smaller than given size.)+ Defaults to "lower_bound".+ """+ self.__width = width+ self.__height = height++ self.__resize_target = resize_target+ self.__keep_aspect_ratio = keep_aspect_ratio+ self.__multiple_of = ensure_multiple_of+ self.__resize_method = resize_method+ self.__image_interpolation_method = image_interpolation_method++ def constrain_to_multiple_of(self, x, min_val=0, max_val=None):+ y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)++ if max_val is not None and y > max_val:+ y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)++ if y < min_val:+ y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)++ return y++ def get_size(self, width, height):+ # determine new height and width+ scale_height = self.__height / height+ scale_width = self.__width / width++ if self.__keep_aspect_ratio:+ if self.__resize_method == "lower_bound":+ # scale such that output size is lower bound+ if scale_width > scale_height:+ # fit width+ scale_height = scale_width+ else:+ # fit height+ scale_width = scale_height+ elif self.__resize_method == "upper_bound":+ # scale such that output size is upper bound+ if scale_width < scale_height:+ # fit width+ scale_height = scale_width+ else:+ # fit height+ scale_width = scale_height+ elif self.__resize_method == "minimal":+ # scale as least as possbile+ if abs(1 - scale_width) < abs(1 - scale_height):+ # fit width+ scale_height = scale_width+ else:+ # fit height+ scale_width = scale_height+ else:+ raise ValueError(+ f"resize_method {self.__resize_method} not implemented"+ )++ if self.__resize_method == "lower_bound":+ new_height = self.constrain_to_multiple_of(+ scale_height * height, min_val=self.__height+ )+ new_width = self.constrain_to_multiple_of(+ scale_width * width, min_val=self.__width+ )+ elif self.__resize_method == "upper_bound":+ new_height = self.constrain_to_multiple_of(+ scale_height * height, max_val=self.__height+ )+ new_width = self.constrain_to_multiple_of(+ scale_width * width, max_val=self.__width+ )+ elif self.__resize_method == "minimal":+ new_height = self.constrain_to_multiple_of(scale_height * height)+ new_width = self.constrain_to_multiple_of(scale_width * width)+ else:+ raise ValueError(f"resize_method {self.__resize_method} not implemented")++ return (new_width, new_height)++ def __call__(self, sample):+ width, height = self.get_size(+ sample["image"].shape[1], sample["image"].shape[0]+ )++ # resize sample+ sample["image"] = cv2.resize(+ sample["image"],+ (width, height),+ interpolation=self.__image_interpolation_method,+ )++ if self.__resize_target:+ if "disparity" in sample:+ sample["disparity"] = cv2.resize(+ sample["disparity"],+ (width, height),+ interpolation=cv2.INTER_NEAREST,+ )++ if "depth" in sample:+ sample["depth"] = cv2.resize(+ sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST+ )++ sample["mask"] = cv2.resize(+ sample["mask"].astype(np.float32),+ (width, height),+ interpolation=cv2.INTER_NEAREST,+ )+ sample["mask"] = sample["mask"].astype(bool)++ return sample+++class NormalizeImage(object):+ """Normlize image by given mean and std."""++ def __init__(self, mean, std):+ self.__mean = mean+ self.__std = std++ def __call__(self, sample):+ sample["image"] = (sample["image"] - self.__mean) / self.__std++ return sample+++class PrepareForNet(object):+ """Prepare sample for usage as network input."""++ def __init__(self):+ pass++ def __call__(self, sample):+ image = np.transpose(sample["image"], (2, 0, 1))+ sample["image"] = np.ascontiguousarray(image).astype(np.float32)++ if "mask" in sample:+ sample["mask"] = sample["mask"].astype(np.float32)+ sample["mask"] = np.ascontiguousarray(sample["mask"])++ if "disparity" in sample:+ disparity = sample["disparity"].astype(np.float32)+ sample["disparity"] = np.ascontiguousarray(disparity)++ if "depth" in sample:+ depth = sample["depth"].astype(np.float32)+ sample["depth"] = np.ascontiguousarray(depth)++ return samplediff --git a/DPT/dpt/vit.py b/DPT/dpt/vit.pynew file mode 100644index 0000000..9a60d56--- /dev/null+++ b/DPT/dpt/vit.py@@ -0,0 +1,576 @@+import torch+import torch.nn as nn+import timm+import types+import math+import torch.nn.functional as F+++activations = {}+++def get_activation(name):+ def hook(model, input, output):+ activations[name] = output++ return hook+++attention = {}+++def get_attention(name):+ def hook(module, input, output):+ x = input[0]+ B, N, C = x.shape+ qkv = (+ module.qkv(x)+ .reshape(B, N, 3, module.num_heads, C // module.num_heads)+ .permute(2, 0, 3, 1, 4)+ )+ q, k, v = (+ qkv[0],+ qkv[1],+ qkv[2],+ ) # make torchscript happy (cannot use tensor as tuple)++ attn = (q @ k.transpose(-2, -1)) * module.scale++ attn = attn.softmax(dim=-1) # [:,:,1,1:]+ attention[name] = attn++ return hook+++def get_mean_attention_map(attn, token, shape):+ attn = attn[:, :, token, 1:]+ attn = attn.unflatten(2, torch.Size([shape[2] // 16, shape[3] // 16])).float()+ attn = torch.nn.functional.interpolate(+ attn, size=shape[2:], mode="bicubic", align_corners=False+ ).squeeze(0)++ all_attn = torch.mean(attn, 0)++ return all_attn+++class Slice(nn.Module):+ def __init__(self, start_index=1):+ super(Slice, self).__init__()+ self.start_index = start_index++ def forward(self, x):+ return x[:, self.start_index :]+++class AddReadout(nn.Module):+ def __init__(self, start_index=1):+ super(AddReadout, self).__init__()+ self.start_index = start_index++ def forward(self, x):+ if self.start_index == 2:+ readout = (x[:, 0] + x[:, 1]) / 2+ else:+ readout = x[:, 0]+ return x[:, self.start_index :] + readout.unsqueeze(1)+++class ProjectReadout(nn.Module):+ def __init__(self, in_features, start_index=1):+ super(ProjectReadout, self).__init__()+ self.start_index = start_index++ self.project = nn.Sequential(nn.Linear(2 * in_features, in_features), nn.GELU())++ def forward(self, x):+ readout = x[:, 0].unsqueeze(1).expand_as(x[:, self.start_index :])+ features = torch.cat((x[:, self.start_index :], readout), -1)++ return self.project(features)+++class Transpose(nn.Module):+ def __init__(self, dim0, dim1):+ super(Transpose, self).__init__()+ self.dim0 = dim0+ self.dim1 = dim1++ def forward(self, x):+ x = x.transpose(self.dim0, self.dim1)+ return x+++def forward_vit(pretrained, x):+ b, c, h, w = x.shape++ glob = pretrained.model.forward_flex(x)++ layer_1 = pretrained.activations["1"]+ layer_2 = pretrained.activations["2"]+ layer_3 = pretrained.activations["3"]+ layer_4 = pretrained.activations["4"]++ layer_1 = pretrained.act_postprocess1[0:2](layer_1)+ layer_2 = pretrained.act_postprocess2[0:2](layer_2)+ layer_3 = pretrained.act_postprocess3[0:2](layer_3)+ layer_4 = pretrained.act_postprocess4[0:2](layer_4)++ unflatten = nn.Sequential(+ nn.Unflatten(+ 2,+ torch.Size(+ [+ h // pretrained.model.patch_size[1],+ w // pretrained.model.patch_size[0],+ ]+ ),+ )+ )++ if layer_1.ndim == 3:+ layer_1 = unflatten(layer_1)+ if layer_2.ndim == 3:+ layer_2 = unflatten(layer_2)+ if layer_3.ndim == 3:+ layer_3 = unflatten(layer_3)+ if layer_4.ndim == 3:+ layer_4 = unflatten(layer_4)++ layer_1 = pretrained.act_postprocess1[3 : len(pretrained.act_postprocess1)](layer_1)+ layer_2 = pretrained.act_postprocess2[3 : len(pretrained.act_postprocess2)](layer_2)+ layer_3 = pretrained.act_postprocess3[3 : len(pretrained.act_postprocess3)](layer_3)+ layer_4 = pretrained.act_postprocess4[3 : len(pretrained.act_postprocess4)](layer_4)++ return layer_1, layer_2, layer_3, layer_4+++def _resize_pos_embed(self, posemb, gs_h, gs_w):+ posemb_tok, posemb_grid = (+ posemb[:, : self.start_index],+ posemb[0, self.start_index :],+ )++ gs_old = int(math.sqrt(len(posemb_grid)))++ posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2)+ posemb_grid = F.interpolate(posemb_grid, size=(gs_h, gs_w), mode="bilinear")+ posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_h * gs_w, -1)++ posemb = torch.cat([posemb_tok, posemb_grid], dim=1)++ return posemb+++def forward_flex(self, x):+ b, c, h, w = x.shape++ pos_embed = self._resize_pos_embed(+ self.pos_embed, h // self.patch_size[1], w // self.patch_size[0]+ )++ B = x.shape[0]++ if hasattr(self.patch_embed, "backbone"):+ x = self.patch_embed.backbone(x)+ if isinstance(x, (list, tuple)):+ x = x[-1] # last feature if backbone outputs list/tuple of features++ x = self.patch_embed.proj(x).flatten(2).transpose(1, 2)++ if getattr(self, "dist_token", None) is not None:+ cls_tokens = self.cls_token.expand(+ B, -1, -1+ ) # stole cls_tokens impl from Phil Wang, thanks+ dist_token = self.dist_token.expand(B, -1, -1)+ x = torch.cat((cls_tokens, dist_token, x), dim=1)+ else:+ cls_tokens = self.cls_token.expand(+ B, -1, -1+ ) # stole cls_tokens impl from Phil Wang, thanks+ x = torch.cat((cls_tokens, x), dim=1)++ x = x + pos_embed+ x = self.pos_drop(x)++ for blk in self.blocks:+ x = blk(x)++ x = self.norm(x)++ return x+++def get_readout_oper(vit_features, features, use_readout, start_index=1):+ if use_readout == "ignore":+ readout_oper = [Slice(start_index)] * len(features)+ elif use_readout == "add":+ readout_oper = [AddReadout(start_index)] * len(features)+ elif use_readout == "project":+ readout_oper = [+ ProjectReadout(vit_features, start_index) for out_feat in features+ ]+ else:+ assert (+ False+ ), "wrong operation for readout token, use_readout can be 'ignore', 'add', or 'project'"++ return readout_oper+++def _make_vit_b16_backbone(+ model,+ features=[96, 192, 384, 768],+ size=[384, 384],+ hooks=[2, 5, 8, 11],+ vit_features=768,+ use_readout="ignore",+ start_index=1,+ enable_attention_hooks=False,+):+ pretrained = nn.Module()++ pretrained.model = model+ pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))+ pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))+ pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))+ pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4"))++ pretrained.activations = activations++ if enable_attention_hooks:+ pretrained.model.blocks[hooks[0]].attn.register_forward_hook(+ get_attention("attn_1")+ )+ pretrained.model.blocks[hooks[1]].attn.register_forward_hook(+ get_attention("attn_2")+ )+ pretrained.model.blocks[hooks[2]].attn.register_forward_hook(+ get_attention("attn_3")+ )+ pretrained.model.blocks[hooks[3]].attn.register_forward_hook(+ get_attention("attn_4")+ )+ pretrained.attention = attention++ readout_oper = get_readout_oper(vit_features, features, use_readout, start_index)++ # 32, 48, 136, 384+ pretrained.act_postprocess1 = nn.Sequential(+ readout_oper[0],+ Transpose(1, 2),+ nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),+ nn.Conv2d(+ in_channels=vit_features,+ out_channels=features[0],+ kernel_size=1,+ stride=1,+ padding=0,+ ),+ nn.ConvTranspose2d(+ in_channels=features[0],+ out_channels=features[0],+ kernel_size=4,+ stride=4,+ padding=0,+ bias=True,+ dilation=1,+ groups=1,+ ),+ )++ pretrained.act_postprocess2 = nn.Sequential(+ readout_oper[1],+ Transpose(1, 2),+ nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),+ nn.Conv2d(+ in_channels=vit_features,+ out_channels=features[1],+ kernel_size=1,+ stride=1,+ padding=0,+ ),+ nn.ConvTranspose2d(+ in_channels=features[1],+ out_channels=features[1],+ kernel_size=2,+ stride=2,+ padding=0,+ bias=True,+ dilation=1,+ groups=1,+ ),+ )++ pretrained.act_postprocess3 = nn.Sequential(+ readout_oper[2],+ Transpose(1, 2),+ nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),+ nn.Conv2d(+ in_channels=vit_features,+ out_channels=features[2],+ kernel_size=1,+ stride=1,+ padding=0,+ ),+ )++ pretrained.act_postprocess4 = nn.Sequential(+ readout_oper[3],+ Transpose(1, 2),+ nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),+ nn.Conv2d(+ in_channels=vit_features,+ out_channels=features[3],+ kernel_size=1,+ stride=1,+ padding=0,+ ),+ nn.Conv2d(+ in_channels=features[3],+ out_channels=features[3],+ kernel_size=3,+ stride=2,+ padding=1,+ ),+ )++ pretrained.model.start_index = start_index+ pretrained.model.patch_size = [16, 16]++ # We inject this function into the VisionTransformer instances so that+ # we can use it with interpolated position embeddings without modifying the library source.+ pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)+ pretrained.model._resize_pos_embed = types.MethodType(+ _resize_pos_embed, pretrained.model+ )++ return pretrained+++def _make_vit_b_rn50_backbone(+ model,+ features=[256, 512, 768, 768],+ size=[384, 384],+ hooks=[0, 1, 8, 11],+ vit_features=768,+ use_vit_only=False,+ use_readout="ignore",+ start_index=1,+ enable_attention_hooks=False,+):+ pretrained = nn.Module()++ pretrained.model = model++ if use_vit_only == True:+ pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))+ pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))+ else:+ pretrained.model.patch_embed.backbone.stages[0].register_forward_hook(+ get_activation("1")+ )+ pretrained.model.patch_embed.backbone.stages[1].register_forward_hook(+ get_activation("2")+ )++ pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))+ pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4"))++ if enable_attention_hooks:+ pretrained.model.blocks[2].attn.register_forward_hook(get_attention("attn_1"))+ pretrained.model.blocks[5].attn.register_forward_hook(get_attention("attn_2"))+ pretrained.model.blocks[8].attn.register_forward_hook(get_attention("attn_3"))+ pretrained.model.blocks[11].attn.register_forward_hook(get_attention("attn_4"))+ pretrained.attention = attention++ pretrained.activations = activations++ readout_oper = get_readout_oper(vit_features, features, use_readout, start_index)++ if use_vit_only == True:+ pretrained.act_postprocess1 = nn.Sequential(+ readout_oper[0],+ Transpose(1, 2),+ nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),+ nn.Conv2d(+ in_channels=vit_features,+ out_channels=features[0],+ kernel_size=1,+ stride=1,+ padding=0,+ ),+ nn.ConvTranspose2d(+ in_channels=features[0],+ out_channels=features[0],+ kernel_size=4,+ stride=4,+ padding=0,+ bias=True,+ dilation=1,+ groups=1,+ ),+ )++ pretrained.act_postprocess2 = nn.Sequential(+ readout_oper[1],+ Transpose(1, 2),+ nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),+ nn.Conv2d(+ in_channels=vit_features,+ out_channels=features[1],+ kernel_size=1,+ stride=1,+ padding=0,+ ),+ nn.ConvTranspose2d(+ in_channels=features[1],+ out_channels=features[1],+ kernel_size=2,+ stride=2,+ padding=0,+ bias=True,+ dilation=1,+ groups=1,+ ),+ )+ else:+ pretrained.act_postprocess1 = nn.Sequential(+ nn.Identity(), nn.Identity(), nn.Identity()+ )+ pretrained.act_postprocess2 = nn.Sequential(+ nn.Identity(), nn.Identity(), nn.Identity()+ )++ pretrained.act_postprocess3 = nn.Sequential(+ readout_oper[2],+ Transpose(1, 2),+ nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),+ nn.Conv2d(+ in_channels=vit_features,+ out_channels=features[2],+ kernel_size=1,+ stride=1,+ padding=0,+ ),+ )++ pretrained.act_postprocess4 = nn.Sequential(+ readout_oper[3],+ Transpose(1, 2),+ nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),+ nn.Conv2d(+ in_channels=vit_features,+ out_channels=features[3],+ kernel_size=1,+ stride=1,+ padding=0,+ ),+ nn.Conv2d(+ in_channels=features[3],+ out_channels=features[3],+ kernel_size=3,+ stride=2,+ padding=1,+ ),+ )++ pretrained.model.start_index = start_index+ pretrained.model.patch_size = [16, 16]++ # We inject this function into the VisionTransformer instances so that+ # we can use it with interpolated position embeddings without modifying the library source.+ pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)++ # We inject this function into the VisionTransformer instances so that+ # we can use it with interpolated position embeddings without modifying the library source.+ pretrained.model._resize_pos_embed = types.MethodType(+ _resize_pos_embed, pretrained.model+ )++ return pretrained+++def _make_pretrained_vitb_rn50_384(+ pretrained,+ use_readout="ignore",+ hooks=None,+ use_vit_only=False,+ enable_attention_hooks=False,+):+ model = timm.create_model("vit_base_resnet50_384", pretrained=pretrained)++ hooks = [0, 1, 8, 11] if hooks == None else hooks+ return _make_vit_b_rn50_backbone(+ model,+ features=[256, 512, 768, 768],+ size=[384, 384],+ hooks=hooks,+ use_vit_only=use_vit_only,+ use_readout=use_readout,+ enable_attention_hooks=enable_attention_hooks,+ )+++def _make_pretrained_vitl16_384(+ pretrained, use_readout="ignore", hooks=None, enable_attention_hooks=False+):+ model = timm.create_model("vit_large_patch16_384", pretrained=pretrained)++ hooks = [5, 11, 17, 23] if hooks == None else hooks+ return _make_vit_b16_backbone(+ model,+ features=[256, 512, 1024, 1024],+ hooks=hooks,+ vit_features=1024,+ use_readout=use_readout,+ enable_attention_hooks=enable_attention_hooks,+ )+++def _make_pretrained_vitb16_384(+ pretrained, use_readout="ignore", hooks=None, enable_attention_hooks=False+):+ model = timm.create_model("vit_base_patch16_384", pretrained=pretrained)++ hooks = [2, 5, 8, 11] if hooks == None else hooks+ return _make_vit_b16_backbone(+ model,+ features=[96, 192, 384, 768],+ hooks=hooks,+ use_readout=use_readout,+ enable_attention_hooks=enable_attention_hooks,+ )+++def _make_pretrained_deitb16_384(+ pretrained, use_readout="ignore", hooks=None, enable_attention_hooks=False+):+ model = timm.create_model("vit_deit_base_patch16_384", pretrained=pretrained)++ hooks = [2, 5, 8, 11] if hooks == None else hooks+ return _make_vit_b16_backbone(+ model,+ features=[96, 192, 384, 768],+ hooks=hooks,+ use_readout=use_readout,+ enable_attention_hooks=enable_attention_hooks,+ )+++def _make_pretrained_deitb16_distil_384(+ pretrained, use_readout="ignore", hooks=None, enable_attention_hooks=False+):+ model = timm.create_model(+ "vit_deit_base_distilled_patch16_384", pretrained=pretrained+ )++ hooks = [2, 5, 8, 11] if hooks == None else hooks+ return _make_vit_b16_backbone(+ model,+ features=[96, 192, 384, 768],+ hooks=hooks,+ use_readout=use_readout,+ start_index=2,+ enable_attention_hooks=enable_attention_hooks,+ )diff --git a/DPT/input/.placeholder b/DPT/input/.placeholdernew file mode 100644index 0000000..e69de29diff --git a/DPT/output_monodepth/.placeholder b/DPT/output_monodepth/.placeholdernew file mode 100644index 0000000..e69de29diff --git a/DPT/output_semseg/.placeholder b/DPT/output_semseg/.placeholdernew file mode 100644index 0000000..e69de29diff --git a/DPT/py3d_tools.py b/DPT/py3d_tools.pynew file mode 100644index 0000000..8016320--- /dev/null+++ b/DPT/py3d_tools.py@@ -0,0 +1,1799 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the BSD-style license found in the+# LICENSE file in the root directory of this source tree.++import sys+import math+import warnings+from typing import List, Optional, Sequence, Tuple, Union, Any++import numpy as np+import torch+import torch.nn.functional as F++import copy+import inspect+import torch.nn as nn++Device = Union[str, torch.device]++# Default values for rotation and translation matrices.+_R = torch.eye(3)[None] # (1, 3, 3)+_T = torch.zeros(1, 3) # (1, 3)+++# Provide get_origin and get_args even in Python 3.7.++if sys.version_info >= (3, 8, 0):+ from typing import get_args, get_origin+elif sys.version_info >= (3, 6, 0):++ def get_origin(cls): # pragma: no cover+ return getattr(cls, "__origin__", None)++ def get_args(cls): # pragma: no cover+ return getattr(cls, "__args__", None)+++else:+ raise ImportError("This module requires Python 3.7+")++################################################################+## ██████╗██╗ █████╗ ███████╗███████╗███████╗███████╗ ##+## ██╔════╝██║ ██╔══██╗██╔════╝██╔════╝██╔════╝██╔════╝ ##+## ██║ ██║ ███████║███████╗███████╗█████╗ ███████╗ ##+## ██║ ██║ ██╔══██║╚════██║╚════██║██╔══╝ ╚════██║ ##+## ╚██████╗███████╗██║ ██║███████║███████║███████╗███████║ ##+## ╚═════╝╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝╚══════╝ ##+################################################################++class Transform3d:+ """+ A Transform3d object encapsulates a batch of N 3D transformations, and knows+ how to transform points and normal vectors. Suppose that t is a Transform3d;+ then we can do the following:++ .. code-block:: python++ N = len(t)+ points = torch.randn(N, P, 3)+ normals = torch.randn(N, P, 3)+ points_transformed = t.transform_points(points) # => (N, P, 3)+ normals_transformed = t.transform_normals(normals) # => (N, P, 3)+++ BROADCASTING+ Transform3d objects supports broadcasting. Suppose that t1 and tN are+ Transform3d objects with len(t1) == 1 and len(tN) == N respectively. Then we+ can broadcast transforms like this:++ .. code-block:: python++ t1.transform_points(torch.randn(P, 3)) # => (P, 3)+ t1.transform_points(torch.randn(1, P, 3)) # => (1, P, 3)+ t1.transform_points(torch.randn(M, P, 3)) # => (M, P, 3)+ tN.transform_points(torch.randn(P, 3)) # => (N, P, 3)+ tN.transform_points(torch.randn(1, P, 3)) # => (N, P, 3)+++ COMBINING TRANSFORMS+ Transform3d objects can be combined in two ways: composing and stacking.+ Composing is function composition. Given Transform3d objects t1, t2, t3,+ the following all compute the same thing:++ .. code-block:: python++ y1 = t3.transform_points(t2.transform_points(t1.transform_points(x)))+ y2 = t1.compose(t2).compose(t3).transform_points(x)+ y3 = t1.compose(t2, t3).transform_points(x)+++ Composing transforms should broadcast.++ .. code-block:: python++ if len(t1) == 1 and len(t2) == N, then len(t1.compose(t2)) == N.++ We can also stack a sequence of Transform3d objects, which represents+ composition along the batch dimension; then the following should compute the+ same thing.++ .. code-block:: python++ N, M = len(tN), len(tM)+ xN = torch.randn(N, P, 3)+ xM = torch.randn(M, P, 3)+ y1 = torch.cat([tN.transform_points(xN), tM.transform_points(xM)], dim=0)+ y2 = tN.stack(tM).transform_points(torch.cat([xN, xM], dim=0))++ BUILDING TRANSFORMS+ We provide convenience methods for easily building Transform3d objects+ as compositions of basic transforms.++ .. code-block:: python++ # Scale by 0.5, then translate by (1, 2, 3)+ t1 = Transform3d().scale(0.5).translate(1, 2, 3)++ # Scale each axis by a different amount, then translate, then scale+ t2 = Transform3d().scale(1, 3, 3).translate(2, 3, 1).scale(2.0)++ t3 = t1.compose(t2)+ tN = t1.stack(t3, t3)+++ BACKPROP THROUGH TRANSFORMS+ When building transforms, we can also parameterize them by Torch tensors;+ in this case we can backprop through the construction and application of+ Transform objects, so they could be learned via gradient descent or+ predicted by a neural network.++ .. code-block:: python++ s1_params = torch.randn(N, requires_grad=True)+ t_params = torch.randn(N, 3, requires_grad=True)+ s2_params = torch.randn(N, 3, requires_grad=True)++ t = Transform3d().scale(s1_params).translate(t_params).scale(s2_params)+ x = torch.randn(N, 3)+ y = t.transform_points(x)+ loss = compute_loss(y)+ loss.backward()++ with torch.no_grad():+ s1_params -= lr * s1_params.grad+ t_params -= lr * t_params.grad+ s2_params -= lr * s2_params.grad++ CONVENTIONS+ We adopt a right-hand coordinate system, meaning that rotation about an axis+ with a positive angle results in a counter clockwise rotation.++ This class assumes that transformations are applied on inputs which+ are row vectors. The internal representation of the Nx4x4 transformation+ matrix is of the form:++ .. code-block:: python++ M = [+ [Rxx, Ryx, Rzx, 0],+ [Rxy, Ryy, Rzy, 0],+ [Rxz, Ryz, Rzz, 0],+ [Tx, Ty, Tz, 1],+ ]++ To apply the transformation to points which are row vectors, the M matrix+ can be pre multiplied by the points:++ .. code-block:: python++ points = [[0, 1, 2]] # (1 x 3) xyz coordinates of a point+ transformed_points = points * M++ """++ def __init__(+ self,+ dtype: torch.dtype = torch.float32,+ device: Device = "cpu",+ matrix: Optional[torch.Tensor] = None,+ ) -> None:+ """+ Args:+ dtype: The data type of the transformation matrix.+ to be used if `matrix = None`.+ device: The device for storing the implemented transformation.+ If `matrix != None`, uses the device of input `matrix`.+ matrix: A tensor of shape (4, 4) or of shape (minibatch, 4, 4)+ representing the 4x4 3D transformation matrix.+ If `None`, initializes with identity using+ the specified `device` and `dtype`.+ """++ if matrix is None:+ self._matrix = torch.eye(4, dtype=dtype, device=device).view(1, 4, 4)+ else:+ if matrix.ndim not in (2, 3):+ raise ValueError('"matrix" has to be a 2- or a 3-dimensional tensor.')+ if matrix.shape[-2] != 4 or matrix.shape[-1] != 4:+ raise ValueError(+ '"matrix" has to be a tensor of shape (minibatch, 4, 4)'+ )+ # set dtype and device from matrix+ dtype = matrix.dtype+ device = matrix.device+ self._matrix = matrix.view(-1, 4, 4)++ self._transforms = [] # store transforms to compose+ self._lu = None+ self.device = make_device(device)+ self.dtype = dtype++ def __len__(self) -> int:+ return self.get_matrix().shape[0]++ def __getitem__(+ self, index: Union[int, List[int], slice, torch.Tensor]+ ) -> "Transform3d":+ """+ Args:+ index: Specifying the index of the transform to retrieve.+ Can be an int, slice, list of ints, boolean, long tensor.+ Supports negative indices.++ Returns:+ Transform3d object with selected transforms. The tensors are not cloned.+ """+ if isinstance(index, int):+ index = [index]+ return self.__class__(matrix=self.get_matrix()[index])++ def compose(self, *others: "Transform3d") -> "Transform3d":+ """+ Return a new Transform3d representing the composition of self with the+ given other transforms, which will be stored as an internal list.++ Args:+ *others: Any number of Transform3d objects++ Returns:+ A new Transform3d with the stored transforms+ """+ out = Transform3d(dtype=self.dtype, device=self.device)+ out._matrix = self._matrix.clone()+ for other in others:+ if not isinstance(other, Transform3d):+ msg = "Only possible to compose Transform3d objects; got %s"+ raise ValueError(msg % type(other))+ out._transforms = self._transforms + list(others)+ return out++ def get_matrix(self) -> torch.Tensor:+ """+ Return a matrix which is the result of composing this transform+ with others stored in self.transforms. Where necessary transforms+ are broadcast against each other.+ For example, if self.transforms contains transforms t1, t2, and t3, and+ given a set of points x, the following should be true:++ .. code-block:: python++ y1 = t1.compose(t2, t3).transform(x)+ y2 = t3.transform(t2.transform(t1.transform(x)))+ y1.get_matrix() == y2.get_matrix()++ Returns:+ A transformation matrix representing the composed inputs.+ """+ composed_matrix = self._matrix.clone()+ if len(self._transforms) > 0:+ for other in self._transforms:+ other_matrix = other.get_matrix()+ composed_matrix = _broadcast_bmm(composed_matrix, other_matrix)+ return composed_matrix++ def _get_matrix_inverse(self) -> torch.Tensor:+ """+ Return the inverse of self._matrix.+ """+ return torch.inverse(self._matrix)++ def inverse(self, invert_composed: bool = False) -> "Transform3d":+ """+ Returns a new Transform3d object that represents an inverse of the+ current transformation.++ Args:+ invert_composed:+ - True: First compose the list of stored transformations+ and then apply inverse to the result. This is+ potentially slower for classes of transformations+ with inverses that can be computed efficiently+ (e.g. rotations and translations).+ - False: Invert the individual stored transformations+ independently without composing them.++ Returns:+ A new Transform3d object containing the inverse of the original+ transformation.+ """++ tinv = Transform3d(dtype=self.dtype, device=self.device)++ if invert_composed:+ # first compose then invert+ tinv._matrix = torch.inverse(self.get_matrix())+ else:+ # self._get_matrix_inverse() implements efficient inverse+ # of self._matrix+ i_matrix = self._get_matrix_inverse()++ # 2 cases:+ if len(self._transforms) > 0:+ # a) Either we have a non-empty list of transforms:+ # Here we take self._matrix and append its inverse at the+ # end of the reverted _transforms list. After composing+ # the transformations with get_matrix(), this correctly+ # right-multiplies by the inverse of self._matrix+ # at the end of the composition.+ tinv._transforms = [t.inverse() for t in reversed(self._transforms)]+ last = Transform3d(dtype=self.dtype, device=self.device)+ last._matrix = i_matrix+ tinv._transforms.append(last)+ else:+ # b) Or there are no stored transformations+ # we just set inverted matrix+ tinv._matrix = i_matrix++ return tinv++ def stack(self, *others: "Transform3d") -> "Transform3d":+ """+ Return a new batched Transform3d representing the batch elements from+ self and all the given other transforms all batched together.++ Args:+ *others: Any number of Transform3d objects++ Returns:+ A new Transform3d.+ """+ transforms = [self] + list(others)+ matrix = torch.cat([t.get_matrix() for t in transforms], dim=0)+ out = Transform3d(dtype=self.dtype, device=self.device)+ out._matrix = matrix+ return out++ def transform_points(self, points, eps: Optional[float] = None) -> torch.Tensor:+ """+ Use this transform to transform a set of 3D points. Assumes row major+ ordering of the input points.++ Args:+ points: Tensor of shape (P, 3) or (N, P, 3)+ eps: If eps!=None, the argument is used to clamp the+ last coordinate before performing the final division.+ The clamping corresponds to:+ last_coord := (last_coord.sign() + (last_coord==0)) *+ torch.clamp(last_coord.abs(), eps),+ i.e. the last coordinates that are exactly 0 will+ be clamped to +eps.++ Returns:+ points_out: points of shape (N, P, 3) or (P, 3) depending+ on the dimensions of the transform+ """+ points_batch = points.clone()+ if points_batch.dim() == 2:+ points_batch = points_batch[None] # (P, 3) -> (1, P, 3)+ if points_batch.dim() != 3:+ msg = "Expected points to have dim = 2 or dim = 3: got shape %r"+ raise ValueError(msg % repr(points.shape))++ N, P, _3 = points_batch.shape+ ones = torch.ones(N, P, 1, dtype=points.dtype, device=points.device)+ points_batch = torch.cat([points_batch, ones], dim=2)++ composed_matrix = self.get_matrix()+ points_out = _broadcast_bmm(points_batch, composed_matrix)+ denom = points_out[..., 3:] # denominator+ if eps is not None:+ denom_sign = denom.sign() + (denom == 0.0).type_as(denom)+ denom = denom_sign * torch.clamp(denom.abs(), eps)+ points_out = points_out[..., :3] / denom++ # When transform is (1, 4, 4) and points is (P, 3) return+ # points_out of shape (P, 3)+ if points_out.shape[0] == 1 and points.dim() == 2:+ points_out = points_out.reshape(points.shape)++ return points_out++ def transform_normals(self, normals) -> torch.Tensor:+ """+ Use this transform to transform a set of normal vectors.++ Args:+ normals: Tensor of shape (P, 3) or (N, P, 3)++ Returns:+ normals_out: Tensor of shape (P, 3) or (N, P, 3) depending+ on the dimensions of the transform+ """+ if normals.dim() not in [2, 3]:+ msg = "Expected normals to have dim = 2 or dim = 3: got shape %r"+ raise ValueError(msg % (normals.shape,))+ composed_matrix = self.get_matrix()++ # TODO: inverse is bad! Solve a linear system instead+ mat = composed_matrix[:, :3, :3]+ normals_out = _broadcast_bmm(normals, mat.transpose(1, 2).inverse())++ # This doesn't pass unit tests. TODO investigate further+ # if self._lu is None:+ # self._lu = self._matrix[:, :3, :3].transpose(1, 2).lu()+ # normals_out = normals.lu_solve(*self._lu)++ # When transform is (1, 4, 4) and normals is (P, 3) return+ # normals_out of shape (P, 3)+ if normals_out.shape[0] == 1 and normals.dim() == 2:+ normals_out = normals_out.reshape(normals.shape)++ return normals_out++ def translate(self, *args, **kwargs) -> "Transform3d":+ return self.compose(+ Translate(device=self.device, dtype=self.dtype, *args, **kwargs)+ )++ def scale(self, *args, **kwargs) -> "Transform3d":+ return self.compose(+ Scale(device=self.device, dtype=self.dtype, *args, **kwargs)+ )++ def rotate(self, *args, **kwargs) -> "Transform3d":+ return self.compose(+ Rotate(device=self.device, dtype=self.dtype, *args, **kwargs)+ )++ def rotate_axis_angle(self, *args, **kwargs) -> "Transform3d":+ return self.compose(+ RotateAxisAngle(device=self.device, dtype=self.dtype, *args, **kwargs)+ )++ def clone(self) -> "Transform3d":+ """+ Deep copy of Transforms object. All internal tensors are cloned+ individually.++ Returns:+ new Transforms object.+ """+ other = Transform3d(dtype=self.dtype, device=self.device)+ if self._lu is not None:+ other._lu = [elem.clone() for elem in self._lu]+ other._matrix = self._matrix.clone()+ other._transforms = [t.clone() for t in self._transforms]+ return other++ def to(+ self,+ device: Device,+ copy: bool = False,+ dtype: Optional[torch.dtype] = None,+ ) -> "Transform3d":+ """+ Match functionality of torch.Tensor.to()+ If copy = True or the self Tensor is on a different device, the+ returned tensor is a copy of self with the desired torch.device.+ If copy = False and the self Tensor already has the correct torch.device,+ then self is returned.++ Args:+ device: Device (as str or torch.device) for the new tensor.+ copy: Boolean indicator whether or not to clone self. Default False.+ dtype: If not None, casts the internal tensor variables+ to a given torch.dtype.++ Returns:+ Transform3d object.+ """+ device_ = make_device(device)+ dtype_ = self.dtype if dtype is None else dtype+ skip_to = self.device == device_ and self.dtype == dtype_++ if not copy and skip_to:+ return self++ other = self.clone()++ if skip_to:+ return other++ other.device = device_+ other.dtype = dtype_+ other._matrix = other._matrix.to(device=device_, dtype=dtype_)+ other._transforms = [+ t.to(device_, copy=copy, dtype=dtype_) for t in other._transforms+ ]+ return other++ def cpu(self) -> "Transform3d":+ return self.to("cpu")++ def cuda(self) -> "Transform3d":+ return self.to("cuda")++class Translate(Transform3d):+ def __init__(+ self,+ x,+ y=None,+ z=None,+ dtype: torch.dtype = torch.float32,+ device: Optional[Device] = None,+ ) -> None:+ """+ Create a new Transform3d representing 3D translations.++ Option I: Translate(xyz, dtype=torch.float32, device='cpu')+ xyz should be a tensor of shape (N, 3)++ Option II: Translate(x, y, z, dtype=torch.float32, device='cpu')+ Here x, y, and z will be broadcast against each other and+ concatenated to form the translation. Each can be:+ - A python scalar+ - A torch scalar+ - A 1D torch tensor+ """+ xyz = _handle_input(x, y, z, dtype, device, "Translate")+ super().__init__(device=xyz.device, dtype=dtype)+ N = xyz.shape[0]++ mat = torch.eye(4, dtype=dtype, device=self.device)+ mat = mat.view(1, 4, 4).repeat(N, 1, 1)+ mat[:, 3, :3] = xyz+ self._matrix = mat++ def _get_matrix_inverse(self) -> torch.Tensor:+ """+ Return the inverse of self._matrix.+ """+ inv_mask = self._matrix.new_ones([1, 4, 4])+ inv_mask[0, 3, :3] = -1.0+ i_matrix = self._matrix * inv_mask+ return i_matrix++class Rotate(Transform3d):+ def __init__(+ self,+ R: torch.Tensor,+ dtype: torch.dtype = torch.float32,+ device: Optional[Device] = None,+ orthogonal_tol: float = 1e-5,+ ) -> None:+ """+ Create a new Transform3d representing 3D rotation using a rotation+ matrix as the input.++ Args:+ R: a tensor of shape (3, 3) or (N, 3, 3)+ orthogonal_tol: tolerance for the test of the orthogonality of R++ """+ device_ = get_device(R, device)+ super().__init__(device=device_, dtype=dtype)+ if R.dim() == 2:+ R = R[None]+ if R.shape[-2:] != (3, 3):+ msg = "R must have shape (3, 3) or (N, 3, 3); got %s"+ raise ValueError(msg % repr(R.shape))+ R = R.to(device=device_, dtype=dtype)+ _check_valid_rotation_matrix(R, tol=orthogonal_tol)+ N = R.shape[0]+ mat = torch.eye(4, dtype=dtype, device=device_)+ mat = mat.view(1, 4, 4).repeat(N, 1, 1)+ mat[:, :3, :3] = R+ self._matrix = mat++ def _get_matrix_inverse(self) -> torch.Tensor:+ """+ Return the inverse of self._matrix.+ """+ return self._matrix.permute(0, 2, 1).contiguous()++class TensorAccessor(nn.Module):+ """+ A helper class to be used with the __getitem__ method. This can be used for+ getting/setting the values for an attribute of a class at one particular+ index. This is useful when the attributes of a class are batched tensors+ and one element in the batch needs to be modified.+ """++ def __init__(self, class_object, index: Union[int, slice]) -> None:+ """+ Args:+ class_object: this should be an instance of a class which has+ attributes which are tensors representing a batch of+ values.+ index: int/slice, an index indicating the position in the batch.+ In __setattr__ and __getattr__ only the value of class+ attributes at this index will be accessed.+ """+ self.__dict__["class_object"] = class_object+ self.__dict__["index"] = index++ def __setattr__(self, name: str, value: Any):+ """+ Update the attribute given by `name` to the value given by `value`+ at the index specified by `self.index`.+ Args:+ name: str, name of the attribute.+ value: value to set the attribute to.+ """+ v = getattr(self.class_object, name)+ if not torch.is_tensor(v):+ msg = "Can only set values on attributes which are tensors; got %r"+ raise AttributeError(msg % type(v))++ # Convert the attribute to a tensor if it is not a tensor.+ if not torch.is_tensor(value):+ value = torch.tensor(+ value, device=v.device, dtype=v.dtype, requires_grad=v.requires_grad+ )++ # Check the shapes match the existing shape and the shape of the index.+ if v.dim() > 1 and value.dim() > 1 and value.shape[1:] != v.shape[1:]:+ msg = "Expected value to have shape %r; got %r"+ raise ValueError(msg % (v.shape, value.shape))+ if (+ v.dim() == 0+ and isinstance(self.index, slice)+ and len(value) != len(self.index)+ ):+ msg = "Expected value to have len %r; got %r"+ raise ValueError(msg % (len(self.index), len(value)))+ self.class_object.__dict__[name][self.index] = value++ def __getattr__(self, name: str):+ """+ Return the value of the attribute given by "name" on self.class_object+ at the index specified in self.index.+ Args:+ name: string of the attribute name+ """+ if hasattr(self.class_object, name):+ return self.class_object.__dict__[name][self.index]+ else:+ msg = "Attribute %s not found on %r"+ return AttributeError(msg % (name, self.class_object.__name__))++BROADCAST_TYPES = (float, int, list, tuple, torch.Tensor, np.ndarray)++class TensorProperties(nn.Module):+ """+ A mix-in class for storing tensors as properties with helper methods.+ """++ def __init__(+ self,+ dtype: torch.dtype = torch.float32,+ device: Device = "cpu",+ **kwargs,+ ) -> None:+ """+ Args:+ dtype: data type to set for the inputs+ device: Device (as str or torch.device)+ kwargs: any number of keyword arguments. Any arguments which are+ of type (float/int/list/tuple/tensor/array) are broadcasted and+ other keyword arguments are set as attributes.+ """+ super().__init__()+ self.device = make_device(device)+ self._N = 0+ if kwargs is not None:++ # broadcast all inputs which are float/int/list/tuple/tensor/array+ # set as attributes anything else e.g. strings, bools+ args_to_broadcast = {}+ for k, v in kwargs.items():+ if v is None or isinstance(v, (str, bool)):+ setattr(self, k, v)+ elif isinstance(v, BROADCAST_TYPES):+ args_to_broadcast[k] = v+ else:+ msg = "Arg %s with type %r is not broadcastable"+ warnings.warn(msg % (k, type(v)))++ names = args_to_broadcast.keys()+ # convert from type dict.values to tuple+ values = tuple(v for v in args_to_broadcast.values())++ if len(values) > 0:+ broadcasted_values = convert_to_tensors_and_broadcast(+ *values, device=device+ )++ # Set broadcasted values as attributes on self.+ for i, n in enumerate(names):+ setattr(self, n, broadcasted_values[i])+ if self._N == 0:+ self._N = broadcasted_values[i].shape[0]++ def __len__(self) -> int:+ return self._N++ def isempty(self) -> bool:+ return self._N == 0++ def __getitem__(self, index: Union[int, slice]) -> TensorAccessor:+ """+ Args:+ index: an int or slice used to index all the fields.+ Returns:+ if `index` is an index int/slice return a TensorAccessor class+ with getattribute/setattribute methods which return/update the value+ at the index in the original class.+ """+ if isinstance(index, (int, slice)):+ return TensorAccessor(class_object=self, index=index)++ msg = "Expected index of type int or slice; got %r"+ raise ValueError(msg % type(index))++ # pyre-fixme[14]: `to` overrides method defined in `Module` inconsistently.+ def to(self, device: Device = "cpu") -> "TensorProperties":+ """+ In place operation to move class properties which are tensors to a+ specified device. If self has a property "device", update this as well.+ """+ device_ = make_device(device)+ for k in dir(self):+ v = getattr(self, k)+ if k == "device":+ setattr(self, k, device_)+ if torch.is_tensor(v) and v.device != device_:+ setattr(self, k, v.to(device_))+ return self++ def cpu(self) -> "TensorProperties":+ return self.to("cpu")++ # pyre-fixme[14]: `cuda` overrides method defined in `Module` inconsistently.+ def cuda(self, device: Optional[int] = None) -> "TensorProperties":+ return self.to(f"cuda:{device}" if device is not None else "cuda")++ def clone(self, other) -> "TensorProperties":+ """+ Update the tensor properties of other with the cloned properties of self.+ """+ for k in dir(self):+ v = getattr(self, k)+ if inspect.ismethod(v) or k.startswith("__"):+ continue+ if torch.is_tensor(v):+ v_clone = v.clone()+ else:+ v_clone = copy.deepcopy(v)+ setattr(other, k, v_clone)+ return other++ def gather_props(self, batch_idx) -> "TensorProperties":+ """+ This is an in place operation to reformat all tensor class attributes+ based on a set of given indices using torch.gather. This is useful when+ attributes which are batched tensors e.g. shape (N, 3) need to be+ multiplied with another tensor which has a different first dimension+ e.g. packed vertices of shape (V, 3).+ Example+ .. code-block:: python+ self.specular_color = (N, 3) tensor of specular colors for each mesh+ A lighting calculation may use+ .. code-block:: python+ verts_packed = meshes.verts_packed() # (V, 3)+ To multiply these two tensors the batch dimension needs to be the same.+ To achieve this we can do+ .. code-block:: python+ batch_idx = meshes.verts_packed_to_mesh_idx() # (V)+ This gives index of the mesh for each vertex in verts_packed.+ .. code-block:: python+ self.gather_props(batch_idx)+ self.specular_color = (V, 3) tensor with the specular color for+ each packed vertex.+ torch.gather requires the index tensor to have the same shape as the+ input tensor so this method takes care of the reshaping of the index+ tensor to use with class attributes with arbitrary dimensions.+ Args:+ batch_idx: shape (B, ...) where `...` represents an arbitrary+ number of dimensions+ Returns:+ self with all properties reshaped. e.g. a property with shape (N, 3)+ is transformed to shape (B, 3).+ """+ # Iterate through the attributes of the class which are tensors.+ for k in dir(self):+ v = getattr(self, k)+ if torch.is_tensor(v):+ if v.shape[0] > 1:+ # There are different values for each batch element+ # so gather these using the batch_idx.+ # First clone the input batch_idx tensor before+ # modifying it.+ _batch_idx = batch_idx.clone()+ idx_dims = _batch_idx.shape+ tensor_dims = v.shape+ if len(idx_dims) > len(tensor_dims):+ msg = "batch_idx cannot have more dimensions than %s. "+ msg += "got shape %r and %s has shape %r"+ raise ValueError(msg % (k, idx_dims, k, tensor_dims))+ if idx_dims != tensor_dims:+ # To use torch.gather the index tensor (_batch_idx) has+ # to have the same shape as the input tensor.+ new_dims = len(tensor_dims) - len(idx_dims)+ new_shape = idx_dims + (1,) * new_dims+ expand_dims = (-1,) + tensor_dims[1:]+ _batch_idx = _batch_idx.view(*new_shape)+ _batch_idx = _batch_idx.expand(*expand_dims)++ v = v.gather(0, _batch_idx)+ setattr(self, k, v)+ return self++class CamerasBase(TensorProperties):+ """+ `CamerasBase` implements a base class for all cameras.+ For cameras, there are four different coordinate systems (or spaces)+ - World coordinate system: This is the system the object lives - the world.+ - Camera view coordinate system: This is the system that has its origin on the camera+ and the and the Z-axis perpendicular to the image plane.+ In PyTorch3D, we assume that +X points left, and +Y points up and+ +Z points out from the image plane.+ The transformation from world --> view happens after applying a rotation (R)+ and translation (T)+ - NDC coordinate system: This is the normalized coordinate system that confines+ in a volume the rendered part of the object or scene. Also known as view volume.+ For square images, given the PyTorch3D convention, (+1, +1, znear)+ is the top left near corner, and (-1, -1, zfar) is the bottom right far+ corner of the volume.+ The transformation from view --> NDC happens after applying the camera+ projection matrix (P) if defined in NDC space.+ For non square images, we scale the points such that smallest side+ has range [-1, 1] and the largest side has range [-u, u], with u > 1.+ - Screen coordinate system: This is another representation of the view volume with+ the XY coordinates defined in image space instead of a normalized space.+ A better illustration of the coordinate systems can be found in+ pytorch3d/docs/notes/cameras.md.+ It defines methods that are common to all camera models:+ - `get_camera_center` that returns the optical center of the camera in+ world coordinates+ - `get_world_to_view_transform` which returns a 3D transform from+ world coordinates to the camera view coordinates (R, T)+ - `get_full_projection_transform` which composes the projection+ transform (P) with the world-to-view transform (R, T)+ - `transform_points` which takes a set of input points in world coordinates and+ projects to the space the camera is defined in (NDC or screen)+ - `get_ndc_camera_transform` which defines the transform from screen/NDC to+ PyTorch3D's NDC space+ - `transform_points_ndc` which takes a set of points in world coordinates and+ projects them to PyTorch3D's NDC space+ - `transform_points_screen` which takes a set of points in world coordinates and+ projects them to screen space+ For each new camera, one should implement the `get_projection_transform`+ routine that returns the mapping from camera view coordinates to camera+ coordinates (NDC or screen).+ Another useful function that is specific to each camera model is+ `unproject_points` which sends points from camera coordinates (NDC or screen)+ back to camera view or world coordinates depending on the `world_coordinates`+ boolean argument of the function.+ """++ # Used in __getitem__ to index the relevant fields+ # When creating a new camera, this should be set in the __init__+ _FIELDS: Tuple[str, ...] = ()++ # Names of fields which are a constant property of the whole batch, rather+ # than themselves a batch of data.+ # When joining objects into a batch, they will have to agree.+ _SHARED_FIELDS: Tuple[str, ...] = ()++ def get_projection_transform(self):+ """+ Calculate the projective transformation matrix.+ Args:+ **kwargs: parameters for the projection can be passed in as keyword+ arguments to override the default values set in `__init__`.+ Return:+ a `Transform3d` object which represents a batch of projection+ matrices of shape (N, 3, 3)+ """+ raise NotImplementedError()++ def unproject_points(self, xy_depth: torch.Tensor, **kwargs):+ """+ Transform input points from camera coodinates (NDC or screen)+ to the world / camera coordinates.+ Each of the input points `xy_depth` of shape (..., 3) is+ a concatenation of the x, y location and its depth.+ For instance, for an input 2D tensor of shape `(num_points, 3)`+ `xy_depth` takes the following form:+ `xy_depth[i] = [x[i], y[i], depth[i]]`,+ for a each point at an index `i`.+ The following example demonstrates the relationship between+ `transform_points` and `unproject_points`:+ .. code-block:: python+ cameras = # camera object derived from CamerasBase+ xyz = # 3D points of shape (batch_size, num_points, 3)+ # transform xyz to the camera view coordinates+ xyz_cam = cameras.get_world_to_view_transform().transform_points(xyz)+ # extract the depth of each point as the 3rd coord of xyz_cam+ depth = xyz_cam[:, :, 2:]+ # project the points xyz to the camera+ xy = cameras.transform_points(xyz)[:, :, :2]+ # append depth to xy+ xy_depth = torch.cat((xy, depth), dim=2)+ # unproject to the world coordinates+ xyz_unproj_world = cameras.unproject_points(xy_depth, world_coordinates=True)+ print(torch.allclose(xyz, xyz_unproj_world)) # True+ # unproject to the camera coordinates+ xyz_unproj = cameras.unproject_points(xy_depth, world_coordinates=False)+ print(torch.allclose(xyz_cam, xyz_unproj)) # True+ Args:+ xy_depth: torch tensor of shape (..., 3).+ world_coordinates: If `True`, unprojects the points back to world+ coordinates using the camera extrinsics `R` and `T`.+ `False` ignores `R` and `T` and unprojects to+ the camera view coordinates.+ from_ndc: If `False` (default), assumes xy part of input is in+ NDC space if self.in_ndc(), otherwise in screen space. If+ `True`, assumes xy is in NDC space even if the camera+ is defined in screen space.+ Returns+ new_points: unprojected points with the same shape as `xy_depth`.+ """+ raise NotImplementedError()++ def get_camera_center(self, **kwargs) -> torch.Tensor:+ """+ Return the 3D location of the camera optical center+ in the world coordinates.+ Args:+ **kwargs: parameters for the camera extrinsics can be passed in+ as keyword arguments to override the default values+ set in __init__.+ Setting T here will update the values set in init as this+ value may be needed later on in the rendering pipeline e.g. for+ lighting calculations.+ Returns:+ C: a batch of 3D locations of shape (N, 3) denoting+ the locations of the center of each camera in the batch.+ """+ w2v_trans = self.get_world_to_view_transform(**kwargs)+ P = w2v_trans.inverse().get_matrix()+ # the camera center is the translation component (the first 3 elements+ # of the last row) of the inverted world-to-view+ # transform (4x4 RT matrix)+ C = P[:, 3, :3]+ return C++ def get_world_to_view_transform(self, **kwargs) -> Transform3d:+ """+ Return the world-to-view transform.+ Args:+ **kwargs: parameters for the camera extrinsics can be passed in+ as keyword arguments to override the default values+ set in __init__.+ Setting R and T here will update the values set in init as these+ values may be needed later on in the rendering pipeline e.g. for+ lighting calculations.+ Returns:+ A Transform3d object which represents a batch of transforms+ of shape (N, 3, 3)+ """+ R: torch.Tensor = kwargs.get("R", self.R)+ T: torch.Tensor = kwargs.get("T", self.T)+ self.R = R # pyre-ignore[16]+ self.T = T # pyre-ignore[16]+ world_to_view_transform = get_world_to_view_transform(R=R, T=T)+ return world_to_view_transform++ def get_full_projection_transform(self, **kwargs) -> Transform3d:+ """+ Return the full world-to-camera transform composing the+ world-to-view and view-to-camera transforms.+ If camera is defined in NDC space, the projected points are in NDC space.+ If camera is defined in screen space, the projected points are in screen space.+ Args:+ **kwargs: parameters for the projection transforms can be passed in+ as keyword arguments to override the default values+ set in __init__.+ Setting R and T here will update the values set in init as these+ values may be needed later on in the rendering pipeline e.g. for+ lighting calculations.+ Returns:+ a Transform3d object which represents a batch of transforms+ of shape (N, 3, 3)+ """+ self.R: torch.Tensor = kwargs.get("R", self.R) # pyre-ignore[16]+ self.T: torch.Tensor = kwargs.get("T", self.T) # pyre-ignore[16]+ world_to_view_transform = self.get_world_to_view_transform(R=self.R, T=self.T)+ view_to_proj_transform = self.get_projection_transform(**kwargs)+ return world_to_view_transform.compose(view_to_proj_transform)++ def transform_points(+ self, points, eps: Optional[float] = None, **kwargs+ ) -> torch.Tensor:+ """+ Transform input points from world to camera space with the+ projection matrix defined by the camera.+ For `CamerasBase.transform_points`, setting `eps > 0`+ stabilizes gradients since it leads to avoiding division+ by excessively low numbers for points close to the camera plane.+ Args:+ points: torch tensor of shape (..., 3).+ eps: If eps!=None, the argument is used to clamp the+ divisor in the homogeneous normalization of the points+ transformed to the ndc space. Please see+ `transforms.Transform3d.transform_points` for details.+ For `CamerasBase.transform_points`, setting `eps > 0`+ stabilizes gradients since it leads to avoiding division+ by excessively low numbers for points close to the+ camera plane.+ Returns+ new_points: transformed points with the same shape as the input.+ """+ world_to_proj_transform = self.get_full_projection_transform(**kwargs)+ return world_to_proj_transform.transform_points(points, eps=eps)++ def get_ndc_camera_transform(self, **kwargs) -> Transform3d:+ """+ Returns the transform from camera projection space (screen or NDC) to NDC space.+ For cameras that can be specified in screen space, this transform+ allows points to be converted from screen to NDC space.+ The default transform scales the points from [0, W]x[0, H]+ to [-1, 1]x[-u, u] or [-u, u]x[-1, 1] where u > 1 is the aspect ratio of the image.+ This function should be modified per camera definitions if need be,+ e.g. for Perspective/Orthographic cameras we provide a custom implementation.+ This transform assumes PyTorch3D coordinate system conventions for+ both the NDC space and the input points.+ This transform interfaces with the PyTorch3D renderer which assumes+ input points to the renderer to be in NDC space.+ """+ if self.in_ndc():+ return Transform3d(device=self.device, dtype=torch.float32)+ else:+ # For custom cameras which can be defined in screen space,+ # users might might have to implement the screen to NDC transform based+ # on the definition of the camera parameters.+ # See PerspectiveCameras/OrthographicCameras for an example.+ # We don't flip xy because we assume that world points are in+ # PyTorch3D coordinates, and thus conversion from screen to ndc+ # is a mere scaling from image to [-1, 1] scale.+ image_size = kwargs.get("image_size", self.get_image_size())+ return get_screen_to_ndc_transform(+ self, with_xyflip=False, image_size=image_size+ )++ def transform_points_ndc(+ self, points, eps: Optional[float] = None, **kwargs+ ) -> torch.Tensor:+ """+ Transforms points from PyTorch3D world/camera space to NDC space.+ Input points follow the PyTorch3D coordinate system conventions: +X left, +Y up.+ Output points are in NDC space: +X left, +Y up, origin at image center.+ Args:+ points: torch tensor of shape (..., 3).+ eps: If eps!=None, the argument is used to clamp the+ divisor in the homogeneous normalization of the points+ transformed to the ndc space. Please see+ `transforms.Transform3d.transform_points` for details.+ For `CamerasBase.transform_points`, setting `eps > 0`+ stabilizes gradients since it leads to avoiding division+ by excessively low numbers for points close to the+ camera plane.+ Returns+ new_points: transformed points with the same shape as the input.+ """+ world_to_ndc_transform = self.get_full_projection_transform(**kwargs)+ if not self.in_ndc():+ to_ndc_transform = self.get_ndc_camera_transform(**kwargs)+ world_to_ndc_transform = world_to_ndc_transform.compose(to_ndc_transform)++ return world_to_ndc_transform.transform_points(points, eps=eps)++ def transform_points_screen(+ self, points, eps: Optional[float] = None, **kwargs+ ) -> torch.Tensor:+ """+ Transforms points from PyTorch3D world/camera space to screen space.+ Input points follow the PyTorch3D coordinate system conventions: +X left, +Y up.+ Output points are in screen space: +X right, +Y down, origin at top left corner.+ Args:+ points: torch tensor of shape (..., 3).+ eps: If eps!=None, the argument is used to clamp the+ divisor in the homogeneous normalization of the points+ transformed to the ndc space. Please see+ `transforms.Transform3d.transform_points` for details.+ For `CamerasBase.transform_points`, setting `eps > 0`+ stabilizes gradients since it leads to avoiding division+ by excessively low numbers for points close to the+ camera plane.+ Returns+ new_points: transformed points with the same shape as the input.+ """+ points_ndc = self.transform_points_ndc(points, eps=eps, **kwargs)+ image_size = kwargs.get("image_size", self.get_image_size())+ return get_ndc_to_screen_transform(+ self, with_xyflip=True, image_size=image_size+ ).transform_points(points_ndc, eps=eps)++ def clone(self):+ """+ Returns a copy of `self`.+ """+ cam_type = type(self)+ other = cam_type(device=self.device)+ return super().clone(other)++ def is_perspective(self):+ raise NotImplementedError()++ def in_ndc(self):+ """+ Specifies whether the camera is defined in NDC space+ or in screen (image) space+ """+ raise NotImplementedError()++ def get_znear(self):+ return self.znear if hasattr(self, "znear") else None++ def get_image_size(self):+ """+ Returns the image size, if provided, expected in the form of (height, width)+ The image size is used for conversion of projected points to screen coordinates.+ """+ return self.image_size if hasattr(self, "image_size") else None++ def __getitem__(+ self, index: Union[int, List[int], torch.LongTensor]+ ) -> "CamerasBase":+ """+ Override for the __getitem__ method in TensorProperties which needs to be+ refactored.+ Args:+ index: an int/list/long tensor used to index all the fields in the cameras given by+ self._FIELDS.+ Returns:+ if `index` is an index int/list/long tensor return an instance of the current+ cameras class with only the values at the selected index.+ """++ kwargs = {}++ if not isinstance(index, (int, list, torch.LongTensor, torch.cuda.LongTensor)):+ msg = "Invalid index type, expected int, List[int] or torch.LongTensor; got %r"+ raise ValueError(msg % type(index))++ if isinstance(index, int):+ index = [index]++ if max(index) >= len(self):+ raise ValueError(f"Index {max(index)} is out of bounds for select cameras")++ for field in self._FIELDS:+ val = getattr(self, field, None)+ if val is None:+ continue++ # e.g. "in_ndc" is set as attribute "_in_ndc" on the class+ # but provided as "in_ndc" on initialization+ if field.startswith("_"):+ field = field[1:]++ if isinstance(val, (str, bool)):+ kwargs[field] = val+ elif isinstance(val, torch.Tensor):+ # In the init, all inputs will be converted to+ # tensors before setting as attributes+ kwargs[field] = val[index]+ else:+ raise ValueError(f"Field {field} type is not supported for indexing")++ kwargs["device"] = self.device+ return self.__class__(**kwargs)++class FoVPerspectiveCameras(CamerasBase):+ """+ A class which stores a batch of parameters to generate a batch of+ projection matrices by specifying the field of view.+ The definition of the parameters follow the OpenGL perspective camera.++ The extrinsics of the camera (R and T matrices) can also be set in the+ initializer or passed in to `get_full_projection_transform` to get+ the full transformation from world -> ndc.++ The `transform_points` method calculates the full world -> ndc transform+ and then applies it to the input points.++ The transforms can also be returned separately as Transform3d objects.++ * Setting the Aspect Ratio for Non Square Images *++ If the desired output image size is non square (i.e. a tuple of (H, W) where H != W)+ the aspect ratio needs special consideration: There are two aspect ratios+ to be aware of:+ - the aspect ratio of each pixel+ - the aspect ratio of the output image+ The `aspect_ratio` setting in the FoVPerspectiveCameras sets the+ pixel aspect ratio. When using this camera with the differentiable rasterizer+ be aware that in the rasterizer we assume square pixels, but allow+ variable image aspect ratio (i.e rectangle images).++ In most cases you will want to set the camera `aspect_ratio=1.0`+ (i.e. square pixels) and only vary the output image dimensions in pixels+ for rasterization.+ """++ # For __getitem__+ _FIELDS = (+ "K",+ "znear",+ "zfar",+ "aspect_ratio",+ "fov",+ "R",+ "T",+ "degrees",+ )++ _SHARED_FIELDS = ("degrees",)++ def __init__(+ self,+ znear=1.0,+ zfar=100.0,+ aspect_ratio=1.0,+ fov=60.0,+ degrees: bool = True,+ R: torch.Tensor = _R,+ T: torch.Tensor = _T,+ K: Optional[torch.Tensor] = None,+ device: Device = "cpu",+ ) -> None:+ """++ Args:+ znear: near clipping plane of the view frustrum.+ zfar: far clipping plane of the view frustrum.+ aspect_ratio: aspect ratio of the image pixels.+ 1.0 indicates square pixels.+ fov: field of view angle of the camera.+ degrees: bool, set to True if fov is specified in degrees.+ R: Rotation matrix of shape (N, 3, 3)+ T: Translation matrix of shape (N, 3)+ K: (optional) A calibration matrix of shape (N, 4, 4)+ If provided, don't need znear, zfar, fov, aspect_ratio, degrees+ device: Device (as str or torch.device)+ """+ # The initializer formats all inputs to torch tensors and broadcasts+ # all the inputs to have the same batch dimension where necessary.+ super().__init__(+ device=device,+ znear=znear,+ zfar=zfar,+ aspect_ratio=aspect_ratio,+ fov=fov,+ R=R,+ T=T,+ K=K,+ )++ # No need to convert to tensor or broadcast.+ self.degrees = degrees++ def compute_projection_matrix(+ self, znear, zfar, fov, aspect_ratio, degrees: bool+ ) -> torch.Tensor:+ """+ Compute the calibration matrix K of shape (N, 4, 4)++ Args:+ znear: near clipping plane of the view frustrum.+ zfar: far clipping plane of the view frustrum.+ fov: field of view angle of the camera.+ aspect_ratio: aspect ratio of the image pixels.+ 1.0 indicates square pixels.+ degrees: bool, set to True if fov is specified in degrees.++ Returns:+ torch.FloatTensor of the calibration matrix with shape (N, 4, 4)+ """+ K = torch.zeros((self._N, 4, 4), device=self.device, dtype=torch.float32)+ ones = torch.ones((self._N), dtype=torch.float32, device=self.device)+ if degrees:+ fov = (np.pi / 180) * fov++ if not torch.is_tensor(fov):+ fov = torch.tensor(fov, device=self.device)+ tanHalfFov = torch.tan((fov / 2))+ max_y = tanHalfFov * znear+ min_y = -max_y+ max_x = max_y * aspect_ratio+ min_x = -max_x++ # NOTE: In OpenGL the projection matrix changes the handedness of the+ # coordinate frame. i.e the NDC space positive z direction is the+ # camera space negative z direction. This is because the sign of the z+ # in the projection matrix is set to -1.0.+ # In pytorch3d we maintain a right handed coordinate system throughout+ # so the so the z sign is 1.0.+ z_sign = 1.0++ K[:, 0, 0] = 2.0 * znear / (max_x - min_x)+ K[:, 1, 1] = 2.0 * znear / (max_y - min_y)+ K[:, 0, 2] = (max_x + min_x) / (max_x - min_x)+ K[:, 1, 2] = (max_y + min_y) / (max_y - min_y)+ K[:, 3, 2] = z_sign * ones++ # NOTE: This maps the z coordinate from [0, 1] where z = 0 if the point+ # is at the near clipping plane and z = 1 when the point is at the far+ # clipping plane.+ K[:, 2, 2] = z_sign * zfar / (zfar - znear)+ K[:, 2, 3] = -(zfar * znear) / (zfar - znear)++ return K++ def get_projection_transform(self, **kwargs) -> Transform3d:+ """+ Calculate the perspective projection matrix with a symmetric+ viewing frustrum. Use column major order.+ The viewing frustrum will be projected into ndc, s.t.+ (max_x, max_y) -> (+1, +1)+ (min_x, min_y) -> (-1, -1)++ Args:+ **kwargs: parameters for the projection can be passed in as keyword+ arguments to override the default values set in `__init__`.++ Return:+ a Transform3d object which represents a batch of projection+ matrices of shape (N, 4, 4)++ .. code-block:: python++ h1 = (max_y + min_y)/(max_y - min_y)+ w1 = (max_x + min_x)/(max_x - min_x)+ tanhalffov = tan((fov/2))+ s1 = 1/tanhalffov+ s2 = 1/(tanhalffov * (aspect_ratio))++ # To map z to the range [0, 1] use:+ f1 = far / (far - near)+ f2 = -(far * near) / (far - near)++ # Projection matrix+ K = [+ [s1, 0, w1, 0],+ [0, s2, h1, 0],+ [0, 0, f1, f2],+ [0, 0, 1, 0],+ ]+ """+ K = kwargs.get("K", self.K)+ if K is not None:+ if K.shape != (self._N, 4, 4):+ msg = "Expected K to have shape of (%r, 4, 4)"+ raise ValueError(msg % (self._N))+ else:+ K = self.compute_projection_matrix(+ kwargs.get("znear", self.znear),+ kwargs.get("zfar", self.zfar),+ kwargs.get("fov", self.fov),+ kwargs.get("aspect_ratio", self.aspect_ratio),+ kwargs.get("degrees", self.degrees),+ )++ # Transpose the projection matrix as PyTorch3D transforms use row vectors.+ transform = Transform3d(+ matrix=K.transpose(1, 2).contiguous(), device=self.device+ )+ return transform++ def unproject_points(+ self,+ xy_depth: torch.Tensor,+ world_coordinates: bool = True,+ scaled_depth_input: bool = False,+ **kwargs,+ ) -> torch.Tensor:+ """>!+ FoV cameras further allow for passing depth in world units+ (`scaled_depth_input=False`) or in the [0, 1]-normalized units+ (`scaled_depth_input=True`)++ Args:+ scaled_depth_input: If `True`, assumes the input depth is in+ the [0, 1]-normalized units. If `False` the input depth is in+ the world units.+ """++ # obtain the relevant transformation to ndc+ if world_coordinates:+ to_ndc_transform = self.get_full_projection_transform()+ else:+ to_ndc_transform = self.get_projection_transform()++ if scaled_depth_input:+ # the input is scaled depth, so we don't have to do anything+ xy_sdepth = xy_depth+ else:+ # parse out important values from the projection matrix+ K_matrix = self.get_projection_transform(**kwargs.copy()).get_matrix()+ # parse out f1, f2 from K_matrix+ unsqueeze_shape = [1] * xy_depth.dim()+ unsqueeze_shape[0] = K_matrix.shape[0]+ f1 = K_matrix[:, 2, 2].reshape(unsqueeze_shape)+ f2 = K_matrix[:, 3, 2].reshape(unsqueeze_shape)+ # get the scaled depth+ sdepth = (f1 * xy_depth[..., 2:3] + f2) / xy_depth[..., 2:3]+ # concatenate xy + scaled depth+ xy_sdepth = torch.cat((xy_depth[..., 0:2], sdepth), dim=-1)++ # unproject with inverse of the projection+ unprojection_transform = to_ndc_transform.inverse()+ return unprojection_transform.transform_points(xy_sdepth)++ def is_perspective(self):+ return True++ def in_ndc(self):+ return True++#######################################################################################+## ██████╗ ███████╗███████╗██╗███╗ ██╗██╗████████╗██╗ ██████╗ ███╗ ██╗███████╗ ##+## ██╔══██╗██╔════╝██╔════╝██║████╗ ██║██║╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝ ##+## ██║ ██║█████╗ █████╗ ██║██╔██╗ ██║██║ ██║ ██║██║ ██║██╔██╗ ██║███████╗ ##+## ██║ ██║██╔══╝ ██╔══╝ ██║██║╚██╗██║██║ ██║ ██║██║ ██║██║╚██╗██║╚════██║ ##+## ██████╔╝███████╗██║ ██║██║ ╚████║██║ ██║ ██║╚██████╔╝██║ ╚████║███████║ ##+## ╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ##+#######################################################################################++def make_device(device: Device) -> torch.device:+ """+ Makes an actual torch.device object from the device specified as+ either a string or torch.device object. If the device is `cuda` without+ a specific index, the index of the current device is assigned.+ Args:+ device: Device (as str or torch.device)+ Returns:+ A matching torch.device object+ """+ device = torch.device(device) if isinstance(device, str) else device+ if device.type == "cuda" and device.index is None: # pyre-ignore[16]+ # If cuda but with no index, then the current cuda device is indicated.+ # In that case, we fix to that device+ device = torch.device(f"cuda:{torch.cuda.current_device()}")+ return device++def get_device(x, device: Optional[Device] = None) -> torch.device:+ """+ Gets the device of the specified variable x if it is a tensor, or+ falls back to a default CPU device otherwise. Allows overriding by+ providing an explicit device.+ Args:+ x: a torch.Tensor to get the device from or another type+ device: Device (as str or torch.device) to fall back to+ Returns:+ A matching torch.device object+ """++ # User overrides device+ if device is not None:+ return make_device(device)++ # Set device based on input tensor+ if torch.is_tensor(x):+ return x.device++ # Default device is cpu+ return torch.device("cpu")++def _axis_angle_rotation(axis: str, angle: torch.Tensor) -> torch.Tensor:+ """+ Return the rotation matrices for one of the rotations about an axis+ of which Euler angles describe, for each value of the angle given.++ Args:+ axis: Axis label "X" or "Y or "Z".+ angle: any shape tensor of Euler angles in radians++ Returns:+ Rotation matrices as tensor of shape (..., 3, 3).+ """++ cos = torch.cos(angle)+ sin = torch.sin(angle)+ one = torch.ones_like(angle)+ zero = torch.zeros_like(angle)++ if axis == "X":+ R_flat = (one, zero, zero, zero, cos, -sin, zero, sin, cos)+ elif axis == "Y":+ R_flat = (cos, zero, sin, zero, one, zero, -sin, zero, cos)+ elif axis == "Z":+ R_flat = (cos, -sin, zero, sin, cos, zero, zero, zero, one)+ else:+ raise ValueError("letter must be either X, Y or Z.")++ return torch.stack(R_flat, -1).reshape(angle.shape + (3, 3))++def euler_angles_to_matrix(euler_angles: torch.Tensor, convention: str) -> torch.Tensor:+ """+ Convert rotations given as Euler angles in radians to rotation matrices.++ Args:+ euler_angles: Euler angles in radians as tensor of shape (..., 3).+ convention: Convention string of three uppercase letters from+ {"X", "Y", and "Z"}.++ Returns:+ Rotation matrices as tensor of shape (..., 3, 3).+ """+ if euler_angles.dim() == 0 or euler_angles.shape[-1] != 3:+ raise ValueError("Invalid input euler angles.")+ if len(convention) != 3:+ raise ValueError("Convention must have 3 letters.")+ if convention[1] in (convention[0], convention[2]):+ raise ValueError(f"Invalid convention {convention}.")+ for letter in convention:+ if letter not in ("X", "Y", "Z"):+ raise ValueError(f"Invalid letter {letter} in convention string.")+ matrices = [+ _axis_angle_rotation(c, e)+ for c, e in zip(convention, torch.unbind(euler_angles, -1))+ ]+ # return functools.reduce(torch.matmul, matrices)+ return torch.matmul(torch.matmul(matrices[0], matrices[1]), matrices[2])++def _broadcast_bmm(a, b) -> torch.Tensor:+ """+ Batch multiply two matrices and broadcast if necessary.++ Args:+ a: torch tensor of shape (P, K) or (M, P, K)+ b: torch tensor of shape (N, K, K)++ Returns:+ a and b broadcast multiplied. The output batch dimension is max(N, M).++ To broadcast transforms across a batch dimension if M != N then+ expect that either M = 1 or N = 1. The tensor with batch dimension 1 is+ expanded to have shape N or M.+ """+ if a.dim() == 2:+ a = a[None]+ if len(a) != len(b):+ if not ((len(a) == 1) or (len(b) == 1)):+ msg = "Expected batch dim for bmm to be equal or 1; got %r, %r"+ raise ValueError(msg % (a.shape, b.shape))+ if len(a) == 1:+ a = a.expand(len(b), -1, -1)+ if len(b) == 1:+ b = b.expand(len(a), -1, -1)+ return a.bmm(b)++def _safe_det_3x3(t: torch.Tensor):+ """+ Fast determinant calculation for a batch of 3x3 matrices.+ Note, result of this function might not be the same as `torch.det()`.+ The differences might be in the last significant digit.+ Args:+ t: Tensor of shape (N, 3, 3).+ Returns:+ Tensor of shape (N) with determinants.+ """++ det = (+ t[..., 0, 0] * (t[..., 1, 1] * t[..., 2, 2] - t[..., 1, 2] * t[..., 2, 1])+ - t[..., 0, 1] * (t[..., 1, 0] * t[..., 2, 2] - t[..., 2, 0] * t[..., 1, 2])+ + t[..., 0, 2] * (t[..., 1, 0] * t[..., 2, 1] - t[..., 2, 0] * t[..., 1, 1])+ )++ return det++def get_world_to_view_transform(+ R: torch.Tensor = _R, T: torch.Tensor = _T+) -> Transform3d:+ """+ This function returns a Transform3d representing the transformation+ matrix to go from world space to view space by applying a rotation and+ a translation.+ PyTorch3D uses the same convention as Hartley & Zisserman.+ I.e., for camera extrinsic parameters R (rotation) and T (translation),+ we map a 3D point `X_world` in world coordinates to+ a point `X_cam` in camera coordinates with:+ `X_cam = X_world R + T`+ Args:+ R: (N, 3, 3) matrix representing the rotation.+ T: (N, 3) matrix representing the translation.+ Returns:+ a Transform3d object which represents the composed RT transformation.+ """+ # TODO: also support the case where RT is specified as one matrix+ # of shape (N, 4, 4).++ if T.shape[0] != R.shape[0]:+ msg = "Expected R, T to have the same batch dimension; got %r, %r"+ raise ValueError(msg % (R.shape[0], T.shape[0]))+ if T.dim() != 2 or T.shape[1:] != (3,):+ msg = "Expected T to have shape (N, 3); got %r"+ raise ValueError(msg % repr(T.shape))+ if R.dim() != 3 or R.shape[1:] != (3, 3):+ msg = "Expected R to have shape (N, 3, 3); got %r"+ raise ValueError(msg % repr(R.shape))++ # Create a Transform3d object+ T_ = Translate(T, device=T.device)+ R_ = Rotate(R, device=R.device)+ return R_.compose(T_)++def _check_valid_rotation_matrix(R, tol: float = 1e-7) -> None:+ """+ Determine if R is a valid rotation matrix by checking it satisfies the+ following conditions:++ ``RR^T = I and det(R) = 1``++ Args:+ R: an (N, 3, 3) matrix++ Returns:+ None++ Emits a warning if R is an invalid rotation matrix.+ """+ N = R.shape[0]+ eye = torch.eye(3, dtype=R.dtype, device=R.device)+ eye = eye.view(1, 3, 3).expand(N, -1, -1)+ orthogonal = torch.allclose(R.bmm(R.transpose(1, 2)), eye, atol=tol)+ det_R = _safe_det_3x3(R)+ no_distortion = torch.allclose(det_R, torch.ones_like(det_R))+ if not (orthogonal and no_distortion):+ msg = "R is not a valid rotation matrix"+ warnings.warn(msg)+ return++def format_tensor(+ input,+ dtype: torch.dtype = torch.float32,+ device: Device = "cpu",+) -> torch.Tensor:+ """+ Helper function for converting a scalar value to a tensor.+ Args:+ input: Python scalar, Python list/tuple, torch scalar, 1D torch tensor+ dtype: data type for the input+ device: Device (as str or torch.device) on which the tensor should be placed.+ Returns:+ input_vec: torch tensor with optional added batch dimension.+ """+ device_ = make_device(device)+ if not torch.is_tensor(input):+ input = torch.tensor(input, dtype=dtype, device=device_)++ if input.dim() == 0:+ input = input.view(1)++ if input.device == device_:+ return input++ input = input.to(device=device)+ return input++def convert_to_tensors_and_broadcast(+ *args,+ dtype: torch.dtype = torch.float32,+ device: Device = "cpu",+):+ """+ Helper function to handle parsing an arbitrary number of inputs (*args)+ which all need to have the same batch dimension.+ The output is a list of tensors.+ Args:+ *args: an arbitrary number of inputs+ Each of the values in `args` can be one of the following+ - Python scalar+ - Torch scalar+ - Torch tensor of shape (N, K_i) or (1, K_i) where K_i are+ an arbitrary number of dimensions which can vary for each+ value in args. In this case each input is broadcast to a+ tensor of shape (N, K_i)+ dtype: data type to use when creating new tensors.+ device: torch device on which the tensors should be placed.+ Output:+ args: A list of tensors of shape (N, K_i)+ """+ # Convert all inputs to tensors with a batch dimension+ args_1d = [format_tensor(c, dtype, device) for c in args]++ # Find broadcast size+ sizes = [c.shape[0] for c in args_1d]+ N = max(sizes)++ args_Nd = []+ for c in args_1d:+ if c.shape[0] != 1 and c.shape[0] != N:+ msg = "Got non-broadcastable sizes %r" % sizes+ raise ValueError(msg)++ # Expand broadcast dim and keep non broadcast dims the same size+ expand_sizes = (N,) + (-1,) * len(c.shape[1:])+ args_Nd.append(c.expand(*expand_sizes))++ return args_Nd++def _handle_coord(c, dtype: torch.dtype, device: torch.device) -> torch.Tensor:+ """+ Helper function for _handle_input.++ Args:+ c: Python scalar, torch scalar, or 1D torch tensor++ Returns:+ c_vec: 1D torch tensor+ """+ if not torch.is_tensor(c):+ c = torch.tensor(c, dtype=dtype, device=device)+ if c.dim() == 0:+ c = c.view(1)+ if c.device != device or c.dtype != dtype:+ c = c.to(device=device, dtype=dtype)+ return c++def _handle_input(+ x,+ y,+ z,+ dtype: torch.dtype,+ device: Optional[Device],+ name: str,+ allow_singleton: bool = False,+) -> torch.Tensor:+ """+ Helper function to handle parsing logic for building transforms. The output+ is always a tensor of shape (N, 3), but there are several types of allowed+ input.++ Case I: Single Matrix+ In this case x is a tensor of shape (N, 3), and y and z are None. Here just+ return x.++ Case II: Vectors and Scalars+ In this case each of x, y, and z can be one of the following+ - Python scalar+ - Torch scalar+ - Torch tensor of shape (N, 1) or (1, 1)+ In this case x, y and z are broadcast to tensors of shape (N, 1)+ and concatenated to a tensor of shape (N, 3)++ Case III: Singleton (only if allow_singleton=True)+ In this case y and z are None, and x can be one of the following:+ - Python scalar+ - Torch scalar+ - Torch tensor of shape (N, 1) or (1, 1)+ Here x will be duplicated 3 times, and we return a tensor of shape (N, 3)++ Returns:+ xyz: Tensor of shape (N, 3)+ """+ device_ = get_device(x, device)+ # If x is actually a tensor of shape (N, 3) then just return it+ if torch.is_tensor(x) and x.dim() == 2:+ if x.shape[1] != 3:+ msg = "Expected tensor of shape (N, 3); got %r (in %s)"+ raise ValueError(msg % (x.shape, name))+ if y is not None or z is not None:+ msg = "Expected y and z to be None (in %s)" % name+ raise ValueError(msg)+ return x.to(device=device_, dtype=dtype)++ if allow_singleton and y is None and z is None:+ y = x+ z = x++ # Convert all to 1D tensors+ xyz = [_handle_coord(c, dtype, device_) for c in [x, y, z]]++ # Broadcast and concatenate+ sizes = [c.shape[0] for c in xyz]+ N = max(sizes)+ for c in xyz:+ if c.shape[0] != 1 and c.shape[0] != N:+ msg = "Got non-broadcastable sizes %r (in %s)" % (sizes, name)+ raise ValueError(msg)+ xyz = [c.expand(N) for c in xyz]+ xyz = torch.stack(xyz, dim=1)+ return xyzdiff --git a/DPT/requirements.txt b/DPT/requirements.txtnew file mode 100644index 0000000..a41acd4--- /dev/null+++ b/DPT/requirements.txt@@ -0,0 +1,4 @@+# torch==1.8.1+# torchvision==0.9.1+opencv-python==4.5.2.54+timm==0.4.5diff --git a/DPT/run_monodepth.py b/DPT/run_monodepth.pynew file mode 100644index 0000000..cc456bc--- /dev/null+++ b/DPT/run_monodepth.py@@ -0,0 +1,238 @@+"""Compute depth maps for images in the input folder.+"""+import os+import glob+import torch+import cv2+import argparse++import util.io++from torchvision.transforms import Compose++from dpt.models import DPTDepthModel+from dpt.midas_net import MidasNet_large+from dpt.transforms import Resize, NormalizeImage, PrepareForNet++#from util.misc import visualize_attention+++def run(input_path, output_path, model_path, model_type="dpt_hybrid", optimize=True):+ """Run MonoDepthNN to compute depth maps.++ Args:+ input_path (str): path to input folder+ output_path (str): path to output folder+ model_path (str): path to saved model+ """+ print("initialize")++ # select device+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")+ print("device: %s" % device)++ # load network+ if model_type == "dpt_large": # DPT-Large+ net_w = net_h = 384+ model = DPTDepthModel(+ path=model_path,+ backbone="vitl16_384",+ non_negative=True,+ enable_attention_hooks=False,+ )+ normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])+ elif model_type == "dpt_hybrid": # DPT-Hybrid+ net_w = net_h = 384+ model = DPTDepthModel(+ path=model_path,+ backbone="vitb_rn50_384",+ non_negative=True,+ enable_attention_hooks=False,+ )+ normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])+ elif model_type == "dpt_hybrid_kitti":+ net_w = 1216+ net_h = 352++ model = DPTDepthModel(+ path=model_path,+ scale=0.00006016,+ shift=0.00579,+ invert=True,+ backbone="vitb_rn50_384",+ non_negative=True,+ enable_attention_hooks=False,+ )++ normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])+ elif model_type == "dpt_hybrid_nyu":+ net_w = 640+ net_h = 480++ model = DPTDepthModel(+ path=model_path,+ scale=0.000305,+ shift=0.1378,+ invert=True,+ backbone="vitb_rn50_384",+ non_negative=True,+ enable_attention_hooks=False,+ )++ normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])+ elif model_type == "midas_v21": # Convolutional model+ net_w = net_h = 384++ model = MidasNet_large(model_path, non_negative=True)+ normalization = NormalizeImage(+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]+ )+ else:+ assert (+ False+ ), f"model_type '{model_type}' not implemented, use: --model_type [dpt_large|dpt_hybrid|dpt_hybrid_kitti|dpt_hybrid_nyu|midas_v21]"++ transform = Compose(+ [+ Resize(+ net_w,+ net_h,+ resize_target=None,+ keep_aspect_ratio=True,+ ensure_multiple_of=32,+ resize_method="minimal",+ image_interpolation_method=cv2.INTER_CUBIC,+ ),+ normalization,+ PrepareForNet(),+ ]+ )++ model.eval()++ if optimize == True and device == torch.device("cuda"):+ model = model.to(memory_format=torch.channels_last)+ model = model.half()++ model.to(device)++ # get input+ img_names = glob.glob(os.path.join(input_path, "*"))+ num_images = len(img_names)++ # create output folder+ os.makedirs(output_path, exist_ok=True)++ print("start processing")+ for ind, img_name in enumerate(img_names):+ if os.path.isdir(img_name):+ continue++ print(" processing {} ({}/{})".format(img_name, ind + 1, num_images))+ # input++ img = util.io.read_image(img_name)++ if args.kitti_crop is True:+ height, width, _ = img.shape+ top = height - 352+ left = (width - 1216) // 2+ img = img[top : top + 352, left : left + 1216, :]++ img_input = transform({"image": img})["image"]++ # compute+ with torch.no_grad():+ sample = torch.from_numpy(img_input).to(device).unsqueeze(0)++ if optimize == True and device == torch.device("cuda"):+ sample = sample.to(memory_format=torch.channels_last)+ sample = sample.half()++ prediction = model.forward(sample)+ prediction = (+ torch.nn.functional.interpolate(+ prediction.unsqueeze(1),+ size=img.shape[:2],+ mode="bicubic",+ align_corners=False,+ )+ .squeeze()+ .cpu()+ .numpy()+ )++ if model_type == "dpt_hybrid_kitti":+ prediction *= 256++ if model_type == "dpt_hybrid_nyu":+ prediction *= 1000.0++ filename = os.path.join(+ output_path, os.path.splitext(os.path.basename(img_name))[0]+ )+ util.io.write_depth(args.model_type, filename, prediction, bits=2, absolute_depth=args.absolute_depth)++ print("finished")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()++ parser.add_argument(+ "-i", "--input_path", default="input", help="folder with input images"+ )++ parser.add_argument(+ "-o",+ "--output_path",+ default="output_monodepth",+ help="folder for output images",+ )++ parser.add_argument(+ "-m", "--model_weights", default=None, help="path to model weights"+ )++ parser.add_argument(+ "-t",+ "--model_type",+ default="dpt_hybrid",+ help="model type [dpt_large|dpt_hybrid|midas_v21]",+ )++ parser.add_argument("--kitti_crop", dest="kitti_crop", action="store_true")+ parser.add_argument("--absolute_depth", dest="absolute_depth", action="store_true")++ parser.add_argument("--optimize", dest="optimize", action="store_true")+ parser.add_argument("--no-optimize", dest="optimize", action="store_false")++ parser.set_defaults(optimize=True)+ parser.set_defaults(kitti_crop=False)+ parser.set_defaults(absolute_depth=False)++ args = parser.parse_args()++ default_models = {+ "midas_v21": "weights/midas_v21-f6b98070.pt",+ "dpt_large": "weights/dpt_large-midas-2f21e586.pt",+ "dpt_hybrid": "weights/dpt_hybrid-midas-501f0c75.pt",+ "dpt_hybrid_kitti": "weights/dpt_hybrid_kitti-cb926ef4.pt",+ "dpt_hybrid_nyu": "weights/dpt_hybrid_nyu-2ce69ec7.pt",+ }++ if args.model_weights is None:+ args.model_weights = default_models[args.model_type]++ # set torch options+ torch.backends.cudnn.enabled = True+ torch.backends.cudnn.benchmark = True++ # compute depth maps+ run(+ args.input_path,+ args.output_path,+ args.model_weights,+ args.model_type,+ args.optimize,+ )diff --git a/DPT/run_segmentation.py b/DPT/run_segmentation.pynew file mode 100644index 0000000..72f9cc6--- /dev/null+++ b/DPT/run_segmentation.py@@ -0,0 +1,163 @@+"""Compute segmentation maps for images in the input folder.+"""+import os+import glob+import cv2+import argparse++import torch+import torch.nn.functional as F++import util.io++from torchvision.transforms import Compose+from dpt.models import DPTSegmentationModel+from dpt.transforms import Resize, NormalizeImage, PrepareForNet+++def run(input_path, output_path, model_path, model_type="dpt_hybrid", optimize=True):+ """Run segmentation network++ Args:+ input_path (str): path to input folder+ output_path (str): path to output folder+ model_path (str): path to saved model+ """+ print("initialize")++ # select device+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")+ print("device: %s" % device)++ net_w = net_h = 480++ # load network+ if model_type == "dpt_large":+ model = DPTSegmentationModel(+ 150,+ path=model_path,+ backbone="vitl16_384",+ )+ elif model_type == "dpt_hybrid":+ model = DPTSegmentationModel(+ 150,+ path=model_path,+ backbone="vitb_rn50_384",+ )+ else:+ assert (+ False+ ), f"model_type '{model_type}' not implemented, use: --model_type [dpt_large|dpt_hybrid]"++ transform = Compose(+ [+ Resize(+ net_w,+ net_h,+ resize_target=None,+ keep_aspect_ratio=True,+ ensure_multiple_of=32,+ resize_method="minimal",+ image_interpolation_method=cv2.INTER_CUBIC,+ ),+ NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),+ PrepareForNet(),+ ]+ )++ model.eval()++ if optimize == True and device == torch.device("cuda"):+ model = model.to(memory_format=torch.channels_last)+ model = model.half()++ model.to(device)++ # get input+ img_names = glob.glob(os.path.join(input_path, "*"))+ num_images = len(img_names)++ # create output folder+ os.makedirs(output_path, exist_ok=True)++ print("start processing")++ for ind, img_name in enumerate(img_names):++ print(" processing {} ({}/{})".format(img_name, ind + 1, num_images))++ # input+ img = util.io.read_image(img_name)+ img_input = transform({"image": img})["image"]++ # compute+ with torch.no_grad():+ sample = torch.from_numpy(img_input).to(device).unsqueeze(0)+ if optimize == True and device == torch.device("cuda"):+ sample = sample.to(memory_format=torch.channels_last)+ sample = sample.half()++ out = model.forward(sample)++ prediction = torch.nn.functional.interpolate(+ out, size=img.shape[:2], mode="bicubic", align_corners=False+ )+ prediction = torch.argmax(prediction, dim=1) + 1+ prediction = prediction.squeeze().cpu().numpy()++ # output+ filename = os.path.join(+ output_path, os.path.splitext(os.path.basename(img_name))[0]+ )+ util.io.write_segm_img(filename, img, prediction, alpha=0.5)++ print("finished")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()++ parser.add_argument(+ "-i", "--input_path", default="input", help="folder with input images"+ )++ parser.add_argument(+ "-o", "--output_path", default="output_semseg", help="folder for output images"+ )++ parser.add_argument(+ "-m",+ "--model_weights",+ default=None,+ help="path to the trained weights of model",+ )++ # 'vit_large', 'vit_hybrid'+ parser.add_argument("-t", "--model_type", default="dpt_hybrid", help="model type")++ parser.add_argument("--optimize", dest="optimize", action="store_true")+ parser.add_argument("--no-optimize", dest="optimize", action="store_false")+ parser.set_defaults(optimize=True)++ args = parser.parse_args()++ default_models = {+ "dpt_large": "weights/dpt_large-ade20k-b12dca68.pt",+ "dpt_hybrid": "weights/dpt_hybrid-ade20k-53898607.pt",+ }++ if args.model_weights is None:+ args.model_weights = default_models[args.model_type]++ # set torch options+ torch.backends.cudnn.enabled = True+ torch.backends.cudnn.benchmark = True++ # compute segmentation maps+ run(+ args.input_path,+ args.output_path,+ args.model_weights,+ args.model_type,+ args.optimize,+ )diff --git a/DPT/setup.py b/DPT/setup.pynew file mode 100644index 0000000..504e3fe--- /dev/null+++ b/DPT/setup.py@@ -0,0 +1,11 @@+import setuptools++__version__ = '0.0.1dev1'++setuptools.setup(+ name='dpt',+ version=__version__,+ packages=setuptools.find_packages(),+ # Only put dependencies that's not depends on cuda directly.+ install_requires=['timm']+)diff --git a/DPT/util/__init__.py b/DPT/util/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/DPT/util/io.py b/DPT/util/io.pynew file mode 100644index 0000000..1bdd250--- /dev/null+++ b/DPT/util/io.py@@ -0,0 +1,298 @@+"""Utils for monoDepth.+"""+import sys+import re+import numpy as np+import cv2+import torch++from PIL import Image+++from .pallete import get_mask_pallete++def read_pfm(path):+ """Read pfm file.++ Args:+ path (str): path to file++ Returns:+ tuple: (data, scale)+ """+ with open(path, "rb") as file:++ color = None+ width = None+ height = None+ scale = None+ endian = None++ header = file.readline().rstrip()+ if header.decode("ascii") == "PF":+ color = True+ elif header.decode("ascii") == "Pf":+ color = False+ else:+ raise Exception("Not a PFM file: " + path)++ dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii"))+ if dim_match:+ width, height = list(map(int, dim_match.groups()))+ else:+ raise Exception("Malformed PFM header.")++ scale = float(file.readline().decode("ascii").rstrip())+ if scale < 0:+ # little-endian+ endian = "<"+ scale = -scale+ else:+ # big-endian+ endian = ">"++ data = np.fromfile(file, endian + "f")+ shape = (height, width, 3) if color else (height, width)++ data = np.reshape(data, shape)+ data = np.flipud(data)++ return data, scale+++def write_pfm(path, image, scale=1):+ """Write pfm file.++ Args:+ path (str): pathto file+ image (array): data+ scale (int, optional): Scale. Defaults to 1.+ """++ with open(path, "wb") as file:+ color = None++ if image.dtype.name != "float32":+ raise Exception("Image dtype must be float32.")++ image = np.flipud(image)++ if len(image.shape) == 3 and image.shape[2] == 3: # color image+ color = True+ elif (+ len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1+ ): # greyscale+ color = False+ else:+ raise Exception("Image must have H x W x 3, H x W x 1 or H x W dimensions.")++ file.write("PF\n" if color else "Pf\n".encode())+ file.write("%d %d\n".encode() % (image.shape[1], image.shape[0]))++ endian = image.dtype.byteorder++ if endian == "<" or endian == "=" and sys.byteorder == "little":+ scale = -scale++ file.write("%f\n".encode() % scale)++ image.tofile(file)+++def read_image(path):+ """Read image and output RGB image (0-1).++ Args:+ path (str): path to file++ Returns:+ array: RGB image (0-1)+ """+ img = cv2.imread(path)++ if img.ndim == 2:+ img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)++ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0++ return img++def resize_img_cv(img, ds_factor, w_out=None, h_out=None):+ h, w = img.shape[:2]+ if w_out is None and h_out is None:+ if ds_factor == 1:+ return img+ if ds_factor > 1:+ interpolation_method = cv2.INTER_LINEAR+ else:+ interpolation_method = cv2.INTER_AREA+ img = cv2.resize(img, (int(w*ds_factor), int(h*ds_factor)), interpolation=interpolation_method)+ else:+ if w_out > w:+ interpolation_method = cv2.INTER_LINEAR+ else:+ interpolation_method = cv2.INTER_AREA+ img = cv2.resize(img, (int(w_out), int(h_out)), interpolation=interpolation_method)+ return img++def resize_image(img):+ """Resize image and make it fit for network.++ Args:+ img (array): image++ Returns:+ tensor: data ready for network+ """+ height_orig = img.shape[0]+ width_orig = img.shape[1]++ if width_orig > height_orig:+ scale = width_orig / 384+ else:+ scale = height_orig / 384++ height = (np.ceil(height_orig / scale / 32) * 32).astype(int)+ width = (np.ceil(width_orig / scale / 32) * 32).astype(int)++ img_resized = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)++ img_resized = (+ torch.from_numpy(np.transpose(img_resized, (2, 0, 1))).contiguous().float()+ )+ img_resized = img_resized.unsqueeze(0)++ return img_resized+++def resize_depth(depth, width, height):+ """Resize depth map and bring to CPU (numpy).++ Args:+ depth (tensor): depth+ width (int): image width+ height (int): image height++ Returns:+ array: processed depth+ """+ depth = torch.squeeze(depth[0, :, :, :]).to("cpu")++ depth_resized = cv2.resize(+ depth.numpy(), (width, height), interpolation=cv2.INTER_CUBIC+ )++ return depth_resized+++def write_depth(model_name, path, depth, bits=1, absolute_depth=False):+ """Write depth map to pfm and png file.++ Args:+ path (str): filepath without extension+ depth (array): depth+ """+ write_pfm(path + "_" + model_name + ".pfm", depth.astype(np.float32))++ if absolute_depth:+ out = depth+ else:+ depth_min = depth.min()+ depth_max = depth.max()++ max_val = (2 ** (8 * bits)) - 1++ if depth_max - depth_min > np.finfo("float").eps:+ out = max_val * (depth - depth_min) / (depth_max - depth_min)+ else:+ out = np.zeros(depth.shape, dtype=depth.dtype)++ if bits == 1:+ cv2.imwrite(path + "_" + model_name + ".png", out.astype("uint8"), [cv2.IMWRITE_PNG_COMPRESSION, 0])+ elif bits == 2:+ cv2.imwrite(path + "_" + model_name + ".png", out.astype("uint16"), [cv2.IMWRITE_PNG_COMPRESSION, 0])++ return++def write_depth_name(path, depth, bits=1, absolute_depth=False):+ """Write depth map to pfm and png file.++ Args:+ path (str): filepath without extension+ depth (array): depth+ """+ write_pfm(path + ".pfm", depth.astype(np.float32))++ if absolute_depth:+ out = depth * 255++ else:+ depth_min = depth.min()+ depth_max = depth.max()++ max_val = (2 ** (8 * bits)) - 1++ if depth_max - depth_min > np.finfo("float").eps:+ out = max_val * (depth - depth_min) / (depth_max - depth_min)+ else:+ out = np.zeros(depth.shape, dtype=depth.dtype)++ if bits == 1:+ cv2.imwrite(path + ".png", out.astype("uint8"), [cv2.IMWRITE_PNG_COMPRESSION, 0])+ elif bits == 2:+ cv2.imwrite(path + ".png", out.astype("uint16"), [cv2.IMWRITE_PNG_COMPRESSION, 0])++ return++def write_mask(path, depth, bits=1, theta=0.6):+ """Write depth mask to png file.++ Args:+ path (str): filepath without extension+ depth (array): depth+ """++ depth_min = depth.min()+ depth_max = depth.max()++ max_val = (2 ** (8 * bits)) - 1++ if depth_max - depth_min > np.finfo("float").eps:+ out = max_val * (depth > theta)+ else:+ out = np.zeros(depth.shape, dtype=depth.dtype)++ if bits == 1:+ cv2.imwrite(path + ".png", out.astype("uint8"), [cv2.IMWRITE_PNG_COMPRESSION, 0])+ elif bits == 2:+ cv2.imwrite(path + ".png", out.astype("uint16"), [cv2.IMWRITE_PNG_COMPRESSION, 0])++ # write sobel++ # gx = cv2.Sobel(depth, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=3)+ # gy = cv2.Sobel(depth, ddepth=cv2.CV_32F, dx=0, dy=1, ksize=3)++ # print(f"gx is {gx.shape}, gy is {gy.shape}")+ # combined = cv2.addWeighted(gx, 0.5, gy, 0.5, 0)+ # cv2.imwrite(path + "_sobel.png", combined.astype("uint16"), [cv2.IMWRITE_PNG_COMPRESSION, 0])+ return out++def write_segm_img(path, image, labels, palette="detail", alpha=0.5):+ """Write depth map to pfm and png file.++ Args:+ path (str): filepath without extension+ image (array): input image+ labels (array): labeling of the image+ """++ mask = get_mask_pallete(labels, "ade20k")++ img = Image.fromarray(np.uint8(255*image)).convert("RGBA")+ seg = mask.convert("RGBA")++ out = Image.blend(img, seg, alpha)++ out.save(path + ".png")++ returndiff --git a/DPT/util/misc.py b/DPT/util/misc.pynew file mode 100644index 0000000..c05304d--- /dev/null+++ b/DPT/util/misc.py@@ -0,0 +1,63 @@+import matplotlib.pyplot as plt++from dpt.vit import get_mean_attention_map++def visualize_attention(input, model, prediction, model_type):+ input = (input + 1.0)/2.0++ attn1 = model.pretrained.attention["attn_1"]+ attn2 = model.pretrained.attention["attn_2"]+ attn3 = model.pretrained.attention["attn_3"]+ attn4 = model.pretrained.attention["attn_4"]++ plt.subplot(3,4,1), plt.imshow(input.squeeze().permute(1,2,0)), plt.title("Input", fontsize=8), plt.axis("off")+ plt.subplot(3,4,2), plt.imshow(prediction), plt.set_cmap("inferno"), plt.title("Prediction", fontsize=8), plt.axis("off")++ if model_type == "dpt_hybrid":+ h = [3,6,9,12]+ else:+ h = [6,12,18,24]++ # upper left+ plt.subplot(345),+ ax1 = plt.imshow(get_mean_attention_map(attn1, 1, input.shape))+ plt.ylabel("Upper left corner", fontsize=8)+ plt.title(f"Layer {h[0]}", fontsize=8)+ gc = plt.gca()+ gc.axes.xaxis.set_ticklabels([])+ gc.axes.yaxis.set_ticklabels([])+ gc.axes.xaxis.set_ticks([])+ gc.axes.yaxis.set_ticks([])+++ plt.subplot(346),+ plt.imshow(get_mean_attention_map(attn2, 1, input.shape))+ plt.title(f"Layer {h[1]}", fontsize=8)+ plt.axis("off"),++ plt.subplot(347),+ plt.imshow(get_mean_attention_map(attn3, 1, input.shape))+ plt.title(f"Layer {h[2]}", fontsize=8)+ plt.axis("off"),+++ plt.subplot(348),+ plt.imshow(get_mean_attention_map(attn4, 1, input.shape))+ plt.title(f"Layer {h[3]}", fontsize=8)+ plt.axis("off"),+++ # lower right+ plt.subplot(3,4,9), plt.imshow(get_mean_attention_map(attn1, -1, input.shape))+ plt.ylabel("Lower right corner", fontsize=8)+ gc = plt.gca()+ gc.axes.xaxis.set_ticklabels([])+ gc.axes.yaxis.set_ticklabels([])+ gc.axes.xaxis.set_ticks([])+ gc.axes.yaxis.set_ticks([])++ plt.subplot(3,4,10), plt.imshow(get_mean_attention_map(attn2, -1, input.shape)), plt.axis("off")+ plt.subplot(3,4,11), plt.imshow(get_mean_attention_map(attn3, -1, input.shape)), plt.axis("off")+ plt.subplot(3,4,12), plt.imshow(get_mean_attention_map(attn4, -1, input.shape)), plt.axis("off")+ plt.tight_layout()+ plt.show()diff --git a/DPT/util/pallete.py b/DPT/util/pallete.pynew file mode 100644index 0000000..995f50c--- /dev/null+++ b/DPT/util/pallete.py@@ -0,0 +1,50 @@+##++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++## Created by: Hang Zhang+## ECE Department, Rutgers University+## Email: [email protected]+## Copyright (c) 2017+##+## This source code is licensed under the MIT-style license found in the+## LICENSE file in the root directory of this source tree+##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++from PIL import Image++def get_mask_pallete(npimg, dataset='detail'):+ """Get image color pallete for visualizing masks"""+ # recovery boundary+ if dataset == 'pascal_voc':+ npimg[npimg==21] = 255+ # put colormap+ out_img = Image.fromarray(npimg.squeeze().astype('uint8'))+ if dataset == 'ade20k':+ out_img.putpalette(adepallete)+ elif dataset == 'citys':+ out_img.putpalette(citypallete)+ elif dataset in ('detail', 'pascal_voc', 'pascal_aug'):+ out_img.putpalette(vocpallete)+ return out_img++def _get_voc_pallete(num_cls):+ n = num_cls+ pallete = [0]*(n*3)+ for j in range(0,n):+ lab = j+ pallete[j*3+0] = 0+ pallete[j*3+1] = 0+ pallete[j*3+2] = 0+ i = 0+ while (lab > 0):+ pallete[j*3+0] |= (((lab >> 0) & 1) << (7-i))+ pallete[j*3+1] |= (((lab >> 1) & 1) << (7-i))+ pallete[j*3+2] |= (((lab >> 2) & 1) << (7-i))+ i = i + 1+ lab >>= 3+ return pallete++vocpallete = _get_voc_pallete(256)++adepallete = [0,0,0,120,120,120,180,120,120,6,230,230,80,50,50,4,200,3,120,120,80,140,140,140,204,5,255,230,230,230,4,250,7,224,5,255,235,255,7,150,5,61,120,120,70,8,255,51,255,6,82,143,255,140,204,255,4,255,51,7,204,70,3,0,102,200,61,230,250,255,6,51,11,102,255,255,7,71,255,9,224,9,7,230,220,220,220,255,9,92,112,9,255,8,255,214,7,255,224,255,184,6,10,255,71,255,41,10,7,255,255,224,255,8,102,8,255,255,61,6,255,194,7,255,122,8,0,255,20,255,8,41,255,5,153,6,51,255,235,12,255,160,150,20,0,163,255,140,140,140,250,10,15,20,255,0,31,255,0,255,31,0,255,224,0,153,255,0,0,0,255,255,71,0,0,235,255,0,173,255,31,0,255,11,200,200,255,82,0,0,255,245,0,61,255,0,255,112,0,255,133,255,0,0,255,163,0,255,102,0,194,255,0,0,143,255,51,255,0,0,82,255,0,255,41,0,255,173,10,0,255,173,255,0,0,255,153,255,92,0,255,0,255,255,0,245,255,0,102,255,173,0,255,0,20,255,184,184,0,31,255,0,255,61,0,71,255,255,0,204,0,255,194,0,255,82,0,10,255,0,112,255,51,0,255,0,194,255,0,122,255,0,255,163,255,153,0,0,255,10,255,112,0,143,255,0,82,0,255,163,255,0,255,235,0,8,184,170,133,0,255,0,255,92,184,0,255,255,0,31,0,184,255,0,214,255,255,0,112,92,255,0,0,224,255,112,224,255,70,184,160,163,0,255,153,0,255,71,255,0,255,0,163,255,204,0,255,0,143,0,255,235,133,255,0,255,0,235,245,0,255,255,0,122,255,245,0,10,190,212,214,255,0,0,204,255,20,0,255,255,255,0,0,153,255,0,41,255,0,255,204,41,0,255,41,255,0,173,0,255,0,245,255,71,0,255,122,0,255,0,255,184,0,92,255,184,255,0,0,133,255,255,214,0,25,194,194,102,255,0,92,0,255]++citypallete = [+128,64,128,244,35,232,70,70,70,102,102,156,190,153,153,153,153,153,250,170,30,220,220,0,107,142,35,152,251,152,70,130,180,220,20,60,255,0,0,0,0,142,0,0,70,0,60,100,0,80,100,0,0,230,119,11,32,128,192,0,0,64,128,128,64,128,0,192,128,128,192,128,64,64,0,192,64,0,64,192,0,192,192,0,64,64,128,192,64,128,64,192,128,192,192,128,0,0,64,128,0,64,0,128,64,128,128,64,0,0,192,128,0,192,0,128,192,128,128,192,64,0,64,192,0,64,64,128,64,192,128,64,64,0,192,192,0,192,64,128,192,192,128,192,0,64,64,128,64,64,0,192,64,128,192,64,0,64,192,128,64,192,0,192,192,128,192,192,64,64,64,192,64,64,64,192,64,192,192,64,64,64,192,192,64,192,64,192,192,192,192,192,32,0,0,160,0,0,32,128,0,160,128,0,32,0,128,160,0,128,32,128,128,160,128,128,96,0,0,224,0,0,96,128,0,224,128,0,96,0,128,224,0,128,96,128,128,224,128,128,32,64,0,160,64,0,32,192,0,160,192,0,32,64,128,160,64,128,32,192,128,160,192,128,96,64,0,224,64,0,96,192,0,224,192,0,96,64,128,224,64,128,96,192,128,224,192,128,32,0,64,160,0,64,32,128,64,160,128,64,32,0,192,160,0,192,32,128,192,160,128,192,96,0,64,224,0,64,96,128,64,224,128,64,96,0,192,224,0,192,96,128,192,224,128,192,32,64,64,160,64,64,32,192,64,160,192,64,32,64,192,160,64,192,32,192,192,160,192,192,96,64,64,224,64,64,96,192,64,224,192,64,96,64,192,224,64,192,96,192,192,224,192,192,0,32,0,128,32,0,0,160,0,128,160,0,0,32,128,128,32,128,0,160,128,128,160,128,64,32,0,192,32,0,64,160,0,192,160,0,64,32,128,192,32,128,64,160,128,192,160,128,0,96,0,128,96,0,0,224,0,128,224,0,0,96,128,128,96,128,0,224,128,128,224,128,64,96,0,192,96,0,64,224,0,192,224,0,64,96,128,192,96,128,64,224,128,192,224,128,0,32,64,128,32,64,0,160,64,128,160,64,0,32,192,128,32,192,0,160,192,128,160,192,64,32,64,192,32,64,64,160,64,192,160,64,64,32,192,192,32,192,64,160,192,192,160,192,0,96,64,128,96,64,0,224,64,128,224,64,0,96,192,128,96,192,0,224,192,128,224,192,64,96,64,192,96,64,64,224,64,192,224,64,64,96,192,192,96,192,64,224,192,192,224,192,32,32,0,160,32,0,32,160,0,160,160,0,32,32,128,160,32,128,32,160,128,160,160,128,96,32,0,224,32,0,96,160,0,224,160,0,96,32,128,224,32,128,96,160,128,224,160,128,32,96,0,160,96,0,32,224,0,160,224,0,32,96,128,160,96,128,32,224,128,160,224,128,96,96,0,224,96,0,96,224,0,224,224,0,96,96,128,224,96,128,96,224,128,224,224,128,32,32,64,160,32,64,32,160,64,160,160,64,32,32,192,160,32,192,32,160,192,160,160,192,96,32,64,224,32,64,96,160,64,224,160,64,96,32,192,224,32,192,96,160,192,224,160,192,32,96,64,160,96,64,32,224,64,160,224,64,32,96,192,160,96,192,32,224,192,160,224,192,96,96,64,224,96,64,96,224,64,224,224,64,96,96,192,224,96,192,96,224,192,0,0,0]diff --git a/DPT/warp_depth.py b/DPT/warp_depth.pynew file mode 100644index 0000000..f0a1693--- /dev/null+++ b/DPT/warp_depth.py@@ -0,0 +1,323 @@+"""Compute depth maps for images in the input folder.+"""+import os+import glob+import sys+import torch+import cv2+import argparse+import math+import numpy as np+from tqdm import tqdm+sys.path.append('DPT/')+from torchvision.transforms import Compose++from util.io import read_image+from dpt.models import DPTDepthModel+from dpt.midas_net import MidasNet_large+from dpt.transforms import Resize, NormalizeImage, PrepareForNet++from warp_utils import anim_warp_3d, anim_warp_depth_3d+from torchvision.utils import make_grid+#from util.misc import visualize_attention++def tensor_to_img(img, **kwargs):+ grid = make_grid(img, **kwargs)+ ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()+ return ndarr[:, :, ::-1]++def tensor_to_depth(img, **kwargs):+ grid = make_grid(img, **kwargs)+ ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()+ return ndarr[:, :, ::-1]++def run(input_path, output_path, model_path, model_type="dpt_hybrid", optimize=True):+ """Run MonoDepthNN to compute depth maps.++ Args:+ input_path (str): path to input folder+ output_path (str): path to output folder+ model_path (str): path to saved model+ """+ print("initialize")++ # select device+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")+ print("device: %s" % device)++ # load network+ if model_type == "dpt_large": # DPT-Large+ net_w = net_h = 384+ model = DPTDepthModel(+ path=model_path,+ backbone="vitl16_384",+ non_negative=True,+ enable_attention_hooks=False,+ )+ normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])+ elif model_type == "dpt_hybrid": # DPT-Hybrid+ net_w = net_h = 384+ model = DPTDepthModel(+ path=model_path,+ backbone="vitb_rn50_384",+ non_negative=True,+ enable_attention_hooks=False,+ )+ normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])+ elif model_type == "dpt_hybrid_kitti":+ net_w = 1216+ net_h = 352++ model = DPTDepthModel(+ path=model_path,+ scale=0.00006016,+ shift=0.00579,+ invert=True,+ backbone="vitb_rn50_384",+ non_negative=True,+ enable_attention_hooks=False,+ )++ normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])+ elif model_type == "dpt_hybrid_nyu":+ net_w = 640+ net_h = 480++ model = DPTDepthModel(+ path=model_path,+ scale=0.000305,+ shift=0.1378,+ invert=True,+ backbone="vitb_rn50_384",+ non_negative=True,+ enable_attention_hooks=False,+ )++ normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])+ elif model_type == "midas_v21": # Convolutional model+ net_w = net_h = 384++ model = MidasNet_large(model_path, non_negative=True)+ normalization = NormalizeImage(+ mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]+ )+ else:+ assert (+ False+ ), f"model_type '{model_type}' not implemented, use: --model_type [dpt_large|dpt_hybrid|dpt_hybrid_kitti|dpt_hybrid_nyu|midas_v21]"++ transform = Compose(+ [+ Resize(+ net_w,+ net_h,+ resize_target=None,+ keep_aspect_ratio=True,+ ensure_multiple_of=32,+ resize_method="minimal",+ image_interpolation_method=cv2.INTER_CUBIC,+ ),+ normalization,+ PrepareForNet(),+ ]+ )++ ori_transform = Compose(+ [+ Resize(+ 512,+ 512,+ resize_target=None,+ keep_aspect_ratio=True,+ ensure_multiple_of=32,+ resize_method="minimal",+ image_interpolation_method=cv2.INTER_CUBIC,+ ),+ normalization,+ PrepareForNet(),+ ]+ )+ trajectory = []+ k=0+ for t in np.linspace(0, 10, 36):+ tx = 0+ ty = 0+ tz = 0+ rx = 10 * math.cos(2*math.pi*t/10)+ ry = 10 * math.sin(2*math.pi*t/10)+ rz = 0+ trajectory.append((k, tx, ty, tz, rx, ry, rz))+ k+=1++ model.eval()++ if optimize == True and device == torch.device("cuda"):+ model = model.to(memory_format=torch.channels_last)+ model = model.half()++ model.to(device)++ # get input+ # img_names = glob.glob(os.path.join(input_path, "*"))+ # num_images = len(img_names)+ img_name = input_path+ # create output folder+ os.makedirs(output_path, exist_ok=True)++ # print("start processing")+ # for ind, img_name in enumerate(img_names):+ # if os.path.isdir(img_name):+ # continue++ # print(" processing {} ({}/{})".format(img_name, ind + 1, num_images))+ # # input++ img = read_image(img_name)++ img_input = transform({"image": img})["image"]+ img_tensor = ori_transform({"image": img})["image"]+ # compute+ with torch.no_grad():+ sample = torch.from_numpy(img_input).to(device).unsqueeze(0)+ img_tensor = torch.from_numpy(img_tensor).to(device).unsqueeze(0)++ if optimize == True and device == torch.device("cuda"):+ sample = sample.to(memory_format=torch.channels_last)+ sample = sample.half()++ prediction = model.forward(sample) # [1, 384, 384]++ prediction = torch.nn.functional.interpolate(+ prediction.unsqueeze(1),+ size=img.shape[:2],+ mode="bicubic",+ align_corners=False,+ ) # [1, 1, 512, 512]+ # prediction = (prediction - prediction.min()) + 1++ print(prediction.min(), prediction.max())+ print(prediction)+ prediction = (prediction - prediction.min()) / (prediction.max() - prediction.min()) + 0.5+ camera_origin = torch.tensor([0., 0., 0]).to(device)+ rotate_dict = {+ 'Tx': 0,+ 'Ty': 0,+ 'Tz': 0,+ 'Rx': 0,+ 'Ry': 0,+ 'Rz': 0,+ }+ image_frames = []+ depth_frames = []+ fine_name = img_name.replace('png', 'mp4')+ fine_depth_name = img_name.replace('.png', '_depth.mp4')+ for k, tx, ty, tz, rx, ry, rz in tqdm(trajectory):+ rotate_dict['Tx'] = tx+ rotate_dict['Ty'] = ty+ rotate_dict['Tz'] = tz+ rotate_dict['Rx'] = rx+ rotate_dict['Ry'] = ry+ rotate_dict['Rz'] = rz+ # continue+ out_image_tensor, out_depth_tensor = anim_warp_3d(img_tensor, prediction, rotate_dict, camera_origin, device)+ out_image = tensor_to_img(out_image_tensor, normalize=True)+ out_depth = tensor_to_img(out_depth_tensor, normalize=True)+ image_frames.append(out_image)+ depth_frames.append(out_depth)+ # cv2.imwrite('warp_output.png', out_image)+ height, width, layers = image_frames[0].shape+ output_video = cv2.VideoWriter(fine_name, cv2.VideoWriter_fourcc("m", "p", "4", "v"), 24, (width, height))+ output_depth_video = cv2.VideoWriter(fine_depth_name, cv2.VideoWriter_fourcc("m", "p", "4", "v"), 24, (width, height))+ for frame in image_frames:+ output_video.write(np.array(frame))++ for depth_frame in depth_frames:+ output_depth_video.write(np.array(depth_frame))++ output_video.release()+ output_depth_video.release()+++ print("finished")++def warp_depth_fun(input_depth, theta, phi, device):++ theta_180 = theta / math.pi * 180.0 - 90.0+ phi_180 = phi / math.pi * 180.0 - 20.0++ # get input+ prediction = input_depth+ # prediction = (prediction - prediction.min()) + 0.5+ camera_origin = torch.tensor([0., 0., 0]).to(device)+ rotate_dict = {+ 'Tx': 0,+ 'Ty': 0,+ 'Tz': 0,+ 'Rx': theta_180,+ 'Ry': -phi_180,+ 'Rz': 0,+ }+ out_depth_tensor = anim_warp_depth_3d(prediction, rotate_dict, camera_origin, device)++ return out_depth_tensor++if __name__ == "__main__":+ parser = argparse.ArgumentParser()++ parser.add_argument(+ "-i", "--input_path", default="test_img/house.png", help="folder with input images"+ )++ parser.add_argument(+ "-o",+ "--output_path",+ default="output_monodepth",+ help="folder for output images",+ )++ parser.add_argument(+ "-m", "--model_weights", default=None, help="path to model weights"+ )++ parser.add_argument(+ "-t",+ "--model_type",+ default="dpt_hybrid",+ help="model type [dpt_large|dpt_hybrid|midas_v21]",+ )++ parser.add_argument("--kitti_crop", dest="kitti_crop", action="store_true")+ parser.add_argument("--absolute_depth", dest="absolute_depth", action="store_true")++ parser.add_argument("--optimize", dest="optimize", action="store_true")+ parser.add_argument("--no-optimize", dest="optimize", action="store_false")++ parser.set_defaults(optimize=True)+ parser.set_defaults(kitti_crop=False)+ parser.set_defaults(absolute_depth=False)++ args = parser.parse_args()++ default_models = {+ "midas_v21": "DPT/weights/midas_v21-f6b98070.pt",+ "dpt_large": "DPT/weights/dpt_large-midas-2f21e586.pt",+ "dpt_hybrid": "DPT/weights/dpt_hybrid-midas-501f0c75.pt",+ "dpt_hybrid_kitti": "DPT/weights/dpt_hybrid_kitti-cb926ef4.pt",+ "dpt_hybrid_nyu": "DPT/weights/dpt_hybrid_nyu-2ce69ec7.pt",+ }++ if args.model_weights is None:+ args.model_weights = default_models[args.model_type]++ # set torch options+ torch.backends.cudnn.enabled = True+ torch.backends.cudnn.benchmark = True++ # compute depth maps+ run(+ args.input_path,+ args.output_path,+ args.model_weights,+ args.model_type,+ args.optimize,+ )diff --git a/DPT/warp_utils.py b/DPT/warp_utils.pynew file mode 100644index 0000000..538bc59--- /dev/null+++ b/DPT/warp_utils.py@@ -0,0 +1,273 @@+from locale import normalize+import sys, os+import math+import cv2+import numpy as np+import torch+from einops import rearrange+from functools import reduce+from torchvision.utils import save_image+from util.io import write_depth_name+sys.path.extend([+ 'pytorch3d-lite',+])++import py3d_tools as p3d+++def sample_to_cv2(sample: torch.Tensor, type=np.uint8) -> np.ndarray:+ sample_f32 = rearrange(sample.squeeze().cpu().numpy(), "c h w -> h w c").astype(np.float32)+ sample_f32 = ((sample_f32 * 0.5) + 0.5).clip(0, 1)+ sample_int8 = (sample_f32 * 255)+ sample_int8 = cv2.cvtColor(sample_int8, cv2.COLOR_BGR2RGB)+ return sample_int8.astype(type)++def construct_RotationMatrixHomogenous(rotation_angles):+ assert(type(rotation_angles)==list and len(rotation_angles)==3)+ RH = np.eye(4,4)+ cv2.Rodrigues(np.array(rotation_angles), RH[0:3, 0:3])+ return RH++# https://en.wikipedia.org/wiki/Rotation_matrix+def getRotationMatrixManual(rotation_angles):++ rotation_angles = [np.deg2rad(x) for x in rotation_angles]++ phi = rotation_angles[0] # around x+ gamma = rotation_angles[1] # around y+ theta = rotation_angles[2] # around z++ # X rotation+ Rphi = np.eye(4,4)+ sp = np.sin(phi)+ cp = np.cos(phi)+ Rphi[1,1] = cp+ Rphi[2,2] = Rphi[1,1]+ Rphi[1,2] = -sp+ Rphi[2,1] = sp++ # Y rotation+ Rgamma = np.eye(4,4)+ sg = np.sin(gamma)+ cg = np.cos(gamma)+ Rgamma[0,0] = cg+ Rgamma[2,2] = Rgamma[0,0]+ Rgamma[0,2] = sg+ Rgamma[2,0] = -sg++ # Z rotation (in-image-plane)+ Rtheta = np.eye(4,4)+ st = np.sin(theta)+ ct = np.cos(theta)+ Rtheta[0,0] = ct+ Rtheta[1,1] = Rtheta[0,0]+ Rtheta[0,1] = -st+ Rtheta[1,0] = st++ R = reduce(lambda x,y : np.matmul(x,y), [Rphi, Rgamma, Rtheta])++ return R+++def getPoints_for_PerspectiveTranformEstimation(ptsIn, ptsOut, W, H, sidelength):++ ptsIn2D = ptsIn[0,:]+ ptsOut2D = ptsOut[0,:]+ ptsOut2Dlist = []+ ptsIn2Dlist = []++ for i in range(0,4):+ ptsOut2Dlist.append([ptsOut2D[i,0], ptsOut2D[i,1]])+ ptsIn2Dlist.append([ptsIn2D[i,0], ptsIn2D[i,1]])++ pin = np.array(ptsIn2Dlist) + [W/2.,H/2.]+ pout = (np.array(ptsOut2Dlist) + [1.,1.]) * (0.5*sidelength)+ pin = pin.astype(np.float32)+ pout = pout.astype(np.float32)++ return pin, pout++def warpMatrix(W, H, theta, phi, gamma, scale, fV):++ # M is to be estimated+ M = np.eye(4, 4)++ fVhalf = np.deg2rad(fV/2.)+ d = np.sqrt(W*W+H*H)+ sideLength = scale*d/np.cos(fVhalf)+ h = d/(2.0*np.sin(fVhalf))+ n = h-(d/2.0);+ f = h+(d/2.0);++ # Translation along Z-axis by -h+ T = np.eye(4,4)+ T[2,3] = -h++ # Rotation matrices around x,y,z+ R = getRotationMatrixManual([phi, gamma, theta])+++ # Projection Matrix+ P = np.eye(4,4)+ P[0,0] = 1.0/np.tan(fVhalf)+ P[1,1] = P[0,0]+ P[2,2] = -(f+n)/(f-n)+ P[2,3] = -(2.0*f*n)/(f-n)+ P[3,2] = -1.0++ # pythonic matrix multiplication+ F = reduce(lambda x,y : np.matmul(x,y), [P, T, R])++ # shape should be 1,4,3 for ptsIn and ptsOut since perspectiveTransform() expects data in this way.+ # In C++, this can be achieved by Mat ptsIn(1,4,CV_64FC3);+ ptsIn = np.array([[+ [-W/2., H/2., 0.],[ W/2., H/2., 0.],[ W/2.,-H/2., 0.],[-W/2.,-H/2., 0.]+ ]])+ ptsOut = np.array(np.zeros((ptsIn.shape), dtype=ptsIn.dtype))+ ptsOut = cv2.perspectiveTransform(ptsIn, F)++ ptsInPt2f, ptsOutPt2f = getPoints_for_PerspectiveTranformEstimation(ptsIn, ptsOut, W, H, sideLength)++ # check float32 otherwise OpenCV throws an error+ assert(ptsInPt2f.dtype == np.float32)+ assert(ptsOutPt2f.dtype == np.float32)+ M33 = cv2.getPerspectiveTransform(ptsInPt2f,ptsOutPt2f)++ return M33, sideLength++def transform_image_3d(image_tensor, depth_tensor, rot_mat, translate, camera_origin, device):+ # adapted and optimized version of transform_image_3d from Disco Diffusion https://github.com/alembics/disco-diffusion+ # save_image(image_tensor, "warp_input.png", normalize=True)+ prev_img_cv2 = sample_to_cv2(image_tensor, type=np.float32)+ # cv2.imwrite("warp_tmp.png", prev_img_cv2)+ w, h = prev_img_cv2.shape[1], prev_img_cv2.shape[0]++ aspect_ratio = float(w)/float(h)+ near, far, fov_deg = 0.2, 2., 50+ cam_dir = rot_mat @ ((-camera_origin).reshape(1, 3, 1))+ # translate_new = torch.tensor([translate]).to(device) - cam_dir.squeeze(-1)+ translate_new = torch.tensor([translate]).to(device)+ rot_mat_t = rot_mat.transpose(1, 2)+ persp_cam_old = p3d.FoVPerspectiveCameras(near, far, aspect_ratio, fov=fov_deg, degrees=True, device=device)+ persp_cam_new = p3d.FoVPerspectiveCameras(near, far, aspect_ratio, fov=fov_deg, degrees=True, R=rot_mat_t, T=translate_new, device=device)++ # range of [-1,1] is important to torch grid_sample's padding handling+ y,x = torch.meshgrid(torch.linspace(-1.,1.,h,dtype=torch.float32,device=device),torch.linspace(-1.,1.,w,dtype=torch.float32,device=device))+ z = torch.as_tensor(depth_tensor, dtype=torch.float32, device=device)+ # print(z)+ # print(z.min(), z.max())+ # exit()+ xyz_old_world = torch.stack((x.flatten(), y.flatten(), z.flatten()), dim=1)++ xyz_old_cam_xy = persp_cam_old.get_full_projection_transform().transform_points(xyz_old_world)[:,0:2]+ xyz_new_cam_xy = persp_cam_new.get_full_projection_transform().transform_points(xyz_old_world)[:,0:2]+ xyz_new_cam_z = persp_cam_new.get_full_projection_transform().transform_points(xyz_old_world)[:,2]++ offset_xy = xyz_new_cam_xy - xyz_old_cam_xy+ xyz_new_cam_z = xyz_new_cam_z.reshape(1, 1, w, h)+ # warped_depth_cpu = xyz_new_cam_z.cpu().numpy()+ # write_depth_name('warp_depth.png', warped_depth_cpu, bits=2)+ # exit()+ # affine_grid theta param expects a batch of 2D mats. Each is 2x3 to do rotation+translation.+ identity_2d_batch = torch.tensor([[1.,0.,0.],[0.,1.,0.]], device=device).unsqueeze(0)+ # coords_2d will have shape (N,H,W,2).. which is also what grid_sample needs.+ coords_2d = torch.nn.functional.affine_grid(identity_2d_batch, [1,1,h,w], align_corners=False)+ offset_coords_2d = coords_2d - torch.reshape(offset_xy, (h,w,2)).unsqueeze(0)++ # image_tensor = rearrange(torch.from_numpy(prev_img_cv2.astype(np.float32)), 'h w c -> c h w').to(device)+ image_tensor = image_tensor.squeeze(0)+ new_image = torch.nn.functional.grid_sample(+ image_tensor.add(1/512 - 0.0001).unsqueeze(0),+ offset_coords_2d,+ mode="bicubic",+ padding_mode="zeros",+ align_corners=True+ )+ depth_tensor = depth_tensor.squeeze(0)+ new_depth = torch.nn.functional.grid_sample(+ depth_tensor.to(torch.float32).add(1/512 - 0.0001).unsqueeze(0),+ offset_coords_2d,+ mode="bicubic",+ padding_mode="zeros",+ align_corners=True+ )+++ # convert back to cv2 style numpy array+ # result = rearrange(+ # new_image.squeeze().clamp(0,255),+ # 'c h w -> h w c'+ # ).cpu().numpy().astype(prev_img_cv2.dtype)++ return new_image, xyz_new_cam_z++def transform_depth_3d(depth_tensor, rot_mat, translate, camera_origin, device):+ w, h = depth_tensor.shape[2], depth_tensor.shape[3]+ depth_tensor = depth_tensor.to(torch.float32)+ aspect_ratio = float(w)/float(h)+ near, far, fov_deg = 0.2, 2., 100+ cam_dir = rot_mat @ ((-camera_origin).reshape(1, 3, 1))+ # translate_new = torch.tensor([translate]).to(device) - cam_dir.squeeze(-1)+ translate_new = torch.tensor([translate]).to(device).to(torch.float32)+ rot_mat_t = rot_mat.transpose(1, 2)+ persp_cam_old = p3d.FoVPerspectiveCameras(near, far, aspect_ratio, fov=fov_deg, degrees=True, device=device)+ persp_cam_new = p3d.FoVPerspectiveCameras(near, far, aspect_ratio, fov=fov_deg, degrees=True, R=rot_mat_t, T=translate_new, device=device)++ # range of [-1,1] is important to torch grid_sample's padding handling+ y,x = torch.meshgrid(torch.linspace(-1.,1.,h,dtype=torch.float32,device=device),torch.linspace(-1.,1.,w,dtype=torch.float32,device=device))+ z = torch.as_tensor(depth_tensor, dtype=torch.float32, device=device)+ xyz_old_world = torch.stack((x.flatten(), y.flatten(), z.flatten()), dim=1)+ xyz_old_cam_xy = persp_cam_old.get_full_projection_transform().transform_points(xyz_old_world)[:,0:2]+ xyz_new_cam_xy = persp_cam_new.get_full_projection_transform().transform_points(xyz_old_world)[:,0:2]++ offset_xy = xyz_new_cam_xy - xyz_old_cam_xy+ # affine_grid theta param expects a batch of 2D mats. Each is 2x3 to do rotation+translation.+ identity_2d_batch = torch.tensor([[1.,0.,0.],[0.,1.,0.]], device=device).unsqueeze(0)+ # coords_2d will have shape (N,H,W,2).. which is also what grid_sample needs.+ coords_2d = torch.nn.functional.affine_grid(identity_2d_batch, [1,1,h,w], align_corners=False)+ offset_coords_2d = coords_2d - torch.reshape(offset_xy, (h,w,2)).unsqueeze(0)++ depth_tensor = depth_tensor.squeeze(0)+ new_depth = torch.nn.functional.grid_sample(+ depth_tensor.to(torch.float32).add(1/512 - 0.0001).unsqueeze(0),+ offset_coords_2d,+ mode="bicubic",+ padding_mode="border",+ align_corners=True+ )++ return new_depth++def anim_warp_3d(prev_img_cv2, depth, rotate_dict, camera_origin, device):+ TRANSLATION_SCALE = 1.0/200.0 # matches Disco+ translate_xyz = [+ rotate_dict['Tx'] * TRANSLATION_SCALE,+ rotate_dict['Ty'] * TRANSLATION_SCALE,+ -rotate_dict['Tz'] * TRANSLATION_SCALE+ ]+ rotate_xyz = [+ math.radians(rotate_dict['Rx']),+ math.radians(rotate_dict['Ry']),+ math.radians(rotate_dict['Rz'])+ ]+ rot_mat = p3d.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0)+ result, warped_depth = transform_image_3d(prev_img_cv2, depth, rot_mat, translate_xyz, camera_origin, device)+ torch.cuda.empty_cache()+ return result, warped_depth++def anim_warp_depth_3d(depth, rotate_dict, camera_origin, device):+ TRANSLATION_SCALE = 1.0/200.0 # matches Disco+ translate_xyz = [+ rotate_dict['Tx'] * TRANSLATION_SCALE,+ rotate_dict['Ty'] * TRANSLATION_SCALE,+ -rotate_dict['Tz'] * TRANSLATION_SCALE+ ]+ rotate_xyz = [+ math.radians(rotate_dict['Rx']),+ math.radians(rotate_dict['Ry']),+ math.radians(rotate_dict['Rz'])+ ]+ rot_mat = p3d.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0)+ warped_depth = transform_depth_3d(depth, rot_mat.to(torch.float32), translate_xyz, camera_origin, device)+ torch.cuda.empty_cache()+ return warped_depth\ No newline at end of filediff --git a/main.py b/main.pyindex 35c5e0a..df1572b 100644--- a/main.py+++ b/main.py@@ -202,7 +202,7 @@ if __name__ == '__main__':mode="bicubic",align_corners=True,) # [1, 1, 512, 512] [80~150]- DPT.util.io.write_depth(os.path.join(opt.workspace, opt.text.replace(" ", "_") + '_depth'), depth_prediction.squeeze().cpu().numpy(), bits=2)+ DPT.util.io.write_depth_name(os.path.join(opt.workspace, opt.text.replace(" ", "_") + '_depth'), depth_prediction.squeeze().cpu().numpy(), bits=2)disparity = imageio.imread(os.path.join(opt.workspace, opt.text.replace(" ", "_") + '_depth.png')) / 65535.disparity = median_filter(disparity, size=5)depth = 1. / np.maximum(disparity, 1e-2)