backup 06_ovow_code 2026-11-08 10:30:30 (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +8 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/PKG-INFO +5 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/SOURCES.txt +7 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/dependency_links.txt +1 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/top_level.txt +1 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/depth_pro.py +298 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/boundary_metrics.py +332 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/dis5k_sample_list.txt +200 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/__init__.py +2 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/decoder.py +206 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/encoder.py +332 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/fov.py +82 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit.py +123 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit_factory.py +124 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/test_depth_pro.py +27 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/utils.py +112 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/__init__.py +5 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/__init__.py +1 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/hubconf.py +435 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/beit.py +196 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/levit.py +106 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/next_vit.py +39 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin.py +13 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin2.py +34 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin_common.py +52 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/utils.py +249 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/vit.py +221 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/base_model.py +16 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/blocks.py +439 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/dpt_depth.py +166 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net.py +76 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net_custom.py +128 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/model_loader.py +242 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/transforms.py +234 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/__init__.py +24 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/__init__.py +24 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/midas.py +382 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/builder.py +52 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/depth_model.py +152 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/attractor.py +208 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/dist_layers.py +121 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/localbins_layers.py +169 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/patch_transformer.py +91 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/model_io.py +91 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/__init__.py +31 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth.json +58 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth_kitti.json +22 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/zoedepth_v1.py +256 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/__init__.py +31 -0
- OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/config_zoedepth_nk.json +67 -0
.gitattributes
CHANGED
|
@@ -3985,3 +3985,11 @@ PSIVG/PSIVG/data_root/OUT_Simulation/0000/2026-10-31_run/point_cloud/00194.ply f
|
|
| 3985 |
PSIVG/PSIVG/data_root/OUT_Simulation/0000/2026-10-31_run/point_cloud/00195.ply filter=lfs diff=lfs merge=lfs -text
|
| 3986 |
PSIVG/PSIVG/psivg/perception/vipe/vipe_ext.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3987 |
OVOW/engine/oneposeviagen/SAM2-in-video/sam2/_C.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3985 |
PSIVG/PSIVG/data_root/OUT_Simulation/0000/2026-10-31_run/point_cloud/00195.ply filter=lfs diff=lfs merge=lfs -text
|
| 3986 |
PSIVG/PSIVG/psivg/perception/vipe/vipe_ext.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 3987 |
OVOW/engine/oneposeviagen/SAM2-in-video/sam2/_C.so filter=lfs diff=lfs merge=lfs -text
|
| 3988 |
+
OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/city.exr filter=lfs diff=lfs merge=lfs -text
|
| 3989 |
+
OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/courtyard.exr filter=lfs diff=lfs merge=lfs -text
|
| 3990 |
+
OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/forest.exr filter=lfs diff=lfs merge=lfs -text
|
| 3991 |
+
OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/interior.exr filter=lfs diff=lfs merge=lfs -text
|
| 3992 |
+
OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/night.exr filter=lfs diff=lfs merge=lfs -text
|
| 3993 |
+
OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunrise.exr filter=lfs diff=lfs merge=lfs -text
|
| 3994 |
+
OVOW/engine/oneposeviagen/TRELLIS2/assets/hdri/sunset.exr filter=lfs diff=lfs merge=lfs -text
|
| 3995 |
+
OVOW/engine/oneposeviagen/TRELLIS2/o-voxel/o_voxel/_C.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: models
|
| 3 |
+
Version: 0.1
|
| 4 |
+
License-File: LICENSE.txt
|
| 5 |
+
Dynamic: license-file
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
LICENSE.txt
|
| 2 |
+
README.md
|
| 3 |
+
setup.py
|
| 4 |
+
models.egg-info/PKG-INFO
|
| 5 |
+
models.egg-info/SOURCES.txt
|
| 6 |
+
models.egg-info/dependency_links.txt
|
| 7 |
+
models.egg-info/top_level.txt
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/depth_pro.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024 Apple Inc. All Rights Reserved.
|
| 2 |
+
# Depth Pro: Sharp Monocular Metric Depth in Less Than a Second
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Mapping, Optional, Tuple, Union
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch import nn
|
| 12 |
+
from torchvision.transforms import (
|
| 13 |
+
Compose,
|
| 14 |
+
ConvertImageDtype,
|
| 15 |
+
Lambda,
|
| 16 |
+
Normalize,
|
| 17 |
+
ToTensor,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
from .network.decoder import MultiresConvDecoder
|
| 21 |
+
from .network.encoder import DepthProEncoder
|
| 22 |
+
from .network.fov import FOVNetwork
|
| 23 |
+
from .network.vit_factory import VIT_CONFIG_DICT, ViTPreset, create_vit
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class DepthProConfig:
|
| 28 |
+
"""Configuration for DepthPro."""
|
| 29 |
+
|
| 30 |
+
patch_encoder_preset: ViTPreset
|
| 31 |
+
image_encoder_preset: ViTPreset
|
| 32 |
+
decoder_features: int
|
| 33 |
+
|
| 34 |
+
checkpoint_uri: Optional[str] = None
|
| 35 |
+
fov_encoder_preset: Optional[ViTPreset] = None
|
| 36 |
+
use_fov_head: bool = True
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
DEFAULT_MONODEPTH_CONFIG_DICT = DepthProConfig(
|
| 40 |
+
patch_encoder_preset="dinov2l16_384",
|
| 41 |
+
image_encoder_preset="dinov2l16_384",
|
| 42 |
+
checkpoint_uri="./checkpoints/depth_pro.pt",
|
| 43 |
+
decoder_features=256,
|
| 44 |
+
use_fov_head=True,
|
| 45 |
+
fov_encoder_preset="dinov2l16_384",
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def create_backbone_model(
|
| 50 |
+
preset: ViTPreset
|
| 51 |
+
) -> Tuple[nn.Module, ViTPreset]:
|
| 52 |
+
"""Create and load a backbone model given a config.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
----
|
| 56 |
+
preset: A backbone preset to load pre-defind configs.
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
-------
|
| 60 |
+
A Torch module and the associated config.
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
if preset in VIT_CONFIG_DICT:
|
| 64 |
+
config = VIT_CONFIG_DICT[preset]
|
| 65 |
+
model = create_vit(preset=preset, use_pretrained=False)
|
| 66 |
+
else:
|
| 67 |
+
raise KeyError(f"Preset {preset} not found.")
|
| 68 |
+
|
| 69 |
+
return model, config
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def create_model_and_transforms(
|
| 73 |
+
config: DepthProConfig = DEFAULT_MONODEPTH_CONFIG_DICT,
|
| 74 |
+
device: torch.device = torch.device("cpu"),
|
| 75 |
+
precision: torch.dtype = torch.float32,
|
| 76 |
+
) -> Tuple[DepthPro, Compose]:
|
| 77 |
+
"""Create a DepthPro model and load weights from `config.checkpoint_uri`.
|
| 78 |
+
|
| 79 |
+
Args:
|
| 80 |
+
----
|
| 81 |
+
config: The configuration for the DPT model architecture.
|
| 82 |
+
device: The optional Torch device to load the model onto, default runs on "cpu".
|
| 83 |
+
precision: The optional precision used for the model, default is FP32.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
-------
|
| 87 |
+
The Torch DepthPro model and associated Transform.
|
| 88 |
+
|
| 89 |
+
"""
|
| 90 |
+
patch_encoder, patch_encoder_config = create_backbone_model(
|
| 91 |
+
preset=config.patch_encoder_preset
|
| 92 |
+
)
|
| 93 |
+
image_encoder, _ = create_backbone_model(
|
| 94 |
+
preset=config.image_encoder_preset
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
fov_encoder = None
|
| 98 |
+
if config.use_fov_head and config.fov_encoder_preset is not None:
|
| 99 |
+
fov_encoder, _ = create_backbone_model(preset=config.fov_encoder_preset)
|
| 100 |
+
|
| 101 |
+
dims_encoder = patch_encoder_config.encoder_feature_dims
|
| 102 |
+
hook_block_ids = patch_encoder_config.encoder_feature_layer_ids
|
| 103 |
+
encoder = DepthProEncoder(
|
| 104 |
+
dims_encoder=dims_encoder,
|
| 105 |
+
patch_encoder=patch_encoder,
|
| 106 |
+
image_encoder=image_encoder,
|
| 107 |
+
hook_block_ids=hook_block_ids,
|
| 108 |
+
decoder_features=config.decoder_features,
|
| 109 |
+
)
|
| 110 |
+
decoder = MultiresConvDecoder(
|
| 111 |
+
dims_encoder=[config.decoder_features] + list(encoder.dims_encoder),
|
| 112 |
+
dim_decoder=config.decoder_features,
|
| 113 |
+
)
|
| 114 |
+
model = DepthPro(
|
| 115 |
+
encoder=encoder,
|
| 116 |
+
decoder=decoder,
|
| 117 |
+
last_dims=(32, 1),
|
| 118 |
+
use_fov_head=config.use_fov_head,
|
| 119 |
+
fov_encoder=fov_encoder,
|
| 120 |
+
).to(device)
|
| 121 |
+
|
| 122 |
+
if precision == torch.half:
|
| 123 |
+
model.half()
|
| 124 |
+
|
| 125 |
+
transform = Compose(
|
| 126 |
+
[
|
| 127 |
+
ToTensor(),
|
| 128 |
+
Lambda(lambda x: x.to(device)),
|
| 129 |
+
Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
|
| 130 |
+
ConvertImageDtype(precision),
|
| 131 |
+
]
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
if config.checkpoint_uri is not None:
|
| 135 |
+
state_dict = torch.load(config.checkpoint_uri, map_location="cpu")
|
| 136 |
+
missing_keys, unexpected_keys = model.load_state_dict(
|
| 137 |
+
state_dict=state_dict, strict=True
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if len(unexpected_keys) != 0:
|
| 141 |
+
raise KeyError(
|
| 142 |
+
f"Found unexpected keys when loading monodepth: {unexpected_keys}"
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# fc_norm is only for the classification head,
|
| 146 |
+
# which we would not use. We only use the encoding.
|
| 147 |
+
missing_keys = [key for key in missing_keys if "fc_norm" not in key]
|
| 148 |
+
if len(missing_keys) != 0:
|
| 149 |
+
raise KeyError(f"Keys are missing when loading monodepth: {missing_keys}")
|
| 150 |
+
|
| 151 |
+
return model, transform
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class DepthPro(nn.Module):
|
| 155 |
+
"""DepthPro network."""
|
| 156 |
+
|
| 157 |
+
def __init__(
|
| 158 |
+
self,
|
| 159 |
+
encoder: DepthProEncoder,
|
| 160 |
+
decoder: MultiresConvDecoder,
|
| 161 |
+
last_dims: tuple[int, int],
|
| 162 |
+
use_fov_head: bool = True,
|
| 163 |
+
fov_encoder: Optional[nn.Module] = None,
|
| 164 |
+
):
|
| 165 |
+
"""Initialize DepthPro.
|
| 166 |
+
|
| 167 |
+
Args:
|
| 168 |
+
----
|
| 169 |
+
encoder: The DepthProEncoder backbone.
|
| 170 |
+
decoder: The MultiresConvDecoder decoder.
|
| 171 |
+
last_dims: The dimension for the last convolution layers.
|
| 172 |
+
use_fov_head: Whether to use the field-of-view head.
|
| 173 |
+
fov_encoder: A separate encoder for the field of view.
|
| 174 |
+
|
| 175 |
+
"""
|
| 176 |
+
super().__init__()
|
| 177 |
+
|
| 178 |
+
self.encoder = encoder
|
| 179 |
+
self.decoder = decoder
|
| 180 |
+
|
| 181 |
+
dim_decoder = decoder.dim_decoder
|
| 182 |
+
self.head = nn.Sequential(
|
| 183 |
+
nn.Conv2d(
|
| 184 |
+
dim_decoder, dim_decoder // 2, kernel_size=3, stride=1, padding=1
|
| 185 |
+
),
|
| 186 |
+
nn.ConvTranspose2d(
|
| 187 |
+
in_channels=dim_decoder // 2,
|
| 188 |
+
out_channels=dim_decoder // 2,
|
| 189 |
+
kernel_size=2,
|
| 190 |
+
stride=2,
|
| 191 |
+
padding=0,
|
| 192 |
+
bias=True,
|
| 193 |
+
),
|
| 194 |
+
nn.Conv2d(
|
| 195 |
+
dim_decoder // 2,
|
| 196 |
+
last_dims[0],
|
| 197 |
+
kernel_size=3,
|
| 198 |
+
stride=1,
|
| 199 |
+
padding=1,
|
| 200 |
+
),
|
| 201 |
+
nn.ReLU(True),
|
| 202 |
+
nn.Conv2d(last_dims[0], last_dims[1], kernel_size=1, stride=1, padding=0),
|
| 203 |
+
nn.ReLU(),
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# Set the final convolution layer's bias to be 0.
|
| 207 |
+
self.head[4].bias.data.fill_(0)
|
| 208 |
+
|
| 209 |
+
# Set the FOV estimation head.
|
| 210 |
+
if use_fov_head:
|
| 211 |
+
self.fov = FOVNetwork(num_features=dim_decoder, fov_encoder=fov_encoder)
|
| 212 |
+
|
| 213 |
+
@property
|
| 214 |
+
def img_size(self) -> int:
|
| 215 |
+
"""Return the internal image size of the network."""
|
| 216 |
+
return self.encoder.img_size
|
| 217 |
+
|
| 218 |
+
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 219 |
+
"""Decode by projection and fusion of multi-resolution encodings.
|
| 220 |
+
|
| 221 |
+
Args:
|
| 222 |
+
----
|
| 223 |
+
x (torch.Tensor): Input image.
|
| 224 |
+
|
| 225 |
+
Returns:
|
| 226 |
+
-------
|
| 227 |
+
The canonical inverse depth map [m] and the optional estimated field of view [deg].
|
| 228 |
+
|
| 229 |
+
"""
|
| 230 |
+
_, _, H, W = x.shape
|
| 231 |
+
assert H == self.img_size and W == self.img_size
|
| 232 |
+
|
| 233 |
+
encodings = self.encoder(x)
|
| 234 |
+
features, features_0 = self.decoder(encodings)
|
| 235 |
+
canonical_inverse_depth = self.head(features)
|
| 236 |
+
|
| 237 |
+
fov_deg = None
|
| 238 |
+
if hasattr(self, "fov"):
|
| 239 |
+
fov_deg = self.fov.forward(x, features_0.detach())
|
| 240 |
+
|
| 241 |
+
return canonical_inverse_depth, fov_deg
|
| 242 |
+
|
| 243 |
+
@torch.no_grad()
|
| 244 |
+
def infer(
|
| 245 |
+
self,
|
| 246 |
+
x: torch.Tensor,
|
| 247 |
+
f_px: Optional[Union[float, torch.Tensor]] = None,
|
| 248 |
+
interpolation_mode="bilinear",
|
| 249 |
+
) -> Mapping[str, torch.Tensor]:
|
| 250 |
+
"""Infer depth and fov for a given image.
|
| 251 |
+
|
| 252 |
+
If the image is not at network resolution, it is resized to 1536x1536 and
|
| 253 |
+
the estimated depth is resized to the original image resolution.
|
| 254 |
+
Note: if the focal length is given, the estimated value is ignored and the provided
|
| 255 |
+
focal length is use to generate the metric depth values.
|
| 256 |
+
|
| 257 |
+
Args:
|
| 258 |
+
----
|
| 259 |
+
x (torch.Tensor): Input image
|
| 260 |
+
f_px (torch.Tensor): Optional focal length in pixels corresponding to `x`.
|
| 261 |
+
interpolation_mode (str): Interpolation function for downsampling/upsampling.
|
| 262 |
+
|
| 263 |
+
Returns:
|
| 264 |
+
-------
|
| 265 |
+
Tensor dictionary (torch.Tensor): depth [m], focallength [pixels].
|
| 266 |
+
|
| 267 |
+
"""
|
| 268 |
+
if len(x.shape) == 3:
|
| 269 |
+
x = x.unsqueeze(0)
|
| 270 |
+
_, _, H, W = x.shape
|
| 271 |
+
resize = H != self.img_size or W != self.img_size
|
| 272 |
+
|
| 273 |
+
if resize:
|
| 274 |
+
x = nn.functional.interpolate(
|
| 275 |
+
x,
|
| 276 |
+
size=(self.img_size, self.img_size),
|
| 277 |
+
mode=interpolation_mode,
|
| 278 |
+
align_corners=False,
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
canonical_inverse_depth, fov_deg = self.forward(x)
|
| 282 |
+
if f_px is None:
|
| 283 |
+
f_px = 0.5 * W / torch.tan(0.5 * torch.deg2rad(fov_deg.to(torch.float)))
|
| 284 |
+
|
| 285 |
+
inverse_depth = canonical_inverse_depth * (W / f_px)
|
| 286 |
+
f_px = f_px.squeeze()
|
| 287 |
+
|
| 288 |
+
if resize:
|
| 289 |
+
inverse_depth = nn.functional.interpolate(
|
| 290 |
+
inverse_depth, size=(H, W), mode=interpolation_mode, align_corners=False
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
depth = 1.0 / torch.clamp(inverse_depth, min=1e-4, max=1e4)
|
| 294 |
+
|
| 295 |
+
return {
|
| 296 |
+
"depth": depth.squeeze(),
|
| 297 |
+
"focallength_px": f_px,
|
| 298 |
+
}
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/boundary_metrics.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Tuple
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def connected_component(r: np.ndarray, c: np.ndarray) -> List[List[int]]:
|
| 7 |
+
"""Find connected components in the given row and column indices.
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
----
|
| 11 |
+
r (np.ndarray): Row indices.
|
| 12 |
+
c (np.ndarray): Column indices.
|
| 13 |
+
|
| 14 |
+
Yields:
|
| 15 |
+
------
|
| 16 |
+
List[int]: Indices of connected components.
|
| 17 |
+
|
| 18 |
+
"""
|
| 19 |
+
indices = [0]
|
| 20 |
+
for i in range(1, r.size):
|
| 21 |
+
if r[i] == r[indices[-1]] and c[i] == c[indices[-1]] + 1:
|
| 22 |
+
indices.append(i)
|
| 23 |
+
else:
|
| 24 |
+
yield indices
|
| 25 |
+
indices = [i]
|
| 26 |
+
yield indices
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def nms_horizontal(ratio: np.ndarray, threshold: float) -> np.ndarray:
|
| 30 |
+
"""Apply Non-Maximum Suppression (NMS) horizontally on the given ratio matrix.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
----
|
| 34 |
+
ratio (np.ndarray): Input ratio matrix.
|
| 35 |
+
threshold (float): Threshold for NMS.
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
-------
|
| 39 |
+
np.ndarray: Binary mask after applying NMS.
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
mask = np.zeros_like(ratio, dtype=bool)
|
| 43 |
+
r, c = np.nonzero(ratio > threshold)
|
| 44 |
+
if len(r) == 0:
|
| 45 |
+
return mask
|
| 46 |
+
for ids in connected_component(r, c):
|
| 47 |
+
values = [ratio[r[i], c[i]] for i in ids]
|
| 48 |
+
mi = np.argmax(values)
|
| 49 |
+
mask[r[ids[mi]], c[ids[mi]]] = True
|
| 50 |
+
return mask
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def nms_vertical(ratio: np.ndarray, threshold: float) -> np.ndarray:
|
| 54 |
+
"""Apply Non-Maximum Suppression (NMS) vertically on the given ratio matrix.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
----
|
| 58 |
+
ratio (np.ndarray): Input ratio matrix.
|
| 59 |
+
threshold (float): Threshold for NMS.
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
-------
|
| 63 |
+
np.ndarray: Binary mask after applying NMS.
|
| 64 |
+
|
| 65 |
+
"""
|
| 66 |
+
return np.transpose(nms_horizontal(np.transpose(ratio), threshold))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def fgbg_depth(
|
| 70 |
+
d: np.ndarray, t: float
|
| 71 |
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
| 72 |
+
"""Find foreground-background relations between neighboring pixels.
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
----
|
| 76 |
+
d (np.ndarray): Depth matrix.
|
| 77 |
+
t (float): Threshold for comparison.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
-------
|
| 81 |
+
Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: Four matrices indicating
|
| 82 |
+
left, top, right, and bottom foreground-background relations.
|
| 83 |
+
|
| 84 |
+
"""
|
| 85 |
+
right_is_big_enough = (d[..., :, 1:] / d[..., :, :-1]) > t
|
| 86 |
+
left_is_big_enough = (d[..., :, :-1] / d[..., :, 1:]) > t
|
| 87 |
+
bottom_is_big_enough = (d[..., 1:, :] / d[..., :-1, :]) > t
|
| 88 |
+
top_is_big_enough = (d[..., :-1, :] / d[..., 1:, :]) > t
|
| 89 |
+
return (
|
| 90 |
+
left_is_big_enough,
|
| 91 |
+
top_is_big_enough,
|
| 92 |
+
right_is_big_enough,
|
| 93 |
+
bottom_is_big_enough,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def fgbg_depth_thinned(
|
| 98 |
+
d: np.ndarray, t: float
|
| 99 |
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
| 100 |
+
"""Find foreground-background relations between neighboring pixels with Non-Maximum Suppression.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
----
|
| 104 |
+
d (np.ndarray): Depth matrix.
|
| 105 |
+
t (float): Threshold for NMS.
|
| 106 |
+
|
| 107 |
+
Returns:
|
| 108 |
+
-------
|
| 109 |
+
Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: Four matrices indicating
|
| 110 |
+
left, top, right, and bottom foreground-background relations with NMS applied.
|
| 111 |
+
|
| 112 |
+
"""
|
| 113 |
+
right_is_big_enough = nms_horizontal(d[..., :, 1:] / d[..., :, :-1], t)
|
| 114 |
+
left_is_big_enough = nms_horizontal(d[..., :, :-1] / d[..., :, 1:], t)
|
| 115 |
+
bottom_is_big_enough = nms_vertical(d[..., 1:, :] / d[..., :-1, :], t)
|
| 116 |
+
top_is_big_enough = nms_vertical(d[..., :-1, :] / d[..., 1:, :], t)
|
| 117 |
+
return (
|
| 118 |
+
left_is_big_enough,
|
| 119 |
+
top_is_big_enough,
|
| 120 |
+
right_is_big_enough,
|
| 121 |
+
bottom_is_big_enough,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def fgbg_binary_mask(
|
| 126 |
+
d: np.ndarray,
|
| 127 |
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
| 128 |
+
"""Find foreground-background relations between neighboring pixels in binary masks.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
----
|
| 132 |
+
d (np.ndarray): Binary depth matrix.
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
-------
|
| 136 |
+
Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: Four matrices indicating
|
| 137 |
+
left, top, right, and bottom foreground-background relations in binary masks.
|
| 138 |
+
|
| 139 |
+
"""
|
| 140 |
+
assert d.dtype == bool
|
| 141 |
+
right_is_big_enough = d[..., :, 1:] & ~d[..., :, :-1]
|
| 142 |
+
left_is_big_enough = d[..., :, :-1] & ~d[..., :, 1:]
|
| 143 |
+
bottom_is_big_enough = d[..., 1:, :] & ~d[..., :-1, :]
|
| 144 |
+
top_is_big_enough = d[..., :-1, :] & ~d[..., 1:, :]
|
| 145 |
+
return (
|
| 146 |
+
left_is_big_enough,
|
| 147 |
+
top_is_big_enough,
|
| 148 |
+
right_is_big_enough,
|
| 149 |
+
bottom_is_big_enough,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def edge_recall_matting(pr: np.ndarray, gt: np.ndarray, t: float) -> float:
|
| 154 |
+
"""Calculate edge recall for image matting.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
----
|
| 158 |
+
pr (np.ndarray): Predicted depth matrix.
|
| 159 |
+
gt (np.ndarray): Ground truth binary mask.
|
| 160 |
+
t (float): Threshold for NMS.
|
| 161 |
+
|
| 162 |
+
Returns:
|
| 163 |
+
-------
|
| 164 |
+
float: Edge recall value.
|
| 165 |
+
|
| 166 |
+
"""
|
| 167 |
+
assert gt.dtype == bool
|
| 168 |
+
ap, bp, cp, dp = fgbg_depth_thinned(pr, t)
|
| 169 |
+
ag, bg, cg, dg = fgbg_binary_mask(gt)
|
| 170 |
+
return 0.25 * (
|
| 171 |
+
np.count_nonzero(ap & ag) / max(np.count_nonzero(ag), 1)
|
| 172 |
+
+ np.count_nonzero(bp & bg) / max(np.count_nonzero(bg), 1)
|
| 173 |
+
+ np.count_nonzero(cp & cg) / max(np.count_nonzero(cg), 1)
|
| 174 |
+
+ np.count_nonzero(dp & dg) / max(np.count_nonzero(dg), 1)
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def boundary_f1(
|
| 179 |
+
pr: np.ndarray,
|
| 180 |
+
gt: np.ndarray,
|
| 181 |
+
t: float,
|
| 182 |
+
return_p: bool = False,
|
| 183 |
+
return_r: bool = False,
|
| 184 |
+
) -> float:
|
| 185 |
+
"""Calculate Boundary F1 score.
|
| 186 |
+
|
| 187 |
+
Args:
|
| 188 |
+
----
|
| 189 |
+
pr (np.ndarray): Predicted depth matrix.
|
| 190 |
+
gt (np.ndarray): Ground truth depth matrix.
|
| 191 |
+
t (float): Threshold for comparison.
|
| 192 |
+
return_p (bool, optional): If True, return precision. Defaults to False.
|
| 193 |
+
return_r (bool, optional): If True, return recall. Defaults to False.
|
| 194 |
+
|
| 195 |
+
Returns:
|
| 196 |
+
-------
|
| 197 |
+
float: Boundary F1 score, or precision, or recall depending on the flags.
|
| 198 |
+
|
| 199 |
+
"""
|
| 200 |
+
ap, bp, cp, dp = fgbg_depth(pr, t)
|
| 201 |
+
ag, bg, cg, dg = fgbg_depth(gt, t)
|
| 202 |
+
|
| 203 |
+
r = 0.25 * (
|
| 204 |
+
np.count_nonzero(ap & ag) / max(np.count_nonzero(ag), 1)
|
| 205 |
+
+ np.count_nonzero(bp & bg) / max(np.count_nonzero(bg), 1)
|
| 206 |
+
+ np.count_nonzero(cp & cg) / max(np.count_nonzero(cg), 1)
|
| 207 |
+
+ np.count_nonzero(dp & dg) / max(np.count_nonzero(dg), 1)
|
| 208 |
+
)
|
| 209 |
+
p = 0.25 * (
|
| 210 |
+
np.count_nonzero(ap & ag) / max(np.count_nonzero(ap), 1)
|
| 211 |
+
+ np.count_nonzero(bp & bg) / max(np.count_nonzero(bp), 1)
|
| 212 |
+
+ np.count_nonzero(cp & cg) / max(np.count_nonzero(cp), 1)
|
| 213 |
+
+ np.count_nonzero(dp & dg) / max(np.count_nonzero(dp), 1)
|
| 214 |
+
)
|
| 215 |
+
if r + p == 0:
|
| 216 |
+
return 0.0
|
| 217 |
+
if return_p:
|
| 218 |
+
return p
|
| 219 |
+
if return_r:
|
| 220 |
+
return r
|
| 221 |
+
return 2 * (r * p) / (r + p)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def get_thresholds_and_weights(
|
| 225 |
+
t_min: float, t_max: float, N: int
|
| 226 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 227 |
+
"""Generate thresholds and weights for the given range.
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
----
|
| 231 |
+
t_min (float): Minimum threshold.
|
| 232 |
+
t_max (float): Maximum threshold.
|
| 233 |
+
N (int): Number of thresholds.
|
| 234 |
+
|
| 235 |
+
Returns:
|
| 236 |
+
-------
|
| 237 |
+
Tuple[np.ndarray, np.ndarray]: Array of thresholds and corresponding weights.
|
| 238 |
+
|
| 239 |
+
"""
|
| 240 |
+
thresholds = np.linspace(t_min, t_max, N)
|
| 241 |
+
weights = thresholds / thresholds.sum()
|
| 242 |
+
return thresholds, weights
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def invert_depth(depth: np.ndarray, eps: float = 1e-6) -> np.ndarray:
|
| 246 |
+
"""Inverts a depth map with numerical stability.
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
----
|
| 250 |
+
depth (np.ndarray): Depth map to be inverted.
|
| 251 |
+
eps (float): Minimum value to avoid division by zero (default is 1e-6).
|
| 252 |
+
|
| 253 |
+
Returns:
|
| 254 |
+
-------
|
| 255 |
+
np.ndarray: Inverted depth map.
|
| 256 |
+
|
| 257 |
+
"""
|
| 258 |
+
inverse_depth = 1.0 / depth.clip(min=eps)
|
| 259 |
+
return inverse_depth
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def SI_boundary_F1(
|
| 263 |
+
predicted_depth: np.ndarray,
|
| 264 |
+
target_depth: np.ndarray,
|
| 265 |
+
t_min: float = 1.05,
|
| 266 |
+
t_max: float = 1.25,
|
| 267 |
+
N: int = 10,
|
| 268 |
+
) -> float:
|
| 269 |
+
"""Calculate Scale-Invariant Boundary F1 Score for depth-based ground-truth.
|
| 270 |
+
|
| 271 |
+
Args:
|
| 272 |
+
----
|
| 273 |
+
predicted_depth (np.ndarray): Predicted depth matrix.
|
| 274 |
+
target_depth (np.ndarray): Ground truth depth matrix.
|
| 275 |
+
t_min (float, optional): Minimum threshold. Defaults to 1.05.
|
| 276 |
+
t_max (float, optional): Maximum threshold. Defaults to 1.25.
|
| 277 |
+
N (int, optional): Number of thresholds. Defaults to 10.
|
| 278 |
+
|
| 279 |
+
Returns:
|
| 280 |
+
-------
|
| 281 |
+
float: Scale-Invariant Boundary F1 Score.
|
| 282 |
+
|
| 283 |
+
"""
|
| 284 |
+
assert predicted_depth.ndim == target_depth.ndim == 2
|
| 285 |
+
thresholds, weights = get_thresholds_and_weights(t_min, t_max, N)
|
| 286 |
+
f1_scores = np.array(
|
| 287 |
+
[
|
| 288 |
+
boundary_f1(invert_depth(predicted_depth), invert_depth(target_depth), t)
|
| 289 |
+
for t in thresholds
|
| 290 |
+
]
|
| 291 |
+
)
|
| 292 |
+
return np.sum(f1_scores * weights)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def SI_boundary_Recall(
|
| 296 |
+
predicted_depth: np.ndarray,
|
| 297 |
+
target_mask: np.ndarray,
|
| 298 |
+
t_min: float = 1.05,
|
| 299 |
+
t_max: float = 1.25,
|
| 300 |
+
N: int = 10,
|
| 301 |
+
alpha_threshold: float = 0.1,
|
| 302 |
+
) -> float:
|
| 303 |
+
"""Calculate Scale-Invariant Boundary Recall Score for mask-based ground-truth.
|
| 304 |
+
|
| 305 |
+
Args:
|
| 306 |
+
----
|
| 307 |
+
predicted_depth (np.ndarray): Predicted depth matrix.
|
| 308 |
+
target_mask (np.ndarray): Ground truth binary mask.
|
| 309 |
+
t_min (float, optional): Minimum threshold. Defaults to 1.05.
|
| 310 |
+
t_max (float, optional): Maximum threshold. Defaults to 1.25.
|
| 311 |
+
N (int, optional): Number of thresholds. Defaults to 10.
|
| 312 |
+
alpha_threshold (float, optional): Threshold for alpha masking. Defaults to 0.1.
|
| 313 |
+
|
| 314 |
+
Returns:
|
| 315 |
+
-------
|
| 316 |
+
float: Scale-Invariant Boundary Recall Score.
|
| 317 |
+
|
| 318 |
+
"""
|
| 319 |
+
assert predicted_depth.ndim == target_mask.ndim == 2
|
| 320 |
+
thresholds, weights = get_thresholds_and_weights(t_min, t_max, N)
|
| 321 |
+
thresholded_target = target_mask > alpha_threshold
|
| 322 |
+
|
| 323 |
+
recall_scores = np.array(
|
| 324 |
+
[
|
| 325 |
+
edge_recall_matting(
|
| 326 |
+
invert_depth(predicted_depth), thresholded_target, t=float(t)
|
| 327 |
+
)
|
| 328 |
+
for t in thresholds
|
| 329 |
+
]
|
| 330 |
+
)
|
| 331 |
+
weighted_recall = np.sum(recall_scores * weights)
|
| 332 |
+
return weighted_recall
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/eval/dis5k_sample_list.txt
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
DIS5K/DIS-TE1/im/12#Graphics#4#TrafficSign#8245751856_821be14f86_o.jpg
|
| 2 |
+
DIS5K/DIS-TE1/im/13#Insect#4#Butterfly#16023994688_7ff8cdccb1_o.jpg
|
| 3 |
+
DIS5K/DIS-TE1/im/14#Kitchenware#4#Kitchenware#IMG_20210520_205538.jpg
|
| 4 |
+
DIS5K/DIS-TE1/im/14#Kitchenware#8#SweetStand#4848284981_fc90f54b50_o.jpg
|
| 5 |
+
DIS5K/DIS-TE1/im/17#Non-motor Vehicle#4#Cart#15012855035_d10b57014f_o.jpg
|
| 6 |
+
DIS5K/DIS-TE1/im/2#Aircraft#5#Kite#13104545564_5afceec9bd_o.jpg
|
| 7 |
+
DIS5K/DIS-TE1/im/20#Sports#10#Skateboarding#8472763540_bb2390e928_o.jpg
|
| 8 |
+
DIS5K/DIS-TE1/im/21#Tool#14#Sword#32473146960_dcc6b77848_o.jpg
|
| 9 |
+
DIS5K/DIS-TE1/im/21#Tool#15#Tapeline#9680492386_2d2020f282_o.jpg
|
| 10 |
+
DIS5K/DIS-TE1/im/21#Tool#4#Flag#507752845_ef852100f0_o.jpg
|
| 11 |
+
DIS5K/DIS-TE1/im/21#Tool#6#Key#11966089533_3becd78b44_o.jpg
|
| 12 |
+
DIS5K/DIS-TE1/im/21#Tool#8#Scale#31946428472_d28def471b_o.jpg
|
| 13 |
+
DIS5K/DIS-TE1/im/22#Weapon#4#Rifle#8472656430_3eb908b211_o.jpg
|
| 14 |
+
DIS5K/DIS-TE1/im/8#Electronics#3#Earphone#1177468301_641df8c267_o.jpg
|
| 15 |
+
DIS5K/DIS-TE1/im/8#Electronics#9#MusicPlayer#2235782872_7d47847bb4_o.jpg
|
| 16 |
+
DIS5K/DIS-TE2/im/11#Furniture#13#Ladder#3878434417_2ed740586e_o.jpg
|
| 17 |
+
DIS5K/DIS-TE2/im/13#Insect#1#Ant#27047700955_3b3a1271f8_o.jpg
|
| 18 |
+
DIS5K/DIS-TE2/im/13#Insect#11#Spider#5567179191_38d1f65589_o.jpg
|
| 19 |
+
DIS5K/DIS-TE2/im/13#Insect#8#Locust#5237933769_e6687c05e4_o.jpg
|
| 20 |
+
DIS5K/DIS-TE2/im/14#Kitchenware#2#DishRack#70838854_40cf689da7_o.jpg
|
| 21 |
+
DIS5K/DIS-TE2/im/14#Kitchenware#8#SweetStand#8467929412_fef7f4275d_o.jpg
|
| 22 |
+
DIS5K/DIS-TE2/im/16#Music Instrument#2#Harp#28058219806_28e05ff24a_o.jpg
|
| 23 |
+
DIS5K/DIS-TE2/im/17#Non-motor Vehicle#1#BabyCarriage#29794777180_2e1695a0cf_o.jpg
|
| 24 |
+
DIS5K/DIS-TE2/im/19#Ship#3#Sailboat#22442908623_5977e3becf_o.jpg
|
| 25 |
+
DIS5K/DIS-TE2/im/2#Aircraft#5#Kite#44654358051_1400e71cc4_o.jpg
|
| 26 |
+
DIS5K/DIS-TE2/im/21#Tool#11#Stand#IMG_20210520_205442.jpg
|
| 27 |
+
DIS5K/DIS-TE2/im/21#Tool#17#Tripod#9318977876_34615ec9a0_o.jpg
|
| 28 |
+
DIS5K/DIS-TE2/im/5#Artifact#3#Handcraft#50860882577_8482143b1b_o.jpg
|
| 29 |
+
DIS5K/DIS-TE2/im/8#Electronics#10#Robot#3093360210_fee54dc5c5_o.jpg
|
| 30 |
+
DIS5K/DIS-TE2/im/8#Electronics#6#Microphone#47411477652_6da66cbc10_o.jpg
|
| 31 |
+
DIS5K/DIS-TE3/im/14#Kitchenware#4#Kitchenware#2451122898_ef883175dd_o.jpg
|
| 32 |
+
DIS5K/DIS-TE3/im/15#Machine#4#SewingMachine#9311164128_97ba1d3947_o.jpg
|
| 33 |
+
DIS5K/DIS-TE3/im/16#Music Instrument#2#Harp#7670920550_59e992fd7b_o.jpg
|
| 34 |
+
DIS5K/DIS-TE3/im/17#Non-motor Vehicle#1#BabyCarriage#8389984877_1fddf8715c_o.jpg
|
| 35 |
+
DIS5K/DIS-TE3/im/17#Non-motor Vehicle#3#Carriage#5947122724_98e0fc3d1f_o.jpg
|
| 36 |
+
DIS5K/DIS-TE3/im/2#Aircraft#2#Balloon#2487168092_641505883f_o.jpg
|
| 37 |
+
DIS5K/DIS-TE3/im/2#Aircraft#4#Helicopter#8401177591_06c71c8df2_o.jpg
|
| 38 |
+
DIS5K/DIS-TE3/im/20#Sports#1#Archery#12520003103_faa43ea3e0_o.jpg
|
| 39 |
+
DIS5K/DIS-TE3/im/21#Tool#11#Stand#IMG_20210709_221507.jpg
|
| 40 |
+
DIS5K/DIS-TE3/im/21#Tool#2#Clip#5656649687_63d0c6696d_o.jpg
|
| 41 |
+
DIS5K/DIS-TE3/im/21#Tool#6#Key#12878459244_6387a140ea_o.jpg
|
| 42 |
+
DIS5K/DIS-TE3/im/3#Aquatic#1#Lobster#109214461_f52b4b6093_o.jpg
|
| 43 |
+
DIS5K/DIS-TE3/im/4#Architecture#19#Windmill#20195851863_2627117e0e_o.jpg
|
| 44 |
+
DIS5K/DIS-TE3/im/5#Artifact#2#Cage#5821476369_ea23927487_o.jpg
|
| 45 |
+
DIS5K/DIS-TE3/im/8#Electronics#7#MobileHolder#49732997896_7f53c290b5_o.jpg
|
| 46 |
+
DIS5K/DIS-TE4/im/13#Insect#6#Centipede#15302179708_a267850881_o.jpg
|
| 47 |
+
DIS5K/DIS-TE4/im/17#Non-motor Vehicle#11#Tricycle#5771069105_a3aef6f665_o.jpg
|
| 48 |
+
DIS5K/DIS-TE4/im/17#Non-motor Vehicle#2#Bicycle#4245936196_fdf812dcb7_o.jpg
|
| 49 |
+
DIS5K/DIS-TE4/im/17#Non-motor Vehicle#9#ShoppingCart#4674052920_a5b7a2b236_o.jpg
|
| 50 |
+
DIS5K/DIS-TE4/im/18#Plant#1#Bonsai#3539420884_ca8973e2c0_o.jpg
|
| 51 |
+
DIS5K/DIS-TE4/im/2#Aircraft#6#Parachute#33590416634_9d6f2325e7_o.jpg
|
| 52 |
+
DIS5K/DIS-TE4/im/20#Sports#1#Archery#46924476515_0be1caa684_o.jpg
|
| 53 |
+
DIS5K/DIS-TE4/im/20#Sports#8#Racket#19337607166_dd1985fb59_o.jpg
|
| 54 |
+
DIS5K/DIS-TE4/im/21#Tool#6#Key#3193329588_839b0c74ce_o.jpg
|
| 55 |
+
DIS5K/DIS-TE4/im/5#Artifact#2#Cage#5821886526_0573ba2d0d_o.jpg
|
| 56 |
+
DIS5K/DIS-TE4/im/5#Artifact#3#Handcraft#50105138282_3c1d02c968_o.jpg
|
| 57 |
+
DIS5K/DIS-TE4/im/8#Electronics#1#Antenna#4305034305_874f21a701_o.jpg
|
| 58 |
+
DIS5K/DIS-TR/im/1#Accessories#1#Bag#15554964549_3105e51b6f_o.jpg
|
| 59 |
+
DIS5K/DIS-TR/im/1#Accessories#1#Bag#41104261980_098a6c4a56_o.jpg
|
| 60 |
+
DIS5K/DIS-TR/im/1#Accessories#2#Clothes#2284764037_871b2e8ca4_o.jpg
|
| 61 |
+
DIS5K/DIS-TR/im/1#Accessories#3#Eyeglasses#1824643784_70d0134156_o.jpg
|
| 62 |
+
DIS5K/DIS-TR/im/1#Accessories#3#Eyeglasses#3590020230_37b09a29b3_o.jpg
|
| 63 |
+
DIS5K/DIS-TR/im/1#Accessories#3#Eyeglasses#4809652879_4da8a69f3b_o.jpg
|
| 64 |
+
DIS5K/DIS-TR/im/1#Accessories#3#Eyeglasses#792204934_f9b28f99b4_o.jpg
|
| 65 |
+
DIS5K/DIS-TR/im/1#Accessories#5#Jewelry#13909132974_c4750c5fb7_o.jpg
|
| 66 |
+
DIS5K/DIS-TR/im/1#Accessories#7#Shoe#2483391615_9199ece8d6_o.jpg
|
| 67 |
+
DIS5K/DIS-TR/im/1#Accessories#8#Watch#4343266960_f6633b029b_o.jpg
|
| 68 |
+
DIS5K/DIS-TR/im/10#Frame#2#BicycleFrame#17897573_42964dd104_o.jpg
|
| 69 |
+
DIS5K/DIS-TR/im/10#Frame#5#Rack#15898634812_64807069ff_o.jpg
|
| 70 |
+
DIS5K/DIS-TR/im/10#Frame#5#Rack#23928546819_c184cb0b60_o.jpg
|
| 71 |
+
DIS5K/DIS-TR/im/11#Furniture#19#Shower#6189119596_77bcfe80ee_o.jpg
|
| 72 |
+
DIS5K/DIS-TR/im/11#Furniture#2#Bench#3263647075_9306e280b5_o.jpg
|
| 73 |
+
DIS5K/DIS-TR/im/11#Furniture#5#CoatHanger#12774091054_cd5ff520ef_o.jpg
|
| 74 |
+
DIS5K/DIS-TR/im/11#Furniture#6#DentalChair#13878156865_d0439dcb32_o.jpg
|
| 75 |
+
DIS5K/DIS-TR/im/11#Furniture#9#Easel#5861024714_2070cd480c_o.jpg
|
| 76 |
+
DIS5K/DIS-TR/im/12#Graphics#4#TrafficSign#40621867334_f3c32ec189_o.jpg
|
| 77 |
+
DIS5K/DIS-TR/im/13#Insect#1#Ant#3295038190_db5dd0d4f4_o.jpg
|
| 78 |
+
DIS5K/DIS-TR/im/13#Insect#10#Mosquito#24341339_a88a1dad4c_o.jpg
|
| 79 |
+
DIS5K/DIS-TR/im/13#Insect#11#Spider#27171518270_63b78069ff_o.jpg
|
| 80 |
+
DIS5K/DIS-TR/im/13#Insect#11#Spider#49925050281_fa727c154e_o.jpg
|
| 81 |
+
DIS5K/DIS-TR/im/13#Insect#2#Beatle#279616486_2f1e64f591_o.jpg
|
| 82 |
+
DIS5K/DIS-TR/im/13#Insect#3#Bee#43892067695_82cf3e536b_o.jpg
|
| 83 |
+
DIS5K/DIS-TR/im/13#Insect#6#Centipede#20874281788_3e15c90a1c_o.jpg
|
| 84 |
+
DIS5K/DIS-TR/im/13#Insect#7#Dragonfly#14106671120_1b824d77e4_o.jpg
|
| 85 |
+
DIS5K/DIS-TR/im/13#Insect#8#Locust#21637491048_676ef7c9f7_o.jpg
|
| 86 |
+
DIS5K/DIS-TR/im/13#Insect#9#Mantis#1381120202_9dff6987b2_o.jpg
|
| 87 |
+
DIS5K/DIS-TR/im/14#Kitchenware#1#Cup#12812517473_327d6474b8_o.jpg
|
| 88 |
+
DIS5K/DIS-TR/im/14#Kitchenware#10#WineGlass#6402491641_389275d4d1_o.jpg
|
| 89 |
+
DIS5K/DIS-TR/im/14#Kitchenware#3#Hydrovalve#3129932040_8c05825004_o.jpg
|
| 90 |
+
DIS5K/DIS-TR/im/14#Kitchenware#4#Kitchenware#2881934780_87d5218ebb_o.jpg
|
| 91 |
+
DIS5K/DIS-TR/im/14#Kitchenware#4#Kitchenware#IMG_20210520_205527.jpg
|
| 92 |
+
DIS5K/DIS-TR/im/14#Kitchenware#6#Spoon#32989113501_b69eccf0df_o.jpg
|
| 93 |
+
DIS5K/DIS-TR/im/14#Kitchenware#8#SweetStand#2867322189_c56d1e0b87_o.jpg
|
| 94 |
+
DIS5K/DIS-TR/im/15#Machine#1#Gear#19217846720_f5f2807475_o.jpg
|
| 95 |
+
DIS5K/DIS-TR/im/15#Machine#2#Machine#1620160659_9571b7a7ab_o.jpg
|
| 96 |
+
DIS5K/DIS-TR/im/16#Music Instrument#2#Harp#6012801603_1a6e2c16a6_o.jpg
|
| 97 |
+
DIS5K/DIS-TR/im/16#Music Instrument#5#Trombone#8683292118_d223c17ccb_o.jpg
|
| 98 |
+
DIS5K/DIS-TR/im/16#Music Instrument#6#Trumpet#8393262740_b8c216142c_o.jpg
|
| 99 |
+
DIS5K/DIS-TR/im/16#Music Instrument#8#Violin#1511267391_40e4949d68_o.jpg
|
| 100 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#1#BabyCarriage#6989512997_38b3dbc88b_o.jpg
|
| 101 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#12#Wheel#14627183228_b2d68cf501_o.jpg
|
| 102 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#12#Wheel#2932226475_1b2403e549_o.jpg
|
| 103 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#12#Wheel#5420155648_86459905b8_o.jpg
|
| 104 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#2#Bicycle#IMG_20210513_134904.jpg
|
| 105 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#3#Carriage#3311962551_6f211b7bd6_o.jpg
|
| 106 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#4#Cart#2609732026_baf7fff3a1_o.jpg
|
| 107 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#5#Handcart#5821282211_201cefeaf2_o.jpg
|
| 108 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#7#Mower#5779003232_3bb3ae531a_o.jpg
|
| 109 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#9#ShoppingCart#10051622843_ace07e32b8_o.jpg
|
| 110 |
+
DIS5K/DIS-TR/im/17#Non-motor Vehicle#9#ShoppingCart#8075259294_f23e243849_o.jpg
|
| 111 |
+
DIS5K/DIS-TR/im/18#Plant#2#Tree#44800999741_e377e16dbb_o.jpg
|
| 112 |
+
DIS5K/DIS-TR/im/2#Aircraft#1#Airplane#2631761913_3ac67d0223_o.jpg
|
| 113 |
+
DIS5K/DIS-TR/im/2#Aircraft#1#Airplane#37707911566_e908a261b6_o.jpg
|
| 114 |
+
DIS5K/DIS-TR/im/2#Aircraft#3#HangGlider#2557220131_b8506920c5_o.jpg
|
| 115 |
+
DIS5K/DIS-TR/im/2#Aircraft#4#Helicopter#6215659280_5dbd9b4546_o.jpg
|
| 116 |
+
DIS5K/DIS-TR/im/2#Aircraft#6#Parachute#20185790493_e56fcaf8c6_o.jpg
|
| 117 |
+
DIS5K/DIS-TR/im/20#Sports#1#Archery#3871269982_ae4c59a7eb_o.jpg
|
| 118 |
+
DIS5K/DIS-TR/im/20#Sports#9#RockClimbing#9662433268_51299bc50e_o.jpg
|
| 119 |
+
DIS5K/DIS-TR/im/21#Tool#14#Sword#26258479365_2950d7fa37_o.jpg
|
| 120 |
+
DIS5K/DIS-TR/im/21#Tool#15#Tapeline#15505703447_e0fdeaa5a6_o.jpg
|
| 121 |
+
DIS5K/DIS-TR/im/21#Tool#4#Flag#26678602024_9b665742de_o.jpg
|
| 122 |
+
DIS5K/DIS-TR/im/21#Tool#4#Flag#5774823110_d603ce3cc8_o.jpg
|
| 123 |
+
DIS5K/DIS-TR/im/21#Tool#5#Hook#6867989814_dba18d673c_o.jpg
|
| 124 |
+
DIS5K/DIS-TR/im/22#Weapon#4#Rifle#4451713125_cd91719189_o.jpg
|
| 125 |
+
DIS5K/DIS-TR/im/3#Aquatic#2#Seadragon#4910944581_913139b238_o.jpg
|
| 126 |
+
DIS5K/DIS-TR/im/4#Architecture#12#Scaffold#3661448960_8aff24cc4d_o.jpg
|
| 127 |
+
DIS5K/DIS-TR/im/4#Architecture#13#Sculpture#6385318715_9a88d4eba7_o.jpg
|
| 128 |
+
DIS5K/DIS-TR/im/4#Architecture#17#Well#5011603479_75cf42808a_o.jpg
|
| 129 |
+
DIS5K/DIS-TR/im/5#Artifact#2#Cage#4892828841_7f1bc05682_o.jpg
|
| 130 |
+
DIS5K/DIS-TR/im/5#Artifact#3#Handcraft#15404211628_9e9ff2ce2e_o.jpg
|
| 131 |
+
DIS5K/DIS-TR/im/5#Artifact#3#Handcraft#3200169865_7c84cfcccf_o.jpg
|
| 132 |
+
DIS5K/DIS-TR/im/5#Artifact#3#Handcraft#5859295071_c217e7c22f_o.jpg
|
| 133 |
+
DIS5K/DIS-TR/im/6#Automobile#10#SteeringWheel#17200338026_f1e2122d8e_o.jpg
|
| 134 |
+
DIS5K/DIS-TR/im/6#Automobile#3#Car#3780893425_1a7d275e09_o.jpg
|
| 135 |
+
DIS5K/DIS-TR/im/6#Automobile#5#Crane#15282506502_1b1132a7c3_o.jpg
|
| 136 |
+
DIS5K/DIS-TR/im/7#Electrical#1#Cable#16767791875_8e6df41752_o.jpg
|
| 137 |
+
DIS5K/DIS-TR/im/7#Electrical#1#Cable#3291433361_38747324c4_o.jpg
|
| 138 |
+
DIS5K/DIS-TR/im/7#Electrical#1#Cable#4195104238_12a754c61a_o.jpg
|
| 139 |
+
DIS5K/DIS-TR/im/7#Electrical#1#Cable#49645415132_61e5664ecf_o.jpg
|
| 140 |
+
DIS5K/DIS-TR/im/7#Electrical#1#Cable#IMG_20210521_232406.jpg
|
| 141 |
+
DIS5K/DIS-TR/im/7#Electrical#10#UtilityPole#3298312021_92f431e3e9_o.jpg
|
| 142 |
+
DIS5K/DIS-TR/im/7#Electrical#10#UtilityPole#47950134773_fbfff63f4e_o.jpg
|
| 143 |
+
DIS5K/DIS-TR/im/7#Electrical#11#VacuumCleaner#5448403677_6a29e21881_o.jpg
|
| 144 |
+
DIS5K/DIS-TR/im/7#Electrical#2#CeilingLamp#611568868_680ed5d39f_o.jpg
|
| 145 |
+
DIS5K/DIS-TR/im/7#Electrical#3#Fan#3391683115_990525a693_o.jpg
|
| 146 |
+
DIS5K/DIS-TR/im/7#Electrical#6#StreetLamp#150049122_0692266618_o.jpg
|
| 147 |
+
DIS5K/DIS-TR/im/7#Electrical#9#TransmissionTower#31433908671_7e7e277dfe_o.jpg
|
| 148 |
+
DIS5K/DIS-TR/im/8#Electronics#1#Antenna#8727884873_e0622ee5c4_o.jpg
|
| 149 |
+
DIS5K/DIS-TR/im/8#Electronics#2#Camcorder#4172690390_7e5f280ace_o.jpg
|
| 150 |
+
DIS5K/DIS-TR/im/8#Electronics#3#Earphone#413984555_f290febdf5_o.jpg
|
| 151 |
+
DIS5K/DIS-TR/im/8#Electronics#5#Headset#30574225373_3717ed9fa4_o.jpg
|
| 152 |
+
DIS5K/DIS-TR/im/8#Electronics#6#Microphone#538006482_4aae4f5bd6_o.jpg
|
| 153 |
+
DIS5K/DIS-TR/im/8#Electronics#9#MusicPlayer#1306012480_2ea80d2afd_o.jpg
|
| 154 |
+
DIS5K/DIS-TR/im/9#Entertainment#1#GymEquipment#33071754135_8f3195cbd1_o.jpg
|
| 155 |
+
DIS5K/DIS-TR/im/9#Entertainment#2#KidsPlayground#2305807849_be53d724ea_o.jpg
|
| 156 |
+
DIS5K/DIS-TR/im/9#Entertainment#2#KidsPlayground#3862040422_5bbf903204_o.jpg
|
| 157 |
+
DIS5K/DIS-TR/im/9#Entertainment#3#OutdoorFitnessEquipment#10814507005_3dacaa28b3_o.jpg
|
| 158 |
+
DIS5K/DIS-TR/im/9#Entertainment#4#FerrisWheel#81640293_4b0ee62040_o.jpg
|
| 159 |
+
DIS5K/DIS-TR/im/9#Entertainment#5#Swing#49867339188_08073f4b76_o.jpg
|
| 160 |
+
DIS5K/DIS-VD/im/1#Accessories#1#Bag#6815402415_e01c1a41e6_o.jpg
|
| 161 |
+
DIS5K/DIS-VD/im/1#Accessories#5#Jewelry#2744070193_1486582e8d_o.jpg
|
| 162 |
+
DIS5K/DIS-VD/im/10#Frame#1#BasketballHoop#IMG_20210521_232650.jpg
|
| 163 |
+
DIS5K/DIS-VD/im/10#Frame#5#Rack#6156611713_49ebf12b1e_o.jpg
|
| 164 |
+
DIS5K/DIS-VD/im/11#Furniture#11#Handrail#3276641240_1b84b5af85_o.jpg
|
| 165 |
+
DIS5K/DIS-VD/im/11#Furniture#13#Ladder#33423266_5391cf47e9_o.jpg
|
| 166 |
+
DIS5K/DIS-VD/im/11#Furniture#17#Table#3725111755_4fc101e7ab_o.jpg
|
| 167 |
+
DIS5K/DIS-VD/im/11#Furniture#2#Bench#35556410400_7235b58070_o.jpg
|
| 168 |
+
DIS5K/DIS-VD/im/11#Furniture#4#Chair#3301769985_e49de6739f_o.jpg
|
| 169 |
+
DIS5K/DIS-VD/im/11#Furniture#6#DentalChair#23811071619_2a95c3a688_o.jpg
|
| 170 |
+
DIS5K/DIS-VD/im/11#Furniture#9#Easel#8322807354_df6d56542e_o.jpg
|
| 171 |
+
DIS5K/DIS-VD/im/13#Insect#10#Mosquito#12391674863_0cdf430d3f_o.jpg
|
| 172 |
+
DIS5K/DIS-VD/im/13#Insect#7#Dragonfly#14693028899_344ea118f2_o.jpg
|
| 173 |
+
DIS5K/DIS-VD/im/14#Kitchenware#10#WineGlass#4450148455_8f460f541a_o.jpg
|
| 174 |
+
DIS5K/DIS-VD/im/14#Kitchenware#3#Hydrovalve#IMG_20210520_203410.jpg
|
| 175 |
+
DIS5K/DIS-VD/im/15#Machine#3#PlowHarrow#34521712846_df4babb024_o.jpg
|
| 176 |
+
DIS5K/DIS-VD/im/16#Music Instrument#5#Trombone#6222242743_e7189405cd_o.jpg
|
| 177 |
+
DIS5K/DIS-VD/im/17#Non-motor Vehicle#12#Wheel#25677578797_ea47e1d9e8_o.jpg
|
| 178 |
+
DIS5K/DIS-VD/im/17#Non-motor Vehicle#2#Bicycle#5153474856_21560b081b_o.jpg
|
| 179 |
+
DIS5K/DIS-VD/im/17#Non-motor Vehicle#7#Mower#16992510572_8a6ff27398_o.jpg
|
| 180 |
+
DIS5K/DIS-VD/im/19#Ship#2#Canoe#40571458163_7faf8b73d9_o.jpg
|
| 181 |
+
DIS5K/DIS-VD/im/2#Aircraft#1#Airplane#4270588164_66a619e834_o.jpg
|
| 182 |
+
DIS5K/DIS-VD/im/2#Aircraft#4#Helicopter#86789665_650b94b2ee_o.jpg
|
| 183 |
+
DIS5K/DIS-VD/im/20#Sports#14#Wakesurfing#5589577652_5061c168d2_o.jpg
|
| 184 |
+
DIS5K/DIS-VD/im/21#Tool#10#Spade#37018312543_63b21b0784_o.jpg
|
| 185 |
+
DIS5K/DIS-VD/im/21#Tool#14#Sword#24789047250_42df9bf422_o.jpg
|
| 186 |
+
DIS5K/DIS-VD/im/21#Tool#18#Umbrella#IMG_20210513_140445.jpg
|
| 187 |
+
DIS5K/DIS-VD/im/21#Tool#6#Key#43939732715_5a6e28b518_o.jpg
|
| 188 |
+
DIS5K/DIS-VD/im/22#Weapon#1#Cannon#12758066705_90b54295e7_o.jpg
|
| 189 |
+
DIS5K/DIS-VD/im/22#Weapon#4#Rifle#8019368790_fb6dc469a7_o.jpg
|
| 190 |
+
DIS5K/DIS-VD/im/3#Aquatic#5#Shrimp#2582833427_7a99e7356e_o.jpg
|
| 191 |
+
DIS5K/DIS-VD/im/4#Architecture#12#Scaffold#1013402687_590750354e_o.jpg
|
| 192 |
+
DIS5K/DIS-VD/im/4#Architecture#13#Sculpture#17176841759_272a3ed6e3_o.jpg
|
| 193 |
+
DIS5K/DIS-VD/im/4#Architecture#14#Stair#15079108505_0d11281624_o.jpg
|
| 194 |
+
DIS5K/DIS-VD/im/4#Architecture#19#Windmill#2928111082_ceb3051c04_o.jpg
|
| 195 |
+
DIS5K/DIS-VD/im/4#Architecture#3#Crack#3551574032_17dd106d31_o.jpg
|
| 196 |
+
DIS5K/DIS-VD/im/4#Architecture#5#GasStation#4564307581_c3069bdc62_o.jpg
|
| 197 |
+
DIS5K/DIS-VD/im/4#Architecture#8#ObservationTower#2704526950_d4f0ddc807_o.jpg
|
| 198 |
+
DIS5K/DIS-VD/im/5#Artifact#3#Handcraft#10873642323_1bafce3aa5_o.jpg
|
| 199 |
+
DIS5K/DIS-VD/im/6#Automobile#11#Tractor#8594504006_0c2c557d85_o.jpg
|
| 200 |
+
DIS5K/DIS-VD/im/8#Electronics#3#Earphone#8106454803_1178d867cc_o.jpg
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024 Apple Inc. All Rights Reserved.
|
| 2 |
+
"""Depth Pro network blocks."""
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/decoder.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Copyright (C) 2024 Apple Inc. All Rights Reserved.
|
| 2 |
+
|
| 3 |
+
Dense Prediction Transformer Decoder architecture.
|
| 4 |
+
|
| 5 |
+
Implements a variant of Vision Transformers for Dense Prediction, https://arxiv.org/abs/2103.13413
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from typing import Iterable
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch import nn
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class MultiresConvDecoder(nn.Module):
|
| 17 |
+
"""Decoder for multi-resolution encodings."""
|
| 18 |
+
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
dims_encoder: Iterable[int],
|
| 22 |
+
dim_decoder: int,
|
| 23 |
+
):
|
| 24 |
+
"""Initialize multiresolution convolutional decoder.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
----
|
| 28 |
+
dims_encoder: Expected dims at each level from the encoder.
|
| 29 |
+
dim_decoder: Dim of decoder features.
|
| 30 |
+
|
| 31 |
+
"""
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.dims_encoder = list(dims_encoder)
|
| 34 |
+
self.dim_decoder = dim_decoder
|
| 35 |
+
self.dim_out = dim_decoder
|
| 36 |
+
|
| 37 |
+
num_encoders = len(self.dims_encoder)
|
| 38 |
+
|
| 39 |
+
# At the highest resolution, i.e. level 0, we apply projection w/ 1x1 convolution
|
| 40 |
+
# when the dimensions mismatch. Otherwise we do not do anything, which is
|
| 41 |
+
# the default behavior of monodepth.
|
| 42 |
+
conv0 = (
|
| 43 |
+
nn.Conv2d(self.dims_encoder[0], dim_decoder, kernel_size=1, bias=False)
|
| 44 |
+
if self.dims_encoder[0] != dim_decoder
|
| 45 |
+
else nn.Identity()
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
convs = [conv0]
|
| 49 |
+
for i in range(1, num_encoders):
|
| 50 |
+
convs.append(
|
| 51 |
+
nn.Conv2d(
|
| 52 |
+
self.dims_encoder[i],
|
| 53 |
+
dim_decoder,
|
| 54 |
+
kernel_size=3,
|
| 55 |
+
stride=1,
|
| 56 |
+
padding=1,
|
| 57 |
+
bias=False,
|
| 58 |
+
)
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
self.convs = nn.ModuleList(convs)
|
| 62 |
+
|
| 63 |
+
fusions = []
|
| 64 |
+
for i in range(num_encoders):
|
| 65 |
+
fusions.append(
|
| 66 |
+
FeatureFusionBlock2d(
|
| 67 |
+
num_features=dim_decoder,
|
| 68 |
+
deconv=(i != 0),
|
| 69 |
+
batch_norm=False,
|
| 70 |
+
)
|
| 71 |
+
)
|
| 72 |
+
self.fusions = nn.ModuleList(fusions)
|
| 73 |
+
|
| 74 |
+
def forward(self, encodings: torch.Tensor) -> torch.Tensor:
|
| 75 |
+
"""Decode the multi-resolution encodings."""
|
| 76 |
+
num_levels = len(encodings)
|
| 77 |
+
num_encoders = len(self.dims_encoder)
|
| 78 |
+
|
| 79 |
+
if num_levels != num_encoders:
|
| 80 |
+
raise ValueError(
|
| 81 |
+
f"Got encoder output levels={num_levels}, expected levels={num_encoders+1}."
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
# Project features of different encoder dims to the same decoder dim.
|
| 85 |
+
# Fuse features from the lowest resolution (num_levels-1)
|
| 86 |
+
# to the highest (0).
|
| 87 |
+
features = self.convs[-1](encodings[-1])
|
| 88 |
+
lowres_features = features
|
| 89 |
+
features = self.fusions[-1](features)
|
| 90 |
+
for i in range(num_levels - 2, -1, -1):
|
| 91 |
+
features_i = self.convs[i](encodings[i])
|
| 92 |
+
features = self.fusions[i](features, features_i)
|
| 93 |
+
return features, lowres_features
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class ResidualBlock(nn.Module):
|
| 97 |
+
"""Generic implementation of residual blocks.
|
| 98 |
+
|
| 99 |
+
This implements a generic residual block from
|
| 100 |
+
He et al. - Identity Mappings in Deep Residual Networks (2016),
|
| 101 |
+
https://arxiv.org/abs/1603.05027
|
| 102 |
+
which can be further customized via factory functions.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
def __init__(self, residual: nn.Module, shortcut: nn.Module | None = None) -> None:
|
| 106 |
+
"""Initialize ResidualBlock."""
|
| 107 |
+
super().__init__()
|
| 108 |
+
self.residual = residual
|
| 109 |
+
self.shortcut = shortcut
|
| 110 |
+
|
| 111 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 112 |
+
"""Apply residual block."""
|
| 113 |
+
delta_x = self.residual(x)
|
| 114 |
+
|
| 115 |
+
if self.shortcut is not None:
|
| 116 |
+
x = self.shortcut(x)
|
| 117 |
+
|
| 118 |
+
return x + delta_x
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class FeatureFusionBlock2d(nn.Module):
|
| 122 |
+
"""Feature fusion for DPT."""
|
| 123 |
+
|
| 124 |
+
def __init__(
|
| 125 |
+
self,
|
| 126 |
+
num_features: int,
|
| 127 |
+
deconv: bool = False,
|
| 128 |
+
batch_norm: bool = False,
|
| 129 |
+
):
|
| 130 |
+
"""Initialize feature fusion block.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
----
|
| 134 |
+
num_features: Input and output dimensions.
|
| 135 |
+
deconv: Whether to use deconv before the final output conv.
|
| 136 |
+
batch_norm: Whether to use batch normalization in resnet blocks.
|
| 137 |
+
|
| 138 |
+
"""
|
| 139 |
+
super().__init__()
|
| 140 |
+
|
| 141 |
+
self.resnet1 = self._residual_block(num_features, batch_norm)
|
| 142 |
+
self.resnet2 = self._residual_block(num_features, batch_norm)
|
| 143 |
+
|
| 144 |
+
self.use_deconv = deconv
|
| 145 |
+
if deconv:
|
| 146 |
+
self.deconv = nn.ConvTranspose2d(
|
| 147 |
+
in_channels=num_features,
|
| 148 |
+
out_channels=num_features,
|
| 149 |
+
kernel_size=2,
|
| 150 |
+
stride=2,
|
| 151 |
+
padding=0,
|
| 152 |
+
bias=False,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
self.out_conv = nn.Conv2d(
|
| 156 |
+
num_features,
|
| 157 |
+
num_features,
|
| 158 |
+
kernel_size=1,
|
| 159 |
+
stride=1,
|
| 160 |
+
padding=0,
|
| 161 |
+
bias=True,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 165 |
+
|
| 166 |
+
def forward(self, x0: torch.Tensor, x1: torch.Tensor | None = None) -> torch.Tensor:
|
| 167 |
+
"""Process and fuse input features."""
|
| 168 |
+
x = x0
|
| 169 |
+
|
| 170 |
+
if x1 is not None:
|
| 171 |
+
res = self.resnet1(x1)
|
| 172 |
+
x = self.skip_add.add(x, res)
|
| 173 |
+
|
| 174 |
+
x = self.resnet2(x)
|
| 175 |
+
|
| 176 |
+
if self.use_deconv:
|
| 177 |
+
x = self.deconv(x)
|
| 178 |
+
x = self.out_conv(x)
|
| 179 |
+
|
| 180 |
+
return x
|
| 181 |
+
|
| 182 |
+
@staticmethod
|
| 183 |
+
def _residual_block(num_features: int, batch_norm: bool):
|
| 184 |
+
"""Create a residual block."""
|
| 185 |
+
|
| 186 |
+
def _create_block(dim: int, batch_norm: bool) -> list[nn.Module]:
|
| 187 |
+
layers = [
|
| 188 |
+
nn.ReLU(False),
|
| 189 |
+
nn.Conv2d(
|
| 190 |
+
num_features,
|
| 191 |
+
num_features,
|
| 192 |
+
kernel_size=3,
|
| 193 |
+
stride=1,
|
| 194 |
+
padding=1,
|
| 195 |
+
bias=not batch_norm,
|
| 196 |
+
),
|
| 197 |
+
]
|
| 198 |
+
if batch_norm:
|
| 199 |
+
layers.append(nn.BatchNorm2d(dim))
|
| 200 |
+
return layers
|
| 201 |
+
|
| 202 |
+
residual = nn.Sequential(
|
| 203 |
+
*_create_block(dim=num_features, batch_norm=batch_norm),
|
| 204 |
+
*_create_block(dim=num_features, batch_norm=batch_norm),
|
| 205 |
+
)
|
| 206 |
+
return ResidualBlock(residual)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/encoder.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024 Apple Inc. All Rights Reserved.
|
| 2 |
+
# DepthProEncoder combining patch and image encoders.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
from typing import Iterable, Optional
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class DepthProEncoder(nn.Module):
|
| 15 |
+
"""DepthPro Encoder.
|
| 16 |
+
|
| 17 |
+
An encoder aimed at creating multi-resolution encodings from Vision Transformers.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
dims_encoder: Iterable[int],
|
| 23 |
+
patch_encoder: nn.Module,
|
| 24 |
+
image_encoder: nn.Module,
|
| 25 |
+
hook_block_ids: Iterable[int],
|
| 26 |
+
decoder_features: int,
|
| 27 |
+
):
|
| 28 |
+
"""Initialize DepthProEncoder.
|
| 29 |
+
|
| 30 |
+
The framework
|
| 31 |
+
1. creates an image pyramid,
|
| 32 |
+
2. generates overlapping patches with a sliding window at each pyramid level,
|
| 33 |
+
3. creates batched encodings via vision transformer backbones,
|
| 34 |
+
4. produces multi-resolution encodings.
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
----
|
| 38 |
+
img_size: Backbone image resolution.
|
| 39 |
+
dims_encoder: Dimensions of the encoder at different layers.
|
| 40 |
+
patch_encoder: Backbone used for patches.
|
| 41 |
+
image_encoder: Backbone used for global image encoder.
|
| 42 |
+
hook_block_ids: Hooks to obtain intermediate features for the patch encoder model.
|
| 43 |
+
decoder_features: Number of feature output in the decoder.
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
super().__init__()
|
| 47 |
+
|
| 48 |
+
self.dims_encoder = list(dims_encoder)
|
| 49 |
+
self.patch_encoder = patch_encoder
|
| 50 |
+
self.image_encoder = image_encoder
|
| 51 |
+
self.hook_block_ids = list(hook_block_ids)
|
| 52 |
+
|
| 53 |
+
patch_encoder_embed_dim = patch_encoder.embed_dim
|
| 54 |
+
image_encoder_embed_dim = image_encoder.embed_dim
|
| 55 |
+
|
| 56 |
+
self.out_size = int(
|
| 57 |
+
patch_encoder.patch_embed.img_size[0] // patch_encoder.patch_embed.patch_size[0]
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
def _create_project_upsample_block(
|
| 61 |
+
dim_in: int,
|
| 62 |
+
dim_out: int,
|
| 63 |
+
upsample_layers: int,
|
| 64 |
+
dim_int: Optional[int] = None,
|
| 65 |
+
) -> nn.Module:
|
| 66 |
+
if dim_int is None:
|
| 67 |
+
dim_int = dim_out
|
| 68 |
+
# Projection.
|
| 69 |
+
blocks = [
|
| 70 |
+
nn.Conv2d(
|
| 71 |
+
in_channels=dim_in,
|
| 72 |
+
out_channels=dim_int,
|
| 73 |
+
kernel_size=1,
|
| 74 |
+
stride=1,
|
| 75 |
+
padding=0,
|
| 76 |
+
bias=False,
|
| 77 |
+
)
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
# Upsampling.
|
| 81 |
+
blocks += [
|
| 82 |
+
nn.ConvTranspose2d(
|
| 83 |
+
in_channels=dim_int if i == 0 else dim_out,
|
| 84 |
+
out_channels=dim_out,
|
| 85 |
+
kernel_size=2,
|
| 86 |
+
stride=2,
|
| 87 |
+
padding=0,
|
| 88 |
+
bias=False,
|
| 89 |
+
)
|
| 90 |
+
for i in range(upsample_layers)
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
return nn.Sequential(*blocks)
|
| 94 |
+
|
| 95 |
+
self.upsample_latent0 = _create_project_upsample_block(
|
| 96 |
+
dim_in=patch_encoder_embed_dim,
|
| 97 |
+
dim_int=self.dims_encoder[0],
|
| 98 |
+
dim_out=decoder_features,
|
| 99 |
+
upsample_layers=3,
|
| 100 |
+
)
|
| 101 |
+
self.upsample_latent1 = _create_project_upsample_block(
|
| 102 |
+
dim_in=patch_encoder_embed_dim, dim_out=self.dims_encoder[0], upsample_layers=2
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
self.upsample0 = _create_project_upsample_block(
|
| 106 |
+
dim_in=patch_encoder_embed_dim, dim_out=self.dims_encoder[1], upsample_layers=1
|
| 107 |
+
)
|
| 108 |
+
self.upsample1 = _create_project_upsample_block(
|
| 109 |
+
dim_in=patch_encoder_embed_dim, dim_out=self.dims_encoder[2], upsample_layers=1
|
| 110 |
+
)
|
| 111 |
+
self.upsample2 = _create_project_upsample_block(
|
| 112 |
+
dim_in=patch_encoder_embed_dim, dim_out=self.dims_encoder[3], upsample_layers=1
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
self.upsample_lowres = nn.ConvTranspose2d(
|
| 116 |
+
in_channels=image_encoder_embed_dim,
|
| 117 |
+
out_channels=self.dims_encoder[3],
|
| 118 |
+
kernel_size=2,
|
| 119 |
+
stride=2,
|
| 120 |
+
padding=0,
|
| 121 |
+
bias=True,
|
| 122 |
+
)
|
| 123 |
+
self.fuse_lowres = nn.Conv2d(
|
| 124 |
+
in_channels=(self.dims_encoder[3] + self.dims_encoder[3]),
|
| 125 |
+
out_channels=self.dims_encoder[3],
|
| 126 |
+
kernel_size=1,
|
| 127 |
+
stride=1,
|
| 128 |
+
padding=0,
|
| 129 |
+
bias=True,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# Obtain intermediate outputs of the blocks.
|
| 133 |
+
self.patch_encoder.blocks[self.hook_block_ids[0]].register_forward_hook(
|
| 134 |
+
self._hook0
|
| 135 |
+
)
|
| 136 |
+
self.patch_encoder.blocks[self.hook_block_ids[1]].register_forward_hook(
|
| 137 |
+
self._hook1
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
def _hook0(self, model, input, output):
|
| 141 |
+
self.backbone_highres_hook0 = output
|
| 142 |
+
|
| 143 |
+
def _hook1(self, model, input, output):
|
| 144 |
+
self.backbone_highres_hook1 = output
|
| 145 |
+
|
| 146 |
+
@property
|
| 147 |
+
def img_size(self) -> int:
|
| 148 |
+
"""Return the full image size of the SPN network."""
|
| 149 |
+
return self.patch_encoder.patch_embed.img_size[0] * 4
|
| 150 |
+
|
| 151 |
+
def _create_pyramid(
|
| 152 |
+
self, x: torch.Tensor
|
| 153 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 154 |
+
"""Create a 3-level image pyramid."""
|
| 155 |
+
# Original resolution: 1536 by default.
|
| 156 |
+
x0 = x
|
| 157 |
+
|
| 158 |
+
# Middle resolution: 768 by default.
|
| 159 |
+
x1 = F.interpolate(
|
| 160 |
+
x, size=None, scale_factor=0.5, mode="bilinear", align_corners=False
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# Low resolution: 384 by default, corresponding to the backbone resolution.
|
| 164 |
+
x2 = F.interpolate(
|
| 165 |
+
x, size=None, scale_factor=0.25, mode="bilinear", align_corners=False
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
return x0, x1, x2
|
| 169 |
+
|
| 170 |
+
def split(self, x: torch.Tensor, overlap_ratio: float = 0.25) -> torch.Tensor:
|
| 171 |
+
"""Split the input into small patches with sliding window."""
|
| 172 |
+
patch_size = 384
|
| 173 |
+
patch_stride = int(patch_size * (1 - overlap_ratio))
|
| 174 |
+
|
| 175 |
+
image_size = x.shape[-1]
|
| 176 |
+
steps = int(math.ceil((image_size - patch_size) / patch_stride)) + 1
|
| 177 |
+
|
| 178 |
+
x_patch_list = []
|
| 179 |
+
for j in range(steps):
|
| 180 |
+
j0 = j * patch_stride
|
| 181 |
+
j1 = j0 + patch_size
|
| 182 |
+
|
| 183 |
+
for i in range(steps):
|
| 184 |
+
i0 = i * patch_stride
|
| 185 |
+
i1 = i0 + patch_size
|
| 186 |
+
x_patch_list.append(x[..., j0:j1, i0:i1])
|
| 187 |
+
|
| 188 |
+
return torch.cat(x_patch_list, dim=0)
|
| 189 |
+
|
| 190 |
+
def merge(self, x: torch.Tensor, batch_size: int, padding: int = 3) -> torch.Tensor:
|
| 191 |
+
"""Merge the patched input into a image with sliding window."""
|
| 192 |
+
steps = int(math.sqrt(x.shape[0] // batch_size))
|
| 193 |
+
|
| 194 |
+
idx = 0
|
| 195 |
+
|
| 196 |
+
output_list = []
|
| 197 |
+
for j in range(steps):
|
| 198 |
+
output_row_list = []
|
| 199 |
+
for i in range(steps):
|
| 200 |
+
output = x[batch_size * idx : batch_size * (idx + 1)]
|
| 201 |
+
|
| 202 |
+
if j != 0:
|
| 203 |
+
output = output[..., padding:, :]
|
| 204 |
+
if i != 0:
|
| 205 |
+
output = output[..., :, padding:]
|
| 206 |
+
if j != steps - 1:
|
| 207 |
+
output = output[..., :-padding, :]
|
| 208 |
+
if i != steps - 1:
|
| 209 |
+
output = output[..., :, :-padding]
|
| 210 |
+
|
| 211 |
+
output_row_list.append(output)
|
| 212 |
+
idx += 1
|
| 213 |
+
|
| 214 |
+
output_row = torch.cat(output_row_list, dim=-1)
|
| 215 |
+
output_list.append(output_row)
|
| 216 |
+
output = torch.cat(output_list, dim=-2)
|
| 217 |
+
return output
|
| 218 |
+
|
| 219 |
+
def reshape_feature(
|
| 220 |
+
self, embeddings: torch.Tensor, width, height, cls_token_offset=1
|
| 221 |
+
):
|
| 222 |
+
"""Discard class token and reshape 1D feature map to a 2D grid."""
|
| 223 |
+
b, hw, c = embeddings.shape
|
| 224 |
+
|
| 225 |
+
# Remove class token.
|
| 226 |
+
if cls_token_offset > 0:
|
| 227 |
+
embeddings = embeddings[:, cls_token_offset:, :]
|
| 228 |
+
|
| 229 |
+
# Shape: (batch, height, width, dim) -> (batch, dim, height, width)
|
| 230 |
+
embeddings = embeddings.reshape(b, height, width, c).permute(0, 3, 1, 2)
|
| 231 |
+
return embeddings
|
| 232 |
+
|
| 233 |
+
def forward(self, x: torch.Tensor) -> list[torch.Tensor]:
|
| 234 |
+
"""Encode input at multiple resolutions.
|
| 235 |
+
|
| 236 |
+
Args:
|
| 237 |
+
----
|
| 238 |
+
x (torch.Tensor): Input image.
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
-------
|
| 242 |
+
Multi resolution encoded features.
|
| 243 |
+
|
| 244 |
+
"""
|
| 245 |
+
batch_size = x.shape[0]
|
| 246 |
+
|
| 247 |
+
# Step 0: create a 3-level image pyramid.
|
| 248 |
+
x0, x1, x2 = self._create_pyramid(x)
|
| 249 |
+
|
| 250 |
+
# Step 1: split to create batched overlapped mini-images at the backbone (BeiT/ViT/Dino)
|
| 251 |
+
# resolution.
|
| 252 |
+
# 5x5 @ 384x384 at the highest resolution (1536x1536).
|
| 253 |
+
x0_patches = self.split(x0, overlap_ratio=0.25)
|
| 254 |
+
# 3x3 @ 384x384 at the middle resolution (768x768).
|
| 255 |
+
x1_patches = self.split(x1, overlap_ratio=0.5)
|
| 256 |
+
# 1x1 # 384x384 at the lowest resolution (384x384).
|
| 257 |
+
x2_patches = x2
|
| 258 |
+
|
| 259 |
+
# Concatenate all the sliding window patches and form a batch of size (35=5x5+3x3+1x1).
|
| 260 |
+
x_pyramid_patches = torch.cat(
|
| 261 |
+
(x0_patches, x1_patches, x2_patches),
|
| 262 |
+
dim=0,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
# Step 2: Run the backbone (BeiT) model and get the result of large batch size.
|
| 266 |
+
x_pyramid_encodings = self.patch_encoder(x_pyramid_patches)
|
| 267 |
+
x_pyramid_encodings = self.reshape_feature(
|
| 268 |
+
x_pyramid_encodings, self.out_size, self.out_size
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
# Step 3: merging.
|
| 272 |
+
# Merge highres latent encoding.
|
| 273 |
+
x_latent0_encodings = self.reshape_feature(
|
| 274 |
+
self.backbone_highres_hook0,
|
| 275 |
+
self.out_size,
|
| 276 |
+
self.out_size,
|
| 277 |
+
)
|
| 278 |
+
x_latent0_features = self.merge(
|
| 279 |
+
x_latent0_encodings[: batch_size * 5 * 5], batch_size=batch_size, padding=3
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
x_latent1_encodings = self.reshape_feature(
|
| 283 |
+
self.backbone_highres_hook1,
|
| 284 |
+
self.out_size,
|
| 285 |
+
self.out_size,
|
| 286 |
+
)
|
| 287 |
+
x_latent1_features = self.merge(
|
| 288 |
+
x_latent1_encodings[: batch_size * 5 * 5], batch_size=batch_size, padding=3
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
# Split the 35 batch size from pyramid encoding back into 5x5+3x3+1x1.
|
| 292 |
+
x0_encodings, x1_encodings, x2_encodings = torch.split(
|
| 293 |
+
x_pyramid_encodings,
|
| 294 |
+
[len(x0_patches), len(x1_patches), len(x2_patches)],
|
| 295 |
+
dim=0,
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
# 96x96 feature maps by merging 5x5 @ 24x24 patches with overlaps.
|
| 299 |
+
x0_features = self.merge(x0_encodings, batch_size=batch_size, padding=3)
|
| 300 |
+
|
| 301 |
+
# 48x84 feature maps by merging 3x3 @ 24x24 patches with overlaps.
|
| 302 |
+
x1_features = self.merge(x1_encodings, batch_size=batch_size, padding=6)
|
| 303 |
+
|
| 304 |
+
# 24x24 feature maps.
|
| 305 |
+
x2_features = x2_encodings
|
| 306 |
+
|
| 307 |
+
# Apply the image encoder model.
|
| 308 |
+
x_global_features = self.image_encoder(x2_patches)
|
| 309 |
+
x_global_features = self.reshape_feature(
|
| 310 |
+
x_global_features, self.out_size, self.out_size
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
# Upsample feature maps.
|
| 314 |
+
x_latent0_features = self.upsample_latent0(x_latent0_features)
|
| 315 |
+
x_latent1_features = self.upsample_latent1(x_latent1_features)
|
| 316 |
+
|
| 317 |
+
x0_features = self.upsample0(x0_features)
|
| 318 |
+
x1_features = self.upsample1(x1_features)
|
| 319 |
+
x2_features = self.upsample2(x2_features)
|
| 320 |
+
|
| 321 |
+
x_global_features = self.upsample_lowres(x_global_features)
|
| 322 |
+
x_global_features = self.fuse_lowres(
|
| 323 |
+
torch.cat((x2_features, x_global_features), dim=1)
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
return [
|
| 327 |
+
x_latent0_features,
|
| 328 |
+
x_latent1_features,
|
| 329 |
+
x0_features,
|
| 330 |
+
x1_features,
|
| 331 |
+
x_global_features,
|
| 332 |
+
]
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/fov.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024 Apple Inc. All Rights Reserved.
|
| 2 |
+
# Field of View network architecture.
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch import nn
|
| 8 |
+
from torch.nn import functional as F
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class FOVNetwork(nn.Module):
|
| 12 |
+
"""Field of View estimation network."""
|
| 13 |
+
|
| 14 |
+
def __init__(
|
| 15 |
+
self,
|
| 16 |
+
num_features: int,
|
| 17 |
+
fov_encoder: Optional[nn.Module] = None,
|
| 18 |
+
):
|
| 19 |
+
"""Initialize the Field of View estimation block.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
----
|
| 23 |
+
num_features: Number of features used.
|
| 24 |
+
fov_encoder: Optional encoder to bring additional network capacity.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
super().__init__()
|
| 28 |
+
|
| 29 |
+
# Create FOV head.
|
| 30 |
+
fov_head0 = [
|
| 31 |
+
nn.Conv2d(
|
| 32 |
+
num_features, num_features // 2, kernel_size=3, stride=2, padding=1
|
| 33 |
+
), # 128 x 24 x 24
|
| 34 |
+
nn.ReLU(True),
|
| 35 |
+
]
|
| 36 |
+
fov_head = [
|
| 37 |
+
nn.Conv2d(
|
| 38 |
+
num_features // 2, num_features // 4, kernel_size=3, stride=2, padding=1
|
| 39 |
+
), # 64 x 12 x 12
|
| 40 |
+
nn.ReLU(True),
|
| 41 |
+
nn.Conv2d(
|
| 42 |
+
num_features // 4, num_features // 8, kernel_size=3, stride=2, padding=1
|
| 43 |
+
), # 32 x 6 x 6
|
| 44 |
+
nn.ReLU(True),
|
| 45 |
+
nn.Conv2d(num_features // 8, 1, kernel_size=6, stride=1, padding=0),
|
| 46 |
+
]
|
| 47 |
+
if fov_encoder is not None:
|
| 48 |
+
self.encoder = nn.Sequential(
|
| 49 |
+
fov_encoder, nn.Linear(fov_encoder.embed_dim, num_features // 2)
|
| 50 |
+
)
|
| 51 |
+
self.downsample = nn.Sequential(*fov_head0)
|
| 52 |
+
else:
|
| 53 |
+
fov_head = fov_head0 + fov_head
|
| 54 |
+
self.head = nn.Sequential(*fov_head)
|
| 55 |
+
|
| 56 |
+
def forward(self, x: torch.Tensor, lowres_feature: torch.Tensor) -> torch.Tensor:
|
| 57 |
+
"""Forward the fov network.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
----
|
| 61 |
+
x (torch.Tensor): Input image.
|
| 62 |
+
lowres_feature (torch.Tensor): Low resolution feature.
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
-------
|
| 66 |
+
The field of view tensor.
|
| 67 |
+
|
| 68 |
+
"""
|
| 69 |
+
if hasattr(self, "encoder"):
|
| 70 |
+
x = F.interpolate(
|
| 71 |
+
x,
|
| 72 |
+
size=None,
|
| 73 |
+
scale_factor=0.25,
|
| 74 |
+
mode="bilinear",
|
| 75 |
+
align_corners=False,
|
| 76 |
+
)
|
| 77 |
+
x = self.encoder(x)[:, 1:].permute(0, 2, 1)
|
| 78 |
+
lowres_feature = self.downsample(lowres_feature)
|
| 79 |
+
x = x.reshape_as(lowres_feature) + lowres_feature
|
| 80 |
+
else:
|
| 81 |
+
x = lowres_feature
|
| 82 |
+
return self.head(x)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024 Apple Inc. All Rights Reserved.
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
try:
|
| 5 |
+
from timm.layers import resample_abs_pos_embed
|
| 6 |
+
except ImportError as err:
|
| 7 |
+
print("ImportError: {0}".format(err))
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from torch.utils.checkpoint import checkpoint
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def make_vit_b16_backbone(
|
| 14 |
+
model,
|
| 15 |
+
encoder_feature_dims,
|
| 16 |
+
encoder_feature_layer_ids,
|
| 17 |
+
vit_features,
|
| 18 |
+
start_index=1,
|
| 19 |
+
use_grad_checkpointing=False,
|
| 20 |
+
) -> nn.Module:
|
| 21 |
+
"""Make a ViTb16 backbone for the DPT model."""
|
| 22 |
+
if use_grad_checkpointing:
|
| 23 |
+
model.set_grad_checkpointing()
|
| 24 |
+
|
| 25 |
+
vit_model = nn.Module()
|
| 26 |
+
vit_model.hooks = encoder_feature_layer_ids
|
| 27 |
+
vit_model.model = model
|
| 28 |
+
vit_model.features = encoder_feature_dims
|
| 29 |
+
vit_model.vit_features = vit_features
|
| 30 |
+
vit_model.model.start_index = start_index
|
| 31 |
+
vit_model.model.patch_size = vit_model.model.patch_embed.patch_size
|
| 32 |
+
vit_model.model.is_vit = True
|
| 33 |
+
vit_model.model.forward = vit_model.model.forward_features
|
| 34 |
+
|
| 35 |
+
return vit_model
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def forward_features_eva_fixed(self, x):
|
| 39 |
+
"""Encode features."""
|
| 40 |
+
x = self.patch_embed(x)
|
| 41 |
+
x, rot_pos_embed = self._pos_embed(x)
|
| 42 |
+
for blk in self.blocks:
|
| 43 |
+
if self.grad_checkpointing:
|
| 44 |
+
x = checkpoint(blk, x, rot_pos_embed)
|
| 45 |
+
else:
|
| 46 |
+
x = blk(x, rot_pos_embed)
|
| 47 |
+
x = self.norm(x)
|
| 48 |
+
return x
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def resize_vit(model: nn.Module, img_size) -> nn.Module:
|
| 52 |
+
"""Resample the ViT module to the given size."""
|
| 53 |
+
patch_size = model.patch_embed.patch_size
|
| 54 |
+
model.patch_embed.img_size = img_size
|
| 55 |
+
grid_size = tuple([s // p for s, p in zip(img_size, patch_size)])
|
| 56 |
+
model.patch_embed.grid_size = grid_size
|
| 57 |
+
|
| 58 |
+
pos_embed = resample_abs_pos_embed(
|
| 59 |
+
model.pos_embed,
|
| 60 |
+
grid_size, # img_size
|
| 61 |
+
num_prefix_tokens=(
|
| 62 |
+
0 if getattr(model, "no_embed_class", False) else model.num_prefix_tokens
|
| 63 |
+
),
|
| 64 |
+
)
|
| 65 |
+
model.pos_embed = torch.nn.Parameter(pos_embed)
|
| 66 |
+
|
| 67 |
+
return model
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def resize_patch_embed(model: nn.Module, new_patch_size=(16, 16)) -> nn.Module:
|
| 71 |
+
"""Resample the ViT patch size to the given one."""
|
| 72 |
+
# interpolate patch embedding
|
| 73 |
+
if hasattr(model, "patch_embed"):
|
| 74 |
+
old_patch_size = model.patch_embed.patch_size
|
| 75 |
+
|
| 76 |
+
if (
|
| 77 |
+
new_patch_size[0] != old_patch_size[0]
|
| 78 |
+
or new_patch_size[1] != old_patch_size[1]
|
| 79 |
+
):
|
| 80 |
+
patch_embed_proj = model.patch_embed.proj.weight
|
| 81 |
+
patch_embed_proj_bias = model.patch_embed.proj.bias
|
| 82 |
+
use_bias = True if patch_embed_proj_bias is not None else False
|
| 83 |
+
_, _, h, w = patch_embed_proj.shape
|
| 84 |
+
|
| 85 |
+
new_patch_embed_proj = torch.nn.functional.interpolate(
|
| 86 |
+
patch_embed_proj,
|
| 87 |
+
size=[new_patch_size[0], new_patch_size[1]],
|
| 88 |
+
mode="bicubic",
|
| 89 |
+
align_corners=False,
|
| 90 |
+
)
|
| 91 |
+
new_patch_embed_proj = (
|
| 92 |
+
new_patch_embed_proj * (h / new_patch_size[0]) * (w / new_patch_size[1])
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
model.patch_embed.proj = nn.Conv2d(
|
| 96 |
+
in_channels=model.patch_embed.proj.in_channels,
|
| 97 |
+
out_channels=model.patch_embed.proj.out_channels,
|
| 98 |
+
kernel_size=new_patch_size,
|
| 99 |
+
stride=new_patch_size,
|
| 100 |
+
bias=use_bias,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if use_bias:
|
| 104 |
+
model.patch_embed.proj.bias = patch_embed_proj_bias
|
| 105 |
+
|
| 106 |
+
model.patch_embed.proj.weight = torch.nn.Parameter(new_patch_embed_proj)
|
| 107 |
+
|
| 108 |
+
model.patch_size = new_patch_size
|
| 109 |
+
model.patch_embed.patch_size = new_patch_size
|
| 110 |
+
model.patch_embed.img_size = (
|
| 111 |
+
int(
|
| 112 |
+
model.patch_embed.img_size[0]
|
| 113 |
+
* new_patch_size[0]
|
| 114 |
+
/ old_patch_size[0]
|
| 115 |
+
),
|
| 116 |
+
int(
|
| 117 |
+
model.patch_embed.img_size[1]
|
| 118 |
+
* new_patch_size[1]
|
| 119 |
+
/ old_patch_size[1]
|
| 120 |
+
),
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
return model
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/network/vit_factory.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024 Apple Inc. All Rights Reserved.
|
| 2 |
+
# Factory functions to build and load ViT models.
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import logging
|
| 8 |
+
import types
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Dict, List, Literal, Optional
|
| 11 |
+
|
| 12 |
+
import timm
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
|
| 16 |
+
from .vit import (
|
| 17 |
+
forward_features_eva_fixed,
|
| 18 |
+
make_vit_b16_backbone,
|
| 19 |
+
resize_patch_embed,
|
| 20 |
+
resize_vit,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
LOGGER = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
ViTPreset = Literal[
|
| 27 |
+
"dinov2l16_384",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass
|
| 32 |
+
class ViTConfig:
|
| 33 |
+
"""Configuration for ViT."""
|
| 34 |
+
|
| 35 |
+
in_chans: int
|
| 36 |
+
embed_dim: int
|
| 37 |
+
|
| 38 |
+
img_size: int = 384
|
| 39 |
+
patch_size: int = 16
|
| 40 |
+
|
| 41 |
+
# In case we need to rescale the backbone when loading from timm.
|
| 42 |
+
timm_preset: Optional[str] = None
|
| 43 |
+
timm_img_size: int = 384
|
| 44 |
+
timm_patch_size: int = 16
|
| 45 |
+
|
| 46 |
+
# The following 2 parameters are only used by DPT. See dpt_factory.py.
|
| 47 |
+
encoder_feature_layer_ids: List[int] = None
|
| 48 |
+
"""The layers in the Beit/ViT used to constructs encoder features for DPT."""
|
| 49 |
+
encoder_feature_dims: List[int] = None
|
| 50 |
+
"""The dimension of features of encoder layers from Beit/ViT features for DPT."""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
VIT_CONFIG_DICT: Dict[ViTPreset, ViTConfig] = {
|
| 54 |
+
"dinov2l16_384": ViTConfig(
|
| 55 |
+
in_chans=3,
|
| 56 |
+
embed_dim=1024,
|
| 57 |
+
encoder_feature_layer_ids=[5, 11, 17, 23],
|
| 58 |
+
encoder_feature_dims=[256, 512, 1024, 1024],
|
| 59 |
+
img_size=384,
|
| 60 |
+
patch_size=16,
|
| 61 |
+
timm_preset="vit_large_patch14_dinov2",
|
| 62 |
+
timm_img_size=518,
|
| 63 |
+
timm_patch_size=14,
|
| 64 |
+
),
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def create_vit(
|
| 69 |
+
preset: ViTPreset,
|
| 70 |
+
use_pretrained: bool = False,
|
| 71 |
+
checkpoint_uri: str | None = None,
|
| 72 |
+
use_grad_checkpointing: bool = False,
|
| 73 |
+
) -> nn.Module:
|
| 74 |
+
"""Create and load a VIT backbone module.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
----
|
| 78 |
+
preset: The VIT preset to load the pre-defined config.
|
| 79 |
+
use_pretrained: Load pretrained weights if True, default is False.
|
| 80 |
+
checkpoint_uri: Checkpoint to load the wights from.
|
| 81 |
+
use_grad_checkpointing: Use grandient checkpointing.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
-------
|
| 85 |
+
A Torch ViT backbone module.
|
| 86 |
+
|
| 87 |
+
"""
|
| 88 |
+
config = VIT_CONFIG_DICT[preset]
|
| 89 |
+
|
| 90 |
+
img_size = (config.img_size, config.img_size)
|
| 91 |
+
patch_size = (config.patch_size, config.patch_size)
|
| 92 |
+
|
| 93 |
+
if "eva02" in preset:
|
| 94 |
+
model = timm.create_model(config.timm_preset, pretrained=use_pretrained)
|
| 95 |
+
model.forward_features = types.MethodType(forward_features_eva_fixed, model)
|
| 96 |
+
else:
|
| 97 |
+
model = timm.create_model(
|
| 98 |
+
config.timm_preset, pretrained=use_pretrained, dynamic_img_size=True
|
| 99 |
+
)
|
| 100 |
+
model = make_vit_b16_backbone(
|
| 101 |
+
model,
|
| 102 |
+
encoder_feature_dims=config.encoder_feature_dims,
|
| 103 |
+
encoder_feature_layer_ids=config.encoder_feature_layer_ids,
|
| 104 |
+
vit_features=config.embed_dim,
|
| 105 |
+
use_grad_checkpointing=use_grad_checkpointing,
|
| 106 |
+
)
|
| 107 |
+
if config.patch_size != config.timm_patch_size:
|
| 108 |
+
model.model = resize_patch_embed(model.model, new_patch_size=patch_size)
|
| 109 |
+
if config.img_size != config.timm_img_size:
|
| 110 |
+
model.model = resize_vit(model.model, img_size=img_size)
|
| 111 |
+
|
| 112 |
+
if checkpoint_uri is not None:
|
| 113 |
+
state_dict = torch.load(checkpoint_uri, map_location="cpu")
|
| 114 |
+
missing_keys, unexpected_keys = model.load_state_dict(
|
| 115 |
+
state_dict=state_dict, strict=False
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
if len(unexpected_keys) != 0:
|
| 119 |
+
raise KeyError(f"Found unexpected keys when loading vit: {unexpected_keys}")
|
| 120 |
+
if len(missing_keys) != 0:
|
| 121 |
+
raise KeyError(f"Keys are missing when loading vit: {missing_keys}")
|
| 122 |
+
|
| 123 |
+
LOGGER.info(model)
|
| 124 |
+
return model.model
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/test_depth_pro.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
from models.monoD import depth_pro
|
| 3 |
+
|
| 4 |
+
# Load model and preprocessing transform
|
| 5 |
+
model, transform = depth_pro.create_model_and_transforms()
|
| 6 |
+
model.eval()
|
| 7 |
+
|
| 8 |
+
# Load and preprocess an image.
|
| 9 |
+
image_path = "assets/dance/00000.jpg"
|
| 10 |
+
image, _, f_px = depth_pro.load_rgb(image_path)
|
| 11 |
+
image = transform(image)
|
| 12 |
+
|
| 13 |
+
# Run inference.
|
| 14 |
+
import time
|
| 15 |
+
t0 = time.time()
|
| 16 |
+
prediction = model.infer(image, f_px=f_px)
|
| 17 |
+
depth = prediction["depth"] # Depth in [m].
|
| 18 |
+
focallength_px = prediction["focallength_px"] # Focal length in pixels.
|
| 19 |
+
import cv2
|
| 20 |
+
import numpy as np
|
| 21 |
+
depth = depth.clamp(0,30).squeeze().detach().cpu().numpy()
|
| 22 |
+
depth = (depth - depth.min())/(depth.max()-depth.min()) * 255.0
|
| 23 |
+
depth = depth.astype(np.uint8)
|
| 24 |
+
depth = cv2.applyColorMap(depth, cv2.COLORMAP_INFERNO)
|
| 25 |
+
cv2.imwrite("depth.png", depth)
|
| 26 |
+
print(f"Time: {time.time() - t0:.2f}s")
|
| 27 |
+
import pdb; pdb.set_trace()
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/depth_pro/utils.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (C) 2024 Apple Inc. All Rights Reserved.
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any, Dict, List, Tuple, Union
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pillow_heif
|
| 9 |
+
from PIL import ExifTags, Image, TiffTags
|
| 10 |
+
from pillow_heif import register_heif_opener
|
| 11 |
+
|
| 12 |
+
register_heif_opener()
|
| 13 |
+
LOGGER = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def extract_exif(img_pil: Image) -> Dict[str, Any]:
|
| 17 |
+
"""Return exif information as a dictionary.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
----
|
| 21 |
+
img_pil: A Pillow image.
|
| 22 |
+
|
| 23 |
+
Returns:
|
| 24 |
+
-------
|
| 25 |
+
A dictionary with extracted EXIF information.
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
# Get full exif description from get_ifd(0x8769):
|
| 29 |
+
# cf https://pillow.readthedocs.io/en/stable/releasenotes/8.2.0.html#image-getexif-exif-and-gps-ifd
|
| 30 |
+
img_exif = img_pil.getexif().get_ifd(0x8769)
|
| 31 |
+
exif_dict = {ExifTags.TAGS[k]: v for k, v in img_exif.items() if k in ExifTags.TAGS}
|
| 32 |
+
|
| 33 |
+
tiff_tags = img_pil.getexif()
|
| 34 |
+
tiff_dict = {
|
| 35 |
+
TiffTags.TAGS_V2[k].name: v
|
| 36 |
+
for k, v in tiff_tags.items()
|
| 37 |
+
if k in TiffTags.TAGS_V2
|
| 38 |
+
}
|
| 39 |
+
return {**exif_dict, **tiff_dict}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def fpx_from_f35(width: float, height: float, f_mm: float = 50) -> float:
|
| 43 |
+
"""Convert a focal length given in mm (35mm film equivalent) to pixels."""
|
| 44 |
+
return f_mm * np.sqrt(width**2.0 + height**2.0) / np.sqrt(36**2 + 24**2)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def load_rgb(
|
| 48 |
+
path: Union[Path, str], auto_rotate: bool = True, remove_alpha: bool = True
|
| 49 |
+
) -> Tuple[np.ndarray, List[bytes], float]:
|
| 50 |
+
"""Load an RGB image.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
----
|
| 54 |
+
path: The url to the image to load.
|
| 55 |
+
auto_rotate: Rotate the image based on the EXIF data, default is True.
|
| 56 |
+
remove_alpha: Remove the alpha channel, default is True.
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
-------
|
| 60 |
+
img: The image loaded as a numpy array.
|
| 61 |
+
icc_profile: The color profile of the image.
|
| 62 |
+
f_px: The optional focal length in pixels, extracting from the exif data.
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
LOGGER.debug(f"Loading image {path} ...")
|
| 66 |
+
|
| 67 |
+
path = Path(path)
|
| 68 |
+
if path.suffix.lower() in [".heic"]:
|
| 69 |
+
heif_file = pillow_heif.open_heif(path, convert_hdr_to_8bit=True)
|
| 70 |
+
img_pil = heif_file.to_pillow()
|
| 71 |
+
else:
|
| 72 |
+
img_pil = Image.open(path)
|
| 73 |
+
|
| 74 |
+
img_exif = extract_exif(img_pil)
|
| 75 |
+
icc_profile = img_pil.info.get("icc_profile", None)
|
| 76 |
+
|
| 77 |
+
# Rotate the image.
|
| 78 |
+
if auto_rotate:
|
| 79 |
+
exif_orientation = img_exif.get("Orientation", 1)
|
| 80 |
+
if exif_orientation == 3:
|
| 81 |
+
img_pil = img_pil.transpose(Image.ROTATE_180)
|
| 82 |
+
elif exif_orientation == 6:
|
| 83 |
+
img_pil = img_pil.transpose(Image.ROTATE_270)
|
| 84 |
+
elif exif_orientation == 8:
|
| 85 |
+
img_pil = img_pil.transpose(Image.ROTATE_90)
|
| 86 |
+
elif exif_orientation != 1:
|
| 87 |
+
LOGGER.warning(f"Ignoring image orientation {exif_orientation}.")
|
| 88 |
+
|
| 89 |
+
img = np.array(img_pil)
|
| 90 |
+
# Convert to RGB if single channel.
|
| 91 |
+
if img.ndim < 3 or img.shape[2] == 1:
|
| 92 |
+
img = np.dstack((img, img, img))
|
| 93 |
+
|
| 94 |
+
if remove_alpha:
|
| 95 |
+
img = img[:, :, :3]
|
| 96 |
+
|
| 97 |
+
LOGGER.debug(f"\tHxW: {img.shape[0]}x{img.shape[1]}")
|
| 98 |
+
|
| 99 |
+
# Extract the focal length from exif data.
|
| 100 |
+
f_35mm = img_exif.get(
|
| 101 |
+
"FocalLengthIn35mmFilm",
|
| 102 |
+
img_exif.get(
|
| 103 |
+
"FocalLenIn35mmFilm", img_exif.get("FocalLengthIn35mmFormat", None)
|
| 104 |
+
),
|
| 105 |
+
)
|
| 106 |
+
if f_35mm is not None and f_35mm > 0:
|
| 107 |
+
LOGGER.debug(f"\tfocal length @ 35mm film: {f_35mm}mm")
|
| 108 |
+
f_px = fpx_from_f35(img.shape[1], img.shape[0], f_35mm)
|
| 109 |
+
else:
|
| 110 |
+
f_px = None
|
| 111 |
+
|
| 112 |
+
return img, icc_profile, f_px
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .hubconf import *
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/hubconf.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
dependencies = ["torch"]
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
from .midas.dpt_depth import DPTDepthModel
|
| 6 |
+
from .midas.midas_net import MidasNet
|
| 7 |
+
from .midas.midas_net_custom import MidasNet_small
|
| 8 |
+
|
| 9 |
+
def DPT_BEiT_L_512(pretrained=True, **kwargs):
|
| 10 |
+
""" # This docstring shows up in hub.help()
|
| 11 |
+
MiDaS DPT_BEiT_L_512 model for monocular depth estimation
|
| 12 |
+
pretrained (bool): load pretrained weights into model
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
model = DPTDepthModel(
|
| 16 |
+
path=None,
|
| 17 |
+
backbone="beitl16_512",
|
| 18 |
+
non_negative=True,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
if pretrained:
|
| 22 |
+
checkpoint = (
|
| 23 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_512.pt"
|
| 24 |
+
)
|
| 25 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 26 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 27 |
+
)
|
| 28 |
+
model.load_state_dict(state_dict)
|
| 29 |
+
|
| 30 |
+
return model
|
| 31 |
+
|
| 32 |
+
def DPT_BEiT_L_384(pretrained=True, **kwargs):
|
| 33 |
+
""" # This docstring shows up in hub.help()
|
| 34 |
+
MiDaS DPT_BEiT_L_384 model for monocular depth estimation
|
| 35 |
+
pretrained (bool): load pretrained weights into model
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
model = DPTDepthModel(
|
| 39 |
+
path=None,
|
| 40 |
+
backbone="beitl16_384",
|
| 41 |
+
non_negative=True,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
if pretrained:
|
| 45 |
+
checkpoint = (
|
| 46 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_384.pt"
|
| 47 |
+
)
|
| 48 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 49 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 50 |
+
)
|
| 51 |
+
model.load_state_dict(state_dict)
|
| 52 |
+
|
| 53 |
+
return model
|
| 54 |
+
|
| 55 |
+
def DPT_BEiT_B_384(pretrained=True, **kwargs):
|
| 56 |
+
""" # This docstring shows up in hub.help()
|
| 57 |
+
MiDaS DPT_BEiT_B_384 model for monocular depth estimation
|
| 58 |
+
pretrained (bool): load pretrained weights into model
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
model = DPTDepthModel(
|
| 62 |
+
path=None,
|
| 63 |
+
backbone="beitb16_384",
|
| 64 |
+
non_negative=True,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
if pretrained:
|
| 68 |
+
checkpoint = (
|
| 69 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_base_384.pt"
|
| 70 |
+
)
|
| 71 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 72 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 73 |
+
)
|
| 74 |
+
model.load_state_dict(state_dict)
|
| 75 |
+
|
| 76 |
+
return model
|
| 77 |
+
|
| 78 |
+
def DPT_SwinV2_L_384(pretrained=True, **kwargs):
|
| 79 |
+
""" # This docstring shows up in hub.help()
|
| 80 |
+
MiDaS DPT_SwinV2_L_384 model for monocular depth estimation
|
| 81 |
+
pretrained (bool): load pretrained weights into model
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
model = DPTDepthModel(
|
| 85 |
+
path=None,
|
| 86 |
+
backbone="swin2l24_384",
|
| 87 |
+
non_negative=True,
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if pretrained:
|
| 91 |
+
checkpoint = (
|
| 92 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin2_large_384.pt"
|
| 93 |
+
)
|
| 94 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 95 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 96 |
+
)
|
| 97 |
+
model.load_state_dict(state_dict)
|
| 98 |
+
|
| 99 |
+
return model
|
| 100 |
+
|
| 101 |
+
def DPT_SwinV2_B_384(pretrained=True, **kwargs):
|
| 102 |
+
""" # This docstring shows up in hub.help()
|
| 103 |
+
MiDaS DPT_SwinV2_B_384 model for monocular depth estimation
|
| 104 |
+
pretrained (bool): load pretrained weights into model
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
model = DPTDepthModel(
|
| 108 |
+
path=None,
|
| 109 |
+
backbone="swin2b24_384",
|
| 110 |
+
non_negative=True,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
if pretrained:
|
| 114 |
+
checkpoint = (
|
| 115 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin2_base_384.pt"
|
| 116 |
+
)
|
| 117 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 118 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 119 |
+
)
|
| 120 |
+
model.load_state_dict(state_dict)
|
| 121 |
+
|
| 122 |
+
return model
|
| 123 |
+
|
| 124 |
+
def DPT_SwinV2_T_256(pretrained=True, **kwargs):
|
| 125 |
+
""" # This docstring shows up in hub.help()
|
| 126 |
+
MiDaS DPT_SwinV2_T_256 model for monocular depth estimation
|
| 127 |
+
pretrained (bool): load pretrained weights into model
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
model = DPTDepthModel(
|
| 131 |
+
path=None,
|
| 132 |
+
backbone="swin2t16_256",
|
| 133 |
+
non_negative=True,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
if pretrained:
|
| 137 |
+
checkpoint = (
|
| 138 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin2_tiny_256.pt"
|
| 139 |
+
)
|
| 140 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 141 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 142 |
+
)
|
| 143 |
+
model.load_state_dict(state_dict)
|
| 144 |
+
|
| 145 |
+
return model
|
| 146 |
+
|
| 147 |
+
def DPT_Swin_L_384(pretrained=True, **kwargs):
|
| 148 |
+
""" # This docstring shows up in hub.help()
|
| 149 |
+
MiDaS DPT_Swin_L_384 model for monocular depth estimation
|
| 150 |
+
pretrained (bool): load pretrained weights into model
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
model = DPTDepthModel(
|
| 154 |
+
path=None,
|
| 155 |
+
backbone="swinl12_384",
|
| 156 |
+
non_negative=True,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
if pretrained:
|
| 160 |
+
checkpoint = (
|
| 161 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin_large_384.pt"
|
| 162 |
+
)
|
| 163 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 164 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 165 |
+
)
|
| 166 |
+
model.load_state_dict(state_dict)
|
| 167 |
+
|
| 168 |
+
return model
|
| 169 |
+
|
| 170 |
+
def DPT_Next_ViT_L_384(pretrained=True, **kwargs):
|
| 171 |
+
""" # This docstring shows up in hub.help()
|
| 172 |
+
MiDaS DPT_Next_ViT_L_384 model for monocular depth estimation
|
| 173 |
+
pretrained (bool): load pretrained weights into model
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
model = DPTDepthModel(
|
| 177 |
+
path=None,
|
| 178 |
+
backbone="next_vit_large_6m",
|
| 179 |
+
non_negative=True,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
if pretrained:
|
| 183 |
+
checkpoint = (
|
| 184 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_next_vit_large_384.pt"
|
| 185 |
+
)
|
| 186 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 187 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 188 |
+
)
|
| 189 |
+
model.load_state_dict(state_dict)
|
| 190 |
+
|
| 191 |
+
return model
|
| 192 |
+
|
| 193 |
+
def DPT_LeViT_224(pretrained=True, **kwargs):
|
| 194 |
+
""" # This docstring shows up in hub.help()
|
| 195 |
+
MiDaS DPT_LeViT_224 model for monocular depth estimation
|
| 196 |
+
pretrained (bool): load pretrained weights into model
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
model = DPTDepthModel(
|
| 200 |
+
path=None,
|
| 201 |
+
backbone="levit_384",
|
| 202 |
+
non_negative=True,
|
| 203 |
+
head_features_1=64,
|
| 204 |
+
head_features_2=8,
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
if pretrained:
|
| 208 |
+
checkpoint = (
|
| 209 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_levit_224.pt"
|
| 210 |
+
)
|
| 211 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 212 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 213 |
+
)
|
| 214 |
+
model.load_state_dict(state_dict)
|
| 215 |
+
|
| 216 |
+
return model
|
| 217 |
+
|
| 218 |
+
def DPT_Large(pretrained=True, **kwargs):
|
| 219 |
+
""" # This docstring shows up in hub.help()
|
| 220 |
+
MiDaS DPT-Large model for monocular depth estimation
|
| 221 |
+
pretrained (bool): load pretrained weights into model
|
| 222 |
+
"""
|
| 223 |
+
|
| 224 |
+
model = DPTDepthModel(
|
| 225 |
+
path=None,
|
| 226 |
+
backbone="vitl16_384",
|
| 227 |
+
non_negative=True,
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
if pretrained:
|
| 231 |
+
checkpoint = (
|
| 232 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3/dpt_large_384.pt"
|
| 233 |
+
)
|
| 234 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 235 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 236 |
+
)
|
| 237 |
+
model.load_state_dict(state_dict)
|
| 238 |
+
|
| 239 |
+
return model
|
| 240 |
+
|
| 241 |
+
def DPT_Hybrid(pretrained=True, **kwargs):
|
| 242 |
+
""" # This docstring shows up in hub.help()
|
| 243 |
+
MiDaS DPT-Hybrid model for monocular depth estimation
|
| 244 |
+
pretrained (bool): load pretrained weights into model
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
model = DPTDepthModel(
|
| 248 |
+
path=None,
|
| 249 |
+
backbone="vitb_rn50_384",
|
| 250 |
+
non_negative=True,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
if pretrained:
|
| 254 |
+
checkpoint = (
|
| 255 |
+
"https://github.com/isl-org/MiDaS/releases/download/v3/dpt_hybrid_384.pt"
|
| 256 |
+
)
|
| 257 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 258 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 259 |
+
)
|
| 260 |
+
model.load_state_dict(state_dict)
|
| 261 |
+
|
| 262 |
+
return model
|
| 263 |
+
|
| 264 |
+
def MiDaS(pretrained=True, **kwargs):
|
| 265 |
+
""" # This docstring shows up in hub.help()
|
| 266 |
+
MiDaS v2.1 model for monocular depth estimation
|
| 267 |
+
pretrained (bool): load pretrained weights into model
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
model = MidasNet()
|
| 271 |
+
|
| 272 |
+
if pretrained:
|
| 273 |
+
checkpoint = (
|
| 274 |
+
"https://github.com/isl-org/MiDaS/releases/download/v2_1/midas_v21_384.pt"
|
| 275 |
+
)
|
| 276 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 277 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 278 |
+
)
|
| 279 |
+
model.load_state_dict(state_dict)
|
| 280 |
+
|
| 281 |
+
return model
|
| 282 |
+
|
| 283 |
+
def MiDaS_small(pretrained=True, **kwargs):
|
| 284 |
+
""" # This docstring shows up in hub.help()
|
| 285 |
+
MiDaS v2.1 small model for monocular depth estimation on resource-constrained devices
|
| 286 |
+
pretrained (bool): load pretrained weights into model
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
model = MidasNet_small(None, features=64, backbone="efficientnet_lite3", exportable=True, non_negative=True, blocks={'expand': True})
|
| 290 |
+
|
| 291 |
+
if pretrained:
|
| 292 |
+
checkpoint = (
|
| 293 |
+
"https://github.com/isl-org/MiDaS/releases/download/v2_1/midas_v21_small_256.pt"
|
| 294 |
+
)
|
| 295 |
+
state_dict = torch.hub.load_state_dict_from_url(
|
| 296 |
+
checkpoint, map_location=torch.device('cpu'), progress=True, check_hash=True
|
| 297 |
+
)
|
| 298 |
+
model.load_state_dict(state_dict)
|
| 299 |
+
|
| 300 |
+
return model
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def transforms():
|
| 304 |
+
import cv2
|
| 305 |
+
from torchvision.transforms import Compose
|
| 306 |
+
from midas.transforms import Resize, NormalizeImage, PrepareForNet
|
| 307 |
+
from midas import transforms
|
| 308 |
+
|
| 309 |
+
transforms.default_transform = Compose(
|
| 310 |
+
[
|
| 311 |
+
lambda img: {"image": img / 255.0},
|
| 312 |
+
Resize(
|
| 313 |
+
384,
|
| 314 |
+
384,
|
| 315 |
+
resize_target=None,
|
| 316 |
+
keep_aspect_ratio=True,
|
| 317 |
+
ensure_multiple_of=32,
|
| 318 |
+
resize_method="upper_bound",
|
| 319 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 320 |
+
),
|
| 321 |
+
NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 322 |
+
PrepareForNet(),
|
| 323 |
+
lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0),
|
| 324 |
+
]
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
transforms.small_transform = Compose(
|
| 328 |
+
[
|
| 329 |
+
lambda img: {"image": img / 255.0},
|
| 330 |
+
Resize(
|
| 331 |
+
256,
|
| 332 |
+
256,
|
| 333 |
+
resize_target=None,
|
| 334 |
+
keep_aspect_ratio=True,
|
| 335 |
+
ensure_multiple_of=32,
|
| 336 |
+
resize_method="upper_bound",
|
| 337 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 338 |
+
),
|
| 339 |
+
NormalizeImage(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 340 |
+
PrepareForNet(),
|
| 341 |
+
lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0),
|
| 342 |
+
]
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
transforms.dpt_transform = Compose(
|
| 346 |
+
[
|
| 347 |
+
lambda img: {"image": img / 255.0},
|
| 348 |
+
Resize(
|
| 349 |
+
384,
|
| 350 |
+
384,
|
| 351 |
+
resize_target=None,
|
| 352 |
+
keep_aspect_ratio=True,
|
| 353 |
+
ensure_multiple_of=32,
|
| 354 |
+
resize_method="minimal",
|
| 355 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 356 |
+
),
|
| 357 |
+
NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
| 358 |
+
PrepareForNet(),
|
| 359 |
+
lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0),
|
| 360 |
+
]
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
transforms.beit512_transform = Compose(
|
| 364 |
+
[
|
| 365 |
+
lambda img: {"image": img / 255.0},
|
| 366 |
+
Resize(
|
| 367 |
+
512,
|
| 368 |
+
512,
|
| 369 |
+
resize_target=None,
|
| 370 |
+
keep_aspect_ratio=True,
|
| 371 |
+
ensure_multiple_of=32,
|
| 372 |
+
resize_method="minimal",
|
| 373 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 374 |
+
),
|
| 375 |
+
NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
| 376 |
+
PrepareForNet(),
|
| 377 |
+
lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0),
|
| 378 |
+
]
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
transforms.swin384_transform = Compose(
|
| 382 |
+
[
|
| 383 |
+
lambda img: {"image": img / 255.0},
|
| 384 |
+
Resize(
|
| 385 |
+
384,
|
| 386 |
+
384,
|
| 387 |
+
resize_target=None,
|
| 388 |
+
keep_aspect_ratio=False,
|
| 389 |
+
ensure_multiple_of=32,
|
| 390 |
+
resize_method="minimal",
|
| 391 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 392 |
+
),
|
| 393 |
+
NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
| 394 |
+
PrepareForNet(),
|
| 395 |
+
lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0),
|
| 396 |
+
]
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
transforms.swin256_transform = Compose(
|
| 400 |
+
[
|
| 401 |
+
lambda img: {"image": img / 255.0},
|
| 402 |
+
Resize(
|
| 403 |
+
256,
|
| 404 |
+
256,
|
| 405 |
+
resize_target=None,
|
| 406 |
+
keep_aspect_ratio=False,
|
| 407 |
+
ensure_multiple_of=32,
|
| 408 |
+
resize_method="minimal",
|
| 409 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 410 |
+
),
|
| 411 |
+
NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
| 412 |
+
PrepareForNet(),
|
| 413 |
+
lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0),
|
| 414 |
+
]
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
transforms.levit_transform = Compose(
|
| 418 |
+
[
|
| 419 |
+
lambda img: {"image": img / 255.0},
|
| 420 |
+
Resize(
|
| 421 |
+
224,
|
| 422 |
+
224,
|
| 423 |
+
resize_target=None,
|
| 424 |
+
keep_aspect_ratio=False,
|
| 425 |
+
ensure_multiple_of=32,
|
| 426 |
+
resize_method="minimal",
|
| 427 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 428 |
+
),
|
| 429 |
+
NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
|
| 430 |
+
PrepareForNet(),
|
| 431 |
+
lambda sample: torch.from_numpy(sample["image"]).unsqueeze(0),
|
| 432 |
+
]
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
return transforms
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/beit.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import timm
|
| 2 |
+
import torch
|
| 3 |
+
import types
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
from .utils import forward_adapted_unflatten, make_backbone_default
|
| 9 |
+
from timm.models.beit import gen_relative_position_index
|
| 10 |
+
from torch.utils.checkpoint import checkpoint
|
| 11 |
+
from typing import Optional
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def forward_beit(pretrained, x):
|
| 15 |
+
return forward_adapted_unflatten(pretrained, x, "forward_features")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def patch_embed_forward(self, x):
|
| 19 |
+
"""
|
| 20 |
+
Modification of timm.models.layers.patch_embed.py: PatchEmbed.forward to support arbitrary window sizes.
|
| 21 |
+
"""
|
| 22 |
+
x = self.proj(x)
|
| 23 |
+
if self.flatten:
|
| 24 |
+
x = x.flatten(2).transpose(1, 2)
|
| 25 |
+
x = self.norm(x)
|
| 26 |
+
return x
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _get_rel_pos_bias(self, window_size):
|
| 30 |
+
"""
|
| 31 |
+
Modification of timm.models.beit.py: Attention._get_rel_pos_bias to support arbitrary window sizes.
|
| 32 |
+
"""
|
| 33 |
+
old_height = 2 * self.window_size[0] - 1
|
| 34 |
+
old_width = 2 * self.window_size[1] - 1
|
| 35 |
+
|
| 36 |
+
new_height = 2 * window_size[0] - 1
|
| 37 |
+
new_width = 2 * window_size[1] - 1
|
| 38 |
+
|
| 39 |
+
old_relative_position_bias_table = self.relative_position_bias_table
|
| 40 |
+
|
| 41 |
+
old_num_relative_distance = self.num_relative_distance
|
| 42 |
+
new_num_relative_distance = new_height * new_width + 3
|
| 43 |
+
|
| 44 |
+
old_sub_table = old_relative_position_bias_table[:old_num_relative_distance - 3]
|
| 45 |
+
|
| 46 |
+
old_sub_table = old_sub_table.reshape(1, old_width, old_height, -1).permute(0, 3, 1, 2)
|
| 47 |
+
new_sub_table = F.interpolate(old_sub_table, size=(int(new_height), int(new_width)), mode="bilinear")
|
| 48 |
+
new_sub_table = new_sub_table.permute(0, 2, 3, 1).reshape(new_num_relative_distance - 3, -1)
|
| 49 |
+
|
| 50 |
+
new_relative_position_bias_table = torch.cat(
|
| 51 |
+
[new_sub_table, old_relative_position_bias_table[old_num_relative_distance - 3:]])
|
| 52 |
+
|
| 53 |
+
key = str(window_size[1]) + "," + str(window_size[0])
|
| 54 |
+
if key not in self.relative_position_indices.keys():
|
| 55 |
+
self.relative_position_indices[key] = gen_relative_position_index(window_size)
|
| 56 |
+
|
| 57 |
+
relative_position_bias = new_relative_position_bias_table[
|
| 58 |
+
self.relative_position_indices[key].view(-1)].view(
|
| 59 |
+
window_size[0] * window_size[1] + 1,
|
| 60 |
+
window_size[0] * window_size[1] + 1, -1) # Wh*Ww,Wh*Ww,nH
|
| 61 |
+
relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
|
| 62 |
+
return relative_position_bias.unsqueeze(0)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def attention_forward(self, x, resolution, shared_rel_pos_bias: Optional[torch.Tensor] = None):
|
| 66 |
+
"""
|
| 67 |
+
Modification of timm.models.beit.py: Attention.forward to support arbitrary window sizes.
|
| 68 |
+
"""
|
| 69 |
+
B, N, C = x.shape
|
| 70 |
+
|
| 71 |
+
qkv_bias = torch.cat((self.q_bias, self.k_bias, self.v_bias)) if self.q_bias is not None else None
|
| 72 |
+
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
|
| 73 |
+
qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
|
| 74 |
+
q, k, v = qkv.unbind(0) # make torchscript happy (cannot use tensor as tuple)
|
| 75 |
+
|
| 76 |
+
q = q * self.scale
|
| 77 |
+
attn = (q @ k.transpose(-2, -1))
|
| 78 |
+
|
| 79 |
+
if self.relative_position_bias_table is not None:
|
| 80 |
+
window_size = tuple(np.array(resolution) // 16)
|
| 81 |
+
attn = attn + self._get_rel_pos_bias(window_size)
|
| 82 |
+
if shared_rel_pos_bias is not None:
|
| 83 |
+
attn = attn + shared_rel_pos_bias
|
| 84 |
+
|
| 85 |
+
attn = attn.softmax(dim=-1)
|
| 86 |
+
attn = self.attn_drop(attn)
|
| 87 |
+
|
| 88 |
+
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
|
| 89 |
+
x = self.proj(x)
|
| 90 |
+
x = self.proj_drop(x)
|
| 91 |
+
return x
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def block_forward(self, x, resolution, shared_rel_pos_bias: Optional[torch.Tensor] = None):
|
| 95 |
+
"""
|
| 96 |
+
Modification of timm.models.beit.py: Block.forward to support arbitrary window sizes.
|
| 97 |
+
"""
|
| 98 |
+
if self.gamma_1 is None:
|
| 99 |
+
x = x + self.drop_path(self.attn(self.norm1(x), resolution, shared_rel_pos_bias=shared_rel_pos_bias))
|
| 100 |
+
x = x + self.drop_path(self.mlp(self.norm2(x)))
|
| 101 |
+
else:
|
| 102 |
+
x = x + self.drop_path(self.gamma_1 * self.attn(self.norm1(x), resolution,
|
| 103 |
+
shared_rel_pos_bias=shared_rel_pos_bias))
|
| 104 |
+
x = x + self.drop_path(self.gamma_2 * self.mlp(self.norm2(x)))
|
| 105 |
+
return x
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def beit_forward_features(self, x):
|
| 109 |
+
"""
|
| 110 |
+
Modification of timm.models.beit.py: Beit.forward_features to support arbitrary window sizes.
|
| 111 |
+
"""
|
| 112 |
+
resolution = x.shape[2:]
|
| 113 |
+
|
| 114 |
+
x = self.patch_embed(x)
|
| 115 |
+
x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
|
| 116 |
+
if self.pos_embed is not None:
|
| 117 |
+
x = x + self.pos_embed
|
| 118 |
+
x = self.pos_drop(x)
|
| 119 |
+
|
| 120 |
+
rel_pos_bias = self.rel_pos_bias() if self.rel_pos_bias is not None else None
|
| 121 |
+
for blk in self.blocks:
|
| 122 |
+
if self.grad_checkpointing and not torch.jit.is_scripting():
|
| 123 |
+
x = checkpoint(blk, x, shared_rel_pos_bias=rel_pos_bias)
|
| 124 |
+
else:
|
| 125 |
+
x = blk(x, resolution, shared_rel_pos_bias=rel_pos_bias)
|
| 126 |
+
x = self.norm(x)
|
| 127 |
+
return x
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _make_beit_backbone(
|
| 131 |
+
model,
|
| 132 |
+
features=[96, 192, 384, 768],
|
| 133 |
+
size=[384, 384],
|
| 134 |
+
hooks=[0, 4, 8, 11],
|
| 135 |
+
vit_features=768,
|
| 136 |
+
use_readout="ignore",
|
| 137 |
+
start_index=1,
|
| 138 |
+
start_index_readout=1,
|
| 139 |
+
):
|
| 140 |
+
backbone = make_backbone_default(model, features, size, hooks, vit_features, use_readout, start_index,
|
| 141 |
+
start_index_readout)
|
| 142 |
+
|
| 143 |
+
backbone.model.patch_embed.forward = types.MethodType(patch_embed_forward, backbone.model.patch_embed)
|
| 144 |
+
backbone.model.forward_features = types.MethodType(beit_forward_features, backbone.model)
|
| 145 |
+
|
| 146 |
+
for block in backbone.model.blocks:
|
| 147 |
+
attn = block.attn
|
| 148 |
+
attn._get_rel_pos_bias = types.MethodType(_get_rel_pos_bias, attn)
|
| 149 |
+
attn.forward = types.MethodType(attention_forward, attn)
|
| 150 |
+
attn.relative_position_indices = {}
|
| 151 |
+
|
| 152 |
+
block.forward = types.MethodType(block_forward, block)
|
| 153 |
+
|
| 154 |
+
return backbone
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _make_pretrained_beitl16_512(pretrained, use_readout="ignore", hooks=None):
|
| 158 |
+
model = timm.create_model("beit_large_patch16_512", pretrained=pretrained)
|
| 159 |
+
|
| 160 |
+
hooks = [5, 11, 17, 23] if hooks is None else hooks
|
| 161 |
+
|
| 162 |
+
features = [256, 512, 1024, 1024]
|
| 163 |
+
|
| 164 |
+
return _make_beit_backbone(
|
| 165 |
+
model,
|
| 166 |
+
features=features,
|
| 167 |
+
size=[512, 512],
|
| 168 |
+
hooks=hooks,
|
| 169 |
+
vit_features=1024,
|
| 170 |
+
use_readout=use_readout,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _make_pretrained_beitl16_384(pretrained, use_readout="ignore", hooks=None):
|
| 175 |
+
model = timm.create_model("beit_large_patch16_384", pretrained=pretrained)
|
| 176 |
+
|
| 177 |
+
hooks = [5, 11, 17, 23] if hooks is None else hooks
|
| 178 |
+
return _make_beit_backbone(
|
| 179 |
+
model,
|
| 180 |
+
features=[256, 512, 1024, 1024],
|
| 181 |
+
hooks=hooks,
|
| 182 |
+
vit_features=1024,
|
| 183 |
+
use_readout=use_readout,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _make_pretrained_beitb16_384(pretrained, use_readout="ignore", hooks=None):
|
| 188 |
+
model = timm.create_model("beit_base_patch16_384", pretrained=pretrained)
|
| 189 |
+
|
| 190 |
+
hooks = [2, 5, 8, 11] if hooks is None else hooks
|
| 191 |
+
return _make_beit_backbone(
|
| 192 |
+
model,
|
| 193 |
+
features=[96, 192, 384, 768],
|
| 194 |
+
hooks=hooks,
|
| 195 |
+
use_readout=use_readout,
|
| 196 |
+
)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/levit.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import timm
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from .utils import activations, get_activation, Transpose
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def forward_levit(pretrained, x):
|
| 10 |
+
pretrained.model.forward_features(x)
|
| 11 |
+
|
| 12 |
+
layer_1 = pretrained.activations["1"]
|
| 13 |
+
layer_2 = pretrained.activations["2"]
|
| 14 |
+
layer_3 = pretrained.activations["3"]
|
| 15 |
+
|
| 16 |
+
layer_1 = pretrained.act_postprocess1(layer_1)
|
| 17 |
+
layer_2 = pretrained.act_postprocess2(layer_2)
|
| 18 |
+
layer_3 = pretrained.act_postprocess3(layer_3)
|
| 19 |
+
|
| 20 |
+
return layer_1, layer_2, layer_3
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _make_levit_backbone(
|
| 24 |
+
model,
|
| 25 |
+
hooks=[3, 11, 21],
|
| 26 |
+
patch_grid=[14, 14]
|
| 27 |
+
):
|
| 28 |
+
pretrained = nn.Module()
|
| 29 |
+
|
| 30 |
+
pretrained.model = model
|
| 31 |
+
pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))
|
| 32 |
+
pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))
|
| 33 |
+
pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))
|
| 34 |
+
|
| 35 |
+
pretrained.activations = activations
|
| 36 |
+
|
| 37 |
+
patch_grid_size = np.array(patch_grid, dtype=int)
|
| 38 |
+
|
| 39 |
+
pretrained.act_postprocess1 = nn.Sequential(
|
| 40 |
+
Transpose(1, 2),
|
| 41 |
+
nn.Unflatten(2, torch.Size(patch_grid_size.tolist()))
|
| 42 |
+
)
|
| 43 |
+
pretrained.act_postprocess2 = nn.Sequential(
|
| 44 |
+
Transpose(1, 2),
|
| 45 |
+
nn.Unflatten(2, torch.Size((np.ceil(patch_grid_size / 2).astype(int)).tolist()))
|
| 46 |
+
)
|
| 47 |
+
pretrained.act_postprocess3 = nn.Sequential(
|
| 48 |
+
Transpose(1, 2),
|
| 49 |
+
nn.Unflatten(2, torch.Size((np.ceil(patch_grid_size / 4).astype(int)).tolist()))
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
return pretrained
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ConvTransposeNorm(nn.Sequential):
|
| 56 |
+
"""
|
| 57 |
+
Modification of
|
| 58 |
+
https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: ConvNorm
|
| 59 |
+
such that ConvTranspose2d is used instead of Conv2d.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(
|
| 63 |
+
self, in_chs, out_chs, kernel_size=1, stride=1, pad=0, dilation=1,
|
| 64 |
+
groups=1, bn_weight_init=1):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.add_module('c',
|
| 67 |
+
nn.ConvTranspose2d(in_chs, out_chs, kernel_size, stride, pad, dilation, groups, bias=False))
|
| 68 |
+
self.add_module('bn', nn.BatchNorm2d(out_chs))
|
| 69 |
+
|
| 70 |
+
nn.init.constant_(self.bn.weight, bn_weight_init)
|
| 71 |
+
|
| 72 |
+
@torch.no_grad()
|
| 73 |
+
def fuse(self):
|
| 74 |
+
c, bn = self._modules.values()
|
| 75 |
+
w = bn.weight / (bn.running_var + bn.eps) ** 0.5
|
| 76 |
+
w = c.weight * w[:, None, None, None]
|
| 77 |
+
b = bn.bias - bn.running_mean * bn.weight / (bn.running_var + bn.eps) ** 0.5
|
| 78 |
+
m = nn.ConvTranspose2d(
|
| 79 |
+
w.size(1), w.size(0), w.shape[2:], stride=self.c.stride,
|
| 80 |
+
padding=self.c.padding, dilation=self.c.dilation, groups=self.c.groups)
|
| 81 |
+
m.weight.data.copy_(w)
|
| 82 |
+
m.bias.data.copy_(b)
|
| 83 |
+
return m
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def stem_b4_transpose(in_chs, out_chs, activation):
|
| 87 |
+
"""
|
| 88 |
+
Modification of
|
| 89 |
+
https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: stem_b16
|
| 90 |
+
such that ConvTranspose2d is used instead of Conv2d and stem is also reduced to the half.
|
| 91 |
+
"""
|
| 92 |
+
return nn.Sequential(
|
| 93 |
+
ConvTransposeNorm(in_chs, out_chs, 3, 2, 1),
|
| 94 |
+
activation(),
|
| 95 |
+
ConvTransposeNorm(out_chs, out_chs // 2, 3, 2, 1),
|
| 96 |
+
activation())
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _make_pretrained_levit_384(pretrained, hooks=None):
|
| 100 |
+
model = timm.create_model("levit_384", pretrained=pretrained)
|
| 101 |
+
|
| 102 |
+
hooks = [3, 11, 21] if hooks == None else hooks
|
| 103 |
+
return _make_levit_backbone(
|
| 104 |
+
model,
|
| 105 |
+
hooks=hooks
|
| 106 |
+
)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/next_vit.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import timm
|
| 2 |
+
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from .utils import activations, forward_default, get_activation
|
| 7 |
+
|
| 8 |
+
from ..external.next_vit.classification.nextvit import *
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def forward_next_vit(pretrained, x):
|
| 12 |
+
return forward_default(pretrained, x, "forward")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _make_next_vit_backbone(
|
| 16 |
+
model,
|
| 17 |
+
hooks=[2, 6, 36, 39],
|
| 18 |
+
):
|
| 19 |
+
pretrained = nn.Module()
|
| 20 |
+
|
| 21 |
+
pretrained.model = model
|
| 22 |
+
pretrained.model.features[hooks[0]].register_forward_hook(get_activation("1"))
|
| 23 |
+
pretrained.model.features[hooks[1]].register_forward_hook(get_activation("2"))
|
| 24 |
+
pretrained.model.features[hooks[2]].register_forward_hook(get_activation("3"))
|
| 25 |
+
pretrained.model.features[hooks[3]].register_forward_hook(get_activation("4"))
|
| 26 |
+
|
| 27 |
+
pretrained.activations = activations
|
| 28 |
+
|
| 29 |
+
return pretrained
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _make_pretrained_next_vit_large_6m(hooks=None):
|
| 33 |
+
model = timm.create_model("nextvit_large")
|
| 34 |
+
|
| 35 |
+
hooks = [2, 6, 36, 39] if hooks == None else hooks
|
| 36 |
+
return _make_next_vit_backbone(
|
| 37 |
+
model,
|
| 38 |
+
hooks=hooks,
|
| 39 |
+
)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import timm
|
| 2 |
+
|
| 3 |
+
from .swin_common import _make_swin_backbone
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _make_pretrained_swinl12_384(pretrained, hooks=None):
|
| 7 |
+
model = timm.create_model("swin_large_patch4_window12_384", pretrained=pretrained)
|
| 8 |
+
|
| 9 |
+
hooks = [1, 1, 17, 1] if hooks == None else hooks
|
| 10 |
+
return _make_swin_backbone(
|
| 11 |
+
model,
|
| 12 |
+
hooks=hooks
|
| 13 |
+
)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin2.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import timm
|
| 2 |
+
|
| 3 |
+
from .swin_common import _make_swin_backbone
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def _make_pretrained_swin2l24_384(pretrained, hooks=None):
|
| 7 |
+
model = timm.create_model("swinv2_large_window12to24_192to384_22kft1k", pretrained=pretrained)
|
| 8 |
+
|
| 9 |
+
hooks = [1, 1, 17, 1] if hooks == None else hooks
|
| 10 |
+
return _make_swin_backbone(
|
| 11 |
+
model,
|
| 12 |
+
hooks=hooks
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _make_pretrained_swin2b24_384(pretrained, hooks=None):
|
| 17 |
+
model = timm.create_model("swinv2_base_window12to24_192to384_22kft1k", pretrained=pretrained)
|
| 18 |
+
|
| 19 |
+
hooks = [1, 1, 17, 1] if hooks == None else hooks
|
| 20 |
+
return _make_swin_backbone(
|
| 21 |
+
model,
|
| 22 |
+
hooks=hooks
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _make_pretrained_swin2t16_256(pretrained, hooks=None):
|
| 27 |
+
model = timm.create_model("swinv2_tiny_window16_256", pretrained=pretrained)
|
| 28 |
+
|
| 29 |
+
hooks = [1, 1, 5, 1] if hooks == None else hooks
|
| 30 |
+
return _make_swin_backbone(
|
| 31 |
+
model,
|
| 32 |
+
hooks=hooks,
|
| 33 |
+
patch_grid=[64, 64]
|
| 34 |
+
)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/swin_common.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
from .utils import activations, forward_default, get_activation, Transpose
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def forward_swin(pretrained, x):
|
| 10 |
+
return forward_default(pretrained, x)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _make_swin_backbone(
|
| 14 |
+
model,
|
| 15 |
+
hooks=[1, 1, 17, 1],
|
| 16 |
+
patch_grid=[96, 96]
|
| 17 |
+
):
|
| 18 |
+
pretrained = nn.Module()
|
| 19 |
+
|
| 20 |
+
pretrained.model = model
|
| 21 |
+
pretrained.model.layers[0].blocks[hooks[0]].register_forward_hook(get_activation("1"))
|
| 22 |
+
pretrained.model.layers[1].blocks[hooks[1]].register_forward_hook(get_activation("2"))
|
| 23 |
+
pretrained.model.layers[2].blocks[hooks[2]].register_forward_hook(get_activation("3"))
|
| 24 |
+
pretrained.model.layers[3].blocks[hooks[3]].register_forward_hook(get_activation("4"))
|
| 25 |
+
|
| 26 |
+
pretrained.activations = activations
|
| 27 |
+
|
| 28 |
+
if hasattr(model, "patch_grid"):
|
| 29 |
+
used_patch_grid = model.patch_grid
|
| 30 |
+
else:
|
| 31 |
+
used_patch_grid = patch_grid
|
| 32 |
+
|
| 33 |
+
patch_grid_size = np.array(used_patch_grid, dtype=int)
|
| 34 |
+
|
| 35 |
+
pretrained.act_postprocess1 = nn.Sequential(
|
| 36 |
+
Transpose(1, 2),
|
| 37 |
+
nn.Unflatten(2, torch.Size(patch_grid_size.tolist()))
|
| 38 |
+
)
|
| 39 |
+
pretrained.act_postprocess2 = nn.Sequential(
|
| 40 |
+
Transpose(1, 2),
|
| 41 |
+
nn.Unflatten(2, torch.Size((patch_grid_size // 2).tolist()))
|
| 42 |
+
)
|
| 43 |
+
pretrained.act_postprocess3 = nn.Sequential(
|
| 44 |
+
Transpose(1, 2),
|
| 45 |
+
nn.Unflatten(2, torch.Size((patch_grid_size // 4).tolist()))
|
| 46 |
+
)
|
| 47 |
+
pretrained.act_postprocess4 = nn.Sequential(
|
| 48 |
+
Transpose(1, 2),
|
| 49 |
+
nn.Unflatten(2, torch.Size((patch_grid_size // 8).tolist()))
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
return pretrained
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/utils.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Slice(nn.Module):
|
| 7 |
+
def __init__(self, start_index=1):
|
| 8 |
+
super(Slice, self).__init__()
|
| 9 |
+
self.start_index = start_index
|
| 10 |
+
|
| 11 |
+
def forward(self, x):
|
| 12 |
+
return x[:, self.start_index:]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AddReadout(nn.Module):
|
| 16 |
+
def __init__(self, start_index=1):
|
| 17 |
+
super(AddReadout, self).__init__()
|
| 18 |
+
self.start_index = start_index
|
| 19 |
+
|
| 20 |
+
def forward(self, x):
|
| 21 |
+
if self.start_index == 2:
|
| 22 |
+
readout = (x[:, 0] + x[:, 1]) / 2
|
| 23 |
+
else:
|
| 24 |
+
readout = x[:, 0]
|
| 25 |
+
return x[:, self.start_index:] + readout.unsqueeze(1)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class ProjectReadout(nn.Module):
|
| 29 |
+
def __init__(self, in_features, start_index=1):
|
| 30 |
+
super(ProjectReadout, self).__init__()
|
| 31 |
+
self.start_index = start_index
|
| 32 |
+
|
| 33 |
+
self.project = nn.Sequential(nn.Linear(2 * in_features, in_features), nn.GELU())
|
| 34 |
+
|
| 35 |
+
def forward(self, x):
|
| 36 |
+
readout = x[:, 0].unsqueeze(1).expand_as(x[:, self.start_index:])
|
| 37 |
+
features = torch.cat((x[:, self.start_index:], readout), -1)
|
| 38 |
+
|
| 39 |
+
return self.project(features)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Transpose(nn.Module):
|
| 43 |
+
def __init__(self, dim0, dim1):
|
| 44 |
+
super(Transpose, self).__init__()
|
| 45 |
+
self.dim0 = dim0
|
| 46 |
+
self.dim1 = dim1
|
| 47 |
+
|
| 48 |
+
def forward(self, x):
|
| 49 |
+
x = x.transpose(self.dim0, self.dim1)
|
| 50 |
+
return x
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
activations = {}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_activation(name):
|
| 57 |
+
def hook(model, input, output):
|
| 58 |
+
activations[name] = output
|
| 59 |
+
|
| 60 |
+
return hook
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def forward_default(pretrained, x, function_name="forward_features"):
|
| 64 |
+
exec(f"pretrained.model.{function_name}(x)")
|
| 65 |
+
|
| 66 |
+
layer_1 = pretrained.activations["1"]
|
| 67 |
+
layer_2 = pretrained.activations["2"]
|
| 68 |
+
layer_3 = pretrained.activations["3"]
|
| 69 |
+
layer_4 = pretrained.activations["4"]
|
| 70 |
+
|
| 71 |
+
if hasattr(pretrained, "act_postprocess1"):
|
| 72 |
+
layer_1 = pretrained.act_postprocess1(layer_1)
|
| 73 |
+
if hasattr(pretrained, "act_postprocess2"):
|
| 74 |
+
layer_2 = pretrained.act_postprocess2(layer_2)
|
| 75 |
+
if hasattr(pretrained, "act_postprocess3"):
|
| 76 |
+
layer_3 = pretrained.act_postprocess3(layer_3)
|
| 77 |
+
if hasattr(pretrained, "act_postprocess4"):
|
| 78 |
+
layer_4 = pretrained.act_postprocess4(layer_4)
|
| 79 |
+
|
| 80 |
+
return layer_1, layer_2, layer_3, layer_4
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def forward_adapted_unflatten(pretrained, x, function_name="forward_features"):
|
| 84 |
+
b, c, h, w = x.shape
|
| 85 |
+
|
| 86 |
+
exec(f"glob = pretrained.model.{function_name}(x)")
|
| 87 |
+
|
| 88 |
+
layer_1 = pretrained.activations["1"]
|
| 89 |
+
layer_2 = pretrained.activations["2"]
|
| 90 |
+
layer_3 = pretrained.activations["3"]
|
| 91 |
+
layer_4 = pretrained.activations["4"]
|
| 92 |
+
|
| 93 |
+
layer_1 = pretrained.act_postprocess1[0:2](layer_1)
|
| 94 |
+
layer_2 = pretrained.act_postprocess2[0:2](layer_2)
|
| 95 |
+
layer_3 = pretrained.act_postprocess3[0:2](layer_3)
|
| 96 |
+
layer_4 = pretrained.act_postprocess4[0:2](layer_4)
|
| 97 |
+
|
| 98 |
+
unflatten = nn.Sequential(
|
| 99 |
+
nn.Unflatten(
|
| 100 |
+
2,
|
| 101 |
+
torch.Size(
|
| 102 |
+
[
|
| 103 |
+
h // pretrained.model.patch_size[1],
|
| 104 |
+
w // pretrained.model.patch_size[0],
|
| 105 |
+
]
|
| 106 |
+
),
|
| 107 |
+
)
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
if layer_1.ndim == 3:
|
| 111 |
+
layer_1 = unflatten(layer_1)
|
| 112 |
+
if layer_2.ndim == 3:
|
| 113 |
+
layer_2 = unflatten(layer_2)
|
| 114 |
+
if layer_3.ndim == 3:
|
| 115 |
+
layer_3 = unflatten(layer_3)
|
| 116 |
+
if layer_4.ndim == 3:
|
| 117 |
+
layer_4 = unflatten(layer_4)
|
| 118 |
+
|
| 119 |
+
layer_1 = pretrained.act_postprocess1[3: len(pretrained.act_postprocess1)](layer_1)
|
| 120 |
+
layer_2 = pretrained.act_postprocess2[3: len(pretrained.act_postprocess2)](layer_2)
|
| 121 |
+
layer_3 = pretrained.act_postprocess3[3: len(pretrained.act_postprocess3)](layer_3)
|
| 122 |
+
layer_4 = pretrained.act_postprocess4[3: len(pretrained.act_postprocess4)](layer_4)
|
| 123 |
+
|
| 124 |
+
return layer_1, layer_2, layer_3, layer_4
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def get_readout_oper(vit_features, features, use_readout, start_index=1):
|
| 128 |
+
if use_readout == "ignore":
|
| 129 |
+
readout_oper = [Slice(start_index)] * len(features)
|
| 130 |
+
elif use_readout == "add":
|
| 131 |
+
readout_oper = [AddReadout(start_index)] * len(features)
|
| 132 |
+
elif use_readout == "project":
|
| 133 |
+
readout_oper = [
|
| 134 |
+
ProjectReadout(vit_features, start_index) for out_feat in features
|
| 135 |
+
]
|
| 136 |
+
else:
|
| 137 |
+
assert (
|
| 138 |
+
False
|
| 139 |
+
), "wrong operation for readout token, use_readout can be 'ignore', 'add', or 'project'"
|
| 140 |
+
|
| 141 |
+
return readout_oper
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def make_backbone_default(
|
| 145 |
+
model,
|
| 146 |
+
features=[96, 192, 384, 768],
|
| 147 |
+
size=[384, 384],
|
| 148 |
+
hooks=[2, 5, 8, 11],
|
| 149 |
+
vit_features=768,
|
| 150 |
+
use_readout="ignore",
|
| 151 |
+
start_index=1,
|
| 152 |
+
start_index_readout=1,
|
| 153 |
+
):
|
| 154 |
+
pretrained = nn.Module()
|
| 155 |
+
|
| 156 |
+
pretrained.model = model
|
| 157 |
+
pretrained.model.blocks[hooks[0]].register_forward_hook(get_activation("1"))
|
| 158 |
+
pretrained.model.blocks[hooks[1]].register_forward_hook(get_activation("2"))
|
| 159 |
+
pretrained.model.blocks[hooks[2]].register_forward_hook(get_activation("3"))
|
| 160 |
+
pretrained.model.blocks[hooks[3]].register_forward_hook(get_activation("4"))
|
| 161 |
+
|
| 162 |
+
pretrained.activations = activations
|
| 163 |
+
|
| 164 |
+
readout_oper = get_readout_oper(vit_features, features, use_readout, start_index_readout)
|
| 165 |
+
|
| 166 |
+
# 32, 48, 136, 384
|
| 167 |
+
pretrained.act_postprocess1 = nn.Sequential(
|
| 168 |
+
readout_oper[0],
|
| 169 |
+
Transpose(1, 2),
|
| 170 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
| 171 |
+
nn.Conv2d(
|
| 172 |
+
in_channels=vit_features,
|
| 173 |
+
out_channels=features[0],
|
| 174 |
+
kernel_size=1,
|
| 175 |
+
stride=1,
|
| 176 |
+
padding=0,
|
| 177 |
+
),
|
| 178 |
+
nn.ConvTranspose2d(
|
| 179 |
+
in_channels=features[0],
|
| 180 |
+
out_channels=features[0],
|
| 181 |
+
kernel_size=4,
|
| 182 |
+
stride=4,
|
| 183 |
+
padding=0,
|
| 184 |
+
bias=True,
|
| 185 |
+
dilation=1,
|
| 186 |
+
groups=1,
|
| 187 |
+
),
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
pretrained.act_postprocess2 = nn.Sequential(
|
| 191 |
+
readout_oper[1],
|
| 192 |
+
Transpose(1, 2),
|
| 193 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
| 194 |
+
nn.Conv2d(
|
| 195 |
+
in_channels=vit_features,
|
| 196 |
+
out_channels=features[1],
|
| 197 |
+
kernel_size=1,
|
| 198 |
+
stride=1,
|
| 199 |
+
padding=0,
|
| 200 |
+
),
|
| 201 |
+
nn.ConvTranspose2d(
|
| 202 |
+
in_channels=features[1],
|
| 203 |
+
out_channels=features[1],
|
| 204 |
+
kernel_size=2,
|
| 205 |
+
stride=2,
|
| 206 |
+
padding=0,
|
| 207 |
+
bias=True,
|
| 208 |
+
dilation=1,
|
| 209 |
+
groups=1,
|
| 210 |
+
),
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
pretrained.act_postprocess3 = nn.Sequential(
|
| 214 |
+
readout_oper[2],
|
| 215 |
+
Transpose(1, 2),
|
| 216 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
| 217 |
+
nn.Conv2d(
|
| 218 |
+
in_channels=vit_features,
|
| 219 |
+
out_channels=features[2],
|
| 220 |
+
kernel_size=1,
|
| 221 |
+
stride=1,
|
| 222 |
+
padding=0,
|
| 223 |
+
),
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
pretrained.act_postprocess4 = nn.Sequential(
|
| 227 |
+
readout_oper[3],
|
| 228 |
+
Transpose(1, 2),
|
| 229 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
| 230 |
+
nn.Conv2d(
|
| 231 |
+
in_channels=vit_features,
|
| 232 |
+
out_channels=features[3],
|
| 233 |
+
kernel_size=1,
|
| 234 |
+
stride=1,
|
| 235 |
+
padding=0,
|
| 236 |
+
),
|
| 237 |
+
nn.Conv2d(
|
| 238 |
+
in_channels=features[3],
|
| 239 |
+
out_channels=features[3],
|
| 240 |
+
kernel_size=3,
|
| 241 |
+
stride=2,
|
| 242 |
+
padding=1,
|
| 243 |
+
),
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
pretrained.model.start_index = start_index
|
| 247 |
+
pretrained.model.patch_size = [16, 16]
|
| 248 |
+
|
| 249 |
+
return pretrained
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/backbones/vit.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import timm
|
| 4 |
+
import types
|
| 5 |
+
import math
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
|
| 8 |
+
from .utils import (activations, forward_adapted_unflatten, get_activation, get_readout_oper,
|
| 9 |
+
make_backbone_default, Transpose)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def forward_vit(pretrained, x):
|
| 13 |
+
return forward_adapted_unflatten(pretrained, x, "forward_flex")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _resize_pos_embed(self, posemb, gs_h, gs_w):
|
| 17 |
+
posemb_tok, posemb_grid = (
|
| 18 |
+
posemb[:, : self.start_index],
|
| 19 |
+
posemb[0, self.start_index:],
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
gs_old = int(math.sqrt(len(posemb_grid)))
|
| 23 |
+
|
| 24 |
+
posemb_grid = posemb_grid.reshape(1, gs_old, gs_old, -1).permute(0, 3, 1, 2)
|
| 25 |
+
posemb_grid = F.interpolate(posemb_grid, size=(gs_h, gs_w), mode="bilinear")
|
| 26 |
+
posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, gs_h * gs_w, -1)
|
| 27 |
+
|
| 28 |
+
posemb = torch.cat([posemb_tok, posemb_grid], dim=1)
|
| 29 |
+
|
| 30 |
+
return posemb
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def forward_flex(self, x):
|
| 34 |
+
b, c, h, w = x.shape
|
| 35 |
+
|
| 36 |
+
pos_embed = self._resize_pos_embed(
|
| 37 |
+
self.pos_embed, h // self.patch_size[1], w // self.patch_size[0]
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
B = x.shape[0]
|
| 41 |
+
|
| 42 |
+
if hasattr(self.patch_embed, "backbone"):
|
| 43 |
+
x = self.patch_embed.backbone(x)
|
| 44 |
+
if isinstance(x, (list, tuple)):
|
| 45 |
+
x = x[-1] # last feature if backbone outputs list/tuple of features
|
| 46 |
+
|
| 47 |
+
x = self.patch_embed.proj(x).flatten(2).transpose(1, 2)
|
| 48 |
+
|
| 49 |
+
if getattr(self, "dist_token", None) is not None:
|
| 50 |
+
cls_tokens = self.cls_token.expand(
|
| 51 |
+
B, -1, -1
|
| 52 |
+
) # stole cls_tokens impl from Phil Wang, thanks
|
| 53 |
+
dist_token = self.dist_token.expand(B, -1, -1)
|
| 54 |
+
x = torch.cat((cls_tokens, dist_token, x), dim=1)
|
| 55 |
+
else:
|
| 56 |
+
if self.no_embed_class:
|
| 57 |
+
x = x + pos_embed
|
| 58 |
+
cls_tokens = self.cls_token.expand(
|
| 59 |
+
B, -1, -1
|
| 60 |
+
) # stole cls_tokens impl from Phil Wang, thanks
|
| 61 |
+
x = torch.cat((cls_tokens, x), dim=1)
|
| 62 |
+
|
| 63 |
+
if not self.no_embed_class:
|
| 64 |
+
x = x + pos_embed
|
| 65 |
+
x = self.pos_drop(x)
|
| 66 |
+
|
| 67 |
+
for blk in self.blocks:
|
| 68 |
+
x = blk(x)
|
| 69 |
+
|
| 70 |
+
x = self.norm(x)
|
| 71 |
+
|
| 72 |
+
return x
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _make_vit_b16_backbone(
|
| 76 |
+
model,
|
| 77 |
+
features=[96, 192, 384, 768],
|
| 78 |
+
size=[384, 384],
|
| 79 |
+
hooks=[2, 5, 8, 11],
|
| 80 |
+
vit_features=768,
|
| 81 |
+
use_readout="ignore",
|
| 82 |
+
start_index=1,
|
| 83 |
+
start_index_readout=1,
|
| 84 |
+
):
|
| 85 |
+
pretrained = make_backbone_default(model, features, size, hooks, vit_features, use_readout, start_index,
|
| 86 |
+
start_index_readout)
|
| 87 |
+
|
| 88 |
+
# We inject this function into the VisionTransformer instances so that
|
| 89 |
+
# we can use it with interpolated position embeddings without modifying the library source.
|
| 90 |
+
pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)
|
| 91 |
+
pretrained.model._resize_pos_embed = types.MethodType(
|
| 92 |
+
_resize_pos_embed, pretrained.model
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
return pretrained
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _make_pretrained_vitl16_384(pretrained, use_readout="ignore", hooks=None):
|
| 99 |
+
model = timm.create_model("vit_large_patch16_384", pretrained=pretrained)
|
| 100 |
+
|
| 101 |
+
hooks = [5, 11, 17, 23] if hooks == None else hooks
|
| 102 |
+
return _make_vit_b16_backbone(
|
| 103 |
+
model,
|
| 104 |
+
features=[256, 512, 1024, 1024],
|
| 105 |
+
hooks=hooks,
|
| 106 |
+
vit_features=1024,
|
| 107 |
+
use_readout=use_readout,
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _make_pretrained_vitb16_384(pretrained, use_readout="ignore", hooks=None):
|
| 112 |
+
model = timm.create_model("vit_base_patch16_384", pretrained=pretrained)
|
| 113 |
+
|
| 114 |
+
hooks = [2, 5, 8, 11] if hooks == None else hooks
|
| 115 |
+
return _make_vit_b16_backbone(
|
| 116 |
+
model, features=[96, 192, 384, 768], hooks=hooks, use_readout=use_readout
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _make_vit_b_rn50_backbone(
|
| 121 |
+
model,
|
| 122 |
+
features=[256, 512, 768, 768],
|
| 123 |
+
size=[384, 384],
|
| 124 |
+
hooks=[0, 1, 8, 11],
|
| 125 |
+
vit_features=768,
|
| 126 |
+
patch_size=[16, 16],
|
| 127 |
+
number_stages=2,
|
| 128 |
+
use_vit_only=False,
|
| 129 |
+
use_readout="ignore",
|
| 130 |
+
start_index=1,
|
| 131 |
+
):
|
| 132 |
+
pretrained = nn.Module()
|
| 133 |
+
|
| 134 |
+
pretrained.model = model
|
| 135 |
+
|
| 136 |
+
used_number_stages = 0 if use_vit_only else number_stages
|
| 137 |
+
for s in range(used_number_stages):
|
| 138 |
+
pretrained.model.patch_embed.backbone.stages[s].register_forward_hook(
|
| 139 |
+
get_activation(str(s + 1))
|
| 140 |
+
)
|
| 141 |
+
for s in range(used_number_stages, 4):
|
| 142 |
+
pretrained.model.blocks[hooks[s]].register_forward_hook(get_activation(str(s + 1)))
|
| 143 |
+
|
| 144 |
+
pretrained.activations = activations
|
| 145 |
+
|
| 146 |
+
readout_oper = get_readout_oper(vit_features, features, use_readout, start_index)
|
| 147 |
+
|
| 148 |
+
for s in range(used_number_stages):
|
| 149 |
+
value = nn.Sequential(nn.Identity(), nn.Identity(), nn.Identity())
|
| 150 |
+
exec(f"pretrained.act_postprocess{s + 1}=value")
|
| 151 |
+
for s in range(used_number_stages, 4):
|
| 152 |
+
if s < number_stages:
|
| 153 |
+
final_layer = nn.ConvTranspose2d(
|
| 154 |
+
in_channels=features[s],
|
| 155 |
+
out_channels=features[s],
|
| 156 |
+
kernel_size=4 // (2 ** s),
|
| 157 |
+
stride=4 // (2 ** s),
|
| 158 |
+
padding=0,
|
| 159 |
+
bias=True,
|
| 160 |
+
dilation=1,
|
| 161 |
+
groups=1,
|
| 162 |
+
)
|
| 163 |
+
elif s > number_stages:
|
| 164 |
+
final_layer = nn.Conv2d(
|
| 165 |
+
in_channels=features[3],
|
| 166 |
+
out_channels=features[3],
|
| 167 |
+
kernel_size=3,
|
| 168 |
+
stride=2,
|
| 169 |
+
padding=1,
|
| 170 |
+
)
|
| 171 |
+
else:
|
| 172 |
+
final_layer = None
|
| 173 |
+
|
| 174 |
+
layers = [
|
| 175 |
+
readout_oper[s],
|
| 176 |
+
Transpose(1, 2),
|
| 177 |
+
nn.Unflatten(2, torch.Size([size[0] // 16, size[1] // 16])),
|
| 178 |
+
nn.Conv2d(
|
| 179 |
+
in_channels=vit_features,
|
| 180 |
+
out_channels=features[s],
|
| 181 |
+
kernel_size=1,
|
| 182 |
+
stride=1,
|
| 183 |
+
padding=0,
|
| 184 |
+
),
|
| 185 |
+
]
|
| 186 |
+
if final_layer is not None:
|
| 187 |
+
layers.append(final_layer)
|
| 188 |
+
|
| 189 |
+
value = nn.Sequential(*layers)
|
| 190 |
+
exec(f"pretrained.act_postprocess{s + 1}=value")
|
| 191 |
+
|
| 192 |
+
pretrained.model.start_index = start_index
|
| 193 |
+
pretrained.model.patch_size = patch_size
|
| 194 |
+
|
| 195 |
+
# We inject this function into the VisionTransformer instances so that
|
| 196 |
+
# we can use it with interpolated position embeddings without modifying the library source.
|
| 197 |
+
pretrained.model.forward_flex = types.MethodType(forward_flex, pretrained.model)
|
| 198 |
+
|
| 199 |
+
# We inject this function into the VisionTransformer instances so that
|
| 200 |
+
# we can use it with interpolated position embeddings without modifying the library source.
|
| 201 |
+
pretrained.model._resize_pos_embed = types.MethodType(
|
| 202 |
+
_resize_pos_embed, pretrained.model
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
return pretrained
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _make_pretrained_vitb_rn50_384(
|
| 209 |
+
pretrained, use_readout="ignore", hooks=None, use_vit_only=False
|
| 210 |
+
):
|
| 211 |
+
model = timm.create_model("vit_base_resnet50_384", pretrained=pretrained)
|
| 212 |
+
|
| 213 |
+
hooks = [0, 1, 8, 11] if hooks == None else hooks
|
| 214 |
+
return _make_vit_b_rn50_backbone(
|
| 215 |
+
model,
|
| 216 |
+
features=[256, 512, 768, 768],
|
| 217 |
+
size=[384, 384],
|
| 218 |
+
hooks=hooks,
|
| 219 |
+
use_vit_only=use_vit_only,
|
| 220 |
+
use_readout=use_readout,
|
| 221 |
+
)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/base_model.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class BaseModel(torch.nn.Module):
|
| 5 |
+
def load(self, path):
|
| 6 |
+
"""Load model from file.
|
| 7 |
+
|
| 8 |
+
Args:
|
| 9 |
+
path (str): file path
|
| 10 |
+
"""
|
| 11 |
+
parameters = torch.load(path, map_location=torch.device('cpu'))
|
| 12 |
+
|
| 13 |
+
if "optimizer" in parameters:
|
| 14 |
+
parameters = parameters["model"]
|
| 15 |
+
|
| 16 |
+
self.load_state_dict(parameters)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/blocks.py
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from .backbones.beit import (
|
| 5 |
+
_make_pretrained_beitl16_512,
|
| 6 |
+
_make_pretrained_beitl16_384,
|
| 7 |
+
_make_pretrained_beitb16_384,
|
| 8 |
+
forward_beit,
|
| 9 |
+
)
|
| 10 |
+
from .backbones.swin_common import (
|
| 11 |
+
forward_swin,
|
| 12 |
+
)
|
| 13 |
+
from .backbones.swin2 import (
|
| 14 |
+
_make_pretrained_swin2l24_384,
|
| 15 |
+
_make_pretrained_swin2b24_384,
|
| 16 |
+
_make_pretrained_swin2t16_256,
|
| 17 |
+
)
|
| 18 |
+
from .backbones.swin import (
|
| 19 |
+
_make_pretrained_swinl12_384,
|
| 20 |
+
)
|
| 21 |
+
from .backbones.levit import (
|
| 22 |
+
_make_pretrained_levit_384,
|
| 23 |
+
forward_levit,
|
| 24 |
+
)
|
| 25 |
+
from .backbones.vit import (
|
| 26 |
+
_make_pretrained_vitb_rn50_384,
|
| 27 |
+
_make_pretrained_vitl16_384,
|
| 28 |
+
_make_pretrained_vitb16_384,
|
| 29 |
+
forward_vit,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None,
|
| 33 |
+
use_vit_only=False, use_readout="ignore", in_features=[96, 256, 512, 1024]):
|
| 34 |
+
if backbone == "beitl16_512":
|
| 35 |
+
pretrained = _make_pretrained_beitl16_512(
|
| 36 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
| 37 |
+
)
|
| 38 |
+
scratch = _make_scratch(
|
| 39 |
+
[256, 512, 1024, 1024], features, groups=groups, expand=expand
|
| 40 |
+
) # BEiT_512-L (backbone)
|
| 41 |
+
elif backbone == "beitl16_384":
|
| 42 |
+
pretrained = _make_pretrained_beitl16_384(
|
| 43 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
| 44 |
+
)
|
| 45 |
+
scratch = _make_scratch(
|
| 46 |
+
[256, 512, 1024, 1024], features, groups=groups, expand=expand
|
| 47 |
+
) # BEiT_384-L (backbone)
|
| 48 |
+
elif backbone == "beitb16_384":
|
| 49 |
+
pretrained = _make_pretrained_beitb16_384(
|
| 50 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
| 51 |
+
)
|
| 52 |
+
scratch = _make_scratch(
|
| 53 |
+
[96, 192, 384, 768], features, groups=groups, expand=expand
|
| 54 |
+
) # BEiT_384-B (backbone)
|
| 55 |
+
elif backbone == "swin2l24_384":
|
| 56 |
+
pretrained = _make_pretrained_swin2l24_384(
|
| 57 |
+
use_pretrained, hooks=hooks
|
| 58 |
+
)
|
| 59 |
+
scratch = _make_scratch(
|
| 60 |
+
[192, 384, 768, 1536], features, groups=groups, expand=expand
|
| 61 |
+
) # Swin2-L/12to24 (backbone)
|
| 62 |
+
elif backbone == "swin2b24_384":
|
| 63 |
+
pretrained = _make_pretrained_swin2b24_384(
|
| 64 |
+
use_pretrained, hooks=hooks
|
| 65 |
+
)
|
| 66 |
+
scratch = _make_scratch(
|
| 67 |
+
[128, 256, 512, 1024], features, groups=groups, expand=expand
|
| 68 |
+
) # Swin2-B/12to24 (backbone)
|
| 69 |
+
elif backbone == "swin2t16_256":
|
| 70 |
+
pretrained = _make_pretrained_swin2t16_256(
|
| 71 |
+
use_pretrained, hooks=hooks
|
| 72 |
+
)
|
| 73 |
+
scratch = _make_scratch(
|
| 74 |
+
[96, 192, 384, 768], features, groups=groups, expand=expand
|
| 75 |
+
) # Swin2-T/16 (backbone)
|
| 76 |
+
elif backbone == "swinl12_384":
|
| 77 |
+
pretrained = _make_pretrained_swinl12_384(
|
| 78 |
+
use_pretrained, hooks=hooks
|
| 79 |
+
)
|
| 80 |
+
scratch = _make_scratch(
|
| 81 |
+
[192, 384, 768, 1536], features, groups=groups, expand=expand
|
| 82 |
+
) # Swin-L/12 (backbone)
|
| 83 |
+
elif backbone == "next_vit_large_6m":
|
| 84 |
+
from .backbones.next_vit import _make_pretrained_next_vit_large_6m
|
| 85 |
+
pretrained = _make_pretrained_next_vit_large_6m(hooks=hooks)
|
| 86 |
+
scratch = _make_scratch(
|
| 87 |
+
in_features, features, groups=groups, expand=expand
|
| 88 |
+
) # Next-ViT-L on ImageNet-1K-6M (backbone)
|
| 89 |
+
elif backbone == "levit_384":
|
| 90 |
+
pretrained = _make_pretrained_levit_384(
|
| 91 |
+
use_pretrained, hooks=hooks
|
| 92 |
+
)
|
| 93 |
+
scratch = _make_scratch(
|
| 94 |
+
[384, 512, 768], features, groups=groups, expand=expand
|
| 95 |
+
) # LeViT 384 (backbone)
|
| 96 |
+
elif backbone == "vitl16_384":
|
| 97 |
+
pretrained = _make_pretrained_vitl16_384(
|
| 98 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
| 99 |
+
)
|
| 100 |
+
scratch = _make_scratch(
|
| 101 |
+
[256, 512, 1024, 1024], features, groups=groups, expand=expand
|
| 102 |
+
) # ViT-L/16 - 85.0% Top1 (backbone)
|
| 103 |
+
elif backbone == "vitb_rn50_384":
|
| 104 |
+
pretrained = _make_pretrained_vitb_rn50_384(
|
| 105 |
+
use_pretrained,
|
| 106 |
+
hooks=hooks,
|
| 107 |
+
use_vit_only=use_vit_only,
|
| 108 |
+
use_readout=use_readout,
|
| 109 |
+
)
|
| 110 |
+
scratch = _make_scratch(
|
| 111 |
+
[256, 512, 768, 768], features, groups=groups, expand=expand
|
| 112 |
+
) # ViT-H/16 - 85.0% Top1 (backbone)
|
| 113 |
+
elif backbone == "vitb16_384":
|
| 114 |
+
pretrained = _make_pretrained_vitb16_384(
|
| 115 |
+
use_pretrained, hooks=hooks, use_readout=use_readout
|
| 116 |
+
)
|
| 117 |
+
scratch = _make_scratch(
|
| 118 |
+
[96, 192, 384, 768], features, groups=groups, expand=expand
|
| 119 |
+
) # ViT-B/16 - 84.6% Top1 (backbone)
|
| 120 |
+
elif backbone == "resnext101_wsl":
|
| 121 |
+
pretrained = _make_pretrained_resnext101_wsl(use_pretrained)
|
| 122 |
+
scratch = _make_scratch([256, 512, 1024, 2048], features, groups=groups, expand=expand) # efficientnet_lite3
|
| 123 |
+
elif backbone == "efficientnet_lite3":
|
| 124 |
+
pretrained = _make_pretrained_efficientnet_lite3(use_pretrained, exportable=exportable)
|
| 125 |
+
scratch = _make_scratch([32, 48, 136, 384], features, groups=groups, expand=expand) # efficientnet_lite3
|
| 126 |
+
else:
|
| 127 |
+
print(f"Backbone '{backbone}' not implemented")
|
| 128 |
+
assert False
|
| 129 |
+
|
| 130 |
+
return pretrained, scratch
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _make_scratch(in_shape, out_shape, groups=1, expand=False):
|
| 134 |
+
scratch = nn.Module()
|
| 135 |
+
|
| 136 |
+
out_shape1 = out_shape
|
| 137 |
+
out_shape2 = out_shape
|
| 138 |
+
out_shape3 = out_shape
|
| 139 |
+
if len(in_shape) >= 4:
|
| 140 |
+
out_shape4 = out_shape
|
| 141 |
+
|
| 142 |
+
if expand:
|
| 143 |
+
out_shape1 = out_shape
|
| 144 |
+
out_shape2 = out_shape*2
|
| 145 |
+
out_shape3 = out_shape*4
|
| 146 |
+
if len(in_shape) >= 4:
|
| 147 |
+
out_shape4 = out_shape*8
|
| 148 |
+
|
| 149 |
+
scratch.layer1_rn = nn.Conv2d(
|
| 150 |
+
in_shape[0], out_shape1, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
| 151 |
+
)
|
| 152 |
+
scratch.layer2_rn = nn.Conv2d(
|
| 153 |
+
in_shape[1], out_shape2, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
| 154 |
+
)
|
| 155 |
+
scratch.layer3_rn = nn.Conv2d(
|
| 156 |
+
in_shape[2], out_shape3, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
| 157 |
+
)
|
| 158 |
+
if len(in_shape) >= 4:
|
| 159 |
+
scratch.layer4_rn = nn.Conv2d(
|
| 160 |
+
in_shape[3], out_shape4, kernel_size=3, stride=1, padding=1, bias=False, groups=groups
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
return scratch
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def _make_pretrained_efficientnet_lite3(use_pretrained, exportable=False):
|
| 167 |
+
efficientnet = torch.hub.load(
|
| 168 |
+
"rwightman/gen-efficientnet-pytorch",
|
| 169 |
+
"tf_efficientnet_lite3",
|
| 170 |
+
pretrained=use_pretrained,
|
| 171 |
+
exportable=exportable
|
| 172 |
+
)
|
| 173 |
+
return _make_efficientnet_backbone(efficientnet)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _make_efficientnet_backbone(effnet):
|
| 177 |
+
pretrained = nn.Module()
|
| 178 |
+
|
| 179 |
+
pretrained.layer1 = nn.Sequential(
|
| 180 |
+
effnet.conv_stem, effnet.bn1, effnet.act1, *effnet.blocks[0:2]
|
| 181 |
+
)
|
| 182 |
+
pretrained.layer2 = nn.Sequential(*effnet.blocks[2:3])
|
| 183 |
+
pretrained.layer3 = nn.Sequential(*effnet.blocks[3:5])
|
| 184 |
+
pretrained.layer4 = nn.Sequential(*effnet.blocks[5:9])
|
| 185 |
+
|
| 186 |
+
return pretrained
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _make_resnet_backbone(resnet):
|
| 190 |
+
pretrained = nn.Module()
|
| 191 |
+
pretrained.layer1 = nn.Sequential(
|
| 192 |
+
resnet.conv1, resnet.bn1, resnet.relu, resnet.maxpool, resnet.layer1
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
pretrained.layer2 = resnet.layer2
|
| 196 |
+
pretrained.layer3 = resnet.layer3
|
| 197 |
+
pretrained.layer4 = resnet.layer4
|
| 198 |
+
|
| 199 |
+
return pretrained
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _make_pretrained_resnext101_wsl(use_pretrained):
|
| 203 |
+
resnet = torch.hub.load("facebookresearch/WSL-Images", "resnext101_32x8d_wsl")
|
| 204 |
+
return _make_resnet_backbone(resnet)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class Interpolate(nn.Module):
|
| 209 |
+
"""Interpolation module.
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
def __init__(self, scale_factor, mode, align_corners=False):
|
| 213 |
+
"""Init.
|
| 214 |
+
|
| 215 |
+
Args:
|
| 216 |
+
scale_factor (float): scaling
|
| 217 |
+
mode (str): interpolation mode
|
| 218 |
+
"""
|
| 219 |
+
super(Interpolate, self).__init__()
|
| 220 |
+
|
| 221 |
+
self.interp = nn.functional.interpolate
|
| 222 |
+
self.scale_factor = scale_factor
|
| 223 |
+
self.mode = mode
|
| 224 |
+
self.align_corners = align_corners
|
| 225 |
+
|
| 226 |
+
def forward(self, x):
|
| 227 |
+
"""Forward pass.
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
x (tensor): input
|
| 231 |
+
|
| 232 |
+
Returns:
|
| 233 |
+
tensor: interpolated data
|
| 234 |
+
"""
|
| 235 |
+
|
| 236 |
+
x = self.interp(
|
| 237 |
+
x, scale_factor=self.scale_factor, mode=self.mode, align_corners=self.align_corners
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
return x
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class ResidualConvUnit(nn.Module):
|
| 244 |
+
"""Residual convolution module.
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
def __init__(self, features):
|
| 248 |
+
"""Init.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
features (int): number of features
|
| 252 |
+
"""
|
| 253 |
+
super().__init__()
|
| 254 |
+
|
| 255 |
+
self.conv1 = nn.Conv2d(
|
| 256 |
+
features, features, kernel_size=3, stride=1, padding=1, bias=True
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
self.conv2 = nn.Conv2d(
|
| 260 |
+
features, features, kernel_size=3, stride=1, padding=1, bias=True
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
self.relu = nn.ReLU(inplace=True)
|
| 264 |
+
|
| 265 |
+
def forward(self, x):
|
| 266 |
+
"""Forward pass.
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
x (tensor): input
|
| 270 |
+
|
| 271 |
+
Returns:
|
| 272 |
+
tensor: output
|
| 273 |
+
"""
|
| 274 |
+
out = self.relu(x)
|
| 275 |
+
out = self.conv1(out)
|
| 276 |
+
out = self.relu(out)
|
| 277 |
+
out = self.conv2(out)
|
| 278 |
+
|
| 279 |
+
return out + x
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class FeatureFusionBlock(nn.Module):
|
| 283 |
+
"""Feature fusion block.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
def __init__(self, features):
|
| 287 |
+
"""Init.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
features (int): number of features
|
| 291 |
+
"""
|
| 292 |
+
super(FeatureFusionBlock, self).__init__()
|
| 293 |
+
|
| 294 |
+
self.resConfUnit1 = ResidualConvUnit(features)
|
| 295 |
+
self.resConfUnit2 = ResidualConvUnit(features)
|
| 296 |
+
|
| 297 |
+
def forward(self, *xs):
|
| 298 |
+
"""Forward pass.
|
| 299 |
+
|
| 300 |
+
Returns:
|
| 301 |
+
tensor: output
|
| 302 |
+
"""
|
| 303 |
+
output = xs[0]
|
| 304 |
+
|
| 305 |
+
if len(xs) == 2:
|
| 306 |
+
output += self.resConfUnit1(xs[1])
|
| 307 |
+
|
| 308 |
+
output = self.resConfUnit2(output)
|
| 309 |
+
|
| 310 |
+
output = nn.functional.interpolate(
|
| 311 |
+
output, scale_factor=2, mode="bilinear", align_corners=True
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
return output
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class ResidualConvUnit_custom(nn.Module):
|
| 320 |
+
"""Residual convolution module.
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
def __init__(self, features, activation, bn):
|
| 324 |
+
"""Init.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
features (int): number of features
|
| 328 |
+
"""
|
| 329 |
+
super().__init__()
|
| 330 |
+
|
| 331 |
+
self.bn = bn
|
| 332 |
+
|
| 333 |
+
self.groups=1
|
| 334 |
+
|
| 335 |
+
self.conv1 = nn.Conv2d(
|
| 336 |
+
features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
self.conv2 = nn.Conv2d(
|
| 340 |
+
features, features, kernel_size=3, stride=1, padding=1, bias=True, groups=self.groups
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
if self.bn==True:
|
| 344 |
+
self.bn1 = nn.BatchNorm2d(features)
|
| 345 |
+
self.bn2 = nn.BatchNorm2d(features)
|
| 346 |
+
|
| 347 |
+
self.activation = activation
|
| 348 |
+
|
| 349 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 350 |
+
|
| 351 |
+
def forward(self, x):
|
| 352 |
+
"""Forward pass.
|
| 353 |
+
|
| 354 |
+
Args:
|
| 355 |
+
x (tensor): input
|
| 356 |
+
|
| 357 |
+
Returns:
|
| 358 |
+
tensor: output
|
| 359 |
+
"""
|
| 360 |
+
|
| 361 |
+
out = self.activation(x)
|
| 362 |
+
out = self.conv1(out)
|
| 363 |
+
if self.bn==True:
|
| 364 |
+
out = self.bn1(out)
|
| 365 |
+
|
| 366 |
+
out = self.activation(out)
|
| 367 |
+
out = self.conv2(out)
|
| 368 |
+
if self.bn==True:
|
| 369 |
+
out = self.bn2(out)
|
| 370 |
+
|
| 371 |
+
if self.groups > 1:
|
| 372 |
+
out = self.conv_merge(out)
|
| 373 |
+
|
| 374 |
+
return self.skip_add.add(out, x)
|
| 375 |
+
|
| 376 |
+
# return out + x
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
class FeatureFusionBlock_custom(nn.Module):
|
| 380 |
+
"""Feature fusion block.
|
| 381 |
+
"""
|
| 382 |
+
|
| 383 |
+
def __init__(self, features, activation, deconv=False, bn=False, expand=False, align_corners=True, size=None):
|
| 384 |
+
"""Init.
|
| 385 |
+
|
| 386 |
+
Args:
|
| 387 |
+
features (int): number of features
|
| 388 |
+
"""
|
| 389 |
+
super(FeatureFusionBlock_custom, self).__init__()
|
| 390 |
+
|
| 391 |
+
self.deconv = deconv
|
| 392 |
+
self.align_corners = align_corners
|
| 393 |
+
|
| 394 |
+
self.groups=1
|
| 395 |
+
|
| 396 |
+
self.expand = expand
|
| 397 |
+
out_features = features
|
| 398 |
+
if self.expand==True:
|
| 399 |
+
out_features = features//2
|
| 400 |
+
|
| 401 |
+
self.out_conv = nn.Conv2d(features, out_features, kernel_size=1, stride=1, padding=0, bias=True, groups=1)
|
| 402 |
+
|
| 403 |
+
self.resConfUnit1 = ResidualConvUnit_custom(features, activation, bn)
|
| 404 |
+
self.resConfUnit2 = ResidualConvUnit_custom(features, activation, bn)
|
| 405 |
+
|
| 406 |
+
self.skip_add = nn.quantized.FloatFunctional()
|
| 407 |
+
|
| 408 |
+
self.size=size
|
| 409 |
+
|
| 410 |
+
def forward(self, *xs, size=None):
|
| 411 |
+
"""Forward pass.
|
| 412 |
+
|
| 413 |
+
Returns:
|
| 414 |
+
tensor: output
|
| 415 |
+
"""
|
| 416 |
+
output = xs[0]
|
| 417 |
+
|
| 418 |
+
if len(xs) == 2:
|
| 419 |
+
res = self.resConfUnit1(xs[1])
|
| 420 |
+
output = self.skip_add.add(output, res)
|
| 421 |
+
# output += res
|
| 422 |
+
|
| 423 |
+
output = self.resConfUnit2(output)
|
| 424 |
+
|
| 425 |
+
if (size is None) and (self.size is None):
|
| 426 |
+
modifier = {"scale_factor": 2}
|
| 427 |
+
elif size is None:
|
| 428 |
+
modifier = {"size": self.size}
|
| 429 |
+
else:
|
| 430 |
+
modifier = {"size": size}
|
| 431 |
+
|
| 432 |
+
output = nn.functional.interpolate(
|
| 433 |
+
output, **modifier, mode="bilinear", align_corners=self.align_corners
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
output = self.out_conv(output)
|
| 437 |
+
|
| 438 |
+
return output
|
| 439 |
+
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/dpt_depth.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
from .base_model import BaseModel
|
| 5 |
+
from .blocks import (
|
| 6 |
+
FeatureFusionBlock_custom,
|
| 7 |
+
Interpolate,
|
| 8 |
+
_make_encoder,
|
| 9 |
+
forward_beit,
|
| 10 |
+
forward_swin,
|
| 11 |
+
forward_levit,
|
| 12 |
+
forward_vit,
|
| 13 |
+
)
|
| 14 |
+
from .backbones.levit import stem_b4_transpose
|
| 15 |
+
from timm.layers import get_act_layer
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _make_fusion_block(features, use_bn, size = None):
|
| 19 |
+
return FeatureFusionBlock_custom(
|
| 20 |
+
features,
|
| 21 |
+
nn.ReLU(False),
|
| 22 |
+
deconv=False,
|
| 23 |
+
bn=use_bn,
|
| 24 |
+
expand=False,
|
| 25 |
+
align_corners=True,
|
| 26 |
+
size=size,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DPT(BaseModel):
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
head,
|
| 34 |
+
features=256,
|
| 35 |
+
backbone="vitb_rn50_384",
|
| 36 |
+
readout="project",
|
| 37 |
+
channels_last=False,
|
| 38 |
+
use_bn=False,
|
| 39 |
+
**kwargs
|
| 40 |
+
):
|
| 41 |
+
|
| 42 |
+
super(DPT, self).__init__()
|
| 43 |
+
|
| 44 |
+
self.channels_last = channels_last
|
| 45 |
+
|
| 46 |
+
# For the Swin, Swin 2, LeViT and Next-ViT Transformers, the hierarchical architectures prevent setting the
|
| 47 |
+
# hooks freely. Instead, the hooks have to be chosen according to the ranges specified in the comments.
|
| 48 |
+
hooks = {
|
| 49 |
+
"beitl16_512": [5, 11, 17, 23],
|
| 50 |
+
"beitl16_384": [5, 11, 17, 23],
|
| 51 |
+
"beitb16_384": [2, 5, 8, 11],
|
| 52 |
+
"swin2l24_384": [1, 1, 17, 1], # Allowed ranges: [0, 1], [0, 1], [ 0, 17], [ 0, 1]
|
| 53 |
+
"swin2b24_384": [1, 1, 17, 1], # [0, 1], [0, 1], [ 0, 17], [ 0, 1]
|
| 54 |
+
"swin2t16_256": [1, 1, 5, 1], # [0, 1], [0, 1], [ 0, 5], [ 0, 1]
|
| 55 |
+
"swinl12_384": [1, 1, 17, 1], # [0, 1], [0, 1], [ 0, 17], [ 0, 1]
|
| 56 |
+
"next_vit_large_6m": [2, 6, 36, 39], # [0, 2], [3, 6], [ 7, 36], [37, 39]
|
| 57 |
+
"levit_384": [3, 11, 21], # [0, 3], [6, 11], [14, 21]
|
| 58 |
+
"vitb_rn50_384": [0, 1, 8, 11],
|
| 59 |
+
"vitb16_384": [2, 5, 8, 11],
|
| 60 |
+
"vitl16_384": [5, 11, 17, 23],
|
| 61 |
+
}[backbone]
|
| 62 |
+
|
| 63 |
+
if "next_vit" in backbone:
|
| 64 |
+
in_features = {
|
| 65 |
+
"next_vit_large_6m": [96, 256, 512, 1024],
|
| 66 |
+
}[backbone]
|
| 67 |
+
else:
|
| 68 |
+
in_features = None
|
| 69 |
+
|
| 70 |
+
# Instantiate backbone and reassemble blocks
|
| 71 |
+
self.pretrained, self.scratch = _make_encoder(
|
| 72 |
+
backbone,
|
| 73 |
+
features,
|
| 74 |
+
False, # Set to true of you want to train from scratch, uses ImageNet weights
|
| 75 |
+
groups=1,
|
| 76 |
+
expand=False,
|
| 77 |
+
exportable=False,
|
| 78 |
+
hooks=hooks,
|
| 79 |
+
use_readout=readout,
|
| 80 |
+
in_features=in_features,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
self.number_layers = len(hooks) if hooks is not None else 4
|
| 84 |
+
size_refinenet3 = None
|
| 85 |
+
self.scratch.stem_transpose = None
|
| 86 |
+
|
| 87 |
+
if "beit" in backbone:
|
| 88 |
+
self.forward_transformer = forward_beit
|
| 89 |
+
elif "swin" in backbone:
|
| 90 |
+
self.forward_transformer = forward_swin
|
| 91 |
+
elif "next_vit" in backbone:
|
| 92 |
+
from .backbones.next_vit import forward_next_vit
|
| 93 |
+
self.forward_transformer = forward_next_vit
|
| 94 |
+
elif "levit" in backbone:
|
| 95 |
+
self.forward_transformer = forward_levit
|
| 96 |
+
size_refinenet3 = 7
|
| 97 |
+
self.scratch.stem_transpose = stem_b4_transpose(256, 128, get_act_layer("hard_swish"))
|
| 98 |
+
else:
|
| 99 |
+
self.forward_transformer = forward_vit
|
| 100 |
+
|
| 101 |
+
self.scratch.refinenet1 = _make_fusion_block(features, use_bn)
|
| 102 |
+
self.scratch.refinenet2 = _make_fusion_block(features, use_bn)
|
| 103 |
+
self.scratch.refinenet3 = _make_fusion_block(features, use_bn, size_refinenet3)
|
| 104 |
+
if self.number_layers >= 4:
|
| 105 |
+
self.scratch.refinenet4 = _make_fusion_block(features, use_bn)
|
| 106 |
+
|
| 107 |
+
self.scratch.output_conv = head
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def forward(self, x):
|
| 111 |
+
if self.channels_last == True:
|
| 112 |
+
x.contiguous(memory_format=torch.channels_last)
|
| 113 |
+
|
| 114 |
+
layers = self.forward_transformer(self.pretrained, x)
|
| 115 |
+
if self.number_layers == 3:
|
| 116 |
+
layer_1, layer_2, layer_3 = layers
|
| 117 |
+
else:
|
| 118 |
+
layer_1, layer_2, layer_3, layer_4 = layers
|
| 119 |
+
|
| 120 |
+
layer_1_rn = self.scratch.layer1_rn(layer_1)
|
| 121 |
+
layer_2_rn = self.scratch.layer2_rn(layer_2)
|
| 122 |
+
layer_3_rn = self.scratch.layer3_rn(layer_3)
|
| 123 |
+
if self.number_layers >= 4:
|
| 124 |
+
layer_4_rn = self.scratch.layer4_rn(layer_4)
|
| 125 |
+
|
| 126 |
+
if self.number_layers == 3:
|
| 127 |
+
path_3 = self.scratch.refinenet3(layer_3_rn, size=layer_2_rn.shape[2:])
|
| 128 |
+
else:
|
| 129 |
+
path_4 = self.scratch.refinenet4(layer_4_rn, size=layer_3_rn.shape[2:])
|
| 130 |
+
path_3 = self.scratch.refinenet3(path_4, layer_3_rn, size=layer_2_rn.shape[2:])
|
| 131 |
+
path_2 = self.scratch.refinenet2(path_3, layer_2_rn, size=layer_1_rn.shape[2:])
|
| 132 |
+
path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
|
| 133 |
+
|
| 134 |
+
if self.scratch.stem_transpose is not None:
|
| 135 |
+
path_1 = self.scratch.stem_transpose(path_1)
|
| 136 |
+
|
| 137 |
+
out = self.scratch.output_conv(path_1)
|
| 138 |
+
|
| 139 |
+
return out
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class DPTDepthModel(DPT):
|
| 143 |
+
def __init__(self, path=None, non_negative=True, **kwargs):
|
| 144 |
+
features = kwargs["features"] if "features" in kwargs else 256
|
| 145 |
+
head_features_1 = kwargs["head_features_1"] if "head_features_1" in kwargs else features
|
| 146 |
+
head_features_2 = kwargs["head_features_2"] if "head_features_2" in kwargs else 32
|
| 147 |
+
kwargs.pop("head_features_1", None)
|
| 148 |
+
kwargs.pop("head_features_2", None)
|
| 149 |
+
|
| 150 |
+
head = nn.Sequential(
|
| 151 |
+
nn.Conv2d(head_features_1, head_features_1 // 2, kernel_size=3, stride=1, padding=1),
|
| 152 |
+
Interpolate(scale_factor=2, mode="bilinear", align_corners=True),
|
| 153 |
+
nn.Conv2d(head_features_1 // 2, head_features_2, kernel_size=3, stride=1, padding=1),
|
| 154 |
+
nn.ReLU(True),
|
| 155 |
+
nn.Conv2d(head_features_2, 1, kernel_size=1, stride=1, padding=0),
|
| 156 |
+
nn.ReLU(True) if non_negative else nn.Identity(),
|
| 157 |
+
nn.Identity(),
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
super().__init__(head, **kwargs)
|
| 161 |
+
|
| 162 |
+
if path is not None:
|
| 163 |
+
self.load(path)
|
| 164 |
+
|
| 165 |
+
def forward(self, x):
|
| 166 |
+
return super().forward(x).squeeze(dim=1)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MidashNet: Network for monocular depth estimation trained by mixing several datasets.
|
| 2 |
+
This file contains code that is adapted from
|
| 3 |
+
https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py
|
| 4 |
+
"""
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
|
| 8 |
+
from .base_model import BaseModel
|
| 9 |
+
from .blocks import FeatureFusionBlock, Interpolate, _make_encoder
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class MidasNet(BaseModel):
|
| 13 |
+
"""Network for monocular depth estimation.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def __init__(self, path=None, features=256, non_negative=True):
|
| 17 |
+
"""Init.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
path (str, optional): Path to saved model. Defaults to None.
|
| 21 |
+
features (int, optional): Number of features. Defaults to 256.
|
| 22 |
+
backbone (str, optional): Backbone network for encoder. Defaults to resnet50
|
| 23 |
+
"""
|
| 24 |
+
print("Loading weights: ", path)
|
| 25 |
+
|
| 26 |
+
super(MidasNet, self).__init__()
|
| 27 |
+
|
| 28 |
+
use_pretrained = False if path is None else True
|
| 29 |
+
|
| 30 |
+
self.pretrained, self.scratch = _make_encoder(backbone="resnext101_wsl", features=features, use_pretrained=use_pretrained)
|
| 31 |
+
|
| 32 |
+
self.scratch.refinenet4 = FeatureFusionBlock(features)
|
| 33 |
+
self.scratch.refinenet3 = FeatureFusionBlock(features)
|
| 34 |
+
self.scratch.refinenet2 = FeatureFusionBlock(features)
|
| 35 |
+
self.scratch.refinenet1 = FeatureFusionBlock(features)
|
| 36 |
+
|
| 37 |
+
self.scratch.output_conv = nn.Sequential(
|
| 38 |
+
nn.Conv2d(features, 128, kernel_size=3, stride=1, padding=1),
|
| 39 |
+
Interpolate(scale_factor=2, mode="bilinear"),
|
| 40 |
+
nn.Conv2d(128, 32, kernel_size=3, stride=1, padding=1),
|
| 41 |
+
nn.ReLU(True),
|
| 42 |
+
nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),
|
| 43 |
+
nn.ReLU(True) if non_negative else nn.Identity(),
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if path:
|
| 47 |
+
self.load(path)
|
| 48 |
+
|
| 49 |
+
def forward(self, x):
|
| 50 |
+
"""Forward pass.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
x (tensor): input data (image)
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
tensor: depth
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
layer_1 = self.pretrained.layer1(x)
|
| 60 |
+
layer_2 = self.pretrained.layer2(layer_1)
|
| 61 |
+
layer_3 = self.pretrained.layer3(layer_2)
|
| 62 |
+
layer_4 = self.pretrained.layer4(layer_3)
|
| 63 |
+
|
| 64 |
+
layer_1_rn = self.scratch.layer1_rn(layer_1)
|
| 65 |
+
layer_2_rn = self.scratch.layer2_rn(layer_2)
|
| 66 |
+
layer_3_rn = self.scratch.layer3_rn(layer_3)
|
| 67 |
+
layer_4_rn = self.scratch.layer4_rn(layer_4)
|
| 68 |
+
|
| 69 |
+
path_4 = self.scratch.refinenet4(layer_4_rn)
|
| 70 |
+
path_3 = self.scratch.refinenet3(path_4, layer_3_rn)
|
| 71 |
+
path_2 = self.scratch.refinenet2(path_3, layer_2_rn)
|
| 72 |
+
path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
|
| 73 |
+
|
| 74 |
+
out = self.scratch.output_conv(path_1)
|
| 75 |
+
|
| 76 |
+
return torch.squeeze(out, dim=1)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/midas_net_custom.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MidashNet: Network for monocular depth estimation trained by mixing several datasets.
|
| 2 |
+
This file contains code that is adapted from
|
| 3 |
+
https://github.com/thomasjpfan/pytorch_refinenet/blob/master/pytorch_refinenet/refinenet/refinenet_4cascade.py
|
| 4 |
+
"""
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
|
| 8 |
+
from .base_model import BaseModel
|
| 9 |
+
from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class MidasNet_small(BaseModel):
|
| 13 |
+
"""Network for monocular depth estimation.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def __init__(self, path=None, features=64, backbone="efficientnet_lite3", non_negative=True, exportable=True, channels_last=False, align_corners=True,
|
| 17 |
+
blocks={'expand': True}):
|
| 18 |
+
"""Init.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
path (str, optional): Path to saved model. Defaults to None.
|
| 22 |
+
features (int, optional): Number of features. Defaults to 256.
|
| 23 |
+
backbone (str, optional): Backbone network for encoder. Defaults to resnet50
|
| 24 |
+
"""
|
| 25 |
+
print("Loading weights: ", path)
|
| 26 |
+
|
| 27 |
+
super(MidasNet_small, self).__init__()
|
| 28 |
+
|
| 29 |
+
use_pretrained = False if path else True
|
| 30 |
+
|
| 31 |
+
self.channels_last = channels_last
|
| 32 |
+
self.blocks = blocks
|
| 33 |
+
self.backbone = backbone
|
| 34 |
+
|
| 35 |
+
self.groups = 1
|
| 36 |
+
|
| 37 |
+
features1=features
|
| 38 |
+
features2=features
|
| 39 |
+
features3=features
|
| 40 |
+
features4=features
|
| 41 |
+
self.expand = False
|
| 42 |
+
if "expand" in self.blocks and self.blocks['expand'] == True:
|
| 43 |
+
self.expand = True
|
| 44 |
+
features1=features
|
| 45 |
+
features2=features*2
|
| 46 |
+
features3=features*4
|
| 47 |
+
features4=features*8
|
| 48 |
+
|
| 49 |
+
self.pretrained, self.scratch = _make_encoder(self.backbone, features, use_pretrained, groups=self.groups, expand=self.expand, exportable=exportable)
|
| 50 |
+
|
| 51 |
+
self.scratch.activation = nn.ReLU(False)
|
| 52 |
+
|
| 53 |
+
self.scratch.refinenet4 = FeatureFusionBlock_custom(features4, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners)
|
| 54 |
+
self.scratch.refinenet3 = FeatureFusionBlock_custom(features3, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners)
|
| 55 |
+
self.scratch.refinenet2 = FeatureFusionBlock_custom(features2, self.scratch.activation, deconv=False, bn=False, expand=self.expand, align_corners=align_corners)
|
| 56 |
+
self.scratch.refinenet1 = FeatureFusionBlock_custom(features1, self.scratch.activation, deconv=False, bn=False, align_corners=align_corners)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
self.scratch.output_conv = nn.Sequential(
|
| 60 |
+
nn.Conv2d(features, features//2, kernel_size=3, stride=1, padding=1, groups=self.groups),
|
| 61 |
+
Interpolate(scale_factor=2, mode="bilinear"),
|
| 62 |
+
nn.Conv2d(features//2, 32, kernel_size=3, stride=1, padding=1),
|
| 63 |
+
self.scratch.activation,
|
| 64 |
+
nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),
|
| 65 |
+
nn.ReLU(True) if non_negative else nn.Identity(),
|
| 66 |
+
nn.Identity(),
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
if path:
|
| 70 |
+
self.load(path)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
"""Forward pass.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
x (tensor): input data (image)
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
tensor: depth
|
| 81 |
+
"""
|
| 82 |
+
if self.channels_last==True:
|
| 83 |
+
print("self.channels_last = ", self.channels_last)
|
| 84 |
+
x.contiguous(memory_format=torch.channels_last)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
layer_1 = self.pretrained.layer1(x)
|
| 88 |
+
layer_2 = self.pretrained.layer2(layer_1)
|
| 89 |
+
layer_3 = self.pretrained.layer3(layer_2)
|
| 90 |
+
layer_4 = self.pretrained.layer4(layer_3)
|
| 91 |
+
|
| 92 |
+
layer_1_rn = self.scratch.layer1_rn(layer_1)
|
| 93 |
+
layer_2_rn = self.scratch.layer2_rn(layer_2)
|
| 94 |
+
layer_3_rn = self.scratch.layer3_rn(layer_3)
|
| 95 |
+
layer_4_rn = self.scratch.layer4_rn(layer_4)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
path_4 = self.scratch.refinenet4(layer_4_rn)
|
| 99 |
+
path_3 = self.scratch.refinenet3(path_4, layer_3_rn)
|
| 100 |
+
path_2 = self.scratch.refinenet2(path_3, layer_2_rn)
|
| 101 |
+
path_1 = self.scratch.refinenet1(path_2, layer_1_rn)
|
| 102 |
+
|
| 103 |
+
out = self.scratch.output_conv(path_1)
|
| 104 |
+
|
| 105 |
+
return torch.squeeze(out, dim=1)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def fuse_model(m):
|
| 110 |
+
prev_previous_type = nn.Identity()
|
| 111 |
+
prev_previous_name = ''
|
| 112 |
+
previous_type = nn.Identity()
|
| 113 |
+
previous_name = ''
|
| 114 |
+
for name, module in m.named_modules():
|
| 115 |
+
if prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d and type(module) == nn.ReLU:
|
| 116 |
+
# print("FUSED ", prev_previous_name, previous_name, name)
|
| 117 |
+
torch.quantization.fuse_modules(m, [prev_previous_name, previous_name, name], inplace=True)
|
| 118 |
+
elif prev_previous_type == nn.Conv2d and previous_type == nn.BatchNorm2d:
|
| 119 |
+
# print("FUSED ", prev_previous_name, previous_name)
|
| 120 |
+
torch.quantization.fuse_modules(m, [prev_previous_name, previous_name], inplace=True)
|
| 121 |
+
# elif previous_type == nn.Conv2d and type(module) == nn.ReLU:
|
| 122 |
+
# print("FUSED ", previous_name, name)
|
| 123 |
+
# torch.quantization.fuse_modules(m, [previous_name, name], inplace=True)
|
| 124 |
+
|
| 125 |
+
prev_previous_type = previous_type
|
| 126 |
+
prev_previous_name = previous_name
|
| 127 |
+
previous_type = type(module)
|
| 128 |
+
previous_name = name
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/model_loader.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
from midas.dpt_depth import DPTDepthModel
|
| 5 |
+
from midas.midas_net import MidasNet
|
| 6 |
+
from midas.midas_net_custom import MidasNet_small
|
| 7 |
+
from midas.transforms import Resize, NormalizeImage, PrepareForNet
|
| 8 |
+
|
| 9 |
+
from torchvision.transforms import Compose
|
| 10 |
+
|
| 11 |
+
default_models = {
|
| 12 |
+
"dpt_beit_large_512": "weights/dpt_beit_large_512.pt",
|
| 13 |
+
"dpt_beit_large_384": "weights/dpt_beit_large_384.pt",
|
| 14 |
+
"dpt_beit_base_384": "weights/dpt_beit_base_384.pt",
|
| 15 |
+
"dpt_swin2_large_384": "weights/dpt_swin2_large_384.pt",
|
| 16 |
+
"dpt_swin2_base_384": "weights/dpt_swin2_base_384.pt",
|
| 17 |
+
"dpt_swin2_tiny_256": "weights/dpt_swin2_tiny_256.pt",
|
| 18 |
+
"dpt_swin_large_384": "weights/dpt_swin_large_384.pt",
|
| 19 |
+
"dpt_next_vit_large_384": "weights/dpt_next_vit_large_384.pt",
|
| 20 |
+
"dpt_levit_224": "weights/dpt_levit_224.pt",
|
| 21 |
+
"dpt_large_384": "weights/dpt_large_384.pt",
|
| 22 |
+
"dpt_hybrid_384": "weights/dpt_hybrid_384.pt",
|
| 23 |
+
"midas_v21_384": "weights/midas_v21_384.pt",
|
| 24 |
+
"midas_v21_small_256": "weights/midas_v21_small_256.pt",
|
| 25 |
+
"openvino_midas_v21_small_256": "weights/openvino_midas_v21_small_256.xml",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_model(device, model_path, model_type="dpt_large_384", optimize=True, height=None, square=False):
|
| 30 |
+
"""Load the specified network.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
device (device): the torch device used
|
| 34 |
+
model_path (str): path to saved model
|
| 35 |
+
model_type (str): the type of the model to be loaded
|
| 36 |
+
optimize (bool): optimize the model to half-integer on CUDA?
|
| 37 |
+
height (int): inference encoder image height
|
| 38 |
+
square (bool): resize to a square resolution?
|
| 39 |
+
|
| 40 |
+
Returns:
|
| 41 |
+
The loaded network, the transform which prepares images as input to the network and the dimensions of the
|
| 42 |
+
network input
|
| 43 |
+
"""
|
| 44 |
+
if "openvino" in model_type:
|
| 45 |
+
from openvino.runtime import Core
|
| 46 |
+
|
| 47 |
+
keep_aspect_ratio = not square
|
| 48 |
+
|
| 49 |
+
if model_type == "dpt_beit_large_512":
|
| 50 |
+
model = DPTDepthModel(
|
| 51 |
+
path=model_path,
|
| 52 |
+
backbone="beitl16_512",
|
| 53 |
+
non_negative=True,
|
| 54 |
+
)
|
| 55 |
+
net_w, net_h = 512, 512
|
| 56 |
+
resize_mode = "minimal"
|
| 57 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 58 |
+
|
| 59 |
+
elif model_type == "dpt_beit_large_384":
|
| 60 |
+
model = DPTDepthModel(
|
| 61 |
+
path=model_path,
|
| 62 |
+
backbone="beitl16_384",
|
| 63 |
+
non_negative=True,
|
| 64 |
+
)
|
| 65 |
+
net_w, net_h = 384, 384
|
| 66 |
+
resize_mode = "minimal"
|
| 67 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 68 |
+
|
| 69 |
+
elif model_type == "dpt_beit_base_384":
|
| 70 |
+
model = DPTDepthModel(
|
| 71 |
+
path=model_path,
|
| 72 |
+
backbone="beitb16_384",
|
| 73 |
+
non_negative=True,
|
| 74 |
+
)
|
| 75 |
+
net_w, net_h = 384, 384
|
| 76 |
+
resize_mode = "minimal"
|
| 77 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 78 |
+
|
| 79 |
+
elif model_type == "dpt_swin2_large_384":
|
| 80 |
+
model = DPTDepthModel(
|
| 81 |
+
path=model_path,
|
| 82 |
+
backbone="swin2l24_384",
|
| 83 |
+
non_negative=True,
|
| 84 |
+
)
|
| 85 |
+
net_w, net_h = 384, 384
|
| 86 |
+
keep_aspect_ratio = False
|
| 87 |
+
resize_mode = "minimal"
|
| 88 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 89 |
+
|
| 90 |
+
elif model_type == "dpt_swin2_base_384":
|
| 91 |
+
model = DPTDepthModel(
|
| 92 |
+
path=model_path,
|
| 93 |
+
backbone="swin2b24_384",
|
| 94 |
+
non_negative=True,
|
| 95 |
+
)
|
| 96 |
+
net_w, net_h = 384, 384
|
| 97 |
+
keep_aspect_ratio = False
|
| 98 |
+
resize_mode = "minimal"
|
| 99 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 100 |
+
|
| 101 |
+
elif model_type == "dpt_swin2_tiny_256":
|
| 102 |
+
model = DPTDepthModel(
|
| 103 |
+
path=model_path,
|
| 104 |
+
backbone="swin2t16_256",
|
| 105 |
+
non_negative=True,
|
| 106 |
+
)
|
| 107 |
+
net_w, net_h = 256, 256
|
| 108 |
+
keep_aspect_ratio = False
|
| 109 |
+
resize_mode = "minimal"
|
| 110 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 111 |
+
|
| 112 |
+
elif model_type == "dpt_swin_large_384":
|
| 113 |
+
model = DPTDepthModel(
|
| 114 |
+
path=model_path,
|
| 115 |
+
backbone="swinl12_384",
|
| 116 |
+
non_negative=True,
|
| 117 |
+
)
|
| 118 |
+
net_w, net_h = 384, 384
|
| 119 |
+
keep_aspect_ratio = False
|
| 120 |
+
resize_mode = "minimal"
|
| 121 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 122 |
+
|
| 123 |
+
elif model_type == "dpt_next_vit_large_384":
|
| 124 |
+
model = DPTDepthModel(
|
| 125 |
+
path=model_path,
|
| 126 |
+
backbone="next_vit_large_6m",
|
| 127 |
+
non_negative=True,
|
| 128 |
+
)
|
| 129 |
+
net_w, net_h = 384, 384
|
| 130 |
+
resize_mode = "minimal"
|
| 131 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 132 |
+
|
| 133 |
+
# We change the notation from dpt_levit_224 (MiDaS notation) to levit_384 (timm notation) here, where the 224 refers
|
| 134 |
+
# to the resolution 224x224 used by LeViT and 384 is the first entry of the embed_dim, see _cfg and model_cfgs of
|
| 135 |
+
# https://github.com/rwightman/pytorch-image-models/blob/main/timm/models/levit.py
|
| 136 |
+
# (commit id: 927f031293a30afb940fff0bee34b85d9c059b0e)
|
| 137 |
+
elif model_type == "dpt_levit_224":
|
| 138 |
+
model = DPTDepthModel(
|
| 139 |
+
path=model_path,
|
| 140 |
+
backbone="levit_384",
|
| 141 |
+
non_negative=True,
|
| 142 |
+
head_features_1=64,
|
| 143 |
+
head_features_2=8,
|
| 144 |
+
)
|
| 145 |
+
net_w, net_h = 224, 224
|
| 146 |
+
keep_aspect_ratio = False
|
| 147 |
+
resize_mode = "minimal"
|
| 148 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 149 |
+
|
| 150 |
+
elif model_type == "dpt_large_384":
|
| 151 |
+
model = DPTDepthModel(
|
| 152 |
+
path=model_path,
|
| 153 |
+
backbone="vitl16_384",
|
| 154 |
+
non_negative=True,
|
| 155 |
+
)
|
| 156 |
+
net_w, net_h = 384, 384
|
| 157 |
+
resize_mode = "minimal"
|
| 158 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 159 |
+
|
| 160 |
+
elif model_type == "dpt_hybrid_384":
|
| 161 |
+
model = DPTDepthModel(
|
| 162 |
+
path=model_path,
|
| 163 |
+
backbone="vitb_rn50_384",
|
| 164 |
+
non_negative=True,
|
| 165 |
+
)
|
| 166 |
+
net_w, net_h = 384, 384
|
| 167 |
+
resize_mode = "minimal"
|
| 168 |
+
normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 169 |
+
|
| 170 |
+
elif model_type == "midas_v21_384":
|
| 171 |
+
model = MidasNet(model_path, non_negative=True)
|
| 172 |
+
net_w, net_h = 384, 384
|
| 173 |
+
resize_mode = "upper_bound"
|
| 174 |
+
normalization = NormalizeImage(
|
| 175 |
+
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
elif model_type == "midas_v21_small_256":
|
| 179 |
+
model = MidasNet_small(model_path, features=64, backbone="efficientnet_lite3", exportable=True,
|
| 180 |
+
non_negative=True, blocks={'expand': True})
|
| 181 |
+
net_w, net_h = 256, 256
|
| 182 |
+
resize_mode = "upper_bound"
|
| 183 |
+
normalization = NormalizeImage(
|
| 184 |
+
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
elif model_type == "openvino_midas_v21_small_256":
|
| 188 |
+
ie = Core()
|
| 189 |
+
uncompiled_model = ie.read_model(model=model_path)
|
| 190 |
+
model = ie.compile_model(uncompiled_model, "CPU")
|
| 191 |
+
net_w, net_h = 256, 256
|
| 192 |
+
resize_mode = "upper_bound"
|
| 193 |
+
normalization = NormalizeImage(
|
| 194 |
+
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
else:
|
| 198 |
+
print(f"model_type '{model_type}' not implemented, use: --model_type large")
|
| 199 |
+
assert False
|
| 200 |
+
|
| 201 |
+
if not "openvino" in model_type:
|
| 202 |
+
print("Model loaded, number of parameters = {:.0f}M".format(sum(p.numel() for p in model.parameters()) / 1e6))
|
| 203 |
+
else:
|
| 204 |
+
print("Model loaded, optimized with OpenVINO")
|
| 205 |
+
|
| 206 |
+
if "openvino" in model_type:
|
| 207 |
+
keep_aspect_ratio = False
|
| 208 |
+
|
| 209 |
+
if height is not None:
|
| 210 |
+
net_w, net_h = height, height
|
| 211 |
+
|
| 212 |
+
transform = Compose(
|
| 213 |
+
[
|
| 214 |
+
Resize(
|
| 215 |
+
net_w,
|
| 216 |
+
net_h,
|
| 217 |
+
resize_target=None,
|
| 218 |
+
keep_aspect_ratio=keep_aspect_ratio,
|
| 219 |
+
ensure_multiple_of=32,
|
| 220 |
+
resize_method=resize_mode,
|
| 221 |
+
image_interpolation_method=cv2.INTER_CUBIC,
|
| 222 |
+
),
|
| 223 |
+
normalization,
|
| 224 |
+
PrepareForNet(),
|
| 225 |
+
]
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
if not "openvino" in model_type:
|
| 229 |
+
model.eval()
|
| 230 |
+
|
| 231 |
+
if optimize and (device == torch.device("cuda")):
|
| 232 |
+
if not "openvino" in model_type:
|
| 233 |
+
model = model.to(memory_format=torch.channels_last)
|
| 234 |
+
model = model.half()
|
| 235 |
+
else:
|
| 236 |
+
print("Error: OpenVINO models are already optimized. No optimization to half-float possible.")
|
| 237 |
+
exit()
|
| 238 |
+
|
| 239 |
+
if not "openvino" in model_type:
|
| 240 |
+
model.to(device)
|
| 241 |
+
|
| 242 |
+
return model, transform, net_w, net_h
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/midas_c/midas/transforms.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
import math
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA):
|
| 7 |
+
"""Rezise the sample to ensure the given size. Keeps aspect ratio.
|
| 8 |
+
|
| 9 |
+
Args:
|
| 10 |
+
sample (dict): sample
|
| 11 |
+
size (tuple): image size
|
| 12 |
+
|
| 13 |
+
Returns:
|
| 14 |
+
tuple: new size
|
| 15 |
+
"""
|
| 16 |
+
shape = list(sample["disparity"].shape)
|
| 17 |
+
|
| 18 |
+
if shape[0] >= size[0] and shape[1] >= size[1]:
|
| 19 |
+
return sample
|
| 20 |
+
|
| 21 |
+
scale = [0, 0]
|
| 22 |
+
scale[0] = size[0] / shape[0]
|
| 23 |
+
scale[1] = size[1] / shape[1]
|
| 24 |
+
|
| 25 |
+
scale = max(scale)
|
| 26 |
+
|
| 27 |
+
shape[0] = math.ceil(scale * shape[0])
|
| 28 |
+
shape[1] = math.ceil(scale * shape[1])
|
| 29 |
+
|
| 30 |
+
# resize
|
| 31 |
+
sample["image"] = cv2.resize(
|
| 32 |
+
sample["image"], tuple(shape[::-1]), interpolation=image_interpolation_method
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
sample["disparity"] = cv2.resize(
|
| 36 |
+
sample["disparity"], tuple(shape[::-1]), interpolation=cv2.INTER_NEAREST
|
| 37 |
+
)
|
| 38 |
+
sample["mask"] = cv2.resize(
|
| 39 |
+
sample["mask"].astype(np.float32),
|
| 40 |
+
tuple(shape[::-1]),
|
| 41 |
+
interpolation=cv2.INTER_NEAREST,
|
| 42 |
+
)
|
| 43 |
+
sample["mask"] = sample["mask"].astype(bool)
|
| 44 |
+
|
| 45 |
+
return tuple(shape)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Resize(object):
|
| 49 |
+
"""Resize sample to given size (width, height).
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
width,
|
| 55 |
+
height,
|
| 56 |
+
resize_target=True,
|
| 57 |
+
keep_aspect_ratio=False,
|
| 58 |
+
ensure_multiple_of=1,
|
| 59 |
+
resize_method="lower_bound",
|
| 60 |
+
image_interpolation_method=cv2.INTER_AREA,
|
| 61 |
+
):
|
| 62 |
+
"""Init.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
width (int): desired output width
|
| 66 |
+
height (int): desired output height
|
| 67 |
+
resize_target (bool, optional):
|
| 68 |
+
True: Resize the full sample (image, mask, target).
|
| 69 |
+
False: Resize image only.
|
| 70 |
+
Defaults to True.
|
| 71 |
+
keep_aspect_ratio (bool, optional):
|
| 72 |
+
True: Keep the aspect ratio of the input sample.
|
| 73 |
+
Output sample might not have the given width and height, and
|
| 74 |
+
resize behaviour depends on the parameter 'resize_method'.
|
| 75 |
+
Defaults to False.
|
| 76 |
+
ensure_multiple_of (int, optional):
|
| 77 |
+
Output width and height is constrained to be multiple of this parameter.
|
| 78 |
+
Defaults to 1.
|
| 79 |
+
resize_method (str, optional):
|
| 80 |
+
"lower_bound": Output will be at least as large as the given size.
|
| 81 |
+
"upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
|
| 82 |
+
"minimal": Scale as least as possible. (Output size might be smaller than given size.)
|
| 83 |
+
Defaults to "lower_bound".
|
| 84 |
+
"""
|
| 85 |
+
self.__width = width
|
| 86 |
+
self.__height = height
|
| 87 |
+
|
| 88 |
+
self.__resize_target = resize_target
|
| 89 |
+
self.__keep_aspect_ratio = keep_aspect_ratio
|
| 90 |
+
self.__multiple_of = ensure_multiple_of
|
| 91 |
+
self.__resize_method = resize_method
|
| 92 |
+
self.__image_interpolation_method = image_interpolation_method
|
| 93 |
+
|
| 94 |
+
def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
|
| 95 |
+
y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 96 |
+
|
| 97 |
+
if max_val is not None and y > max_val:
|
| 98 |
+
y = (np.floor(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 99 |
+
|
| 100 |
+
if y < min_val:
|
| 101 |
+
y = (np.ceil(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 102 |
+
|
| 103 |
+
return y
|
| 104 |
+
|
| 105 |
+
def get_size(self, width, height):
|
| 106 |
+
# determine new height and width
|
| 107 |
+
scale_height = self.__height / height
|
| 108 |
+
scale_width = self.__width / width
|
| 109 |
+
|
| 110 |
+
if self.__keep_aspect_ratio:
|
| 111 |
+
if self.__resize_method == "lower_bound":
|
| 112 |
+
# scale such that output size is lower bound
|
| 113 |
+
if scale_width > scale_height:
|
| 114 |
+
# fit width
|
| 115 |
+
scale_height = scale_width
|
| 116 |
+
else:
|
| 117 |
+
# fit height
|
| 118 |
+
scale_width = scale_height
|
| 119 |
+
elif self.__resize_method == "upper_bound":
|
| 120 |
+
# scale such that output size is upper bound
|
| 121 |
+
if scale_width < scale_height:
|
| 122 |
+
# fit width
|
| 123 |
+
scale_height = scale_width
|
| 124 |
+
else:
|
| 125 |
+
# fit height
|
| 126 |
+
scale_width = scale_height
|
| 127 |
+
elif self.__resize_method == "minimal":
|
| 128 |
+
# scale as least as possbile
|
| 129 |
+
if abs(1 - scale_width) < abs(1 - scale_height):
|
| 130 |
+
# fit width
|
| 131 |
+
scale_height = scale_width
|
| 132 |
+
else:
|
| 133 |
+
# fit height
|
| 134 |
+
scale_width = scale_height
|
| 135 |
+
else:
|
| 136 |
+
raise ValueError(
|
| 137 |
+
f"resize_method {self.__resize_method} not implemented"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if self.__resize_method == "lower_bound":
|
| 141 |
+
new_height = self.constrain_to_multiple_of(
|
| 142 |
+
scale_height * height, min_val=self.__height
|
| 143 |
+
)
|
| 144 |
+
new_width = self.constrain_to_multiple_of(
|
| 145 |
+
scale_width * width, min_val=self.__width
|
| 146 |
+
)
|
| 147 |
+
elif self.__resize_method == "upper_bound":
|
| 148 |
+
new_height = self.constrain_to_multiple_of(
|
| 149 |
+
scale_height * height, max_val=self.__height
|
| 150 |
+
)
|
| 151 |
+
new_width = self.constrain_to_multiple_of(
|
| 152 |
+
scale_width * width, max_val=self.__width
|
| 153 |
+
)
|
| 154 |
+
elif self.__resize_method == "minimal":
|
| 155 |
+
new_height = self.constrain_to_multiple_of(scale_height * height)
|
| 156 |
+
new_width = self.constrain_to_multiple_of(scale_width * width)
|
| 157 |
+
else:
|
| 158 |
+
raise ValueError(f"resize_method {self.__resize_method} not implemented")
|
| 159 |
+
|
| 160 |
+
return (new_width, new_height)
|
| 161 |
+
|
| 162 |
+
def __call__(self, sample):
|
| 163 |
+
width, height = self.get_size(
|
| 164 |
+
sample["image"].shape[1], sample["image"].shape[0]
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# resize sample
|
| 168 |
+
sample["image"] = cv2.resize(
|
| 169 |
+
sample["image"],
|
| 170 |
+
(width, height),
|
| 171 |
+
interpolation=self.__image_interpolation_method,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
if self.__resize_target:
|
| 175 |
+
if "disparity" in sample:
|
| 176 |
+
sample["disparity"] = cv2.resize(
|
| 177 |
+
sample["disparity"],
|
| 178 |
+
(width, height),
|
| 179 |
+
interpolation=cv2.INTER_NEAREST,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
if "depth" in sample:
|
| 183 |
+
sample["depth"] = cv2.resize(
|
| 184 |
+
sample["depth"], (width, height), interpolation=cv2.INTER_NEAREST
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
sample["mask"] = cv2.resize(
|
| 188 |
+
sample["mask"].astype(np.float32),
|
| 189 |
+
(width, height),
|
| 190 |
+
interpolation=cv2.INTER_NEAREST,
|
| 191 |
+
)
|
| 192 |
+
sample["mask"] = sample["mask"].astype(bool)
|
| 193 |
+
|
| 194 |
+
return sample
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class NormalizeImage(object):
|
| 198 |
+
"""Normlize image by given mean and std.
|
| 199 |
+
"""
|
| 200 |
+
|
| 201 |
+
def __init__(self, mean, std):
|
| 202 |
+
self.__mean = mean
|
| 203 |
+
self.__std = std
|
| 204 |
+
|
| 205 |
+
def __call__(self, sample):
|
| 206 |
+
sample["image"] = (sample["image"] - self.__mean) / self.__std
|
| 207 |
+
|
| 208 |
+
return sample
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class PrepareForNet(object):
|
| 212 |
+
"""Prepare sample for usage as network input.
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
def __init__(self):
|
| 216 |
+
pass
|
| 217 |
+
|
| 218 |
+
def __call__(self, sample):
|
| 219 |
+
image = np.transpose(sample["image"], (2, 0, 1))
|
| 220 |
+
sample["image"] = np.ascontiguousarray(image).astype(np.float32)
|
| 221 |
+
|
| 222 |
+
if "mask" in sample:
|
| 223 |
+
sample["mask"] = sample["mask"].astype(np.float32)
|
| 224 |
+
sample["mask"] = np.ascontiguousarray(sample["mask"])
|
| 225 |
+
|
| 226 |
+
if "disparity" in sample:
|
| 227 |
+
disparity = sample["disparity"].astype(np.float32)
|
| 228 |
+
sample["disparity"] = np.ascontiguousarray(disparity)
|
| 229 |
+
|
| 230 |
+
if "depth" in sample:
|
| 231 |
+
depth = sample["depth"].astype(np.float32)
|
| 232 |
+
sample["depth"] = np.ascontiguousarray(depth)
|
| 233 |
+
|
| 234 |
+
return sample
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/base_models/midas.py
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
import numpy as np
|
| 28 |
+
from torchvision.transforms import Normalize
|
| 29 |
+
import importlib
|
| 30 |
+
|
| 31 |
+
def denormalize(x):
|
| 32 |
+
"""Reverses the imagenet normalization applied to the input.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
x (torch.Tensor - shape(N,3,H,W)): input tensor
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
torch.Tensor - shape(N,3,H,W): Denormalized input
|
| 39 |
+
"""
|
| 40 |
+
mean = torch.Tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(x.device)
|
| 41 |
+
std = torch.Tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(x.device)
|
| 42 |
+
return x * std + mean
|
| 43 |
+
|
| 44 |
+
def get_activation(name, bank):
|
| 45 |
+
def hook(model, input, output):
|
| 46 |
+
bank[name] = output
|
| 47 |
+
return hook
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Resize(object):
|
| 51 |
+
"""Resize sample to given size (width, height).
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(
|
| 55 |
+
self,
|
| 56 |
+
width,
|
| 57 |
+
height,
|
| 58 |
+
resize_target=True,
|
| 59 |
+
keep_aspect_ratio=False,
|
| 60 |
+
ensure_multiple_of=1,
|
| 61 |
+
resize_method="lower_bound",
|
| 62 |
+
):
|
| 63 |
+
"""Init.
|
| 64 |
+
Args:
|
| 65 |
+
width (int): desired output width
|
| 66 |
+
height (int): desired output height
|
| 67 |
+
resize_target (bool, optional):
|
| 68 |
+
True: Resize the full sample (image, mask, target).
|
| 69 |
+
False: Resize image only.
|
| 70 |
+
Defaults to True.
|
| 71 |
+
keep_aspect_ratio (bool, optional):
|
| 72 |
+
True: Keep the aspect ratio of the input sample.
|
| 73 |
+
Output sample might not have the given width and height, and
|
| 74 |
+
resize behaviour depends on the parameter 'resize_method'.
|
| 75 |
+
Defaults to False.
|
| 76 |
+
ensure_multiple_of (int, optional):
|
| 77 |
+
Output width and height is constrained to be multiple of this parameter.
|
| 78 |
+
Defaults to 1.
|
| 79 |
+
resize_method (str, optional):
|
| 80 |
+
"lower_bound": Output will be at least as large as the given size.
|
| 81 |
+
"upper_bound": Output will be at max as large as the given size. (Output size might be smaller than given size.)
|
| 82 |
+
"minimal": Scale as least as possible. (Output size might be smaller than given size.)
|
| 83 |
+
Defaults to "lower_bound".
|
| 84 |
+
"""
|
| 85 |
+
print("Params passed to Resize transform:")
|
| 86 |
+
print("\twidth: ", width)
|
| 87 |
+
print("\theight: ", height)
|
| 88 |
+
print("\tresize_target: ", resize_target)
|
| 89 |
+
print("\tkeep_aspect_ratio: ", keep_aspect_ratio)
|
| 90 |
+
print("\tensure_multiple_of: ", ensure_multiple_of)
|
| 91 |
+
print("\tresize_method: ", resize_method)
|
| 92 |
+
|
| 93 |
+
self.__width = width
|
| 94 |
+
self.__height = height
|
| 95 |
+
|
| 96 |
+
self.__keep_aspect_ratio = keep_aspect_ratio
|
| 97 |
+
self.__multiple_of = ensure_multiple_of
|
| 98 |
+
self.__resize_method = resize_method
|
| 99 |
+
|
| 100 |
+
def constrain_to_multiple_of(self, x, min_val=0, max_val=None):
|
| 101 |
+
y = (np.round(x / self.__multiple_of) * self.__multiple_of).astype(int)
|
| 102 |
+
|
| 103 |
+
if max_val is not None and y > max_val:
|
| 104 |
+
y = (np.floor(x / self.__multiple_of)
|
| 105 |
+
* self.__multiple_of).astype(int)
|
| 106 |
+
|
| 107 |
+
if y < min_val:
|
| 108 |
+
y = (np.ceil(x / self.__multiple_of)
|
| 109 |
+
* self.__multiple_of).astype(int)
|
| 110 |
+
|
| 111 |
+
return y
|
| 112 |
+
|
| 113 |
+
def get_size(self, width, height):
|
| 114 |
+
# determine new height and width
|
| 115 |
+
scale_height = self.__height / height
|
| 116 |
+
scale_width = self.__width / width
|
| 117 |
+
|
| 118 |
+
if self.__keep_aspect_ratio:
|
| 119 |
+
if self.__resize_method == "lower_bound":
|
| 120 |
+
# scale such that output size is lower bound
|
| 121 |
+
if scale_width > scale_height:
|
| 122 |
+
# fit width
|
| 123 |
+
scale_height = scale_width
|
| 124 |
+
else:
|
| 125 |
+
# fit height
|
| 126 |
+
scale_width = scale_height
|
| 127 |
+
elif self.__resize_method == "upper_bound":
|
| 128 |
+
# scale such that output size is upper bound
|
| 129 |
+
if scale_width < scale_height:
|
| 130 |
+
# fit width
|
| 131 |
+
scale_height = scale_width
|
| 132 |
+
else:
|
| 133 |
+
# fit height
|
| 134 |
+
scale_width = scale_height
|
| 135 |
+
elif self.__resize_method == "minimal":
|
| 136 |
+
# scale as least as possbile
|
| 137 |
+
if abs(1 - scale_width) < abs(1 - scale_height):
|
| 138 |
+
# fit width
|
| 139 |
+
scale_height = scale_width
|
| 140 |
+
else:
|
| 141 |
+
# fit height
|
| 142 |
+
scale_width = scale_height
|
| 143 |
+
else:
|
| 144 |
+
raise ValueError(
|
| 145 |
+
f"resize_method {self.__resize_method} not implemented"
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
if self.__resize_method == "lower_bound":
|
| 149 |
+
new_height = self.constrain_to_multiple_of(
|
| 150 |
+
scale_height * height, min_val=self.__height
|
| 151 |
+
)
|
| 152 |
+
new_width = self.constrain_to_multiple_of(
|
| 153 |
+
scale_width * width, min_val=self.__width
|
| 154 |
+
)
|
| 155 |
+
elif self.__resize_method == "upper_bound":
|
| 156 |
+
new_height = self.constrain_to_multiple_of(
|
| 157 |
+
scale_height * height, max_val=self.__height
|
| 158 |
+
)
|
| 159 |
+
new_width = self.constrain_to_multiple_of(
|
| 160 |
+
scale_width * width, max_val=self.__width
|
| 161 |
+
)
|
| 162 |
+
elif self.__resize_method == "minimal":
|
| 163 |
+
new_height = self.constrain_to_multiple_of(scale_height * height)
|
| 164 |
+
new_width = self.constrain_to_multiple_of(scale_width * width)
|
| 165 |
+
else:
|
| 166 |
+
raise ValueError(
|
| 167 |
+
f"resize_method {self.__resize_method} not implemented")
|
| 168 |
+
|
| 169 |
+
return (new_width, new_height)
|
| 170 |
+
|
| 171 |
+
def __call__(self, x):
|
| 172 |
+
width, height = self.get_size(*x.shape[-2:][::-1])
|
| 173 |
+
return nn.functional.interpolate(x, (int(height), int(width)), mode='bilinear', align_corners=True)
|
| 174 |
+
|
| 175 |
+
class PrepForMidas(object):
|
| 176 |
+
def __init__(self, resize_mode="minimal", keep_aspect_ratio=True, img_size=384, do_resize=True):
|
| 177 |
+
if isinstance(img_size, int):
|
| 178 |
+
img_size = (img_size, img_size)
|
| 179 |
+
net_h, net_w = img_size
|
| 180 |
+
self.normalization = Normalize(
|
| 181 |
+
mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
|
| 182 |
+
self.resizer = Resize(net_w, net_h, keep_aspect_ratio=keep_aspect_ratio, ensure_multiple_of=32, resize_method=resize_mode) \
|
| 183 |
+
if do_resize else nn.Identity()
|
| 184 |
+
|
| 185 |
+
def __call__(self, x):
|
| 186 |
+
return self.normalization(self.resizer(x))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class MidasCore(nn.Module):
|
| 190 |
+
def __init__(self, midas, trainable=False, fetch_features=True, layer_names=('out_conv', 'l4_rn', 'r4', 'r3', 'r2', 'r1'), freeze_bn=False, keep_aspect_ratio=True,
|
| 191 |
+
img_size=384, **kwargs):
|
| 192 |
+
"""Midas Base model used for multi-scale feature extraction.
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
midas (torch.nn.Module): Midas model.
|
| 196 |
+
trainable (bool, optional): Train midas model. Defaults to False.
|
| 197 |
+
fetch_features (bool, optional): Extract multi-scale features. Defaults to True.
|
| 198 |
+
layer_names (tuple, optional): Layers used for feature extraction. Order = (head output features, last layer features, ...decoder features). Defaults to ('out_conv', 'l4_rn', 'r4', 'r3', 'r2', 'r1').
|
| 199 |
+
freeze_bn (bool, optional): Freeze BatchNorm. Generally results in better finetuning performance. Defaults to False.
|
| 200 |
+
keep_aspect_ratio (bool, optional): Keep the aspect ratio of input images while resizing. Defaults to True.
|
| 201 |
+
img_size (int, tuple, optional): Input resolution. Defaults to 384.
|
| 202 |
+
"""
|
| 203 |
+
super().__init__()
|
| 204 |
+
self.core = midas
|
| 205 |
+
self.output_channels = None
|
| 206 |
+
self.core_out = {}
|
| 207 |
+
self.trainable = trainable
|
| 208 |
+
self.fetch_features = fetch_features
|
| 209 |
+
# midas.scratch.output_conv = nn.Identity()
|
| 210 |
+
self.handles = []
|
| 211 |
+
# self.layer_names = ['out_conv','l4_rn', 'r4', 'r3', 'r2', 'r1']
|
| 212 |
+
self.layer_names = layer_names
|
| 213 |
+
|
| 214 |
+
self.set_trainable(trainable)
|
| 215 |
+
self.set_fetch_features(fetch_features)
|
| 216 |
+
|
| 217 |
+
self.prep = PrepForMidas(keep_aspect_ratio=keep_aspect_ratio,
|
| 218 |
+
img_size=img_size, do_resize=kwargs.get('do_resize', True))
|
| 219 |
+
|
| 220 |
+
if freeze_bn:
|
| 221 |
+
self.freeze_bn()
|
| 222 |
+
|
| 223 |
+
def set_trainable(self, trainable):
|
| 224 |
+
self.trainable = trainable
|
| 225 |
+
if trainable:
|
| 226 |
+
self.unfreeze()
|
| 227 |
+
else:
|
| 228 |
+
self.freeze()
|
| 229 |
+
return self
|
| 230 |
+
|
| 231 |
+
def set_fetch_features(self, fetch_features):
|
| 232 |
+
self.fetch_features = fetch_features
|
| 233 |
+
if fetch_features:
|
| 234 |
+
if len(self.handles) == 0:
|
| 235 |
+
self.attach_hooks(self.core)
|
| 236 |
+
else:
|
| 237 |
+
self.remove_hooks()
|
| 238 |
+
return self
|
| 239 |
+
|
| 240 |
+
def freeze(self):
|
| 241 |
+
for p in self.parameters():
|
| 242 |
+
p.requires_grad = False
|
| 243 |
+
self.trainable = False
|
| 244 |
+
return self
|
| 245 |
+
|
| 246 |
+
def unfreeze(self):
|
| 247 |
+
for p in self.parameters():
|
| 248 |
+
p.requires_grad = True
|
| 249 |
+
self.trainable = True
|
| 250 |
+
return self
|
| 251 |
+
|
| 252 |
+
def freeze_bn(self):
|
| 253 |
+
for m in self.modules():
|
| 254 |
+
if isinstance(m, nn.BatchNorm2d):
|
| 255 |
+
m.eval()
|
| 256 |
+
return self
|
| 257 |
+
|
| 258 |
+
def forward(self, x, denorm=False, return_rel_depth=False):
|
| 259 |
+
with torch.no_grad():
|
| 260 |
+
if denorm:
|
| 261 |
+
x = denormalize(x)
|
| 262 |
+
x = self.prep(x)
|
| 263 |
+
# print("Shape after prep: ", x.shape)
|
| 264 |
+
|
| 265 |
+
with torch.set_grad_enabled(self.trainable):
|
| 266 |
+
|
| 267 |
+
# print("Input size to Midascore", x.shape)
|
| 268 |
+
rel_depth = self.core(x)
|
| 269 |
+
# print("Output from midas shape", rel_depth.shape)
|
| 270 |
+
if not self.fetch_features:
|
| 271 |
+
return rel_depth
|
| 272 |
+
out = [self.core_out[k] for k in self.layer_names]
|
| 273 |
+
|
| 274 |
+
if return_rel_depth:
|
| 275 |
+
return rel_depth, out
|
| 276 |
+
return out
|
| 277 |
+
|
| 278 |
+
def get_rel_pos_params(self):
|
| 279 |
+
for name, p in self.core.pretrained.named_parameters():
|
| 280 |
+
if "relative_position" in name:
|
| 281 |
+
yield p
|
| 282 |
+
|
| 283 |
+
def get_enc_params_except_rel_pos(self):
|
| 284 |
+
for name, p in self.core.pretrained.named_parameters():
|
| 285 |
+
if "relative_position" not in name:
|
| 286 |
+
yield p
|
| 287 |
+
|
| 288 |
+
def freeze_encoder(self, freeze_rel_pos=False):
|
| 289 |
+
if freeze_rel_pos:
|
| 290 |
+
for p in self.core.pretrained.parameters():
|
| 291 |
+
p.requires_grad = False
|
| 292 |
+
else:
|
| 293 |
+
for p in self.get_enc_params_except_rel_pos():
|
| 294 |
+
p.requires_grad = False
|
| 295 |
+
return self
|
| 296 |
+
|
| 297 |
+
def attach_hooks(self, midas):
|
| 298 |
+
if len(self.handles) > 0:
|
| 299 |
+
self.remove_hooks()
|
| 300 |
+
if "out_conv" in self.layer_names:
|
| 301 |
+
self.handles.append(list(midas.scratch.output_conv.children())[
|
| 302 |
+
3].register_forward_hook(get_activation("out_conv", self.core_out)))
|
| 303 |
+
if "r4" in self.layer_names:
|
| 304 |
+
self.handles.append(midas.scratch.refinenet4.register_forward_hook(
|
| 305 |
+
get_activation("r4", self.core_out)))
|
| 306 |
+
if "r3" in self.layer_names:
|
| 307 |
+
self.handles.append(midas.scratch.refinenet3.register_forward_hook(
|
| 308 |
+
get_activation("r3", self.core_out)))
|
| 309 |
+
if "r2" in self.layer_names:
|
| 310 |
+
self.handles.append(midas.scratch.refinenet2.register_forward_hook(
|
| 311 |
+
get_activation("r2", self.core_out)))
|
| 312 |
+
if "r1" in self.layer_names:
|
| 313 |
+
self.handles.append(midas.scratch.refinenet1.register_forward_hook(
|
| 314 |
+
get_activation("r1", self.core_out)))
|
| 315 |
+
if "l4_rn" in self.layer_names:
|
| 316 |
+
self.handles.append(midas.scratch.layer4_rn.register_forward_hook(
|
| 317 |
+
get_activation("l4_rn", self.core_out)))
|
| 318 |
+
|
| 319 |
+
return self
|
| 320 |
+
|
| 321 |
+
def remove_hooks(self):
|
| 322 |
+
for h in self.handles:
|
| 323 |
+
h.remove()
|
| 324 |
+
return self
|
| 325 |
+
|
| 326 |
+
def __del__(self):
|
| 327 |
+
self.remove_hooks()
|
| 328 |
+
|
| 329 |
+
def set_output_channels(self, model_type):
|
| 330 |
+
self.output_channels = MIDAS_SETTINGS[model_type]
|
| 331 |
+
|
| 332 |
+
@staticmethod
|
| 333 |
+
def build(midas_model_type="DPT_BEiT_L_384", train_midas=False, use_pretrained_midas=True, fetch_features=False, freeze_bn=True, force_keep_ar=False, force_reload=False, **kwargs):
|
| 334 |
+
if midas_model_type not in MIDAS_SETTINGS:
|
| 335 |
+
raise ValueError(
|
| 336 |
+
f"Invalid model type: {midas_model_type}. Must be one of {list(MIDAS_SETTINGS.keys())}")
|
| 337 |
+
if "img_size" in kwargs:
|
| 338 |
+
kwargs = MidasCore.parse_img_size(kwargs)
|
| 339 |
+
img_size = kwargs.pop("img_size", [384, 384])
|
| 340 |
+
print("img_size", img_size)
|
| 341 |
+
hubconf = importlib.import_module(f"models.monoD.zoeDepth.midas_c.hubconf")
|
| 342 |
+
midas = getattr(hubconf, midas_model_type)(pretrained=False)
|
| 343 |
+
ckpt_path = "models/monoD/zoeDepth/ckpts/dpt_beit_large_384.pt"
|
| 344 |
+
midas_ckpt = torch.load(ckpt_path, map_location=torch.device('cpu'))
|
| 345 |
+
midas.load_state_dict(midas_ckpt)
|
| 346 |
+
# midas = torch.hub.load("intel-isl/MiDaS", midas_model_type,
|
| 347 |
+
# pretrained=use_pretrained_midas, force_reload=force_reload)
|
| 348 |
+
kwargs.update({'keep_aspect_ratio': force_keep_ar})
|
| 349 |
+
midas_core = MidasCore(midas, trainable=train_midas, fetch_features=fetch_features,
|
| 350 |
+
freeze_bn=freeze_bn, img_size=img_size, **kwargs)
|
| 351 |
+
midas_core.set_output_channels(midas_model_type)
|
| 352 |
+
return midas_core
|
| 353 |
+
|
| 354 |
+
@staticmethod
|
| 355 |
+
def build_from_config(config):
|
| 356 |
+
return MidasCore.build(**config)
|
| 357 |
+
|
| 358 |
+
@staticmethod
|
| 359 |
+
def parse_img_size(config):
|
| 360 |
+
assert 'img_size' in config
|
| 361 |
+
if isinstance(config['img_size'], str):
|
| 362 |
+
assert "," in config['img_size'], "img_size should be a string with comma separated img_size=H,W"
|
| 363 |
+
config['img_size'] = list(map(int, config['img_size'].split(",")))
|
| 364 |
+
assert len(
|
| 365 |
+
config['img_size']) == 2, "img_size should be a string with comma separated img_size=H,W"
|
| 366 |
+
elif isinstance(config['img_size'], int):
|
| 367 |
+
config['img_size'] = [config['img_size'], config['img_size']]
|
| 368 |
+
else:
|
| 369 |
+
assert isinstance(config['img_size'], list) and len(
|
| 370 |
+
config['img_size']) == 2, "img_size should be a list of H,W"
|
| 371 |
+
return config
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
nchannels2models = {
|
| 375 |
+
tuple([256]*5): ["DPT_BEiT_L_384", "DPT_BEiT_L_512", "DPT_BEiT_B_384", "DPT_SwinV2_L_384", "DPT_SwinV2_B_384", "DPT_SwinV2_T_256", "DPT_Large", "DPT_Hybrid"],
|
| 376 |
+
(512, 256, 128, 64, 64): ["MiDaS_small"]
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
# Model name to number of output channels
|
| 380 |
+
MIDAS_SETTINGS = {m: k for k, v in nchannels2models.items()
|
| 381 |
+
for m in v
|
| 382 |
+
}
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/builder.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
from importlib import import_module
|
| 26 |
+
from models.monoD.zoeDepth.models.depth_model import DepthModel
|
| 27 |
+
|
| 28 |
+
def build_model(config) -> DepthModel:
|
| 29 |
+
"""Builds a model from a config. The model is specified by the model name and version in the config. The model is then constructed using the build_from_config function of the model interface.
|
| 30 |
+
This function should be used to construct models for training and evaluation.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
config (dict): Config dict. Config is constructed in utils/config.py. Each model has its own config file(s) saved in its root model folder.
|
| 34 |
+
|
| 35 |
+
Returns:
|
| 36 |
+
torch.nn.Module: Model corresponding to name and version as specified in config
|
| 37 |
+
"""
|
| 38 |
+
module_name = f"models.monoD.zoeDepth.models.{config.model}"
|
| 39 |
+
try:
|
| 40 |
+
module = import_module(module_name)
|
| 41 |
+
except ModuleNotFoundError as e:
|
| 42 |
+
# print the original error message
|
| 43 |
+
print(e)
|
| 44 |
+
raise ValueError(
|
| 45 |
+
f"Model {config.model} not found. Refer above error for details.") from e
|
| 46 |
+
try:
|
| 47 |
+
get_version = getattr(module, "get_version")
|
| 48 |
+
except AttributeError as e:
|
| 49 |
+
raise ValueError(
|
| 50 |
+
f"Model {config.model} has no get_version function.") from e
|
| 51 |
+
|
| 52 |
+
return get_version(config.version_name).build_from_config(config)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/depth_model.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import torch
|
| 27 |
+
import torch.nn as nn
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
from torchvision import transforms
|
| 30 |
+
import PIL.Image
|
| 31 |
+
from PIL import Image
|
| 32 |
+
from typing import Union
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class DepthModel(nn.Module):
|
| 36 |
+
def __init__(self):
|
| 37 |
+
super().__init__()
|
| 38 |
+
self.device = 'cpu'
|
| 39 |
+
|
| 40 |
+
def to(self, device) -> nn.Module:
|
| 41 |
+
self.device = device
|
| 42 |
+
return super().to(device)
|
| 43 |
+
|
| 44 |
+
def forward(self, x, *args, **kwargs):
|
| 45 |
+
raise NotImplementedError
|
| 46 |
+
|
| 47 |
+
def _infer(self, x: torch.Tensor):
|
| 48 |
+
"""
|
| 49 |
+
Inference interface for the model
|
| 50 |
+
Args:
|
| 51 |
+
x (torch.Tensor): input tensor of shape (b, c, h, w)
|
| 52 |
+
Returns:
|
| 53 |
+
torch.Tensor: output tensor of shape (b, 1, h, w)
|
| 54 |
+
"""
|
| 55 |
+
return self(x)['metric_depth']
|
| 56 |
+
|
| 57 |
+
def _infer_with_pad_aug(self, x: torch.Tensor, pad_input: bool=True, fh: float=3, fw: float=3, upsampling_mode: str='bicubic', padding_mode="reflect", **kwargs) -> torch.Tensor:
|
| 58 |
+
"""
|
| 59 |
+
Inference interface for the model with padding augmentation
|
| 60 |
+
Padding augmentation fixes the boundary artifacts in the output depth map.
|
| 61 |
+
Boundary artifacts are sometimes caused by the fact that the model is trained on NYU raw dataset which has a black or white border around the image.
|
| 62 |
+
This augmentation pads the input image and crops the prediction back to the original size / view.
|
| 63 |
+
|
| 64 |
+
Note: This augmentation is not required for the models trained with 'avoid_boundary'=True.
|
| 65 |
+
Args:
|
| 66 |
+
x (torch.Tensor): input tensor of shape (b, c, h, w)
|
| 67 |
+
pad_input (bool, optional): whether to pad the input or not. Defaults to True.
|
| 68 |
+
fh (float, optional): height padding factor. The padding is calculated as sqrt(h/2) * fh. Defaults to 3.
|
| 69 |
+
fw (float, optional): width padding factor. The padding is calculated as sqrt(w/2) * fw. Defaults to 3.
|
| 70 |
+
upsampling_mode (str, optional): upsampling mode. Defaults to 'bicubic'.
|
| 71 |
+
padding_mode (str, optional): padding mode. Defaults to "reflect".
|
| 72 |
+
Returns:
|
| 73 |
+
torch.Tensor: output tensor of shape (b, 1, h, w)
|
| 74 |
+
"""
|
| 75 |
+
# assert x is nchw and c = 3
|
| 76 |
+
assert x.dim() == 4, "x must be 4 dimensional, got {}".format(x.dim())
|
| 77 |
+
assert x.shape[1] == 3, "x must have 3 channels, got {}".format(x.shape[1])
|
| 78 |
+
|
| 79 |
+
if pad_input:
|
| 80 |
+
assert fh > 0 or fw > 0, "atlease one of fh and fw must be greater than 0"
|
| 81 |
+
pad_h = int(np.sqrt(x.shape[2]/2) * fh)
|
| 82 |
+
pad_w = int(np.sqrt(x.shape[3]/2) * fw)
|
| 83 |
+
padding = [pad_w, pad_w]
|
| 84 |
+
if pad_h > 0:
|
| 85 |
+
padding += [pad_h, pad_h]
|
| 86 |
+
|
| 87 |
+
x = F.pad(x, padding, mode=padding_mode, **kwargs)
|
| 88 |
+
out = self._infer(x)
|
| 89 |
+
if out.shape[-2:] != x.shape[-2:]:
|
| 90 |
+
out = F.interpolate(out, size=(x.shape[2], x.shape[3]), mode=upsampling_mode, align_corners=False)
|
| 91 |
+
if pad_input:
|
| 92 |
+
# crop to the original size, handling the case where pad_h and pad_w is 0
|
| 93 |
+
if pad_h > 0:
|
| 94 |
+
out = out[:, :, pad_h:-pad_h,:]
|
| 95 |
+
if pad_w > 0:
|
| 96 |
+
out = out[:, :, :, pad_w:-pad_w]
|
| 97 |
+
return out
|
| 98 |
+
|
| 99 |
+
def infer_with_flip_aug(self, x, pad_input: bool=True, **kwargs) -> torch.Tensor:
|
| 100 |
+
"""
|
| 101 |
+
Inference interface for the model with horizontal flip augmentation
|
| 102 |
+
Horizontal flip augmentation improves the accuracy of the model by averaging the output of the model with and without horizontal flip.
|
| 103 |
+
Args:
|
| 104 |
+
x (torch.Tensor): input tensor of shape (b, c, h, w)
|
| 105 |
+
pad_input (bool, optional): whether to use padding augmentation. Defaults to True.
|
| 106 |
+
Returns:
|
| 107 |
+
torch.Tensor: output tensor of shape (b, 1, h, w)
|
| 108 |
+
"""
|
| 109 |
+
# infer with horizontal flip and average
|
| 110 |
+
out = self._infer_with_pad_aug(x, pad_input=pad_input, **kwargs)
|
| 111 |
+
out_flip = self._infer_with_pad_aug(torch.flip(x, dims=[3]), pad_input=pad_input, **kwargs)
|
| 112 |
+
out = (out + torch.flip(out_flip, dims=[3])) / 2
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
def infer(self, x, pad_input: bool=True, with_flip_aug: bool=True, **kwargs) -> torch.Tensor:
|
| 116 |
+
"""
|
| 117 |
+
Inference interface for the model
|
| 118 |
+
Args:
|
| 119 |
+
x (torch.Tensor): input tensor of shape (b, c, h, w)
|
| 120 |
+
pad_input (bool, optional): whether to use padding augmentation. Defaults to True.
|
| 121 |
+
with_flip_aug (bool, optional): whether to use horizontal flip augmentation. Defaults to True.
|
| 122 |
+
Returns:
|
| 123 |
+
torch.Tensor: output tensor of shape (b, 1, h, w)
|
| 124 |
+
"""
|
| 125 |
+
if with_flip_aug:
|
| 126 |
+
return self.infer_with_flip_aug(x, pad_input=pad_input, **kwargs)
|
| 127 |
+
else:
|
| 128 |
+
return self._infer_with_pad_aug(x, pad_input=pad_input, **kwargs)
|
| 129 |
+
|
| 130 |
+
@torch.no_grad()
|
| 131 |
+
def infer_pil(self, pil_img, pad_input: bool=True, with_flip_aug: bool=True, output_type: str="numpy", **kwargs) -> Union[np.ndarray, PIL.Image.Image, torch.Tensor]:
|
| 132 |
+
"""
|
| 133 |
+
Inference interface for the model for PIL image
|
| 134 |
+
Args:
|
| 135 |
+
pil_img (PIL.Image.Image): input PIL image
|
| 136 |
+
pad_input (bool, optional): whether to use padding augmentation. Defaults to True.
|
| 137 |
+
with_flip_aug (bool, optional): whether to use horizontal flip augmentation. Defaults to True.
|
| 138 |
+
output_type (str, optional): output type. Supported values are 'numpy', 'pil' and 'tensor'. Defaults to "numpy".
|
| 139 |
+
"""
|
| 140 |
+
x = transforms.ToTensor()(pil_img).unsqueeze(0).to(self.device)
|
| 141 |
+
out_tensor = self.infer(x, pad_input=pad_input, with_flip_aug=with_flip_aug, **kwargs)
|
| 142 |
+
if output_type == "numpy":
|
| 143 |
+
return out_tensor.squeeze().cpu().numpy()
|
| 144 |
+
elif output_type == "pil":
|
| 145 |
+
# uint16 is required for depth pil image
|
| 146 |
+
out_16bit_numpy = (out_tensor.squeeze().cpu().numpy()*256).astype(np.uint16)
|
| 147 |
+
return Image.fromarray(out_16bit_numpy)
|
| 148 |
+
elif output_type == "tensor":
|
| 149 |
+
return out_tensor.squeeze().cpu()
|
| 150 |
+
else:
|
| 151 |
+
raise ValueError(f"output_type {output_type} not supported. Supported values are 'numpy', 'pil' and 'tensor'")
|
| 152 |
+
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/attractor.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@torch.jit.script
|
| 30 |
+
def exp_attractor(dx, alpha: float = 300, gamma: int = 2):
|
| 31 |
+
"""Exponential attractor: dc = exp(-alpha*|dx|^gamma) * dx , where dx = a - c, a = attractor point, c = bin center, dc = shift in bin centermmary for exp_attractor
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center.
|
| 35 |
+
alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300.
|
| 36 |
+
gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2.
|
| 37 |
+
|
| 38 |
+
Returns:
|
| 39 |
+
torch.Tensor : Delta shifts - dc; New bin centers = Old bin centers + dc
|
| 40 |
+
"""
|
| 41 |
+
return torch.exp(-alpha*(torch.abs(dx)**gamma)) * (dx)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@torch.jit.script
|
| 45 |
+
def inv_attractor(dx, alpha: float = 300, gamma: int = 2):
|
| 46 |
+
"""Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center
|
| 47 |
+
This is the default one according to the accompanying paper.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center.
|
| 51 |
+
alpha (float, optional): Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction. Defaults to 300.
|
| 52 |
+
gamma (int, optional): Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected. Lower gamma = farther reach. Defaults to 2.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
torch.Tensor: Delta shifts - dc; New bin centers = Old bin centers + dc
|
| 56 |
+
"""
|
| 57 |
+
return dx.div(1+alpha*dx.pow(gamma))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class AttractorLayer(nn.Module):
|
| 61 |
+
def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,
|
| 62 |
+
alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):
|
| 63 |
+
"""
|
| 64 |
+
Attractor layer for bin centers. Bin centers are bounded on the interval (min_depth, max_depth)
|
| 65 |
+
"""
|
| 66 |
+
super().__init__()
|
| 67 |
+
|
| 68 |
+
self.n_attractors = n_attractors
|
| 69 |
+
self.n_bins = n_bins
|
| 70 |
+
self.min_depth = min_depth
|
| 71 |
+
self.max_depth = max_depth
|
| 72 |
+
self.alpha = alpha
|
| 73 |
+
self.gamma = gamma
|
| 74 |
+
self.kind = kind
|
| 75 |
+
self.attractor_type = attractor_type
|
| 76 |
+
self.memory_efficient = memory_efficient
|
| 77 |
+
|
| 78 |
+
self._net = nn.Sequential(
|
| 79 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
| 80 |
+
nn.ReLU(inplace=True),
|
| 81 |
+
nn.Conv2d(mlp_dim, n_attractors*2, 1, 1, 0), # x2 for linear norm
|
| 82 |
+
nn.ReLU(inplace=True)
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False):
|
| 86 |
+
"""
|
| 87 |
+
Args:
|
| 88 |
+
x (torch.Tensor) : feature block; shape - n, c, h, w
|
| 89 |
+
b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
tuple(torch.Tensor,torch.Tensor) : new bin centers normed and scaled; shape - n, nbins, h, w
|
| 93 |
+
"""
|
| 94 |
+
if prev_b_embedding is not None:
|
| 95 |
+
if interpolate:
|
| 96 |
+
prev_b_embedding = nn.functional.interpolate(
|
| 97 |
+
prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)
|
| 98 |
+
x = x + prev_b_embedding
|
| 99 |
+
|
| 100 |
+
A = self._net(x)
|
| 101 |
+
eps = 1e-3
|
| 102 |
+
A = A + eps
|
| 103 |
+
n, c, h, w = A.shape
|
| 104 |
+
A = A.view(n, self.n_attractors, 2, h, w)
|
| 105 |
+
A_normed = A / A.sum(dim=2, keepdim=True) # n, a, 2, h, w
|
| 106 |
+
A_normed = A[:, :, 0, ...] # n, na, h, w
|
| 107 |
+
|
| 108 |
+
b_prev = nn.functional.interpolate(
|
| 109 |
+
b_prev, (h, w), mode='bilinear', align_corners=True)
|
| 110 |
+
b_centers = b_prev
|
| 111 |
+
|
| 112 |
+
if self.attractor_type == 'exp':
|
| 113 |
+
dist = exp_attractor
|
| 114 |
+
else:
|
| 115 |
+
dist = inv_attractor
|
| 116 |
+
|
| 117 |
+
if not self.memory_efficient:
|
| 118 |
+
func = {'mean': torch.mean, 'sum': torch.sum}[self.kind]
|
| 119 |
+
# .shape N, nbins, h, w
|
| 120 |
+
delta_c = func(dist(A_normed.unsqueeze(
|
| 121 |
+
2) - b_centers.unsqueeze(1)), dim=1)
|
| 122 |
+
else:
|
| 123 |
+
delta_c = torch.zeros_like(b_centers, device=b_centers.device)
|
| 124 |
+
for i in range(self.n_attractors):
|
| 125 |
+
# .shape N, nbins, h, w
|
| 126 |
+
delta_c += dist(A_normed[:, i, ...].unsqueeze(1) - b_centers)
|
| 127 |
+
|
| 128 |
+
if self.kind == 'mean':
|
| 129 |
+
delta_c = delta_c / self.n_attractors
|
| 130 |
+
|
| 131 |
+
b_new_centers = b_centers + delta_c
|
| 132 |
+
B_centers = (self.max_depth - self.min_depth) * \
|
| 133 |
+
b_new_centers + self.min_depth
|
| 134 |
+
B_centers, _ = torch.sort(B_centers, dim=1)
|
| 135 |
+
B_centers = torch.clip(B_centers, self.min_depth, self.max_depth)
|
| 136 |
+
return b_new_centers, B_centers
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class AttractorLayerUnnormed(nn.Module):
|
| 140 |
+
def __init__(self, in_features, n_bins, n_attractors=16, mlp_dim=128, min_depth=1e-3, max_depth=10,
|
| 141 |
+
alpha=300, gamma=2, kind='sum', attractor_type='exp', memory_efficient=False):
|
| 142 |
+
"""
|
| 143 |
+
Attractor layer for bin centers. Bin centers are unbounded
|
| 144 |
+
"""
|
| 145 |
+
super().__init__()
|
| 146 |
+
|
| 147 |
+
self.n_attractors = n_attractors
|
| 148 |
+
self.n_bins = n_bins
|
| 149 |
+
self.min_depth = min_depth
|
| 150 |
+
self.max_depth = max_depth
|
| 151 |
+
self.alpha = alpha
|
| 152 |
+
self.gamma = gamma
|
| 153 |
+
self.kind = kind
|
| 154 |
+
self.attractor_type = attractor_type
|
| 155 |
+
self.memory_efficient = memory_efficient
|
| 156 |
+
|
| 157 |
+
self._net = nn.Sequential(
|
| 158 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
| 159 |
+
nn.ReLU(inplace=True),
|
| 160 |
+
nn.Conv2d(mlp_dim, n_attractors, 1, 1, 0),
|
| 161 |
+
nn.Softplus()
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False):
|
| 165 |
+
"""
|
| 166 |
+
Args:
|
| 167 |
+
x (torch.Tensor) : feature block; shape - n, c, h, w
|
| 168 |
+
b_prev (torch.Tensor) : previous bin centers normed; shape - n, prev_nbins, h, w
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
tuple(torch.Tensor,torch.Tensor) : new bin centers unbounded; shape - n, nbins, h, w. Two outputs just to keep the API consistent with the normed version
|
| 172 |
+
"""
|
| 173 |
+
if prev_b_embedding is not None:
|
| 174 |
+
if interpolate:
|
| 175 |
+
prev_b_embedding = nn.functional.interpolate(
|
| 176 |
+
prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)
|
| 177 |
+
x = x + prev_b_embedding
|
| 178 |
+
|
| 179 |
+
A = self._net(x)
|
| 180 |
+
n, c, h, w = A.shape
|
| 181 |
+
|
| 182 |
+
b_prev = nn.functional.interpolate(
|
| 183 |
+
b_prev, (h, w), mode='bilinear', align_corners=True)
|
| 184 |
+
b_centers = b_prev
|
| 185 |
+
|
| 186 |
+
if self.attractor_type == 'exp':
|
| 187 |
+
dist = exp_attractor
|
| 188 |
+
else:
|
| 189 |
+
dist = inv_attractor
|
| 190 |
+
|
| 191 |
+
if not self.memory_efficient:
|
| 192 |
+
func = {'mean': torch.mean, 'sum': torch.sum}[self.kind]
|
| 193 |
+
# .shape N, nbins, h, w
|
| 194 |
+
delta_c = func(
|
| 195 |
+
dist(A.unsqueeze(2) - b_centers.unsqueeze(1)), dim=1)
|
| 196 |
+
else:
|
| 197 |
+
delta_c = torch.zeros_like(b_centers, device=b_centers.device)
|
| 198 |
+
for i in range(self.n_attractors):
|
| 199 |
+
delta_c += dist(A[:, i, ...].unsqueeze(1) -
|
| 200 |
+
b_centers) # .shape N, nbins, h, w
|
| 201 |
+
|
| 202 |
+
if self.kind == 'mean':
|
| 203 |
+
delta_c = delta_c / self.n_attractors
|
| 204 |
+
|
| 205 |
+
b_new_centers = b_centers + delta_c
|
| 206 |
+
B_centers = b_new_centers
|
| 207 |
+
|
| 208 |
+
return b_new_centers, B_centers
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/dist_layers.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def log_binom(n, k, eps=1e-7):
|
| 30 |
+
""" log(nCk) using stirling approximation """
|
| 31 |
+
n = n + eps
|
| 32 |
+
k = k + eps
|
| 33 |
+
return n * torch.log(n) - k * torch.log(k) - (n-k) * torch.log(n-k+eps)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class LogBinomial(nn.Module):
|
| 37 |
+
def __init__(self, n_classes=256, act=torch.softmax):
|
| 38 |
+
"""Compute log binomial distribution for n_classes
|
| 39 |
+
|
| 40 |
+
Args:
|
| 41 |
+
n_classes (int, optional): number of output classes. Defaults to 256.
|
| 42 |
+
"""
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.K = n_classes
|
| 45 |
+
self.act = act
|
| 46 |
+
self.register_buffer('k_idx', torch.arange(
|
| 47 |
+
0, n_classes).view(1, -1, 1, 1))
|
| 48 |
+
self.register_buffer('K_minus_1', torch.Tensor(
|
| 49 |
+
[self.K-1]).view(1, -1, 1, 1))
|
| 50 |
+
|
| 51 |
+
def forward(self, x, t=1., eps=1e-4):
|
| 52 |
+
"""Compute log binomial distribution for x
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
x (torch.Tensor - NCHW): probabilities
|
| 56 |
+
t (float, torch.Tensor - NCHW, optional): Temperature of distribution. Defaults to 1..
|
| 57 |
+
eps (float, optional): Small number for numerical stability. Defaults to 1e-4.
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
torch.Tensor -NCHW: log binomial distribution logbinomial(p;t)
|
| 61 |
+
"""
|
| 62 |
+
if x.ndim == 3:
|
| 63 |
+
x = x.unsqueeze(1) # make it nchw
|
| 64 |
+
|
| 65 |
+
one_minus_x = torch.clamp(1 - x, eps, 1)
|
| 66 |
+
x = torch.clamp(x, eps, 1)
|
| 67 |
+
y = log_binom(self.K_minus_1, self.k_idx) + self.k_idx * \
|
| 68 |
+
torch.log(x) + (self.K - 1 - self.k_idx) * torch.log(one_minus_x)
|
| 69 |
+
return self.act(y/t, dim=1)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class ConditionalLogBinomial(nn.Module):
|
| 73 |
+
def __init__(self, in_features, condition_dim, n_classes=256, bottleneck_factor=2, p_eps=1e-4, max_temp=50, min_temp=1e-7, act=torch.softmax):
|
| 74 |
+
"""Conditional Log Binomial distribution
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
in_features (int): number of input channels in main feature
|
| 78 |
+
condition_dim (int): number of input channels in condition feature
|
| 79 |
+
n_classes (int, optional): Number of classes. Defaults to 256.
|
| 80 |
+
bottleneck_factor (int, optional): Hidden dim factor. Defaults to 2.
|
| 81 |
+
p_eps (float, optional): small eps value. Defaults to 1e-4.
|
| 82 |
+
max_temp (float, optional): Maximum temperature of output distribution. Defaults to 50.
|
| 83 |
+
min_temp (float, optional): Minimum temperature of output distribution. Defaults to 1e-7.
|
| 84 |
+
"""
|
| 85 |
+
super().__init__()
|
| 86 |
+
self.p_eps = p_eps
|
| 87 |
+
self.max_temp = max_temp
|
| 88 |
+
self.min_temp = min_temp
|
| 89 |
+
self.log_binomial_transform = LogBinomial(n_classes, act=act)
|
| 90 |
+
bottleneck = (in_features + condition_dim) // bottleneck_factor
|
| 91 |
+
self.mlp = nn.Sequential(
|
| 92 |
+
nn.Conv2d(in_features + condition_dim, bottleneck,
|
| 93 |
+
kernel_size=1, stride=1, padding=0),
|
| 94 |
+
nn.GELU(),
|
| 95 |
+
# 2 for p linear norm, 2 for t linear norm
|
| 96 |
+
nn.Conv2d(bottleneck, 2+2, kernel_size=1, stride=1, padding=0),
|
| 97 |
+
nn.Softplus()
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
def forward(self, x, cond):
|
| 101 |
+
"""Forward pass
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
x (torch.Tensor - NCHW): Main feature
|
| 105 |
+
cond (torch.Tensor - NCHW): condition feature
|
| 106 |
+
|
| 107 |
+
Returns:
|
| 108 |
+
torch.Tensor: Output log binomial distribution
|
| 109 |
+
"""
|
| 110 |
+
pt = self.mlp(torch.concat((x, cond), dim=1))
|
| 111 |
+
p, t = pt[:, :2, ...], pt[:, 2:, ...]
|
| 112 |
+
|
| 113 |
+
p = p + self.p_eps
|
| 114 |
+
p = p[:, 0, ...] / (p[:, 0, ...] + p[:, 1, ...])
|
| 115 |
+
|
| 116 |
+
t = t + self.p_eps
|
| 117 |
+
t = t[:, 0, ...] / (t[:, 0, ...] + t[:, 1, ...])
|
| 118 |
+
t = t.unsqueeze(1)
|
| 119 |
+
t = (self.max_temp - self.min_temp) * t + self.min_temp
|
| 120 |
+
|
| 121 |
+
return self.log_binomial_transform(p, t)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/localbins_layers.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class SeedBinRegressor(nn.Module):
|
| 30 |
+
def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
|
| 31 |
+
"""Bin center regressor network. Bin centers are bounded on (min_depth, max_depth) interval.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
in_features (int): input channels
|
| 35 |
+
n_bins (int, optional): Number of bin centers. Defaults to 16.
|
| 36 |
+
mlp_dim (int, optional): Hidden dimension. Defaults to 256.
|
| 37 |
+
min_depth (float, optional): Min depth value. Defaults to 1e-3.
|
| 38 |
+
max_depth (float, optional): Max depth value. Defaults to 10.
|
| 39 |
+
"""
|
| 40 |
+
super().__init__()
|
| 41 |
+
self.version = "1_1"
|
| 42 |
+
self.min_depth = min_depth
|
| 43 |
+
self.max_depth = max_depth
|
| 44 |
+
|
| 45 |
+
self._net = nn.Sequential(
|
| 46 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
| 47 |
+
nn.ReLU(inplace=True),
|
| 48 |
+
nn.Conv2d(mlp_dim, n_bins, 1, 1, 0),
|
| 49 |
+
nn.ReLU(inplace=True)
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
"""
|
| 54 |
+
Returns tensor of bin_width vectors (centers). One vector b for every pixel
|
| 55 |
+
"""
|
| 56 |
+
B = self._net(x)
|
| 57 |
+
eps = 1e-3
|
| 58 |
+
B = B + eps
|
| 59 |
+
B_widths_normed = B / B.sum(dim=1, keepdim=True)
|
| 60 |
+
B_widths = (self.max_depth - self.min_depth) * \
|
| 61 |
+
B_widths_normed # .shape NCHW
|
| 62 |
+
# pad has the form (left, right, top, bottom, front, back)
|
| 63 |
+
B_widths = nn.functional.pad(
|
| 64 |
+
B_widths, (0, 0, 0, 0, 1, 0), mode='constant', value=self.min_depth)
|
| 65 |
+
B_edges = torch.cumsum(B_widths, dim=1) # .shape NCHW
|
| 66 |
+
|
| 67 |
+
B_centers = 0.5 * (B_edges[:, :-1, ...] + B_edges[:, 1:, ...])
|
| 68 |
+
return B_widths_normed, B_centers
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class SeedBinRegressorUnnormed(nn.Module):
|
| 72 |
+
def __init__(self, in_features, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
|
| 73 |
+
"""Bin center regressor network. Bin centers are unbounded
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
in_features (int): input channels
|
| 77 |
+
n_bins (int, optional): Number of bin centers. Defaults to 16.
|
| 78 |
+
mlp_dim (int, optional): Hidden dimension. Defaults to 256.
|
| 79 |
+
min_depth (float, optional): Not used. (for compatibility with SeedBinRegressor)
|
| 80 |
+
max_depth (float, optional): Not used. (for compatibility with SeedBinRegressor)
|
| 81 |
+
"""
|
| 82 |
+
super().__init__()
|
| 83 |
+
self.version = "1_1"
|
| 84 |
+
self._net = nn.Sequential(
|
| 85 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
| 86 |
+
nn.ReLU(inplace=True),
|
| 87 |
+
nn.Conv2d(mlp_dim, n_bins, 1, 1, 0),
|
| 88 |
+
nn.Softplus()
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
def forward(self, x):
|
| 92 |
+
"""
|
| 93 |
+
Returns tensor of bin_width vectors (centers). One vector b for every pixel
|
| 94 |
+
"""
|
| 95 |
+
B_centers = self._net(x)
|
| 96 |
+
return B_centers, B_centers
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class Projector(nn.Module):
|
| 100 |
+
def __init__(self, in_features, out_features, mlp_dim=128):
|
| 101 |
+
"""Projector MLP
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
in_features (int): input channels
|
| 105 |
+
out_features (int): output channels
|
| 106 |
+
mlp_dim (int, optional): hidden dimension. Defaults to 128.
|
| 107 |
+
"""
|
| 108 |
+
super().__init__()
|
| 109 |
+
|
| 110 |
+
self._net = nn.Sequential(
|
| 111 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
| 112 |
+
nn.ReLU(inplace=True),
|
| 113 |
+
nn.Conv2d(mlp_dim, out_features, 1, 1, 0),
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
def forward(self, x):
|
| 117 |
+
return self._net(x)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class LinearSplitter(nn.Module):
|
| 122 |
+
def __init__(self, in_features, prev_nbins, split_factor=2, mlp_dim=128, min_depth=1e-3, max_depth=10):
|
| 123 |
+
super().__init__()
|
| 124 |
+
|
| 125 |
+
self.prev_nbins = prev_nbins
|
| 126 |
+
self.split_factor = split_factor
|
| 127 |
+
self.min_depth = min_depth
|
| 128 |
+
self.max_depth = max_depth
|
| 129 |
+
|
| 130 |
+
self._net = nn.Sequential(
|
| 131 |
+
nn.Conv2d(in_features, mlp_dim, 1, 1, 0),
|
| 132 |
+
nn.GELU(),
|
| 133 |
+
nn.Conv2d(mlp_dim, prev_nbins * split_factor, 1, 1, 0),
|
| 134 |
+
nn.ReLU()
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
def forward(self, x, b_prev, prev_b_embedding=None, interpolate=True, is_for_query=False):
|
| 138 |
+
"""
|
| 139 |
+
x : feature block; shape - n, c, h, w
|
| 140 |
+
b_prev : previous bin widths normed; shape - n, prev_nbins, h, w
|
| 141 |
+
"""
|
| 142 |
+
if prev_b_embedding is not None:
|
| 143 |
+
if interpolate:
|
| 144 |
+
prev_b_embedding = nn.functional.interpolate(prev_b_embedding, x.shape[-2:], mode='bilinear', align_corners=True)
|
| 145 |
+
x = x + prev_b_embedding
|
| 146 |
+
S = self._net(x)
|
| 147 |
+
eps = 1e-3
|
| 148 |
+
S = S + eps
|
| 149 |
+
n, c, h, w = S.shape
|
| 150 |
+
S = S.view(n, self.prev_nbins, self.split_factor, h, w)
|
| 151 |
+
S_normed = S / S.sum(dim=2, keepdim=True) # fractional splits
|
| 152 |
+
|
| 153 |
+
b_prev = nn.functional.interpolate(b_prev, (h,w), mode='bilinear', align_corners=True)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
b_prev = b_prev / b_prev.sum(dim=1, keepdim=True) # renormalize for gurantees
|
| 157 |
+
# print(b_prev.shape, S_normed.shape)
|
| 158 |
+
# if is_for_query:(1).expand(-1, b_prev.size(0)//n, -1, -1, -1, -1).flatten(0,1) # TODO ? can replace all this with a single torch.repeat?
|
| 159 |
+
b = b_prev.unsqueeze(2) * S_normed
|
| 160 |
+
b = b.flatten(1,2) # .shape n, prev_nbins * split_factor, h, w
|
| 161 |
+
|
| 162 |
+
# calculate bin centers for loss calculation
|
| 163 |
+
B_widths = (self.max_depth - self.min_depth) * b # .shape N, nprev * splitfactor, H, W
|
| 164 |
+
# pad has the form (left, right, top, bottom, front, back)
|
| 165 |
+
B_widths = nn.functional.pad(B_widths, (0,0,0,0,1,0), mode='constant', value=self.min_depth)
|
| 166 |
+
B_edges = torch.cumsum(B_widths, dim=1) # .shape NCHW
|
| 167 |
+
|
| 168 |
+
B_centers = 0.5 * (B_edges[:, :-1, ...] + B_edges[:,1:,...])
|
| 169 |
+
return b, B_centers
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/layers/patch_transformer.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn as nn
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class PatchTransformerEncoder(nn.Module):
|
| 30 |
+
def __init__(self, in_channels, patch_size=10, embedding_dim=128, num_heads=4, use_class_token=False):
|
| 31 |
+
"""ViT-like transformer block
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
in_channels (int): Input channels
|
| 35 |
+
patch_size (int, optional): patch size. Defaults to 10.
|
| 36 |
+
embedding_dim (int, optional): Embedding dimension in transformer model. Defaults to 128.
|
| 37 |
+
num_heads (int, optional): number of attention heads. Defaults to 4.
|
| 38 |
+
use_class_token (bool, optional): Whether to use extra token at the start for global accumulation (called as "class token"). Defaults to False.
|
| 39 |
+
"""
|
| 40 |
+
super(PatchTransformerEncoder, self).__init__()
|
| 41 |
+
self.use_class_token = use_class_token
|
| 42 |
+
encoder_layers = nn.TransformerEncoderLayer(
|
| 43 |
+
embedding_dim, num_heads, dim_feedforward=1024)
|
| 44 |
+
self.transformer_encoder = nn.TransformerEncoder(
|
| 45 |
+
encoder_layers, num_layers=4) # takes shape S,N,E
|
| 46 |
+
|
| 47 |
+
self.embedding_convPxP = nn.Conv2d(in_channels, embedding_dim,
|
| 48 |
+
kernel_size=patch_size, stride=patch_size, padding=0)
|
| 49 |
+
|
| 50 |
+
def positional_encoding_1d(self, sequence_length, batch_size, embedding_dim, device='cpu'):
|
| 51 |
+
"""Generate positional encodings
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
sequence_length (int): Sequence length
|
| 55 |
+
embedding_dim (int): Embedding dimension
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
torch.Tensor SBE: Positional encodings
|
| 59 |
+
"""
|
| 60 |
+
position = torch.arange(
|
| 61 |
+
0, sequence_length, dtype=torch.float32, device=device).unsqueeze(1)
|
| 62 |
+
index = torch.arange(
|
| 63 |
+
0, embedding_dim, 2, dtype=torch.float32, device=device).unsqueeze(0)
|
| 64 |
+
div_term = torch.exp(index * (-torch.log(torch.tensor(10000.0, device=device)) / embedding_dim))
|
| 65 |
+
pos_encoding = position * div_term
|
| 66 |
+
pos_encoding = torch.cat([torch.sin(pos_encoding), torch.cos(pos_encoding)], dim=1)
|
| 67 |
+
pos_encoding = pos_encoding.unsqueeze(1).repeat(1, batch_size, 1)
|
| 68 |
+
return pos_encoding
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def forward(self, x):
|
| 72 |
+
"""Forward pass
|
| 73 |
+
|
| 74 |
+
Args:
|
| 75 |
+
x (torch.Tensor - NCHW): Input feature tensor
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
torch.Tensor - SNE: Transformer output embeddings. S - sequence length (=HW/patch_size^2), N - batch size, E - embedding dim
|
| 79 |
+
"""
|
| 80 |
+
embeddings = self.embedding_convPxP(x).flatten(
|
| 81 |
+
2) # .shape = n,c,s = n, embedding_dim, s
|
| 82 |
+
if self.use_class_token:
|
| 83 |
+
# extra special token at start ?
|
| 84 |
+
embeddings = nn.functional.pad(embeddings, (1, 0))
|
| 85 |
+
|
| 86 |
+
# change to S,N,E format required by transformer
|
| 87 |
+
embeddings = embeddings.permute(2, 0, 1)
|
| 88 |
+
S, N, E = embeddings.shape
|
| 89 |
+
embeddings = embeddings + self.positional_encoding_1d(S, N, E, device=embeddings.device)
|
| 90 |
+
x = self.transformer_encoder(embeddings) # .shape = S, N, E
|
| 91 |
+
return x
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/model_io.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
import torch
|
| 26 |
+
|
| 27 |
+
def load_state_dict(model, state_dict):
|
| 28 |
+
"""Load state_dict into model, handling DataParallel and DistributedDataParallel. Also checks for "model" key in state_dict.
|
| 29 |
+
|
| 30 |
+
DataParallel prefixes state_dict keys with 'module.' when saving.
|
| 31 |
+
If the model is not a DataParallel model but the state_dict is, then prefixes are removed.
|
| 32 |
+
If the model is a DataParallel model but the state_dict is not, then prefixes are added.
|
| 33 |
+
"""
|
| 34 |
+
state_dict = state_dict.get('model', state_dict)
|
| 35 |
+
# if model is a DataParallel model, then state_dict keys are prefixed with 'module.'
|
| 36 |
+
|
| 37 |
+
do_prefix = isinstance(
|
| 38 |
+
model, (torch.nn.DataParallel, torch.nn.parallel.DistributedDataParallel))
|
| 39 |
+
state = {}
|
| 40 |
+
for k, v in state_dict.items():
|
| 41 |
+
if k.startswith('module.') and not do_prefix:
|
| 42 |
+
k = k[7:]
|
| 43 |
+
|
| 44 |
+
if not k.startswith('module.') and do_prefix:
|
| 45 |
+
k = 'module.' + k
|
| 46 |
+
|
| 47 |
+
state[k] = v
|
| 48 |
+
model.load_state_dict(state)
|
| 49 |
+
print("Loaded successfully")
|
| 50 |
+
return model
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def load_wts(model, checkpoint_path):
|
| 54 |
+
ckpt = torch.load(checkpoint_path, map_location='cpu')
|
| 55 |
+
return load_state_dict(model, ckpt)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def load_state_dict_from_url(model, url, **kwargs):
|
| 59 |
+
state_dict = torch.hub.load_state_dict_from_url(url, map_location='cpu', **kwargs)
|
| 60 |
+
return load_state_dict(model, state_dict)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def load_state_from_resource(model, resource: str):
|
| 64 |
+
"""Loads weights to the model from a given resource. A resource can be of following types:
|
| 65 |
+
1. URL. Prefixed with "url::"
|
| 66 |
+
e.g. url::http(s)://url.resource.com/ckpt.pt
|
| 67 |
+
|
| 68 |
+
2. Local path. Prefixed with "local::"
|
| 69 |
+
e.g. local::/path/to/ckpt.pt
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
model (torch.nn.Module): Model
|
| 74 |
+
resource (str): resource string
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
torch.nn.Module: Model with loaded weights
|
| 78 |
+
"""
|
| 79 |
+
print(f"Using pretrained resource {resource}")
|
| 80 |
+
|
| 81 |
+
if resource.startswith('url::'):
|
| 82 |
+
url = resource.split('url::')[1]
|
| 83 |
+
return load_state_dict_from_url(model, url, progress=True)
|
| 84 |
+
|
| 85 |
+
elif resource.startswith('local::'):
|
| 86 |
+
path = resource.split('local::')[1]
|
| 87 |
+
return load_wts(model, path)
|
| 88 |
+
|
| 89 |
+
else:
|
| 90 |
+
raise ValueError("Invalid resource type, only url:: and local:: are supported")
|
| 91 |
+
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
from .zoedepth_v1 import ZoeDepth
|
| 26 |
+
|
| 27 |
+
all_versions = {
|
| 28 |
+
"v1": ZoeDepth,
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
get_version = lambda v : all_versions[v]
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": {
|
| 3 |
+
"name": "ZoeDepth",
|
| 4 |
+
"version_name": "v1",
|
| 5 |
+
"n_bins": 64,
|
| 6 |
+
"bin_embedding_dim": 128,
|
| 7 |
+
"bin_centers_type": "softplus",
|
| 8 |
+
"n_attractors":[16, 8, 4, 1],
|
| 9 |
+
"attractor_alpha": 1000,
|
| 10 |
+
"attractor_gamma": 2,
|
| 11 |
+
"attractor_kind" : "mean",
|
| 12 |
+
"attractor_type" : "inv",
|
| 13 |
+
"midas_model_type" : "DPT_BEiT_L_384",
|
| 14 |
+
"min_temp": 0.0212,
|
| 15 |
+
"max_temp": 50.0,
|
| 16 |
+
"output_distribution": "logbinomial",
|
| 17 |
+
"memory_efficient": true,
|
| 18 |
+
"inverse_midas": false,
|
| 19 |
+
"img_size": [384, 512]
|
| 20 |
+
},
|
| 21 |
+
|
| 22 |
+
"train": {
|
| 23 |
+
"train_midas": true,
|
| 24 |
+
"use_pretrained_midas": true,
|
| 25 |
+
"trainer": "zoedepth",
|
| 26 |
+
"epochs": 5,
|
| 27 |
+
"bs": 16,
|
| 28 |
+
"optim_kwargs": {"lr": 0.000161, "wd": 0.01},
|
| 29 |
+
"sched_kwargs": {"div_factor": 1, "final_div_factor": 10000, "pct_start": 0.7, "three_phase":false, "cycle_momentum": true},
|
| 30 |
+
"same_lr": false,
|
| 31 |
+
"w_si": 1,
|
| 32 |
+
"w_domain": 0.2,
|
| 33 |
+
"w_reg": 0,
|
| 34 |
+
"w_grad": 0,
|
| 35 |
+
"avoid_boundary": false,
|
| 36 |
+
"random_crop": false,
|
| 37 |
+
"input_width": 640,
|
| 38 |
+
"input_height": 480,
|
| 39 |
+
"midas_lr_factor": 1,
|
| 40 |
+
"encoder_lr_factor":10,
|
| 41 |
+
"pos_enc_lr_factor":10,
|
| 42 |
+
"freeze_midas_bn": true
|
| 43 |
+
|
| 44 |
+
},
|
| 45 |
+
|
| 46 |
+
"infer":{
|
| 47 |
+
"train_midas": false,
|
| 48 |
+
"use_pretrained_midas": false,
|
| 49 |
+
"pretrained_resource" : "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_N.pt",
|
| 50 |
+
"force_keep_ar": true
|
| 51 |
+
},
|
| 52 |
+
|
| 53 |
+
"eval":{
|
| 54 |
+
"train_midas": false,
|
| 55 |
+
"use_pretrained_midas": false,
|
| 56 |
+
"pretrained_resource" : "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_N.pt"
|
| 57 |
+
}
|
| 58 |
+
}
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/config_zoedepth_kitti.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": {
|
| 3 |
+
"bin_centers_type": "normed",
|
| 4 |
+
"img_size": [384, 768]
|
| 5 |
+
},
|
| 6 |
+
|
| 7 |
+
"train": {
|
| 8 |
+
},
|
| 9 |
+
|
| 10 |
+
"infer":{
|
| 11 |
+
"train_midas": false,
|
| 12 |
+
"use_pretrained_midas": false,
|
| 13 |
+
"pretrained_resource" : "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_K.pt",
|
| 14 |
+
"force_keep_ar": true
|
| 15 |
+
},
|
| 16 |
+
|
| 17 |
+
"eval":{
|
| 18 |
+
"train_midas": false,
|
| 19 |
+
"use_pretrained_midas": false,
|
| 20 |
+
"pretrained_resource" : "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_K.pt"
|
| 21 |
+
}
|
| 22 |
+
}
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth/zoedepth_v1.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
import itertools
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn as nn
|
| 29 |
+
from models.monoD.zoeDepth.models.depth_model import DepthModel
|
| 30 |
+
from models.monoD.zoeDepth.models.base_models.midas import MidasCore
|
| 31 |
+
from models.monoD.zoeDepth.models.layers.attractor import (
|
| 32 |
+
AttractorLayer, AttractorLayerUnnormed
|
| 33 |
+
)
|
| 34 |
+
from models.monoD.zoeDepth.models.layers.dist_layers import (
|
| 35 |
+
ConditionalLogBinomial
|
| 36 |
+
)
|
| 37 |
+
from models.monoD.zoeDepth.models.layers.localbins_layers import (
|
| 38 |
+
Projector, SeedBinRegressor,
|
| 39 |
+
SeedBinRegressorUnnormed
|
| 40 |
+
)
|
| 41 |
+
from models.monoD.zoeDepth.models.model_io import load_state_from_resource
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class ZoeDepth(DepthModel):
|
| 45 |
+
def __init__(self, core, n_bins=64, bin_centers_type="softplus", bin_embedding_dim=128, min_depth=1e-3, max_depth=10,
|
| 46 |
+
n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', min_temp=5, max_temp=50, train_midas=True,
|
| 47 |
+
midas_lr_factor=10, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, **kwargs):
|
| 48 |
+
"""ZoeDepth model. This is the version of ZoeDepth that has a single metric head
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features
|
| 52 |
+
n_bins (int, optional): Number of bin centers. Defaults to 64.
|
| 53 |
+
bin_centers_type (str, optional): "normed" or "softplus". Activation type used for bin centers. For "normed" bin centers, linear normalization trick is applied. This results in bounded bin centers.
|
| 54 |
+
For "softplus", softplus activation is used and thus are unbounded. Defaults to "softplus".
|
| 55 |
+
bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128.
|
| 56 |
+
min_depth (float, optional): Lower bound for normed bin centers. Defaults to 1e-3.
|
| 57 |
+
max_depth (float, optional): Upper bound for normed bin centers. Defaults to 10.
|
| 58 |
+
n_attractors (List[int], optional): Number of bin attractors at decoder layers. Defaults to [16, 8, 4, 1].
|
| 59 |
+
attractor_alpha (int, optional): Proportional attractor strength. Refer to models.layers.attractor for more details. Defaults to 300.
|
| 60 |
+
attractor_gamma (int, optional): Exponential attractor strength. Refer to models.layers.attractor for more details. Defaults to 2.
|
| 61 |
+
attractor_kind (str, optional): Attraction aggregation "sum" or "mean". Defaults to 'sum'.
|
| 62 |
+
attractor_type (str, optional): Type of attractor to use; "inv" (Inverse attractor) or "exp" (Exponential attractor). Defaults to 'exp'.
|
| 63 |
+
min_temp (int, optional): Lower bound for temperature of output probability distribution. Defaults to 5.
|
| 64 |
+
max_temp (int, optional): Upper bound for temperature of output probability distribution. Defaults to 50.
|
| 65 |
+
train_midas (bool, optional): Whether to train "core", the base midas model. Defaults to True.
|
| 66 |
+
midas_lr_factor (int, optional): Learning rate reduction factor for base midas model except its encoder and positional encodings. Defaults to 10.
|
| 67 |
+
encoder_lr_factor (int, optional): Learning rate reduction factor for the encoder in midas model. Defaults to 10.
|
| 68 |
+
pos_enc_lr_factor (int, optional): Learning rate reduction factor for positional encodings in the base midas model. Defaults to 10.
|
| 69 |
+
"""
|
| 70 |
+
super().__init__()
|
| 71 |
+
|
| 72 |
+
self.core = core
|
| 73 |
+
self.max_depth = max_depth
|
| 74 |
+
self.min_depth = min_depth
|
| 75 |
+
self.min_temp = min_temp
|
| 76 |
+
self.bin_centers_type = bin_centers_type
|
| 77 |
+
|
| 78 |
+
self.midas_lr_factor = midas_lr_factor
|
| 79 |
+
self.encoder_lr_factor = encoder_lr_factor
|
| 80 |
+
self.pos_enc_lr_factor = pos_enc_lr_factor
|
| 81 |
+
self.train_midas = train_midas
|
| 82 |
+
self.inverse_midas = inverse_midas
|
| 83 |
+
|
| 84 |
+
if self.encoder_lr_factor <= 0:
|
| 85 |
+
self.core.freeze_encoder(
|
| 86 |
+
freeze_rel_pos=self.pos_enc_lr_factor <= 0)
|
| 87 |
+
|
| 88 |
+
N_MIDAS_OUT = 32
|
| 89 |
+
btlnck_features = self.core.output_channels[0]
|
| 90 |
+
num_out_features = self.core.output_channels[1:]
|
| 91 |
+
|
| 92 |
+
self.conv2 = nn.Conv2d(btlnck_features, btlnck_features,
|
| 93 |
+
kernel_size=1, stride=1, padding=0) # btlnck conv
|
| 94 |
+
|
| 95 |
+
if bin_centers_type == "normed":
|
| 96 |
+
SeedBinRegressorLayer = SeedBinRegressor
|
| 97 |
+
Attractor = AttractorLayer
|
| 98 |
+
elif bin_centers_type == "softplus":
|
| 99 |
+
SeedBinRegressorLayer = SeedBinRegressorUnnormed
|
| 100 |
+
Attractor = AttractorLayerUnnormed
|
| 101 |
+
elif bin_centers_type == "hybrid1":
|
| 102 |
+
SeedBinRegressorLayer = SeedBinRegressor
|
| 103 |
+
Attractor = AttractorLayerUnnormed
|
| 104 |
+
elif bin_centers_type == "hybrid2":
|
| 105 |
+
SeedBinRegressorLayer = SeedBinRegressorUnnormed
|
| 106 |
+
Attractor = AttractorLayer
|
| 107 |
+
else:
|
| 108 |
+
raise ValueError(
|
| 109 |
+
"bin_centers_type should be one of 'normed', 'softplus', 'hybrid1', 'hybrid2'")
|
| 110 |
+
|
| 111 |
+
self.seed_bin_regressor = SeedBinRegressorLayer(
|
| 112 |
+
btlnck_features, n_bins=n_bins, min_depth=min_depth, max_depth=max_depth)
|
| 113 |
+
self.seed_projector = Projector(btlnck_features, bin_embedding_dim)
|
| 114 |
+
self.projectors = nn.ModuleList([
|
| 115 |
+
Projector(num_out, bin_embedding_dim)
|
| 116 |
+
for num_out in num_out_features
|
| 117 |
+
])
|
| 118 |
+
self.attractors = nn.ModuleList([
|
| 119 |
+
Attractor(bin_embedding_dim, n_bins, n_attractors=n_attractors[i], min_depth=min_depth, max_depth=max_depth,
|
| 120 |
+
alpha=attractor_alpha, gamma=attractor_gamma, kind=attractor_kind, attractor_type=attractor_type)
|
| 121 |
+
for i in range(len(num_out_features))
|
| 122 |
+
])
|
| 123 |
+
|
| 124 |
+
last_in = N_MIDAS_OUT + 1 # +1 for relative depth
|
| 125 |
+
|
| 126 |
+
# use log binomial instead of softmax
|
| 127 |
+
self.conditional_log_binomial = ConditionalLogBinomial(
|
| 128 |
+
last_in, bin_embedding_dim, n_classes=n_bins, min_temp=min_temp, max_temp=max_temp)
|
| 129 |
+
|
| 130 |
+
def forward(self, x, return_final_centers=False, denorm=False, return_probs=False, **kwargs):
|
| 131 |
+
"""
|
| 132 |
+
Args:
|
| 133 |
+
x (torch.Tensor): Input image tensor of shape (B, C, H, W)
|
| 134 |
+
return_final_centers (bool, optional): Whether to return the final bin centers. Defaults to False.
|
| 135 |
+
denorm (bool, optional): Whether to denormalize the input image. This reverses ImageNet normalization as midas normalization is different. Defaults to False.
|
| 136 |
+
return_probs (bool, optional): Whether to return the output probability distribution. Defaults to False.
|
| 137 |
+
|
| 138 |
+
Returns:
|
| 139 |
+
dict: Dictionary containing the following keys:
|
| 140 |
+
- rel_depth (torch.Tensor): Relative depth map of shape (B, H, W)
|
| 141 |
+
- metric_depth (torch.Tensor): Metric depth map of shape (B, 1, H, W)
|
| 142 |
+
- bin_centers (torch.Tensor): Bin centers of shape (B, n_bins). Present only if return_final_centers is True
|
| 143 |
+
- probs (torch.Tensor): Output probability distribution of shape (B, n_bins, H, W). Present only if return_probs is True
|
| 144 |
+
|
| 145 |
+
"""
|
| 146 |
+
b, c, h, w = x.shape
|
| 147 |
+
# print("input shape ", x.shape)
|
| 148 |
+
self.orig_input_width = w
|
| 149 |
+
self.orig_input_height = h
|
| 150 |
+
rel_depth, out = self.core(x, denorm=denorm, return_rel_depth=True)
|
| 151 |
+
# print("output shapes", rel_depth.shape, out.shape)
|
| 152 |
+
|
| 153 |
+
outconv_activation = out[0]
|
| 154 |
+
btlnck = out[1]
|
| 155 |
+
x_blocks = out[2:]
|
| 156 |
+
|
| 157 |
+
x_d0 = self.conv2(btlnck)
|
| 158 |
+
x = x_d0
|
| 159 |
+
_, seed_b_centers = self.seed_bin_regressor(x)
|
| 160 |
+
|
| 161 |
+
if self.bin_centers_type == 'normed' or self.bin_centers_type == 'hybrid2':
|
| 162 |
+
b_prev = (seed_b_centers - self.min_depth) / \
|
| 163 |
+
(self.max_depth - self.min_depth)
|
| 164 |
+
else:
|
| 165 |
+
b_prev = seed_b_centers
|
| 166 |
+
|
| 167 |
+
prev_b_embedding = self.seed_projector(x)
|
| 168 |
+
|
| 169 |
+
# unroll this loop for better performance
|
| 170 |
+
for projector, attractor, x in zip(self.projectors, self.attractors, x_blocks):
|
| 171 |
+
b_embedding = projector(x)
|
| 172 |
+
b, b_centers = attractor(
|
| 173 |
+
b_embedding, b_prev, prev_b_embedding, interpolate=True)
|
| 174 |
+
b_prev = b.clone()
|
| 175 |
+
prev_b_embedding = b_embedding.clone()
|
| 176 |
+
|
| 177 |
+
last = outconv_activation
|
| 178 |
+
|
| 179 |
+
if self.inverse_midas:
|
| 180 |
+
# invert depth followed by normalization
|
| 181 |
+
rel_depth = 1.0 / (rel_depth + 1e-6)
|
| 182 |
+
rel_depth = (rel_depth - rel_depth.min()) / \
|
| 183 |
+
(rel_depth.max() - rel_depth.min())
|
| 184 |
+
# concat rel depth with last. First interpolate rel depth to last size
|
| 185 |
+
rel_cond = rel_depth.unsqueeze(1)
|
| 186 |
+
rel_cond = nn.functional.interpolate(
|
| 187 |
+
rel_cond, size=last.shape[2:], mode='bilinear', align_corners=True)
|
| 188 |
+
last = torch.cat([last, rel_cond], dim=1)
|
| 189 |
+
|
| 190 |
+
b_embedding = nn.functional.interpolate(
|
| 191 |
+
b_embedding, last.shape[-2:], mode='bilinear', align_corners=True)
|
| 192 |
+
x = self.conditional_log_binomial(last, b_embedding)
|
| 193 |
+
|
| 194 |
+
# Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor
|
| 195 |
+
# print(x.shape, b_centers.shape)
|
| 196 |
+
b_centers = nn.functional.interpolate(
|
| 197 |
+
b_centers, x.shape[-2:], mode='bilinear', align_corners=True)
|
| 198 |
+
out = torch.sum(x * b_centers, dim=1, keepdim=True)
|
| 199 |
+
|
| 200 |
+
# Structure output dict
|
| 201 |
+
output = dict(metric_depth=out)
|
| 202 |
+
if return_final_centers or return_probs:
|
| 203 |
+
output['bin_centers'] = b_centers
|
| 204 |
+
|
| 205 |
+
if return_probs:
|
| 206 |
+
output['probs'] = x
|
| 207 |
+
|
| 208 |
+
return output
|
| 209 |
+
|
| 210 |
+
def get_lr_params(self, lr):
|
| 211 |
+
"""
|
| 212 |
+
Learning rate configuration for different layers of the model
|
| 213 |
+
Args:
|
| 214 |
+
lr (float) : Base learning rate
|
| 215 |
+
Returns:
|
| 216 |
+
list : list of parameters to optimize and their learning rates, in the format required by torch optimizers.
|
| 217 |
+
"""
|
| 218 |
+
param_conf = []
|
| 219 |
+
if self.train_midas:
|
| 220 |
+
if self.encoder_lr_factor > 0:
|
| 221 |
+
param_conf.append({'params': self.core.get_enc_params_except_rel_pos(
|
| 222 |
+
), 'lr': lr / self.encoder_lr_factor})
|
| 223 |
+
|
| 224 |
+
if self.pos_enc_lr_factor > 0:
|
| 225 |
+
param_conf.append(
|
| 226 |
+
{'params': self.core.get_rel_pos_params(), 'lr': lr / self.pos_enc_lr_factor})
|
| 227 |
+
|
| 228 |
+
midas_params = self.core.core.scratch.parameters()
|
| 229 |
+
midas_lr_factor = self.midas_lr_factor
|
| 230 |
+
param_conf.append(
|
| 231 |
+
{'params': midas_params, 'lr': lr / midas_lr_factor})
|
| 232 |
+
|
| 233 |
+
remaining_modules = []
|
| 234 |
+
for name, child in self.named_children():
|
| 235 |
+
if name != 'core':
|
| 236 |
+
remaining_modules.append(child)
|
| 237 |
+
remaining_params = itertools.chain(
|
| 238 |
+
*[child.parameters() for child in remaining_modules])
|
| 239 |
+
|
| 240 |
+
param_conf.append({'params': remaining_params, 'lr': lr})
|
| 241 |
+
|
| 242 |
+
return param_conf
|
| 243 |
+
|
| 244 |
+
@staticmethod
|
| 245 |
+
def build(midas_model_type="DPT_BEiT_L_384", pretrained_resource=None, use_pretrained_midas=False, train_midas=False, freeze_midas_bn=True, **kwargs):
|
| 246 |
+
core = MidasCore.build(midas_model_type=midas_model_type, use_pretrained_midas=use_pretrained_midas,
|
| 247 |
+
train_midas=train_midas, fetch_features=True, freeze_bn=freeze_midas_bn, **kwargs)
|
| 248 |
+
model = ZoeDepth(core, **kwargs)
|
| 249 |
+
if pretrained_resource:
|
| 250 |
+
assert isinstance(pretrained_resource, str), "pretrained_resource must be a string"
|
| 251 |
+
model = load_state_from_resource(model, pretrained_resource)
|
| 252 |
+
return model
|
| 253 |
+
|
| 254 |
+
@staticmethod
|
| 255 |
+
def build_from_config(config):
|
| 256 |
+
return ZoeDepth.build(**config)
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MIT License
|
| 2 |
+
|
| 3 |
+
# Copyright (c) 2022 Intelligent Systems Lab Org
|
| 4 |
+
|
| 5 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
# in the Software without restriction, including without limitation the rights
|
| 8 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
# furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
# The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
# copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
# SOFTWARE.
|
| 22 |
+
|
| 23 |
+
# File author: Shariq Farooq Bhat
|
| 24 |
+
|
| 25 |
+
from .zoedepth_nk_v1 import ZoeDepthNK
|
| 26 |
+
|
| 27 |
+
all_versions = {
|
| 28 |
+
"v1": ZoeDepthNK,
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
get_version = lambda v : all_versions[v]
|
OVOW/engine/oneposeviagen/SpaTrackerV2/models/monoD/zoeDepth/models/zoedepth_nk/config_zoedepth_nk.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model": {
|
| 3 |
+
"name": "ZoeDepthNK",
|
| 4 |
+
"version_name": "v1",
|
| 5 |
+
"bin_conf" : [
|
| 6 |
+
{
|
| 7 |
+
"name": "nyu",
|
| 8 |
+
"n_bins": 64,
|
| 9 |
+
"min_depth": 1e-3,
|
| 10 |
+
"max_depth": 10.0
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"name": "kitti",
|
| 14 |
+
"n_bins": 64,
|
| 15 |
+
"min_depth": 1e-3,
|
| 16 |
+
"max_depth": 80.0
|
| 17 |
+
}
|
| 18 |
+
],
|
| 19 |
+
"bin_embedding_dim": 128,
|
| 20 |
+
"bin_centers_type": "softplus",
|
| 21 |
+
"n_attractors":[16, 8, 4, 1],
|
| 22 |
+
"attractor_alpha": 1000,
|
| 23 |
+
"attractor_gamma": 2,
|
| 24 |
+
"attractor_kind" : "mean",
|
| 25 |
+
"attractor_type" : "inv",
|
| 26 |
+
"min_temp": 0.0212,
|
| 27 |
+
"max_temp": 50.0,
|
| 28 |
+
"memory_efficient": true,
|
| 29 |
+
"midas_model_type" : "DPT_BEiT_L_384",
|
| 30 |
+
"img_size": [384, 512]
|
| 31 |
+
},
|
| 32 |
+
|
| 33 |
+
"train": {
|
| 34 |
+
"train_midas": true,
|
| 35 |
+
"use_pretrained_midas": true,
|
| 36 |
+
"trainer": "zoedepth_nk",
|
| 37 |
+
"epochs": 5,
|
| 38 |
+
"bs": 16,
|
| 39 |
+
"optim_kwargs": {"lr": 0.0002512, "wd": 0.01},
|
| 40 |
+
"sched_kwargs": {"div_factor": 1, "final_div_factor": 10000, "pct_start": 0.7, "three_phase":false, "cycle_momentum": true},
|
| 41 |
+
"same_lr": false,
|
| 42 |
+
"w_si": 1,
|
| 43 |
+
"w_domain": 100,
|
| 44 |
+
"avoid_boundary": false,
|
| 45 |
+
"random_crop": false,
|
| 46 |
+
"input_width": 640,
|
| 47 |
+
"input_height": 480,
|
| 48 |
+
"w_grad": 0,
|
| 49 |
+
"w_reg": 0,
|
| 50 |
+
"midas_lr_factor": 10,
|
| 51 |
+
"encoder_lr_factor":10,
|
| 52 |
+
"pos_enc_lr_factor":10
|
| 53 |
+
},
|
| 54 |
+
|
| 55 |
+
"infer": {
|
| 56 |
+
"train_midas": false,
|
| 57 |
+
"pretrained_resource": "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_NK.pt",
|
| 58 |
+
"use_pretrained_midas": false,
|
| 59 |
+
"force_keep_ar": true
|
| 60 |
+
},
|
| 61 |
+
|
| 62 |
+
"eval": {
|
| 63 |
+
"train_midas": false,
|
| 64 |
+
"pretrained_resource": "url::https://github.com/isl-org/ZoeDepth/releases/download/v1.0/ZoeD_M12_NK.pt",
|
| 65 |
+
"use_pretrained_midas": false
|
| 66 |
+
}
|
| 67 |
+
}
|