diff --git a/.gitattributes b/.gitattributes index f389ee9137558df8b5ab72b00d9f646b2ed744b9..301d8b5258e06b9befe46be71be9929d24a051fd 100644 --- a/.gitattributes +++ b/.gitattributes @@ -62,3 +62,5 @@ checkpoints/hawor/hawor/checkpoints/hawor.ckpt.1 filter=lfs diff=lfs merge=lfs - checkpoints/hawor/hawor/checkpoints/infiller.pt.1 filter=lfs diff=lfs merge=lfs -text reconstruction/modules/HaWoR/thirdparty/Metric3D/media/screenshots/challenge.PNG filter=lfs diff=lfs merge=lfs -text reconstruction/modules/HaWoR/thirdparty/Metric3D/training/kitti_json_files/eigen_train.json filter=lfs diff=lfs merge=lfs -text +reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/human.ply filter=lfs diff=lfs merge=lfs -text +reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3Dfy_results/0.glb filter=lfs diff=lfs merge=lfs -text diff --git a/reconstruction/modules/InterFormer/mmseg.yaml b/reconstruction/modules/InterFormer/mmseg.yaml new file mode 100644 index 0000000000000000000000000000000000000000..233a5ccbdcad1009fc868c6688a901746fbe0fcb --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg.yaml @@ -0,0 +1,257 @@ +name: mmseg +channels: + - pytorch + - nvidia + - defaults +dependencies: + - _libgcc_mutex=0.1=main + - _openmp_mutex=5.1=1_gnu + - blas=1.0=mkl + - brotlipy=0.7.0=py310h7f8727e_1002 + - bzip2=1.0.8=h7b6447c_0 + - ca-certificates=2023.05.30=h06a4308_0 + - certifi=2023.5.7=py310h06a4308_0 + - cffi=1.15.1=py310h5eee18b_3 + - charset-normalizer=2.0.4=pyhd3eb1b0_0 + - cryptography=39.0.1=py310h9ce1e76_2 + - cuda=11.6.1=0 + - cuda-cccl=11.6.55=hf6102b2_0 + - cuda-command-line-tools=11.6.2=0 + - cuda-compiler=11.6.2=0 + - cuda-cudart=11.6.55=he381448_0 + - cuda-cudart-dev=11.6.55=h42ad0f4_0 + - cuda-cuobjdump=11.6.124=h2eeebcb_0 + - cuda-cupti=11.6.124=h86345e5_0 + - cuda-cuxxfilt=11.6.124=hecbf4f6_0 + - cuda-driver-dev=11.6.55=0 + - cuda-gdb=12.1.105=0 + - cuda-libraries=11.6.1=0 + - cuda-libraries-dev=11.6.1=0 + - cuda-memcheck=11.8.86=0 + - cuda-nsight=12.1.105=0 + - cuda-nsight-compute=12.1.1=0 + - cuda-nvcc=11.6.124=hbba6d2d_0 + - cuda-nvdisasm=12.1.105=0 + - cuda-nvml-dev=11.6.55=haa9ef22_0 + - cuda-nvprof=12.1.105=0 + - cuda-nvprune=11.6.124=he22ec0a_0 + - cuda-nvrtc=11.6.124=h020bade_0 + - cuda-nvrtc-dev=11.6.124=h249d397_0 + - cuda-nvtx=11.6.124=h0630a44_0 + - cuda-nvvp=12.1.105=0 + - cuda-runtime=11.6.1=0 + - cuda-samples=11.6.101=h8efea70_0 + - cuda-sanitizer-api=12.1.105=0 + - cuda-toolkit=11.6.1=0 + - cuda-tools=11.6.1=0 + - cuda-visual-tools=11.6.1=0 + - ffmpeg=4.2.2=h20bf706_0 + - freetype=2.12.1=h4a9f257_0 + - gds-tools=1.6.1.9=0 + - giflib=5.2.1=h5eee18b_3 + - gmp=6.2.1=h295c915_3 + - gnutls=3.6.15=he1e5248_0 + - idna=3.4=py310h06a4308_0 + - intel-openmp=2023.1.0=hdb19cb5_46305 + - jpeg=9e=h5eee18b_1 + - lame=3.100=h7b6447c_0 + - lcms2=2.12=h3be6417_0 + - ld_impl_linux-64=2.38=h1181459_1 + - lerc=3.0=h295c915_0 + - libcublas=11.9.2.110=h5e84587_0 + - libcublas-dev=11.9.2.110=h5c901ab_0 + - libcufft=10.7.1.112=hf425ae0_0 + - libcufft-dev=10.7.1.112=ha5ce4c0_0 + - libcufile=1.6.1.9=0 + - libcufile-dev=1.6.1.9=0 + - libcurand=10.3.2.106=0 + - libcurand-dev=10.3.2.106=0 + - libcusolver=11.3.4.124=h33c3c4e_0 + - libcusparse=11.7.2.124=h7538f96_0 + - libcusparse-dev=11.7.2.124=hbbe9722_0 + - libdeflate=1.17=h5eee18b_0 + - libffi=3.4.4=h6a678d5_0 + - libgcc-ng=11.2.0=h1234567_1 + - libgomp=11.2.0=h1234567_1 + - libidn2=2.3.4=h5eee18b_0 + - libnpp=11.6.3.124=hd2722f0_0 + - libnpp-dev=11.6.3.124=h3c42840_0 + - libnvjpeg=11.6.2.124=hd473ad6_0 + - libnvjpeg-dev=11.6.2.124=hb5906b9_0 + - libopus=1.3.1=h7b6447c_0 + - libpng=1.6.39=h5eee18b_0 + - libstdcxx-ng=11.2.0=h1234567_1 + - libtasn1=4.19.0=h5eee18b_0 + - libtiff=4.5.0=h6a678d5_2 + - libunistring=0.9.10=h27cfd23_0 + - libuuid=1.41.5=h5eee18b_0 + - libvpx=1.7.0=h439df22_0 + - libwebp=1.2.4=h11a3e52_1 + - libwebp-base=1.2.4=h5eee18b_1 + - lz4-c=1.9.4=h6a678d5_0 + - mkl=2023.1.0=h6d00ec8_46342 + - mkl-service=2.4.0=py310h5eee18b_1 + - mkl_fft=1.3.6=py310h1128e8f_1 + - mkl_random=1.2.2=py310h1128e8f_1 + - ncurses=6.4=h6a678d5_0 + - nettle=3.7.3=hbbd107a_1 + - nsight-compute=2023.1.1.4=0 + - numpy=1.25.0=py310h5f9d8c6_0 + - numpy-base=1.25.0=py310hb5e798b_0 + - openh264=2.1.1=h4ff587b_0 + - openssl=3.0.9=h7f8727e_0 + - pillow=9.4.0=py310h6a678d5_0 + - pip=23.1.2=py310h06a4308_0 + - pycparser=2.21=pyhd3eb1b0_0 + - pyopenssl=23.0.0=py310h06a4308_0 + - pysocks=1.7.1=py310h06a4308_0 + - python=3.10.11=h955ad1f_3 + - pytorch=1.13.1=py3.10_cuda11.6_cudnn8.3.2_0 + - pytorch-cuda=11.6=h867d48c_1 + - pytorch-mutex=1.0=cuda + - readline=8.2=h5eee18b_0 + - sqlite=3.41.2=h5eee18b_0 + - tbb=2021.8.0=hdb19cb5_0 + - tk=8.6.12=h1ccaba5_0 + - torchaudio=0.13.1=py310_cu116 + - torchvision=0.14.1=py310_cu116 + - typing_extensions=4.6.3=py310h06a4308_0 + - urllib3=1.26.16=py310h06a4308_0 + - x264=1!157.20191217=h7b6447c_0 + - xz=5.4.2=h5eee18b_0 + - zlib=1.2.13=h5eee18b_0 + - zstd=1.5.5=hc292b87_0 + - pip: + - absl-py==2.1.0 + - addict==2.4.0 + - aiohappyeyeballs==2.6.1 + - aiohttp==3.12.15 + - aiosignal==1.4.0 + - aliyun-python-sdk-core==2.15.1 + - aliyun-python-sdk-kms==2.16.3 + - asttokens==2.4.1 + - async-timeout==5.0.1 + - attrs==25.3.0 + - basicsr==0.0.0 + - beautifulsoup4==4.12.3 + - cachetools==5.3.3 + - click==8.1.7 + - colorama==0.4.6 + - contourpy==1.2.1 + - crcmod==1.7 + - cycler==0.12.1 + - datasets==4.0.0 + - decorator==5.1.1 + - dill==0.3.8 + - einops==0.8.0 + - exceptiongroup==1.2.2 + - executing==2.0.1 + - filelock==3.14.0 + - fonttools==4.51.0 + - frozenlist==1.7.0 + - fsspec==2024.5.0 + - ftfy==6.2.0 + - future==1.0.0 + - fvcore==0.1.5.post20221221 + - gdown==5.2.0 + - google-auth==2.29.0 + - google-auth-oauthlib==1.0.0 + - grpcio==1.63.0 + - h5py==3.11.0 + - hf-xet==1.1.7 + - huggingface-hub==0.34.4 + - imageio==2.34.1 + - importlib-metadata==7.1.0 + - iopath==0.1.10 + - ipdb==0.13.13 + - ipython==8.26.0 + - jedi==0.19.1 + - jmespath==0.10.0 + - kiwisolver==1.4.5 + - lazy-loader==0.4 + - lmdb==1.7.2 + - markdown==3.6 + - markdown-it-py==3.0.0 + - markupsafe==2.1.5 + - matplotlib==3.9.0 + - matplotlib-inline==0.1.7 + - mdurl==0.1.2 + - mmcv==2.0.0 + - mmdet==3.3.0 + - mmengine==0.10.4 + - mmsegmentation==1.2.2 + - model-index==0.1.11 + - modelscope==1.30.0 + - multidict==6.6.4 + - multiprocess==0.70.16 + - networkx==3.3 + - oauthlib==3.2.2 + - omegaconf==2.4.0.dev3 + - opencv-python==4.9.0.80 + - opendatalab==0.0.10 + - openmim==0.3.9 + - openxlab==0.0.38 + - ordered-set==4.1.0 + - oss2==2.17.0 + - packaging==24.0 + - pandas==2.2.2 + - parso==0.8.4 + - pexpect==4.9.0 + - platformdirs==4.2.2 + - portalocker==3.2.0 + - prettytable==3.10.0 + - prompt-toolkit==3.0.47 + - propcache==0.3.2 + - protobuf==3.20.3 + - psutil==6.0.0 + - ptyprocess==0.7.0 + - pure-eval==0.2.2 + - pyarrow==21.0.0 + - pyasn1==0.6.0 + - pyasn1-modules==0.4.0 + - pycocotools==2.0.7 + - pycryptodome==3.20.0 + - pygments==2.18.0 + - pyparsing==3.1.2 + - python-dateutil==2.9.0.post0 + - pytz==2023.4 + - pyyaml==6.0.1 + - regex==2024.5.15 + - requests==2.32.4 + - requests-oauthlib==2.0.0 + - rich==13.4.2 + - rsa==4.9 + - safetensors==0.4.3 + - scikit-image==0.23.2 + - scipy==1.13.0 + - seaborn==0.13.2 + - setuptools==60.2.0 + - shapely==2.0.4 + - six==1.16.0 + - smmap==5.0.1 + - soupsieve==2.6 + - stack-data==0.6.3 + - tabulate==0.9.0 + - tb-nightly==2.21.0a20250719 + - tensorboard==2.13.0 + - tensorboard-data-server==0.7.0 + - tensorboardx==2.6 + - termcolor==2.3.0 + - terminaltables==3.1.10 + - thop==0.1.1-2209072238 + - threadpoolctl==3.1.0 + - tifffile==2024.5.10 + - timm==1.0.3 + - tomli==2.0.1 + - tqdm==4.67.1 + - traitlets==5.14.3 + - tzdata==2024.1 + - wcwidth==0.2.13 + - werkzeug==3.0.3 + - wheel==0.26.0 + - xxhash==3.5.0 + - yacs==0.1.8 + - yapf==0.40.2 + - yarl==1.20.1 + - zipp==3.18.2 +prefix: /home/suyuejiao/anaconda3/envs/mmseg diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/uper_head.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/uper_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69e763fba490b4043353a91c5c2862b758971579 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/uper_head.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0125312ebd94350d39c1c27a7dce86f2c9ccab6 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db81d8a691f748bda36b511279eecf0ecb389b7a Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/__pycache__/vpd_depth_head.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ann_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ann_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2b40ef5aa1da0bc2473597fedca5b3f33973beb0 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ann_head.py @@ -0,0 +1,245 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import SelfAttentionBlock as _SelfAttentionBlock +from .decode_head import BaseDecodeHead + + +class PPMConcat(nn.ModuleList): + """Pyramid Pooling Module that only concat the features of each layer. + + Args: + pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module. + """ + + def __init__(self, pool_scales=(1, 3, 6, 8)): + super().__init__( + [nn.AdaptiveAvgPool2d(pool_scale) for pool_scale in pool_scales]) + + def forward(self, feats): + """Forward function.""" + ppm_outs = [] + for ppm in self: + ppm_out = ppm(feats) + ppm_outs.append(ppm_out.view(*feats.shape[:2], -1)) + concat_outs = torch.cat(ppm_outs, dim=2) + return concat_outs + + +class SelfAttentionBlock(_SelfAttentionBlock): + """Make a ANN used SelfAttentionBlock. + + Args: + low_in_channels (int): Input channels of lower level feature, + which is the key feature for self-attention. + high_in_channels (int): Input channels of higher level feature, + which is the query feature for self-attention. + channels (int): Output channels of key/query transform. + out_channels (int): Output channels. + share_key_query (bool): Whether share projection weight between key + and query projection. + query_scale (int): The scale of query feature map. + key_pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module of key feature. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict|None): Config of activation layers. + """ + + def __init__(self, low_in_channels, high_in_channels, channels, + out_channels, share_key_query, query_scale, key_pool_scales, + conv_cfg, norm_cfg, act_cfg): + key_psp = PPMConcat(key_pool_scales) + if query_scale > 1: + query_downsample = nn.MaxPool2d(kernel_size=query_scale) + else: + query_downsample = None + super().__init__( + key_in_channels=low_in_channels, + query_in_channels=high_in_channels, + channels=channels, + out_channels=out_channels, + share_key_query=share_key_query, + query_downsample=query_downsample, + key_downsample=key_psp, + key_query_num_convs=1, + key_query_norm=True, + value_out_num_convs=1, + value_out_norm=False, + matmul_norm=True, + with_out=True, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + +class AFNB(nn.Module): + """Asymmetric Fusion Non-local Block(AFNB) + + Args: + low_in_channels (int): Input channels of lower level feature, + which is the key feature for self-attention. + high_in_channels (int): Input channels of higher level feature, + which is the query feature for self-attention. + channels (int): Output channels of key/query transform. + out_channels (int): Output channels. + and query projection. + query_scales (tuple[int]): The scales of query feature map. + Default: (1,) + key_pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module of key feature. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict|None): Config of activation layers. + """ + + def __init__(self, low_in_channels, high_in_channels, channels, + out_channels, query_scales, key_pool_scales, conv_cfg, + norm_cfg, act_cfg): + super().__init__() + self.stages = nn.ModuleList() + for query_scale in query_scales: + self.stages.append( + SelfAttentionBlock( + low_in_channels=low_in_channels, + high_in_channels=high_in_channels, + channels=channels, + out_channels=out_channels, + share_key_query=False, + query_scale=query_scale, + key_pool_scales=key_pool_scales, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.bottleneck = ConvModule( + out_channels + high_in_channels, + out_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None) + + def forward(self, low_feats, high_feats): + """Forward function.""" + priors = [stage(high_feats, low_feats) for stage in self.stages] + context = torch.stack(priors, dim=0).sum(dim=0) + output = self.bottleneck(torch.cat([context, high_feats], 1)) + return output + + +class APNB(nn.Module): + """Asymmetric Pyramid Non-local Block (APNB) + + Args: + in_channels (int): Input channels of key/query feature, + which is the key feature for self-attention. + channels (int): Output channels of key/query transform. + out_channels (int): Output channels. + query_scales (tuple[int]): The scales of query feature map. + Default: (1,) + key_pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module of key feature. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict|None): Config of activation layers. + """ + + def __init__(self, in_channels, channels, out_channels, query_scales, + key_pool_scales, conv_cfg, norm_cfg, act_cfg): + super().__init__() + self.stages = nn.ModuleList() + for query_scale in query_scales: + self.stages.append( + SelfAttentionBlock( + low_in_channels=in_channels, + high_in_channels=in_channels, + channels=channels, + out_channels=out_channels, + share_key_query=True, + query_scale=query_scale, + key_pool_scales=key_pool_scales, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.bottleneck = ConvModule( + 2 * in_channels, + out_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, feats): + """Forward function.""" + priors = [stage(feats, feats) for stage in self.stages] + context = torch.stack(priors, dim=0).sum(dim=0) + output = self.bottleneck(torch.cat([context, feats], 1)) + return output + + +@MODELS.register_module() +class ANNHead(BaseDecodeHead): + """Asymmetric Non-local Neural Networks for Semantic Segmentation. + + This head is the implementation of `ANNNet + `_. + + Args: + project_channels (int): Projection channels for Nonlocal. + query_scales (tuple[int]): The scales of query feature map. + Default: (1,) + key_pool_scales (tuple[int]): The pooling scales of key feature map. + Default: (1, 3, 6, 8). + """ + + def __init__(self, + project_channels, + query_scales=(1, ), + key_pool_scales=(1, 3, 6, 8), + **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + assert len(self.in_channels) == 2 + low_in_channels, high_in_channels = self.in_channels + self.project_channels = project_channels + self.fusion = AFNB( + low_in_channels=low_in_channels, + high_in_channels=high_in_channels, + out_channels=high_in_channels, + channels=project_channels, + query_scales=query_scales, + key_pool_scales=key_pool_scales, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.bottleneck = ConvModule( + high_in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.context = APNB( + in_channels=self.channels, + out_channels=self.channels, + channels=project_channels, + query_scales=query_scales, + key_pool_scales=key_pool_scales, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + low_feats, high_feats = self._transform_inputs(inputs) + output = self.fusion(low_feats, high_feats) + output = self.dropout(output) + output = self.bottleneck(output) + output = self.context(output) + output = self.cls_seg(output) + + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/apc_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/apc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..728f39659c63680944306fddc9e33b7c9172c1ba --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/apc_head.py @@ -0,0 +1,159 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class ACM(nn.Module): + """Adaptive Context Module used in APCNet. + + Args: + pool_scale (int): Pooling scale used in Adaptive Context + Module to extract region features. + fusion (bool): Add one conv to fuse residual feature. + in_channels (int): Input channels. + channels (int): Channels after modules, before conv_seg. + conv_cfg (dict | None): Config of conv layers. + norm_cfg (dict | None): Config of norm layers. + act_cfg (dict): Config of activation layers. + """ + + def __init__(self, pool_scale, fusion, in_channels, channels, conv_cfg, + norm_cfg, act_cfg): + super().__init__() + self.pool_scale = pool_scale + self.fusion = fusion + self.in_channels = in_channels + self.channels = channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.pooled_redu_conv = ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.input_redu_conv = ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.global_info = ConvModule( + self.channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.gla = nn.Conv2d(self.channels, self.pool_scale**2, 1, 1, 0) + + self.residual_conv = ConvModule( + self.channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + if self.fusion: + self.fusion_conv = ConvModule( + self.channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, x): + """Forward function.""" + pooled_x = F.adaptive_avg_pool2d(x, self.pool_scale) + # [batch_size, channels, h, w] + x = self.input_redu_conv(x) + # [batch_size, channels, pool_scale, pool_scale] + pooled_x = self.pooled_redu_conv(pooled_x) + batch_size = x.size(0) + # [batch_size, pool_scale * pool_scale, channels] + pooled_x = pooled_x.view(batch_size, self.channels, + -1).permute(0, 2, 1).contiguous() + # [batch_size, h * w, pool_scale * pool_scale] + affinity_matrix = self.gla(x + resize( + self.global_info(F.adaptive_avg_pool2d(x, 1)), size=x.shape[2:]) + ).permute(0, 2, 3, 1).reshape( + batch_size, -1, self.pool_scale**2) + affinity_matrix = F.sigmoid(affinity_matrix) + # [batch_size, h * w, channels] + z_out = torch.matmul(affinity_matrix, pooled_x) + # [batch_size, channels, h * w] + z_out = z_out.permute(0, 2, 1).contiguous() + # [batch_size, channels, h, w] + z_out = z_out.view(batch_size, self.channels, x.size(2), x.size(3)) + z_out = self.residual_conv(z_out) + z_out = F.relu(z_out + x) + if self.fusion: + z_out = self.fusion_conv(z_out) + + return z_out + + +@MODELS.register_module() +class APCHead(BaseDecodeHead): + """Adaptive Pyramid Context Network for Semantic Segmentation. + + This head is the implementation of + `APCNet `_. + + Args: + pool_scales (tuple[int]): Pooling scales used in Adaptive Context + Module. Default: (1, 2, 3, 6). + fusion (bool): Add one conv to fuse residual feature. + """ + + def __init__(self, pool_scales=(1, 2, 3, 6), fusion=True, **kwargs): + super().__init__(**kwargs) + assert isinstance(pool_scales, (list, tuple)) + self.pool_scales = pool_scales + self.fusion = fusion + acm_modules = [] + for pool_scale in self.pool_scales: + acm_modules.append( + ACM(pool_scale, + self.fusion, + self.in_channels, + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + self.acm_modules = nn.ModuleList(acm_modules) + self.bottleneck = ConvModule( + self.in_channels + len(pool_scales) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + acm_outs = [x] + for acm_module in self.acm_modules: + acm_outs.append(acm_module(x)) + acm_outs = torch.cat(acm_outs, dim=1) + output = self.bottleneck(acm_outs) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/aspp_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/aspp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7185d7de58d35ef17e5d54e0e75b045e8724c4 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/aspp_head.py @@ -0,0 +1,122 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class ASPPModule(nn.ModuleList): + """Atrous Spatial Pyramid Pooling (ASPP) Module. + + Args: + dilations (tuple[int]): Dilation rate of each layer. + in_channels (int): Input channels. + channels (int): Channels after modules, before conv_seg. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict): Config of activation layers. + """ + + def __init__(self, dilations, in_channels, channels, conv_cfg, norm_cfg, + act_cfg): + super().__init__() + self.dilations = dilations + self.in_channels = in_channels + self.channels = channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + for dilation in dilations: + self.append( + ConvModule( + self.in_channels, + self.channels, + 1 if dilation == 1 else 3, + dilation=dilation, + padding=0 if dilation == 1 else dilation, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + + def forward(self, x): + """Forward function.""" + aspp_outs = [] + for aspp_module in self: + aspp_outs.append(aspp_module(x)) + + return aspp_outs + + +@MODELS.register_module() +class ASPPHead(BaseDecodeHead): + """Rethinking Atrous Convolution for Semantic Image Segmentation. + + This head is the implementation of `DeepLabV3 + `_. + + Args: + dilations (tuple[int]): Dilation rates for ASPP module. + Default: (1, 6, 12, 18). + """ + + def __init__(self, dilations=(1, 6, 12, 18), **kwargs): + super().__init__(**kwargs) + assert isinstance(dilations, (list, tuple)) + self.dilations = dilations + self.image_pool = nn.Sequential( + nn.AdaptiveAvgPool2d(1), + ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + self.aspp_modules = ASPPModule( + dilations, + self.in_channels, + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.bottleneck = ConvModule( + (len(dilations) + 1) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def _forward_feature(self, inputs): + """Forward function for feature maps before classifying each pixel with + ``self.cls_seg`` fc. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + feats (Tensor): A tensor of shape (batch_size, self.channels, + H, W) which is feature map for last layer of decoder head. + """ + x = self._transform_inputs(inputs) + aspp_outs = [ + resize( + self.image_pool(x), + size=x.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + ] + aspp_outs.extend(self.aspp_modules(x)) + aspp_outs = torch.cat(aspp_outs, dim=1) + feats = self.bottleneck(aspp_outs) + return feats + + def forward(self, inputs): + """Forward function.""" + output = self._forward_feature(inputs) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/cascade_decode_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/cascade_decode_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2bcb9302235e3881696dff6657e3e7fb12609b --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/cascade_decode_head.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from abc import ABCMeta, abstractmethod +from typing import List + +from torch import Tensor + +from mmseg.utils import ConfigType +from .decode_head import BaseDecodeHead + + +class BaseCascadeDecodeHead(BaseDecodeHead, metaclass=ABCMeta): + """Base class for cascade decode head used in + :class:`CascadeEncoderDecoder.""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + @abstractmethod + def forward(self, inputs, prev_output): + """Placeholder of forward function.""" + pass + + def loss(self, inputs: List[Tensor], prev_output: Tensor, + batch_data_samples: List[dict], train_cfg: ConfigType) -> Tensor: + """Forward function for training. + + Args: + inputs (List[Tensor]): List of multi-level img features. + prev_output (Tensor): The output of previous decode head. + batch_data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_sem_seg`. + train_cfg (dict): The training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + seg_logits = self.forward(inputs, prev_output) + losses = self.loss_by_feat(seg_logits, batch_data_samples) + + return losses + + def predict(self, inputs: List[Tensor], prev_output: Tensor, + batch_img_metas: List[dict], tese_cfg: ConfigType): + """Forward function for testing. + + Args: + inputs (List[Tensor]): List of multi-level img features. + prev_output (Tensor): The output of previous decode head. + batch_img_metas (dict): List Image info where each dict may also + contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + test_cfg (dict): The testing config. + + Returns: + Tensor: Output segmentation map. + """ + seg_logits = self.forward(inputs, prev_output) + + return self.predict_by_feat(seg_logits, batch_img_metas) diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/cc_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/cc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e9075a2648d77f6bca6bb29f3e7db52a329f7afb --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/cc_head.py @@ -0,0 +1,43 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + +try: + from mmcv.ops import CrissCrossAttention +except ModuleNotFoundError: + CrissCrossAttention = None + + +@MODELS.register_module() +class CCHead(FCNHead): + """CCNet: Criss-Cross Attention for Semantic Segmentation. + + This head is the implementation of `CCNet + `_. + + Args: + recurrence (int): Number of recurrence of Criss Cross Attention + module. Default: 2. + """ + + def __init__(self, recurrence=2, **kwargs): + if CrissCrossAttention is None: + raise RuntimeError('Please install mmcv-full for ' + 'CrissCrossAttention ops') + super().__init__(num_convs=2, **kwargs) + self.recurrence = recurrence + self.cca = CrissCrossAttention(self.channels) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + output = self.convs[0](x) + for _ in range(self.recurrence): + output = self.cca(output) + output = self.convs[1](output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/da_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/da_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d87214365d2f8695b60ccab0c1850669ff8dd295 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/da_head.py @@ -0,0 +1,184 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +import torch.nn.functional as F +from mmcv.cnn import ConvModule, Scale +from torch import Tensor, nn + +from mmseg.registry import MODELS +from mmseg.utils import SampleList, add_prefix +from ..utils import SelfAttentionBlock as _SelfAttentionBlock +from .decode_head import BaseDecodeHead + + +class PAM(_SelfAttentionBlock): + """Position Attention Module (PAM) + + Args: + in_channels (int): Input channels of key/query feature. + channels (int): Output channels of key/query transform. + """ + + def __init__(self, in_channels, channels): + super().__init__( + key_in_channels=in_channels, + query_in_channels=in_channels, + channels=channels, + out_channels=in_channels, + share_key_query=False, + query_downsample=None, + key_downsample=None, + key_query_num_convs=1, + key_query_norm=False, + value_out_num_convs=1, + value_out_norm=False, + matmul_norm=False, + with_out=False, + conv_cfg=None, + norm_cfg=None, + act_cfg=None) + + self.gamma = Scale(0) + + def forward(self, x): + """Forward function.""" + out = super().forward(x, x) + + out = self.gamma(out) + x + return out + + +class CAM(nn.Module): + """Channel Attention Module (CAM)""" + + def __init__(self): + super().__init__() + self.gamma = Scale(0) + + def forward(self, x): + """Forward function.""" + batch_size, channels, height, width = x.size() + proj_query = x.view(batch_size, channels, -1) + proj_key = x.view(batch_size, channels, -1).permute(0, 2, 1) + energy = torch.bmm(proj_query, proj_key) + energy_new = torch.max( + energy, -1, keepdim=True)[0].expand_as(energy) - energy + attention = F.softmax(energy_new, dim=-1) + proj_value = x.view(batch_size, channels, -1) + + out = torch.bmm(attention, proj_value) + out = out.view(batch_size, channels, height, width) + + out = self.gamma(out) + x + return out + + +@MODELS.register_module() +class DAHead(BaseDecodeHead): + """Dual Attention Network for Scene Segmentation. + + This head is the implementation of `DANet + `_. + + Args: + pam_channels (int): The channels of Position Attention Module(PAM). + """ + + def __init__(self, pam_channels, **kwargs): + super().__init__(**kwargs) + self.pam_channels = pam_channels + self.pam_in_conv = ConvModule( + self.in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.pam = PAM(self.channels, pam_channels) + self.pam_out_conv = ConvModule( + self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.pam_conv_seg = nn.Conv2d( + self.channels, self.num_classes, kernel_size=1) + + self.cam_in_conv = ConvModule( + self.in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.cam = CAM() + self.cam_out_conv = ConvModule( + self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.cam_conv_seg = nn.Conv2d( + self.channels, self.num_classes, kernel_size=1) + + def pam_cls_seg(self, feat): + """PAM feature classification.""" + if self.dropout is not None: + feat = self.dropout(feat) + output = self.pam_conv_seg(feat) + return output + + def cam_cls_seg(self, feat): + """CAM feature classification.""" + if self.dropout is not None: + feat = self.dropout(feat) + output = self.cam_conv_seg(feat) + return output + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + pam_feat = self.pam_in_conv(x) + pam_feat = self.pam(pam_feat) + pam_feat = self.pam_out_conv(pam_feat) + pam_out = self.pam_cls_seg(pam_feat) + + cam_feat = self.cam_in_conv(x) + cam_feat = self.cam(cam_feat) + cam_feat = self.cam_out_conv(cam_feat) + cam_out = self.cam_cls_seg(cam_feat) + + feat_sum = pam_feat + cam_feat + pam_cam_out = self.cls_seg(feat_sum) + + return pam_cam_out, pam_out, cam_out + + def predict(self, inputs, batch_img_metas: List[dict], test_cfg, + **kwargs) -> List[Tensor]: + """Forward function for testing, only ``pam_cam`` is used.""" + seg_logits = self.forward(inputs)[0] + return self.predict_by_feat(seg_logits, batch_img_metas, **kwargs) + + def loss_by_feat(self, seg_logit: Tuple[Tensor], + batch_data_samples: SampleList, **kwargs) -> dict: + """Compute ``pam_cam``, ``pam``, ``cam`` loss.""" + pam_cam_seg_logit, pam_seg_logit, cam_seg_logit = seg_logit + loss = dict() + loss.update( + add_prefix( + super().loss_by_feat(pam_cam_seg_logit, batch_data_samples), + 'pam_cam')) + loss.update( + add_prefix(super().loss_by_feat(pam_seg_logit, batch_data_samples), + 'pam')) + loss.update( + add_prefix(super().loss_by_feat(cam_seg_logit, batch_data_samples), + 'cam')) + return loss diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ddr_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ddr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ba26d6503c09d7efb3ca6664c7baf59c9e6e3ce9 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ddr_head.py @@ -0,0 +1,116 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Tuple, Union + +import torch.nn as nn +from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer +from torch import Tensor + +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.models.losses import accuracy +from mmseg.models.utils import resize +from mmseg.registry import MODELS +from mmseg.utils import OptConfigType, SampleList + + +@MODELS.register_module() +class DDRHead(BaseDecodeHead): + """Decode head for DDRNet. + + Args: + in_channels (int): Number of input channels. + channels (int): Number of output channels. + num_classes (int): Number of classes. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict, optional): Config dict for activation layer. + Default: dict(type='ReLU', inplace=True). + """ + + def __init__(self, + in_channels: int, + channels: int, + num_classes: int, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + **kwargs): + super().__init__( + in_channels, + channels, + num_classes=num_classes, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **kwargs) + + self.head = self._make_base_head(self.in_channels, self.channels) + self.aux_head = self._make_base_head(self.in_channels // 2, + self.channels) + self.aux_cls_seg = nn.Conv2d( + self.channels, self.out_channels, kernel_size=1) + + def init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu') + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def forward( + self, + inputs: Union[Tensor, + Tuple[Tensor]]) -> Union[Tensor, Tuple[Tensor]]: + if self.training: + c3_feat, c5_feat = inputs + x_c = self.head(c5_feat) + x_c = self.cls_seg(x_c) + x_s = self.aux_head(c3_feat) + x_s = self.aux_cls_seg(x_s) + + return x_c, x_s + else: + x_c = self.head(inputs) + x_c = self.cls_seg(x_c) + return x_c + + def _make_base_head(self, in_channels: int, + channels: int) -> nn.Sequential: + layers = [ + ConvModule( + in_channels, + channels, + kernel_size=3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + order=('norm', 'act', 'conv')), + build_norm_layer(self.norm_cfg, channels)[1], + build_activation_layer(self.act_cfg), + ] + + return nn.Sequential(*layers) + + def loss_by_feat(self, seg_logits: Tuple[Tensor], + batch_data_samples: SampleList) -> dict: + loss = dict() + context_logit, spatial_logit = seg_logits + seg_label = self._stack_batch_gt(batch_data_samples) + + context_logit = resize( + context_logit, + size=seg_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + spatial_logit = resize( + spatial_logit, + size=seg_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + seg_label = seg_label.squeeze(1) + + loss['loss_context'] = self.loss_decode[0](context_logit, seg_label) + loss['loss_spatial'] = self.loss_decode[1](spatial_logit, seg_label) + loss['acc_seg'] = accuracy( + context_logit, seg_label, ignore_index=self.ignore_index) + + return loss diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/decode_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/decode_head.py new file mode 100644 index 0000000000000000000000000000000000000000..fd53afe22d9350482e84c989d3d87e4e07d1ee6b --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/decode_head.py @@ -0,0 +1,366 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings +from abc import ABCMeta, abstractmethod +from typing import List, Tuple + +import torch +import torch.nn as nn +from mmengine.model import BaseModule +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures import build_pixel_sampler +from mmseg.utils import ConfigType, SampleList +from ..losses import accuracy +from ..utils import resize + + +class BaseDecodeHead(BaseModule, metaclass=ABCMeta): + """Base class for BaseDecodeHead. + + 1. The ``init_weights`` method is used to initialize decode_head's + model parameters. After segmentor initialization, ``init_weights`` + is triggered when ``segmentor.init_weights()`` is called externally. + + 2. The ``loss`` method is used to calculate the loss of decode_head, + which includes two steps: (1) the decode_head model performs forward + propagation to obtain the feature maps (2) The ``loss_by_feat`` method + is called based on the feature maps to calculate the loss. + + .. code:: text + + loss(): forward() -> loss_by_feat() + + 3. The ``predict`` method is used to predict segmentation results, + which includes two steps: (1) the decode_head model performs forward + propagation to obtain the feature maps (2) The ``predict_by_feat`` method + is called based on the feature maps to predict segmentation results + including post-processing. + + .. code:: text + + predict(): forward() -> predict_by_feat() + + Args: + in_channels (int|Sequence[int]): Input channels. + channels (int): Channels after modules, before conv_seg. + num_classes (int): Number of classes. + out_channels (int): Output channels of conv_seg. Default: None. + threshold (float): Threshold for binary segmentation in the case of + `num_classes==1`. Default: None. + dropout_ratio (float): Ratio of dropout layer. Default: 0.1. + conv_cfg (dict|None): Config of conv layers. Default: None. + norm_cfg (dict|None): Config of norm layers. Default: None. + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU') + in_index (int|Sequence[int]): Input feature index. Default: -1 + input_transform (str|None): Transformation type of input features. + Options: 'resize_concat', 'multiple_select', None. + 'resize_concat': Multiple feature maps will be resize to the + same size as first one and than concat together. + Usually used in FCN head of HRNet. + 'multiple_select': Multiple feature maps will be bundle into + a list and passed into decode head. + None: Only one select feature map is allowed. + Default: None. + loss_decode (dict | Sequence[dict]): Config of decode loss. + The `loss_name` is property of corresponding loss function which + could be shown in training log. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_ce'. + e.g. dict(type='CrossEntropyLoss'), + [dict(type='CrossEntropyLoss', loss_name='loss_ce'), + dict(type='DiceLoss', loss_name='loss_dice')] + Default: dict(type='CrossEntropyLoss'). + ignore_index (int | None): The label index to be ignored. When using + masked BCE loss, ignore_index should be set to None. Default: 255. + sampler (dict|None): The config of segmentation map sampler. + Default: None. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + init_cfg (dict or list[dict], optional): Initialization config dict. + """ + + def __init__(self, + in_channels, + channels, + *, + num_classes, + out_channels=None, + threshold=None, + dropout_ratio=0.1, + conv_cfg=None, + norm_cfg=None, + act_cfg=dict(type='ReLU'), + in_index=-1, + input_transform=None, + loss_decode=dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=1.0), + ignore_index=255, + sampler=None, + align_corners=False, + init_cfg=dict( + type='Normal', std=0.01, override=dict(name='conv_seg'))): + super().__init__(init_cfg) + self._init_inputs(in_channels, in_index, input_transform) + self.channels = channels + self.dropout_ratio = dropout_ratio + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.in_index = in_index + + self.ignore_index = ignore_index + self.align_corners = align_corners + + if out_channels is None: + if num_classes == 2: + warnings.warn('For binary segmentation, we suggest using' + '`out_channels = 1` to define the output' + 'channels of segmentor, and use `threshold`' + 'to convert `seg_logits` into a prediction' + 'applying a threshold') + out_channels = num_classes + + if out_channels != num_classes and out_channels != 1: + raise ValueError( + 'out_channels should be equal to num_classes,' + 'except binary segmentation set out_channels == 1 and' + f'num_classes == 2, but got out_channels={out_channels}' + f'and num_classes={num_classes}') + + if out_channels == 1 and threshold is None: + threshold = 0.3 + warnings.warn('threshold is not defined for binary, and defaults' + 'to 0.3') + self.num_classes = num_classes + self.out_channels = out_channels + self.threshold = threshold + + if isinstance(loss_decode, dict): + self.loss_decode = MODELS.build(loss_decode) + elif isinstance(loss_decode, (list, tuple)): + self.loss_decode = nn.ModuleList() + for loss in loss_decode: + self.loss_decode.append(MODELS.build(loss)) + else: + raise TypeError(f'loss_decode must be a dict or sequence of dict,\ + but got {type(loss_decode)}') + + if sampler is not None: + self.sampler = build_pixel_sampler(sampler, context=self) + else: + self.sampler = None + + self.conv_seg = nn.Conv2d(channels, self.out_channels, kernel_size=1) + if dropout_ratio > 0: + self.dropout = nn.Dropout2d(dropout_ratio) + else: + self.dropout = None + + def extra_repr(self): + """Extra repr.""" + s = f'input_transform={self.input_transform}, ' \ + f'ignore_index={self.ignore_index}, ' \ + f'align_corners={self.align_corners}' + return s + + def _init_inputs(self, in_channels, in_index, input_transform): + """Check and initialize input transforms. + + The in_channels, in_index and input_transform must match. + Specifically, when input_transform is None, only single feature map + will be selected. So in_channels and in_index must be of type int. + When input_transform + + Args: + in_channels (int|Sequence[int]): Input channels. + in_index (int|Sequence[int]): Input feature index. + input_transform (str|None): Transformation type of input features. + Options: 'resize_concat', 'multiple_select', None. + 'resize_concat': Multiple feature maps will be resize to the + same size as first one and than concat together. + Usually used in FCN head of HRNet. + 'multiple_select': Multiple feature maps will be bundle into + a list and passed into decode head. + None: Only one select feature map is allowed. + """ + + if input_transform is not None: + assert input_transform in ['resize_concat', 'multiple_select'] + self.input_transform = input_transform + self.in_index = in_index + if input_transform is not None: + assert isinstance(in_channels, (list, tuple)) + assert isinstance(in_index, (list, tuple)) + assert len(in_channels) == len(in_index) + if input_transform == 'resize_concat': + self.in_channels = sum(in_channels) + else: + self.in_channels = in_channels + else: + assert isinstance(in_channels, int) + assert isinstance(in_index, int) + self.in_channels = in_channels + + def _transform_inputs(self, inputs): + """Transform inputs for decoder. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + Tensor: The transformed inputs + """ + + if self.input_transform == 'resize_concat': + inputs = [inputs[i] for i in self.in_index] + upsampled_inputs = [ + resize( + input=x, + size=inputs[0].shape[2:], + mode='bilinear', + align_corners=self.align_corners) for x in inputs + ] + inputs = torch.cat(upsampled_inputs, dim=1) + elif self.input_transform == 'multiple_select': + inputs = [inputs[i] for i in self.in_index] + else: + inputs = inputs[self.in_index] + + return inputs + + @abstractmethod + def forward(self, inputs): + """Placeholder of forward function.""" + pass + + def cls_seg(self, feat): + """Classify each pixel.""" + if self.dropout is not None: + feat = self.dropout(feat) + output = self.conv_seg(feat) + return output + + def loss(self, inputs: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + """Forward function for training. + + Args: + inputs (Tuple[Tensor]): List of multi-level img features. + batch_data_samples (list[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `img_metas` or `gt_semantic_seg`. + train_cfg (dict): The training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + seg_logits = self.forward(inputs) + losses = self.loss_by_feat(seg_logits, batch_data_samples) + return losses + + def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tensor: + """Forward function for prediction. + + Args: + inputs (Tuple[Tensor]): List of multi-level img features. + batch_img_metas (dict): List Image info where each dict may also + contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + test_cfg (dict): The testing config. + + Returns: + Tensor: Outputs segmentation logits map. + """ + seg_logits = self.forward(inputs) + + return self.predict_by_feat(seg_logits, batch_img_metas) + + def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tensor: + gt_semantic_segs = [ + data_sample.gt_sem_seg.data for data_sample in batch_data_samples + ] + return torch.stack(gt_semantic_segs, dim=0) + + def loss_by_feat(self, seg_logits: Tensor, + batch_data_samples: SampleList) -> dict: + """Compute segmentation loss. + + Args: + seg_logits (Tensor): The output from decode head forward function. + batch_data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_sem_seg`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + + seg_label = self._stack_batch_gt(batch_data_samples) + loss = dict() + seg_logits = resize( + input=seg_logits, + size=seg_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + if self.sampler is not None: + seg_weight = self.sampler.sample(seg_logits, seg_label) + else: + seg_weight = None + seg_label = seg_label.squeeze(1) + + if not isinstance(self.loss_decode, nn.ModuleList): + losses_decode = [self.loss_decode] + else: + losses_decode = self.loss_decode + for loss_decode in losses_decode: + if loss_decode.loss_name not in loss: + loss[loss_decode.loss_name] = loss_decode( + seg_logits, + seg_label, + weight=seg_weight, + ignore_index=self.ignore_index) + else: + loss[loss_decode.loss_name] += loss_decode( + seg_logits, + seg_label, + weight=seg_weight, + ignore_index=self.ignore_index) + + loss['acc_seg'] = accuracy( + seg_logits, seg_label, ignore_index=self.ignore_index) + return loss + + def predict_by_feat(self, seg_logits: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Transform a batch of output seg_logits to the input shape. + + Args: + seg_logits (Tensor): The output from decode head forward function. + batch_img_metas (list[dict]): Meta information of each image, e.g., + image size, scaling factor, etc. + + Returns: + Tensor: Outputs segmentation logits map. + """ + + if isinstance(batch_img_metas[0]['img_shape'], torch.Size): + # slide inference + size = batch_img_metas[0]['img_shape'] + elif 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'][:2] + else: + size = batch_img_metas[0]['img_shape'] + + seg_logits = resize( + input=seg_logits, + size=size, + mode='bilinear', + align_corners=self.align_corners) + return seg_logits diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/dm_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/dm_head.py new file mode 100644 index 0000000000000000000000000000000000000000..7694abd8ac3a470d543c580bd97adceb5b647f7c --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/dm_head.py @@ -0,0 +1,141 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer + +from mmseg.registry import MODELS +from .decode_head import BaseDecodeHead + + +class DCM(nn.Module): + """Dynamic Convolutional Module used in DMNet. + + Args: + filter_size (int): The filter size of generated convolution kernel + used in Dynamic Convolutional Module. + fusion (bool): Add one conv to fuse DCM output feature. + in_channels (int): Input channels. + channels (int): Channels after modules, before conv_seg. + conv_cfg (dict | None): Config of conv layers. + norm_cfg (dict | None): Config of norm layers. + act_cfg (dict): Config of activation layers. + """ + + def __init__(self, filter_size, fusion, in_channels, channels, conv_cfg, + norm_cfg, act_cfg): + super().__init__() + self.filter_size = filter_size + self.fusion = fusion + self.in_channels = in_channels + self.channels = channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.filter_gen_conv = nn.Conv2d(self.in_channels, self.channels, 1, 1, + 0) + + self.input_redu_conv = ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + if self.norm_cfg is not None: + self.norm = build_norm_layer(self.norm_cfg, self.channels)[1] + else: + self.norm = None + self.activate = build_activation_layer(self.act_cfg) + + if self.fusion: + self.fusion_conv = ConvModule( + self.channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, x): + """Forward function.""" + generated_filter = self.filter_gen_conv( + F.adaptive_avg_pool2d(x, self.filter_size)) + x = self.input_redu_conv(x) + b, c, h, w = x.shape + # [1, b * c, h, w], c = self.channels + x = x.view(1, b * c, h, w) + # [b * c, 1, filter_size, filter_size] + generated_filter = generated_filter.view(b * c, 1, self.filter_size, + self.filter_size) + pad = (self.filter_size - 1) // 2 + if (self.filter_size - 1) % 2 == 0: + p2d = (pad, pad, pad, pad) + else: + p2d = (pad + 1, pad, pad + 1, pad) + x = F.pad(input=x, pad=p2d, mode='constant', value=0) + # [1, b * c, h, w] + output = F.conv2d(input=x, weight=generated_filter, groups=b * c) + # [b, c, h, w] + output = output.view(b, c, h, w) + if self.norm is not None: + output = self.norm(output) + output = self.activate(output) + + if self.fusion: + output = self.fusion_conv(output) + + return output + + +@MODELS.register_module() +class DMHead(BaseDecodeHead): + """Dynamic Multi-scale Filters for Semantic Segmentation. + + This head is the implementation of + `DMNet `_. + + Args: + filter_sizes (tuple[int]): The size of generated convolutional filters + used in Dynamic Convolutional Module. Default: (1, 3, 5, 7). + fusion (bool): Add one conv to fuse DCM output feature. + """ + + def __init__(self, filter_sizes=(1, 3, 5, 7), fusion=False, **kwargs): + super().__init__(**kwargs) + assert isinstance(filter_sizes, (list, tuple)) + self.filter_sizes = filter_sizes + self.fusion = fusion + dcm_modules = [] + for filter_size in self.filter_sizes: + dcm_modules.append( + DCM(filter_size, + self.fusion, + self.in_channels, + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + self.dcm_modules = nn.ModuleList(dcm_modules) + self.bottleneck = ConvModule( + self.in_channels + len(filter_sizes) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + dcm_outs = [x] + for dcm_module in self.dcm_modules: + dcm_outs.append(dcm_module(x)) + dcm_outs = torch.cat(dcm_outs, dim=1) + output = self.bottleneck(dcm_outs) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/dnl_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/dnl_head.py new file mode 100644 index 0000000000000000000000000000000000000000..248c11814108d02e88fa7e0cada061b3366e33ff --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/dnl_head.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.cnn import NonLocal2d +from torch import nn + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + + +class DisentangledNonLocal2d(NonLocal2d): + """Disentangled Non-Local Blocks. + + Args: + temperature (float): Temperature to adjust attention. Default: 0.05 + """ + + def __init__(self, *arg, temperature, **kwargs): + super().__init__(*arg, **kwargs) + self.temperature = temperature + self.conv_mask = nn.Conv2d(self.in_channels, 1, kernel_size=1) + + def embedded_gaussian(self, theta_x, phi_x): + """Embedded gaussian with temperature.""" + + # NonLocal2d pairwise_weight: [N, HxW, HxW] + pairwise_weight = torch.matmul(theta_x, phi_x) + if self.use_scale: + # theta_x.shape[-1] is `self.inter_channels` + pairwise_weight /= torch.tensor( + theta_x.shape[-1], + dtype=torch.float, + device=pairwise_weight.device)**torch.tensor( + 0.5, device=pairwise_weight.device) + pairwise_weight /= torch.tensor( + self.temperature, device=pairwise_weight.device) + pairwise_weight = pairwise_weight.softmax(dim=-1) + return pairwise_weight + + def forward(self, x): + # x: [N, C, H, W] + n = x.size(0) + + # g_x: [N, HxW, C] + g_x = self.g(x).view(n, self.inter_channels, -1) + g_x = g_x.permute(0, 2, 1) + + # theta_x: [N, HxW, C], phi_x: [N, C, HxW] + if self.mode == 'gaussian': + theta_x = x.view(n, self.in_channels, -1) + theta_x = theta_x.permute(0, 2, 1) + if self.sub_sample: + phi_x = self.phi(x).view(n, self.in_channels, -1) + else: + phi_x = x.view(n, self.in_channels, -1) + elif self.mode == 'concatenation': + theta_x = self.theta(x).view(n, self.inter_channels, -1, 1) + phi_x = self.phi(x).view(n, self.inter_channels, 1, -1) + else: + theta_x = self.theta(x).view(n, self.inter_channels, -1) + theta_x = theta_x.permute(0, 2, 1) + phi_x = self.phi(x).view(n, self.inter_channels, -1) + + # subtract mean + theta_x -= theta_x.mean(dim=-2, keepdim=True) + phi_x -= phi_x.mean(dim=-1, keepdim=True) + + pairwise_func = getattr(self, self.mode) + # pairwise_weight: [N, HxW, HxW] + pairwise_weight = pairwise_func(theta_x, phi_x) + + # y: [N, HxW, C] + y = torch.matmul(pairwise_weight, g_x) + # y: [N, C, H, W] + y = y.permute(0, 2, 1).contiguous().reshape(n, self.inter_channels, + *x.size()[2:]) + + # unary_mask: [N, 1, HxW] + unary_mask = self.conv_mask(x) + unary_mask = unary_mask.view(n, 1, -1) + unary_mask = unary_mask.softmax(dim=-1) + # unary_x: [N, 1, C] + unary_x = torch.matmul(unary_mask, g_x) + # unary_x: [N, C, 1, 1] + unary_x = unary_x.permute(0, 2, 1).contiguous().reshape( + n, self.inter_channels, 1, 1) + + output = x + self.conv_out(y + unary_x) + + return output + + +@MODELS.register_module() +class DNLHead(FCNHead): + """Disentangled Non-Local Neural Networks. + + This head is the implementation of `DNLNet + `_. + + Args: + reduction (int): Reduction factor of projection transform. Default: 2. + use_scale (bool): Whether to scale pairwise_weight by + sqrt(1/inter_channels). Default: False. + mode (str): The nonlocal mode. Options are 'embedded_gaussian', + 'dot_product'. Default: 'embedded_gaussian.'. + temperature (float): Temperature to adjust attention. Default: 0.05 + """ + + def __init__(self, + reduction=2, + use_scale=True, + mode='embedded_gaussian', + temperature=0.05, + **kwargs): + super().__init__(num_convs=2, **kwargs) + self.reduction = reduction + self.use_scale = use_scale + self.mode = mode + self.temperature = temperature + self.dnl_block = DisentangledNonLocal2d( + in_channels=self.channels, + reduction=self.reduction, + use_scale=self.use_scale, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + mode=self.mode, + temperature=self.temperature) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + output = self.convs[0](x) + output = self.dnl_block(output) + output = self.convs[1](output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/dpt_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/dpt_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d2cfd89daa4df48601e930cfd158dcf3c9a6a837 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/dpt_head.py @@ -0,0 +1,294 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, Linear, build_activation_layer +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class ReassembleBlocks(BaseModule): + """ViTPostProcessBlock, process cls_token in ViT backbone output and + rearrange the feature vector to feature map. + + Args: + in_channels (int): ViT feature channels. Default: 768. + out_channels (List): output channels of each stage. + Default: [96, 192, 384, 768]. + readout_type (str): Type of readout operation. Default: 'ignore'. + patch_size (int): The patch size. Default: 16. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + def __init__(self, + in_channels=768, + out_channels=[96, 192, 384, 768], + readout_type='ignore', + patch_size=16, + init_cfg=None): + super().__init__(init_cfg) + + assert readout_type in ['ignore', 'add', 'project'] + self.readout_type = readout_type + self.patch_size = patch_size + + self.projects = nn.ModuleList([ + ConvModule( + in_channels=in_channels, + out_channels=out_channel, + kernel_size=1, + act_cfg=None, + ) for out_channel in out_channels + ]) + + self.resize_layers = nn.ModuleList([ + nn.ConvTranspose2d( + in_channels=out_channels[0], + out_channels=out_channels[0], + kernel_size=4, + stride=4, + padding=0), + nn.ConvTranspose2d( + in_channels=out_channels[1], + out_channels=out_channels[1], + kernel_size=2, + stride=2, + padding=0), + nn.Identity(), + nn.Conv2d( + in_channels=out_channels[3], + out_channels=out_channels[3], + kernel_size=3, + stride=2, + padding=1) + ]) + if self.readout_type == 'project': + self.readout_projects = nn.ModuleList() + for _ in range(len(self.projects)): + self.readout_projects.append( + nn.Sequential( + Linear(2 * in_channels, in_channels), + build_activation_layer(dict(type='GELU')))) + + def forward(self, inputs): + assert isinstance(inputs, list) + out = [] + for i, x in enumerate(inputs): + assert len(x) == 2 + x, cls_token = x[0], x[1] + feature_shape = x.shape + if self.readout_type == 'project': + x = x.flatten(2).permute((0, 2, 1)) + readout = cls_token.unsqueeze(1).expand_as(x) + x = self.readout_projects[i](torch.cat((x, readout), -1)) + x = x.permute(0, 2, 1).reshape(feature_shape) + elif self.readout_type == 'add': + x = x.flatten(2) + cls_token.unsqueeze(-1) + x = x.reshape(feature_shape) + else: + pass + x = self.projects[i](x) + x = self.resize_layers[i](x) + out.append(x) + return out + + +class PreActResidualConvUnit(BaseModule): + """ResidualConvUnit, pre-activate residual unit. + + Args: + in_channels (int): number of channels in the input feature map. + act_cfg (dict): dictionary to construct and config activation layer. + norm_cfg (dict): dictionary to construct and config norm layer. + stride (int): stride of the first block. Default: 1 + dilation (int): dilation rate for convs layers. Default: 1. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + def __init__(self, + in_channels, + act_cfg, + norm_cfg, + stride=1, + dilation=1, + init_cfg=None): + super().__init__(init_cfg) + + self.conv1 = ConvModule( + in_channels, + in_channels, + 3, + stride=stride, + padding=dilation, + dilation=dilation, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + bias=False, + order=('act', 'conv', 'norm')) + + self.conv2 = ConvModule( + in_channels, + in_channels, + 3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + bias=False, + order=('act', 'conv', 'norm')) + + def forward(self, inputs): + inputs_ = inputs.clone() + x = self.conv1(inputs) + x = self.conv2(x) + return x + inputs_ + + +class FeatureFusionBlock(BaseModule): + """FeatureFusionBlock, merge feature map from different stages. + + Args: + in_channels (int): Input channels. + act_cfg (dict): The activation config for ResidualConvUnit. + norm_cfg (dict): Config dict for normalization layer. + expand (bool): Whether expand the channels in post process block. + Default: False. + align_corners (bool): align_corner setting for bilinear upsample. + Default: True. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + def __init__(self, + in_channels, + act_cfg, + norm_cfg, + expand=False, + align_corners=True, + init_cfg=None): + super().__init__(init_cfg) + + self.in_channels = in_channels + self.expand = expand + self.align_corners = align_corners + + self.out_channels = in_channels + if self.expand: + self.out_channels = in_channels // 2 + + self.project = ConvModule( + self.in_channels, + self.out_channels, + kernel_size=1, + act_cfg=None, + bias=True) + + self.res_conv_unit1 = PreActResidualConvUnit( + in_channels=self.in_channels, act_cfg=act_cfg, norm_cfg=norm_cfg) + self.res_conv_unit2 = PreActResidualConvUnit( + in_channels=self.in_channels, act_cfg=act_cfg, norm_cfg=norm_cfg) + + def forward(self, *inputs): + x = inputs[0] + if len(inputs) == 2: + if x.shape != inputs[1].shape: + res = resize( + inputs[1], + size=(x.shape[2], x.shape[3]), + mode='bilinear', + align_corners=False) + else: + res = inputs[1] + x = x + self.res_conv_unit1(res) + x = self.res_conv_unit2(x) + x = resize( + x, + scale_factor=2, + mode='bilinear', + align_corners=self.align_corners) + x = self.project(x) + return x + + +@MODELS.register_module() +class DPTHead(BaseDecodeHead): + """Vision Transformers for Dense Prediction. + + This head is implemented of `DPT `_. + + Args: + embed_dims (int): The embed dimension of the ViT backbone. + Default: 768. + post_process_channels (List): Out channels of post process conv + layers. Default: [96, 192, 384, 768]. + readout_type (str): Type of readout operation. Default: 'ignore'. + patch_size (int): The patch size. Default: 16. + expand_channels (bool): Whether expand the channels in post process + block. Default: False. + act_cfg (dict): The activation config for residual conv unit. + Default dict(type='ReLU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + """ + + def __init__(self, + embed_dims=768, + post_process_channels=[96, 192, 384, 768], + readout_type='ignore', + patch_size=16, + expand_channels=False, + act_cfg=dict(type='ReLU'), + norm_cfg=dict(type='BN'), + **kwargs): + super().__init__(**kwargs) + + self.in_channels = self.in_channels + self.expand_channels = expand_channels + self.reassemble_blocks = ReassembleBlocks(embed_dims, + post_process_channels, + readout_type, patch_size) + + self.post_process_channels = [ + channel * math.pow(2, i) if expand_channels else channel + for i, channel in enumerate(post_process_channels) + ] + self.convs = nn.ModuleList() + for channel in self.post_process_channels: + self.convs.append( + ConvModule( + channel, + self.channels, + kernel_size=3, + padding=1, + act_cfg=None, + bias=False)) + self.fusion_blocks = nn.ModuleList() + for _ in range(len(self.convs)): + self.fusion_blocks.append( + FeatureFusionBlock(self.channels, act_cfg, norm_cfg)) + self.fusion_blocks[0].res_conv_unit1 = None + self.project = ConvModule( + self.channels, + self.channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg) + self.num_fusion_blocks = len(self.fusion_blocks) + self.num_reassemble_blocks = len(self.reassemble_blocks.resize_layers) + self.num_post_process_channels = len(self.post_process_channels) + assert self.num_fusion_blocks == self.num_reassemble_blocks + assert self.num_reassemble_blocks == self.num_post_process_channels + + def forward(self, inputs): + assert len(inputs) == self.num_reassemble_blocks + x = self._transform_inputs(inputs) + x = self.reassemble_blocks(x) + x = [self.convs[i](feature) for i, feature in enumerate(x)] + out = self.fusion_blocks[0](x[-1]) + for i in range(1, len(self.fusion_blocks)): + out = self.fusion_blocks[i](out, x[-(i + 1)]) + out = self.project(out) + out = self.cls_seg(out) + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ema_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ema_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8dbb0c29b9b533dad962e48d71ae055f20aa07 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ema_head.py @@ -0,0 +1,169 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from .decode_head import BaseDecodeHead + + +def reduce_mean(tensor): + """Reduce mean when distributed training.""" + if not (dist.is_available() and dist.is_initialized()): + return tensor + tensor = tensor.clone() + dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM) + return tensor + + +class EMAModule(nn.Module): + """Expectation Maximization Attention Module used in EMANet. + + Args: + channels (int): Channels of the whole module. + num_bases (int): Number of bases. + num_stages (int): Number of the EM iterations. + """ + + def __init__(self, channels, num_bases, num_stages, momentum): + super().__init__() + assert num_stages >= 1, 'num_stages must be at least 1!' + self.num_bases = num_bases + self.num_stages = num_stages + self.momentum = momentum + + bases = torch.zeros(1, channels, self.num_bases) + bases.normal_(0, math.sqrt(2. / self.num_bases)) + # [1, channels, num_bases] + bases = F.normalize(bases, dim=1, p=2) + self.register_buffer('bases', bases) + + def forward(self, feats): + """Forward function.""" + batch_size, channels, height, width = feats.size() + # [batch_size, channels, height*width] + feats = feats.view(batch_size, channels, height * width) + # [batch_size, channels, num_bases] + bases = self.bases.repeat(batch_size, 1, 1) + + with torch.no_grad(): + for i in range(self.num_stages): + # [batch_size, height*width, num_bases] + attention = torch.einsum('bcn,bck->bnk', feats, bases) + attention = F.softmax(attention, dim=2) + # l1 norm + attention_normed = F.normalize(attention, dim=1, p=1) + # [batch_size, channels, num_bases] + bases = torch.einsum('bcn,bnk->bck', feats, attention_normed) + # l2 norm + bases = F.normalize(bases, dim=1, p=2) + + feats_recon = torch.einsum('bck,bnk->bcn', bases, attention) + feats_recon = feats_recon.view(batch_size, channels, height, width) + + if self.training: + bases = bases.mean(dim=0, keepdim=True) + bases = reduce_mean(bases) + # l2 norm + bases = F.normalize(bases, dim=1, p=2) + self.bases = (1 - + self.momentum) * self.bases + self.momentum * bases + + return feats_recon + + +@MODELS.register_module() +class EMAHead(BaseDecodeHead): + """Expectation Maximization Attention Networks for Semantic Segmentation. + + This head is the implementation of `EMANet + `_. + + Args: + ema_channels (int): EMA module channels + num_bases (int): Number of bases. + num_stages (int): Number of the EM iterations. + concat_input (bool): Whether concat the input and output of convs + before classification layer. Default: True + momentum (float): Momentum to update the base. Default: 0.1. + """ + + def __init__(self, + ema_channels, + num_bases, + num_stages, + concat_input=True, + momentum=0.1, + **kwargs): + super().__init__(**kwargs) + self.ema_channels = ema_channels + self.num_bases = num_bases + self.num_stages = num_stages + self.concat_input = concat_input + self.momentum = momentum + self.ema_module = EMAModule(self.ema_channels, self.num_bases, + self.num_stages, self.momentum) + + self.ema_in_conv = ConvModule( + self.in_channels, + self.ema_channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + # project (0, inf) -> (-inf, inf) + self.ema_mid_conv = ConvModule( + self.ema_channels, + self.ema_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=None, + act_cfg=None) + for param in self.ema_mid_conv.parameters(): + param.requires_grad = False + + self.ema_out_conv = ConvModule( + self.ema_channels, + self.ema_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=None) + self.bottleneck = ConvModule( + self.ema_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + if self.concat_input: + self.conv_cat = ConvModule( + self.in_channels + self.channels, + self.channels, + kernel_size=3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + feats = self.ema_in_conv(x) + identity = feats + feats = self.ema_mid_conv(feats) + recon = self.ema_module(feats) + recon = F.relu(recon, inplace=True) + recon = self.ema_out_conv(recon) + output = F.relu(identity + recon, inplace=True) + output = self.bottleneck(output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/enc_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/enc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..2bba73b3010b31cd39547b79bd507073f14bdb32 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/enc_head.py @@ -0,0 +1,196 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule, build_norm_layer +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import ConfigType, SampleList +from ..utils import Encoding, resize +from .decode_head import BaseDecodeHead + + +class EncModule(nn.Module): + """Encoding Module used in EncNet. + + Args: + in_channels (int): Input channels. + num_codes (int): Number of code words. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict): Config of activation layers. + """ + + def __init__(self, in_channels, num_codes, conv_cfg, norm_cfg, act_cfg): + super().__init__() + self.encoding_project = ConvModule( + in_channels, + in_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + # TODO: resolve this hack + # change to 1d + if norm_cfg is not None: + encoding_norm_cfg = norm_cfg.copy() + if encoding_norm_cfg['type'] in ['BN', 'IN']: + encoding_norm_cfg['type'] += '1d' + else: + encoding_norm_cfg['type'] = encoding_norm_cfg['type'].replace( + '2d', '1d') + else: + # fallback to BN1d + encoding_norm_cfg = dict(type='BN1d') + self.encoding = nn.Sequential( + Encoding(channels=in_channels, num_codes=num_codes), + build_norm_layer(encoding_norm_cfg, num_codes)[1], + nn.ReLU(inplace=True)) + self.fc = nn.Sequential( + nn.Linear(in_channels, in_channels), nn.Sigmoid()) + + def forward(self, x): + """Forward function.""" + encoding_projection = self.encoding_project(x) + encoding_feat = self.encoding(encoding_projection).mean(dim=1) + batch_size, channels, _, _ = x.size() + gamma = self.fc(encoding_feat) + y = gamma.view(batch_size, channels, 1, 1) + output = F.relu_(x + x * y) + return encoding_feat, output + + +@MODELS.register_module() +class EncHead(BaseDecodeHead): + """Context Encoding for Semantic Segmentation. + + This head is the implementation of `EncNet + `_. + + Args: + num_codes (int): Number of code words. Default: 32. + use_se_loss (bool): Whether use Semantic Encoding Loss (SE-loss) to + regularize the training. Default: True. + add_lateral (bool): Whether use lateral connection to fuse features. + Default: False. + loss_se_decode (dict): Config of decode loss. + Default: dict(type='CrossEntropyLoss', use_sigmoid=True). + """ + + def __init__(self, + num_codes=32, + use_se_loss=True, + add_lateral=False, + loss_se_decode=dict( + type='CrossEntropyLoss', + use_sigmoid=True, + loss_weight=0.2), + **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + self.use_se_loss = use_se_loss + self.add_lateral = add_lateral + self.num_codes = num_codes + self.bottleneck = ConvModule( + self.in_channels[-1], + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + if add_lateral: + self.lateral_convs = nn.ModuleList() + for in_channels in self.in_channels[:-1]: # skip the last one + self.lateral_convs.append( + ConvModule( + in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + self.fusion = ConvModule( + len(self.in_channels) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.enc_module = EncModule( + self.channels, + num_codes=num_codes, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + if self.use_se_loss: + self.loss_se_decode = MODELS.build(loss_se_decode) + self.se_layer = nn.Linear(self.channels, self.num_classes) + + def forward(self, inputs): + """Forward function.""" + inputs = self._transform_inputs(inputs) + feat = self.bottleneck(inputs[-1]) + if self.add_lateral: + laterals = [ + resize( + lateral_conv(inputs[i]), + size=feat.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + for i, lateral_conv in enumerate(self.lateral_convs) + ] + feat = self.fusion(torch.cat([feat, *laterals], 1)) + encode_feat, output = self.enc_module(feat) + output = self.cls_seg(output) + if self.use_se_loss: + se_output = self.se_layer(encode_feat) + return output, se_output + else: + return output + + def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType): + """Forward function for testing, ignore se_loss.""" + if self.use_se_loss: + seg_logits = self.forward(inputs)[0] + else: + seg_logits = self.forward(inputs) + return self.predict_by_feat(seg_logits, batch_img_metas) + + @staticmethod + def _convert_to_onehot_labels(seg_label, num_classes): + """Convert segmentation label to onehot. + + Args: + seg_label (Tensor): Segmentation label of shape (N, H, W). + num_classes (int): Number of classes. + + Returns: + Tensor: Onehot labels of shape (N, num_classes). + """ + + batch_size = seg_label.size(0) + onehot_labels = seg_label.new_zeros((batch_size, num_classes)) + for i in range(batch_size): + hist = seg_label[i].float().histc( + bins=num_classes, min=0, max=num_classes - 1) + onehot_labels[i] = hist > 0 + return onehot_labels + + def loss_by_feat(self, seg_logit: Tuple[Tensor], + batch_data_samples: SampleList, **kwargs) -> dict: + """Compute segmentation and semantic encoding loss.""" + seg_logit, se_seg_logit = seg_logit + loss = dict() + loss.update(super().loss_by_feat(seg_logit, batch_data_samples)) + + seg_label = self._stack_batch_gt(batch_data_samples) + se_loss = self.loss_se_decode( + se_seg_logit, + self._convert_to_onehot_labels(seg_label, self.num_classes)) + loss['loss_se'] = se_loss + return loss diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/fcn_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/fcn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..341801888368d307da6b926a2c89f72b6b06476d --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/fcn_head.py @@ -0,0 +1,96 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class FCNHead(BaseDecodeHead): + """Fully Convolution Networks for Semantic Segmentation. + + This head is implemented of `FCNNet `_. + + Args: + num_convs (int): Number of convs in the head. Default: 2. + kernel_size (int): The kernel size for convs in the head. Default: 3. + concat_input (bool): Whether concat the input and output of convs + before classification layer. + dilation (int): The dilation rate for convs in the head. Default: 1. + """ + + def __init__(self, + num_convs=2, + kernel_size=3, + concat_input=True, + dilation=1, + **kwargs): + assert num_convs >= 0 and dilation > 0 and isinstance(dilation, int) + self.num_convs = num_convs + self.concat_input = concat_input + self.kernel_size = kernel_size + super().__init__(**kwargs) + if num_convs == 0: + assert self.in_channels == self.channels + + conv_padding = (kernel_size // 2) * dilation + convs = [] + convs.append( + ConvModule( + self.in_channels, + self.channels, + kernel_size=kernel_size, + padding=conv_padding, + dilation=dilation, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + for i in range(num_convs - 1): + convs.append( + ConvModule( + self.channels, + self.channels, + kernel_size=kernel_size, + padding=conv_padding, + dilation=dilation, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + if num_convs == 0: + self.convs = nn.Identity() + else: + self.convs = nn.Sequential(*convs) + if self.concat_input: + self.conv_cat = ConvModule( + self.in_channels + self.channels, + self.channels, + kernel_size=kernel_size, + padding=kernel_size // 2, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def _forward_feature(self, inputs): + """Forward function for feature maps before classifying each pixel with + ``self.cls_seg`` fc. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + feats (Tensor): A tensor of shape (batch_size, self.channels, + H, W) which is feature map for last layer of decoder head. + """ + x = self._transform_inputs(inputs) + feats = self.convs(x) + if self.concat_input: + feats = self.conv_cat(torch.cat([x, feats], dim=1)) + return feats + + def forward(self, inputs): + """Forward function.""" + output = self._forward_feature(inputs) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/fpn_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/fpn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..25f481fe81c5f4f0aa37903aaf135dc63c930bf8 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/fpn_head.py @@ -0,0 +1,68 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import numpy as np +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import Upsample, resize +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class FPNHead(BaseDecodeHead): + """Panoptic Feature Pyramid Networks. + + This head is the implementation of `Semantic FPN + `_. + + Args: + feature_strides (tuple[int]): The strides for input feature maps. + stack_lateral. All strides suppose to be power of 2. The first + one is of largest resolution. + """ + + def __init__(self, feature_strides, **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + assert len(feature_strides) == len(self.in_channels) + assert min(feature_strides) == feature_strides[0] + self.feature_strides = feature_strides + + self.scale_heads = nn.ModuleList() + for i in range(len(feature_strides)): + head_length = max( + 1, + int(np.log2(feature_strides[i]) - np.log2(feature_strides[0]))) + scale_head = [] + for k in range(head_length): + scale_head.append( + ConvModule( + self.in_channels[i] if k == 0 else self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + if feature_strides[i] != feature_strides[0]: + scale_head.append( + Upsample( + scale_factor=2, + mode='bilinear', + align_corners=self.align_corners)) + self.scale_heads.append(nn.Sequential(*scale_head)) + + def forward(self, inputs): + + x = self._transform_inputs(inputs) + + output = self.scale_heads[0](x[0]) + for i in range(1, len(self.feature_strides)): + # non inplace + output = output + resize( + self.scale_heads[i](x[i]), + size=output.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/gc_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/gc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..14f0ef021c1143d493e17f347f1f4da1145470b8 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/gc_head.py @@ -0,0 +1,48 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.cnn import ContextBlock + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + + +@MODELS.register_module() +class GCHead(FCNHead): + """GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond. + + This head is the implementation of `GCNet + `_. + + Args: + ratio (float): Multiplier of channels ratio. Default: 1/4. + pooling_type (str): The pooling type of context aggregation. + Options are 'att', 'avg'. Default: 'avg'. + fusion_types (tuple[str]): The fusion type for feature fusion. + Options are 'channel_add', 'channel_mul'. Default: ('channel_add',) + """ + + def __init__(self, + ratio=1 / 4., + pooling_type='att', + fusion_types=('channel_add', ), + **kwargs): + super().__init__(num_convs=2, **kwargs) + self.ratio = ratio + self.pooling_type = pooling_type + self.fusion_types = fusion_types + self.gc_block = ContextBlock( + in_channels=self.channels, + ratio=self.ratio, + pooling_type=self.pooling_type, + fusion_types=self.fusion_types) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + output = self.convs[0](x) + output = self.gc_block(output) + output = self.convs[1](output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ham_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ham_head.py new file mode 100644 index 0000000000000000000000000000000000000000..073d8011b05dc8c5e8d48cc8b77484a27f7b2100 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ham_head.py @@ -0,0 +1,255 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Originally from https://github.com/visual-attention-network/segnext +# Licensed under the Apache License, Version 2.0 (the "License") +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.device import get_device + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class Matrix_Decomposition_2D_Base(nn.Module): + """Base class of 2D Matrix Decomposition. + + Args: + MD_S (int): The number of spatial coefficient in + Matrix Decomposition, it may be used for calculation + of the number of latent dimension D in Matrix + Decomposition. Defaults: 1. + MD_R (int): The number of latent dimension R in + Matrix Decomposition. Defaults: 64. + train_steps (int): The number of iteration steps in + Multiplicative Update (MU) rule to solve Non-negative + Matrix Factorization (NMF) in training. Defaults: 6. + eval_steps (int): The number of iteration steps in + Multiplicative Update (MU) rule to solve Non-negative + Matrix Factorization (NMF) in evaluation. Defaults: 7. + inv_t (int): Inverted multiple number to make coefficient + smaller in softmax. Defaults: 100. + rand_init (bool): Whether to initialize randomly. + Defaults: True. + """ + + def __init__(self, + MD_S=1, + MD_R=64, + train_steps=6, + eval_steps=7, + inv_t=100, + rand_init=True): + super().__init__() + + self.S = MD_S + self.R = MD_R + + self.train_steps = train_steps + self.eval_steps = eval_steps + + self.inv_t = inv_t + + self.rand_init = rand_init + + def _build_bases(self, B, S, D, R, device=None): + raise NotImplementedError + + def local_step(self, x, bases, coef): + raise NotImplementedError + + def local_inference(self, x, bases): + # (B * S, D, N)^T @ (B * S, D, R) -> (B * S, N, R) + coef = torch.bmm(x.transpose(1, 2), bases) + coef = F.softmax(self.inv_t * coef, dim=-1) + + steps = self.train_steps if self.training else self.eval_steps + for _ in range(steps): + bases, coef = self.local_step(x, bases, coef) + + return bases, coef + + def compute_coef(self, x, bases, coef): + raise NotImplementedError + + def forward(self, x, return_bases=False): + """Forward Function.""" + B, C, H, W = x.shape + + # (B, C, H, W) -> (B * S, D, N) + D = C // self.S + N = H * W + x = x.view(B * self.S, D, N) + if not self.rand_init and not hasattr(self, 'bases'): + bases = self._build_bases(1, self.S, D, self.R, device=x.device) + self.register_buffer('bases', bases) + + # (S, D, R) -> (B * S, D, R) + if self.rand_init: + bases = self._build_bases(B, self.S, D, self.R, device=x.device) + else: + bases = self.bases.repeat(B, 1, 1) + + bases, coef = self.local_inference(x, bases) + + # (B * S, N, R) + coef = self.compute_coef(x, bases, coef) + + # (B * S, D, R) @ (B * S, N, R)^T -> (B * S, D, N) + x = torch.bmm(bases, coef.transpose(1, 2)) + + # (B * S, D, N) -> (B, C, H, W) + x = x.view(B, C, H, W) + + return x + + +class NMF2D(Matrix_Decomposition_2D_Base): + """Non-negative Matrix Factorization (NMF) module. + + It is inherited from ``Matrix_Decomposition_2D_Base`` module. + """ + + def __init__(self, args=dict()): + super().__init__(**args) + + self.inv_t = 1 + + def _build_bases(self, B, S, D, R, device=None): + """Build bases in initialization.""" + if device is None: + device = get_device() + bases = torch.rand((B * S, D, R)).to(device) + bases = F.normalize(bases, dim=1) + + return bases + + def local_step(self, x, bases, coef): + """Local step in iteration to renew bases and coefficient.""" + # (B * S, D, N)^T @ (B * S, D, R) -> (B * S, N, R) + numerator = torch.bmm(x.transpose(1, 2), bases) + # (B * S, N, R) @ [(B * S, D, R)^T @ (B * S, D, R)] -> (B * S, N, R) + denominator = coef.bmm(bases.transpose(1, 2).bmm(bases)) + # Multiplicative Update + coef = coef * numerator / (denominator + 1e-6) + + # (B * S, D, N) @ (B * S, N, R) -> (B * S, D, R) + numerator = torch.bmm(x, coef) + # (B * S, D, R) @ [(B * S, N, R)^T @ (B * S, N, R)] -> (B * S, D, R) + denominator = bases.bmm(coef.transpose(1, 2).bmm(coef)) + # Multiplicative Update + bases = bases * numerator / (denominator + 1e-6) + + return bases, coef + + def compute_coef(self, x, bases, coef): + """Compute coefficient.""" + # (B * S, D, N)^T @ (B * S, D, R) -> (B * S, N, R) + numerator = torch.bmm(x.transpose(1, 2), bases) + # (B * S, N, R) @ (B * S, D, R)^T @ (B * S, D, R) -> (B * S, N, R) + denominator = coef.bmm(bases.transpose(1, 2).bmm(bases)) + # multiplication update + coef = coef * numerator / (denominator + 1e-6) + + return coef + + +class Hamburger(nn.Module): + """Hamburger Module. It consists of one slice of "ham" (matrix + decomposition) and two slices of "bread" (linear transformation). + + Args: + ham_channels (int): Input and output channels of feature. + ham_kwargs (dict): Config of matrix decomposition module. + norm_cfg (dict | None): Config of norm layers. + """ + + def __init__(self, + ham_channels=512, + ham_kwargs=dict(), + norm_cfg=None, + **kwargs): + super().__init__() + + self.ham_in = ConvModule( + ham_channels, ham_channels, 1, norm_cfg=None, act_cfg=None) + + self.ham = NMF2D(ham_kwargs) + + self.ham_out = ConvModule( + ham_channels, ham_channels, 1, norm_cfg=norm_cfg, act_cfg=None) + + def forward(self, x): + enjoy = self.ham_in(x) + enjoy = F.relu(enjoy, inplace=True) + enjoy = self.ham(enjoy) + enjoy = self.ham_out(enjoy) + ham = F.relu(x + enjoy, inplace=True) + + return ham + + +@MODELS.register_module() +class LightHamHead(BaseDecodeHead): + """SegNeXt decode head. + + This decode head is the implementation of `SegNeXt: Rethinking + Convolutional Attention Design for Semantic + Segmentation `_. + Inspiration from https://github.com/visual-attention-network/segnext. + + Specifically, LightHamHead is inspired by HamNet from + `Is Attention Better Than Matrix Decomposition? + `. + + Args: + ham_channels (int): input channels for Hamburger. + Defaults: 512. + ham_kwargs (int): kwagrs for Ham. Defaults: dict(). + """ + + def __init__(self, ham_channels=512, ham_kwargs=dict(), **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + self.ham_channels = ham_channels + + self.squeeze = ConvModule( + sum(self.in_channels), + self.ham_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + self.hamburger = Hamburger(ham_channels, ham_kwargs, **kwargs) + + self.align = ConvModule( + self.ham_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + inputs = self._transform_inputs(inputs) + + inputs = [ + resize( + level, + size=inputs[0].shape[2:], + mode='bilinear', + align_corners=self.align_corners) for level in inputs + ] + + inputs = torch.cat(inputs, dim=1) + # apply a conv block to squeeze feature map + x = self.squeeze(inputs) + # apply hamburger module + x = self.hamburger(x) + + # apply a conv block to align feature map + output = self.align(x) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/interformer_decoder.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/interformer_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..ba58bb96d90376325ea57b7159237ad0cf8808dc --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/interformer_decoder.py @@ -0,0 +1,921 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple, Dict + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.model import BaseModule +from typing import Optional +import numpy as np +import cv2 +from PIL import Image + +try: + from mmdet.models.dense_heads import \ + Mask2FormerHead as MMDET_Mask2FormerHead +except ModuleNotFoundError: + MMDET_Mask2FormerHead = BaseModule + +from mmengine.structures import InstanceData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures.seg_data_sample import SegDataSample +from mmseg.utils import ConfigType, SampleList + +# moving from parent classes +from mmseg.utils import OptConfigType, OptMultiConfig +import copy +from mmdet.models.layers import Mask2FormerTransformerDecoder, SinePositionalEncoding +from mmseg.registry import TASK_UTILS +from mmengine.model import ModuleList, caffe2_xavier_init +from mmcv.cnn import Conv2d +from .decode_head import BaseDecodeHead +from mmdet.models.utils import multi_apply, get_uncertain_point_coords_with_randomness +from mmcv.ops import point_sample +from mmdet.utils import reduce_mean, InstanceList +from typing import Union + + +class UNetDecoder(nn.Module): + def __init__(self, in_channels_list, out_channels): + super(UNetDecoder, self).__init__() + + self.upconv1 = nn.ConvTranspose2d(in_channels_list[3], in_channels_list[2], kernel_size=2, stride=2) + self.conv1 = nn.Conv2d(in_channels_list[2] * 2, in_channels_list[2], kernel_size=3, padding=1) + + self.upconv2 = nn.ConvTranspose2d(in_channels_list[2], in_channels_list[1], kernel_size=2, stride=2) + self.conv2 = nn.Conv2d(in_channels_list[1] * 2, in_channels_list[1], kernel_size=3, padding=1) + + self.upconv3 = nn.ConvTranspose2d(in_channels_list[1], in_channels_list[0], kernel_size=2, stride=2) + self.conv3 = nn.Conv2d(in_channels_list[0] * 2, out_channels, kernel_size=3, padding=1) + + def forward(self, features): + x1 = features[3] + x2 = self.upconv1(x1) + x2 = torch.cat((x2, features[2]), dim=1) # Concatenate + x2 = self.conv1(x2) + + x3 = self.upconv2(x2) + x3 = torch.cat((x3, features[1]), dim=1) # Concatenate + x3 = self.conv2(x3) + + x4 = self.upconv3(x3) + x4 = torch.cat((x4, features[0]), dim=1) # Concatenate + x4 = self.conv3(x4) + + return x4, [x1,x2,x3] + +def _get_activation_fn(activation): + """Return an activation function given a string""" + if activation == "relu": + return F.relu + if activation == "gelu": + return F.gelu + if activation == "glu": + return F.glu + raise RuntimeError(F"activation should be relu/gelu, not {activation}.") + +class CrossAttentionLayer(nn.Module): + + def __init__(self, d_model=256, nhead=8, dropout=0.0, + activation="relu"): + super().__init__() + self.multihead_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout) + + self.norm = nn.LayerNorm(d_model) + self.dropout = nn.Dropout(dropout) + + self.activation = _get_activation_fn(activation) + + self._reset_parameters() + + def _reset_parameters(self): + for p in self.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + + def with_pos_embed(self, tensor, pos: Optional[Tensor]): + return tensor if pos is None else tensor + pos + + def forward_pre(self, tgt, memory, + memory_mask: Optional[Tensor] = None, + memory_key_padding_mask: Optional[Tensor] = None, + pos: Optional[Tensor] = None, + query_pos: Optional[Tensor] = None): + tgt2 = self.norm(tgt) + tgt2 = self.multihead_attn(query=self.with_pos_embed(tgt2, query_pos), + key=self.with_pos_embed(memory, pos), + value=memory, attn_mask=memory_mask, + key_padding_mask=memory_key_padding_mask)[0] + tgt = tgt + self.dropout(tgt2) + + return tgt + + def forward(self, tgt, memory, + memory_mask: Optional[Tensor] = None, + memory_key_padding_mask: Optional[Tensor] = None, + pos: Optional[Tensor] = None, + query_pos: Optional[Tensor] = None): + + return self.forward_pre(tgt, memory, memory_mask, + memory_key_padding_mask, pos, query_pos) + +class Attention(nn.Module): + def __init__(self, dim=256, heads=8): + super().__init__() + self.heads = heads + head_dim = dim // heads + self.scale = head_dim ** -0.5 + self.attn = None + + self.qkv = nn.Linear(dim, dim * 3) + self.proj = nn.Linear(dim, dim) + + + @property + def unwrapped(self): + return self + + def forward(self, x, mask=None): + B, N, C = x.shape + qkv = ( + self.qkv(x) + .reshape(B, N, 3, self.heads, C // self.heads) + .permute(2, 0, 3, 1, 4) + ) + q, k, v = ( + qkv[0], + qkv[1], + qkv[2], + ) + + attn = (q @ k.transpose(-2, -1)) * self.scale + attn = attn.softmax(dim=-1) + + x = (attn @ v).transpose(1, 2).reshape(B, N, C) + x = self.proj(x) + + return x, attn + +def select_top_k_features_from_regional_similarity(feature_A: torch.Tensor, feature_B: torch.Tensor, k: int = 5): + + if feature_A.shape[1] != feature_B.shape[1]: + raise ValueError("Not match") + + batch_size, channels, h_A, w_A = feature_A.shape + _, _, h_B, w_B = feature_B.shape + + if h_B != 2 * h_A or w_B != 2 * w_A: + raise ValueError("2x times Error") + + b_top_left = feature_B[:, :, :h_A, :w_A] + b_top_right = feature_B[:, :, :h_A, w_A:] + b_bottom_left = feature_B[:, :, h_A:, :w_A] + b_bottom_right = feature_B[:, :, h_A:, w_A:] + + b_sub_regions = [b_top_left, b_top_right, b_bottom_left, b_bottom_right] + + pixelwise_similarities_list = [] + for b_sub in b_sub_regions: + + cosine_sim_map = F.cosine_similarity(feature_A, b_sub, dim=1) + pixelwise_similarities_list.append(cosine_sim_map) + + + sim_map_top = torch.cat([pixelwise_similarities_list[0], pixelwise_similarities_list[1]], dim=2) # [B, H_A, 2*W_A] = [B, H_A, W_B] + sim_map_bottom = torch.cat([pixelwise_similarities_list[2], pixelwise_similarities_list[3]], dim=2) # [B, H_A, 2*W_A] = [B, H_A, W_B] + + total_similarity_map = torch.cat([sim_map_top, sim_map_bottom], dim=1) # [B, 2*H_A, W_B] = [B, H_B, W_B] + + final_selected_features = [] + + for b_idx in range(batch_size): + + batch_similarity = total_similarity_map[b_idx].flatten() + + _, top_k_indices_flat = torch.topk(batch_similarity, k=k, largest=True, sorted=True) + + current_batch_top_k_features = [] + for k_idx in range(k): + flat_idx = top_k_indices_flat[k_idx].item() + + h_coord = flat_idx // w_B + w_coord = flat_idx % w_B + + selected_feature = feature_B[b_idx, :, h_coord, w_coord].unsqueeze(-1).unsqueeze(-1) + current_batch_top_k_features.append(selected_feature) + + all_batches_top_k_flat_indices = [] + for b_idx in range(batch_size): + batch_similarity = total_similarity_map[b_idx].flatten() + _, top_k_indices_flat = torch.topk(batch_similarity, k=k, largest=True, sorted=True) + all_batches_top_k_flat_indices.append(top_k_indices_flat) + + final_selected_features_list = [] + + for k_val_idx in range(k): + features_for_this_k_across_batches = [] + for b_idx in range(batch_size): + flat_idx = all_batches_top_k_flat_indices[b_idx][k_val_idx].item() + h_coord = flat_idx // w_B + w_coord = flat_idx % w_B + + selected_feature = feature_B[b_idx, :, h_coord, w_coord].unsqueeze(-1).unsqueeze(-1) + features_for_this_k_across_batches.append(selected_feature) + + final_selected_features_list.append(torch.stack(features_for_this_k_across_batches, dim=0)) + + return final_selected_features_list + + +@MODELS.register_module() +class InterFormerDecoder(BaseDecodeHead): + + + def __init__(self, + in_channels: List[int], + feat_channels: int, + out_channels: int, + num_queries: int = 100, + num_transformer_feat_level: int = 3, + pixel_decoder: ConfigType = ..., + enforce_decoder_input_project: bool = False, + transformer_decoder: ConfigType = ..., + positional_encoding: ConfigType = dict( + num_feats=128, normalize=True), + loss_cls: ConfigType = dict( + type='CrossEntropyLoss', + use_sigmoid=False, + loss_weight=2.0, + reduction='mean', + class_weight=[1.0] * 133 + [0.1]), + loss_mask: ConfigType = dict( + type='CrossEntropyLoss', + use_sigmoid=True, + reduction='mean', + loss_weight=5.0), + loss_dice: ConfigType = dict( + type='DiceLoss', + use_sigmoid=True, + activate=True, + reduction='mean', + naive_dice=True, + eps=1.0, + loss_weight=5.0), + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + init_cfg: OptMultiConfig = None, + num_classes=10, + align_corners=False, + ignore_index=255, + **kwargs): + super().__init__(in_channels=3,channels=out_channels,num_classes=num_classes) + + self.num_classes = num_classes + self.align_corners = align_corners + self.out_channels = num_classes + self.ignore_index = ignore_index + + feat_channels = feat_channels + + + self.num_queries = num_queries + self.num_transformer_feat_level = num_transformer_feat_level + self.num_heads = transformer_decoder.layer_cfg.cross_attn_cfg.num_heads + self.num_transformer_decoder_layers = transformer_decoder.num_layers + + assert pixel_decoder.encoder.layer_cfg. \ + self_attn_cfg.num_levels == num_transformer_feat_level + pixel_decoder_ = copy.deepcopy(pixel_decoder) + pixel_decoder_.update( + in_channels=in_channels, + feat_channels=feat_channels, + out_channels=out_channels) + self.pixel_decoder = MODELS.build(pixel_decoder_) + self.transformer_decoder = Mask2FormerTransformerDecoder( + **transformer_decoder) + self.decoder_embed_dims = self.transformer_decoder.embed_dims + self.decoder_input_projs = ModuleList() + # from low resolution to high resolution + for _ in range(num_transformer_feat_level): + if (self.decoder_embed_dims != feat_channels + or enforce_decoder_input_project): + self.decoder_input_projs.append( + Conv2d( + feat_channels, self.decoder_embed_dims, kernel_size=1)) + else: + self.decoder_input_projs.append(nn.Identity()) + self.decoder_positional_encoding = SinePositionalEncoding( + **positional_encoding) + self.query_embed = nn.Embedding(self.num_queries, feat_channels) #position + self.query_feat = nn.Embedding(self.num_queries, feat_channels) #content + # from low resolution to high resolution + self.level_embed = nn.Embedding(self.num_transformer_feat_level, + feat_channels) + + self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1) + self.mask_embed = nn.Sequential( + nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True), + nn.Linear(feat_channels, feat_channels), nn.ReLU(inplace=True), + nn.Linear(feat_channels, out_channels)) + + + self.mlp = nn.Sequential(nn.Linear(112*112, 256), nn.ReLU(inplace=True), + nn.Linear(256,128), nn.ReLU(inplace=True), + nn.Linear(128,5),nn.ReLU(inplace=True)) + + self.test_cfg = test_cfg + self.train_cfg = train_cfg + if train_cfg: + self.assigner = TASK_UTILS.build(self.train_cfg['assigner']) + self.sampler = TASK_UTILS.build( + self.train_cfg['sampler'], default_args=dict(context=self)) + self.num_points = self.train_cfg.get('num_points', 12544) + self.oversample_ratio = self.train_cfg.get('oversample_ratio', 3.0) + self.importance_sample_ratio = self.train_cfg.get( + 'importance_sample_ratio', 0.75) + + + self.class_weight = loss_cls.class_weight + self.loss_cls = MODELS.build(loss_cls) + self.loss_mask = MODELS.build(loss_mask) + self.loss_dice = MODELS.build(loss_dice) + + + self.cbdecoder = UNetDecoder(in_channels_list=[128, 256, 512, 1024], out_channels=1) + self.proj_cb = ModuleList() + channels = [1024,512,256] + for i in range(num_transformer_feat_level): + self.proj_cb.append( + Conv2d( + channels[i], self.decoder_embed_dims, kernel_size=1)) + self.cross_attn_cb = CrossAttentionLayer() + self.self_attn_cb = Attention() + self.norm_cb = nn.LayerNorm(256) + + def _seg_data_to_instance_data(self, batch_data_samples: SampleList): + + batch_img_metas = [] + batch_gt_instances = [] + + for data_sample in batch_data_samples: + batch_img_metas.append(data_sample.metainfo) + gt_sem_seg = data_sample.gt_sem_seg.data + classes = torch.unique( + gt_sem_seg, + sorted=False, + return_inverse=False, + return_counts=False) + + gt_labels = classes[classes != self.ignore_index] + + masks = [] + for class_id in gt_labels: + masks.append(gt_sem_seg == class_id) + + if len(masks) == 0: + gt_masks = torch.zeros( + (0, gt_sem_seg.shape[-2], + gt_sem_seg.shape[-1])).to(gt_sem_seg).long() + else: + gt_masks = torch.stack(masks).squeeze(1).long() + + instance_data = InstanceData(labels=gt_labels, masks=gt_masks) + batch_gt_instances.append(instance_data) + return batch_gt_instances, batch_img_metas + + def compute_loss_for_cb(self, cb_pred, batch_data_samples): + # add supervision for cb prediction + gt_cbs = [] + for data_sample in batch_data_samples: + img_path = data_sample.metainfo['img_path'] + filename = img_path.split('.')[0].split('/')[-1] + cb_gt_path = '/mnt/nvme1/suyuejiao/egohos_split_data/train/label_contact_first/'+filename+'.png' + cb_gt_np = np.array(Image.open(cb_gt_path).resize((448, 448))) + gt_cbs.append(torch.from_numpy(cb_gt_np).to(cb_pred)) + + gt_cbs = torch.stack(gt_cbs).squeeze(1).float() + + criterion = nn.BCEWithLogitsLoss() + loss = criterion(cb_pred.squeeze(1), gt_cbs) + return loss + + + + def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + + batch_gt_instances, batch_img_metas = self._seg_data_to_instance_data( + batch_data_samples) + + all_cls_scores, all_mask_preds, cb_pred = self.forward(x, batch_data_samples) + + # add loss for cb prediction + loss_cb = self.compute_loss_for_cb(cb_pred,batch_data_samples) + + # loss + losses = self.loss_by_feat(all_cls_scores, all_mask_preds, + batch_gt_instances, batch_img_metas) + losses['cb']=loss_cb + + # adding the consistency loss + mask_cls_results = all_cls_scores[-1] + mask_pred_results = all_mask_preds[-1] + if 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'] + else: + size = batch_img_metas[0]['img_shape'] + # upsample mask + mask_pred_results = F.interpolate( + mask_pred_results, size=size, mode='bilinear', align_corners=False) + cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1] + mask_pred = mask_pred_results.sigmoid() + seg_logits = torch.einsum('bqc, bqhw->bchw', cls_score, mask_pred) + pred_results_index = torch.argmax(seg_logits,dim=1) + + left_hand_pred = torch.zeros(pred_results_index.shape) + left_hand_pred[pred_results_index==1] = 1 + + threshold_left = 150 + if left_hand_pred.sum() >= threshold_left: + index_left = 1 + else: + index_left = 0 + + right_hand_pred = torch.zeros(pred_results_index.shape) + right_hand_pred[pred_results_index==2] = 1 + + threshold_right = threshold_left + if right_hand_pred.sum() >= threshold_right: + index_right = 1 + else: + index_right = 0 + + if index_left == 0 or index_right == 0: + index_two = 0 + else: + index_two = 1 + + left_object_pred = torch.zeros(pred_results_index.shape) + left_object_pred[pred_results_index==3] = 1 + right_object_pred = torch.zeros(pred_results_index.shape) + right_object_pred[pred_results_index==4] = 1 + two_object_pred = torch.zeros(pred_results_index.shape) + two_object_pred[pred_results_index==5] = 1 + loss_left = (1-index_left)*(left_object_pred.sum()-left_object_pred.sum()*index_left) + loss_right = (1-index_right)*(right_object_pred.sum()-right_object_pred.sum()*index_right) + loss_two = (1-index_two)*(two_object_pred.sum()-two_object_pred.sum()*index_two) + consistency_loss = loss_left + loss_right + loss_two + + losses['consistency'] = consistency_loss + + return losses + + def loss_by_feat(self, all_cls_scores: Tensor, all_mask_preds: Tensor, + batch_gt_instances: List[InstanceData], + batch_img_metas: List[dict]) -> Dict[str, Tensor]: + + num_dec_layers = len(all_cls_scores) + batch_gt_instances_list = [ + batch_gt_instances for _ in range(num_dec_layers) + ] + img_metas_list = [batch_img_metas for _ in range(num_dec_layers)] + losses_cls, losses_mask, losses_dice = multi_apply( + self._loss_by_feat_single, all_cls_scores, all_mask_preds, + batch_gt_instances_list, img_metas_list) + + loss_dict = dict() + # loss from the last decoder layer + loss_dict['loss_cls'] = losses_cls[-1] + loss_dict['loss_mask'] = losses_mask[-1] + loss_dict['loss_dice'] = losses_dice[-1] + # loss from other decoder layers + num_dec_layer = 0 + for loss_cls_i, loss_mask_i, loss_dice_i in zip( + losses_cls[:-1], losses_mask[:-1], losses_dice[:-1]): + loss_dict[f'd{num_dec_layer}.loss_cls'] = loss_cls_i + loss_dict[f'd{num_dec_layer}.loss_mask'] = loss_mask_i + loss_dict[f'd{num_dec_layer}.loss_dice'] = loss_dice_i + num_dec_layer += 1 + return loss_dict + + def _loss_by_feat_single(self, cls_scores: Tensor, mask_preds: Tensor, + batch_gt_instances: List[InstanceData], + batch_img_metas: List[dict]) -> Tuple[Tensor]: + """Loss function for outputs from a single decoder layer. + + Args: + cls_scores (Tensor): Mask score logits from a single decoder layer + for all images. Shape (batch_size, num_queries, + cls_out_channels). Note `cls_out_channels` should includes + background. + mask_preds (Tensor): Mask logits for a pixel decoder for all + images. Shape (batch_size, num_queries, h, w). + batch_gt_instances (list[obj:`InstanceData`]): each contains + ``labels`` and ``masks``. + batch_img_metas (list[dict]): List of image meta information. + + Returns: + tuple[Tensor]: Loss components for outputs from a single \ + decoder layer. + """ + num_imgs = cls_scores.size(0) + cls_scores_list = [cls_scores[i] for i in range(num_imgs)] + mask_preds_list = [mask_preds[i] for i in range(num_imgs)] + (labels_list, label_weights_list, mask_targets_list, mask_weights_list, + avg_factor) = self.get_targets(cls_scores_list, mask_preds_list, + batch_gt_instances, batch_img_metas) + + labels = torch.stack(labels_list, dim=0) + + label_weights = torch.stack(label_weights_list, dim=0) + + mask_targets = torch.cat(mask_targets_list, dim=0) + + mask_weights = torch.stack(mask_weights_list, dim=0) + + cls_scores = cls_scores.flatten(0, 1) + labels = labels.flatten(0, 1) + label_weights = label_weights.flatten(0, 1) + + class_weight = cls_scores.new_tensor(self.class_weight) + loss_cls = self.loss_cls( + cls_scores, + labels, + label_weights, + avg_factor=class_weight[labels].sum()) + + num_total_masks = reduce_mean(cls_scores.new_tensor([avg_factor])) + num_total_masks = max(num_total_masks, 1) + + # extract positive ones + # shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w) + mask_preds = mask_preds[mask_weights > 0] + + if mask_targets.shape[0] == 0: + # zero match + loss_dice = mask_preds.sum() + loss_mask = mask_preds.sum() + return loss_cls, loss_mask, loss_dice + + with torch.no_grad(): + points_coords = get_uncertain_point_coords_with_randomness( + mask_preds.unsqueeze(1), None, self.num_points, + self.oversample_ratio, self.importance_sample_ratio) + # shape (num_total_gts, h, w) -> (num_total_gts, num_points) + mask_point_targets = point_sample( + mask_targets.unsqueeze(1).float(), points_coords).squeeze(1) + # shape (num_queries, h, w) -> (num_queries, num_points) + mask_point_preds = point_sample( + mask_preds.unsqueeze(1), points_coords).squeeze(1) + + # dice loss + loss_dice = self.loss_dice( + mask_point_preds, mask_point_targets, avg_factor=num_total_masks) + + # mask loss + # shape (num_queries, num_points) -> (num_queries * num_points, ) + mask_point_preds = mask_point_preds.reshape(-1) + # shape (num_total_gts, num_points) -> (num_total_gts * num_points, ) + mask_point_targets = mask_point_targets.reshape(-1) + loss_mask = self.loss_mask( + mask_point_preds, + mask_point_targets, + avg_factor=num_total_masks * self.num_points) + + return loss_cls, loss_mask, loss_dice + + def get_targets( + self, + cls_scores_list: List[Tensor], + mask_preds_list: List[Tensor], + batch_gt_instances: InstanceList, + batch_img_metas: List[dict], + return_sampling_results: bool = False + ) -> Tuple[List[Union[Tensor, int]]]: + """Compute classification and mask targets for all images for a decoder + layer. + + Args: + cls_scores_list (list[Tensor]): Mask score logits from a single + decoder layer for all images. Each with shape (num_queries, + cls_out_channels). + mask_preds_list (list[Tensor]): Mask logits from a single decoder + layer for all images. Each with shape (num_queries, h, w). + batch_gt_instances (list[obj:`InstanceData`]): each contains + ``labels`` and ``masks``. + batch_img_metas (list[dict]): List of image meta information. + return_sampling_results (bool): Whether to return the sampling + results. Defaults to False. + + Returns: + tuple: a tuple containing the following targets. + + - labels_list (list[Tensor]): Labels of all images.\ + Each with shape (num_queries, ). + - label_weights_list (list[Tensor]): Label weights\ + of all images. Each with shape (num_queries, ). + - mask_targets_list (list[Tensor]): Mask targets of\ + all images. Each with shape (num_queries, h, w). + - mask_weights_list (list[Tensor]): Mask weights of\ + all images. Each with shape (num_queries, ). + - avg_factor (int): Average factor that is used to average\ + the loss. When using sampling method, avg_factor is + usually the sum of positive and negative priors. When + using `MaskPseudoSampler`, `avg_factor` is usually equal + to the number of positive priors. + + additional_returns: This function enables user-defined returns from + `self._get_targets_single`. These returns are currently refined + to properties at each feature map (i.e. having HxW dimension). + The results will be concatenated after the end. + """ + results = multi_apply(self._get_targets_single, cls_scores_list, + mask_preds_list, batch_gt_instances, + batch_img_metas) + (labels_list, label_weights_list, mask_targets_list, mask_weights_list, + pos_inds_list, neg_inds_list, sampling_results_list) = results[:7] + rest_results = list(results[7:]) + + avg_factor = sum( + [results.avg_factor for results in sampling_results_list]) + + res = (labels_list, label_weights_list, mask_targets_list, + mask_weights_list, avg_factor) + if return_sampling_results: + res = res + (sampling_results_list) + + return res + tuple(rest_results) + + def _get_targets_single(self, cls_score: Tensor, mask_pred: Tensor, + gt_instances: InstanceData, + img_meta: dict) -> Tuple[Tensor]: + """Compute classification and mask targets for one image. + + Args: + cls_score (Tensor): Mask score logits from a single decoder layer + for one image. Shape (num_queries, cls_out_channels). + mask_pred (Tensor): Mask logits for a single decoder layer for one + image. Shape (num_queries, h, w). + gt_instances (:obj:`InstanceData`): It contains ``labels`` and + ``masks``. + img_meta (dict): Image informtation. + + Returns: + tuple[Tensor]: A tuple containing the following for one image. + + - labels (Tensor): Labels of each image. \ + shape (num_queries, ). + - label_weights (Tensor): Label weights of each image. \ + shape (num_queries, ). + - mask_targets (Tensor): Mask targets of each image. \ + shape (num_queries, h, w). + - mask_weights (Tensor): Mask weights of each image. \ + shape (num_queries, ). + - pos_inds (Tensor): Sampled positive indices for each \ + image. + - neg_inds (Tensor): Sampled negative indices for each \ + image. + - sampling_result (:obj:`SamplingResult`): Sampling results. + """ + gt_labels = gt_instances.labels + gt_masks = gt_instances.masks + # sample points + num_queries = cls_score.shape[0] + num_gts = gt_labels.shape[0] + + point_coords = torch.rand((1, self.num_points, 2), + device=cls_score.device) + # shape (num_queries, num_points) + mask_points_pred = point_sample( + mask_pred.unsqueeze(1), point_coords.repeat(num_queries, 1, + 1)).squeeze(1) + # shape (num_gts, num_points) + gt_points_masks = point_sample( + gt_masks.unsqueeze(1).float(), point_coords.repeat(num_gts, 1, + 1)).squeeze(1) + + sampled_gt_instances = InstanceData( + labels=gt_labels, masks=gt_points_masks) + sampled_pred_instances = InstanceData( + scores=cls_score, masks=mask_points_pred) + # assign and sample + assign_result = self.assigner.assign( + pred_instances=sampled_pred_instances, + gt_instances=sampled_gt_instances, + img_meta=img_meta) + pred_instances = InstanceData(scores=cls_score, masks=mask_pred) + sampling_result = self.sampler.sample( + assign_result=assign_result, + pred_instances=pred_instances, + gt_instances=gt_instances) + pos_inds = sampling_result.pos_inds + neg_inds = sampling_result.neg_inds + + # label target + labels = gt_labels.new_full((self.num_queries, ), + self.num_classes, + dtype=torch.long) + labels[pos_inds] = gt_labels[sampling_result.pos_assigned_gt_inds] + label_weights = gt_labels.new_ones((self.num_queries, )) + + # mask target + mask_targets = gt_masks[sampling_result.pos_assigned_gt_inds] + mask_weights = mask_pred.new_zeros((self.num_queries, )) + mask_weights[pos_inds] = 1.0 + + return (labels, label_weights, mask_targets, mask_weights, pos_inds, + neg_inds, sampling_result) + + def _forward_head(self, decoder_out: Tensor, mask_feature: Tensor, + attn_mask_target_size: Tuple[int, int]) -> Tuple[Tensor]: + """Forward for head part which is called after every decoder layer. + + Args: + decoder_out (Tensor): in shape (batch_size, num_queries, c). + mask_feature (Tensor): in shape (batch_size, c, h, w). + attn_mask_target_size (tuple[int, int]): target attention + mask size. + + Returns: + tuple: A tuple contain three elements. + + - cls_pred (Tensor): Classification scores in shape \ + (batch_size, num_queries, cls_out_channels). \ + Note `cls_out_channels` should includes background. + - mask_pred (Tensor): Mask scores in shape \ + (batch_size, num_queries,h, w). + - attn_mask (Tensor): Attention mask in shape \ + (batch_size * num_heads, num_queries, h, w). + """ + + decoder_out = self.transformer_decoder.post_norm(decoder_out) + # shape (batch_size,num_queries, c) + cls_pred = self.cls_embed(decoder_out) + # shape (batch_size,num_queries, num_classes) + mask_embed = self.mask_embed(decoder_out) + # shape ( batch_size, num_queries, c) + mask_pred = torch.einsum('bqc,bchw->bqhw', mask_embed, mask_feature) + attn_mask = F.interpolate( + mask_pred, + attn_mask_target_size, + mode='bilinear', + align_corners=False) + # shape (num_queries, batch_size, h, w) -> + # (batch_size * num_head, num_queries, h, w) + attn_mask = attn_mask.flatten(2).unsqueeze(1).repeat( + (1, self.num_heads, 1, 1)).flatten(0, 1) + attn_mask = attn_mask.sigmoid() < 0.5 + attn_mask = attn_mask.detach() + + return cls_pred, mask_pred, attn_mask + + def forward(self, x: List[Tensor], + batch_data_samples: SampleList) -> Tuple[List[Tensor]]: + """Forward function. + + Args: + x (list[Tensor]): Multi scale Features from the + upstream network, each is a 4D-tensor. + batch_data_samples (List[:obj:`DetDataSample`]): The Data + Samples. It usually includes information such as + `gt_instance`, `gt_panoptic_seg` and `gt_sem_seg`. + + Returns: + tuple[list[Tensor]]: A tuple contains two elements. + + - cls_pred_list (list[Tensor)]: Classification logits \ + for each decoder layer. Each is a 3D-tensor with shape \ + (batch_size, num_queries, cls_out_channels). \ + Note `cls_out_channels` should includes background. + - mask_pred_list (list[Tensor]): Mask logits for each \ + decoder layer. Each with shape (batch_size, num_queries, \ + h, w). + """ + batch_size = x[0].shape[0] + + mask_features, multi_scale_memorys = self.pixel_decoder(x) + + + # add decoder for CB prediction + cb_feat, cb_multi_sclae_features = self.cbdecoder(x) + cb_pred = F.interpolate( + cb_feat, size=(448,448), mode='bilinear', align_corners=False) + + + decoder_inputs = [] + decoder_positional_encodings = [] + for i in range(self.num_transformer_feat_level): + decoder_input = self.decoder_input_projs[i](multi_scale_memorys[i]) + # shape (batch_size, c, h, w) -> (batch_size, h*w, c) + decoder_input = decoder_input.flatten(2).permute(0, 2, 1) + level_embed = self.level_embed.weight[i].view(1, 1, -1) + decoder_input = decoder_input + level_embed + # shape (batch_size, c, h, w) -> (batch_size, h*w, c) + + + cb_feat_align_channel = self.proj_cb[i](cb_multi_sclae_features[i]) + + cb_feat_align_channel = cb_feat_align_channel.flatten(2).permute(0, 2, 1) + + cb_cross_attn = self.cross_attn_cb(cb_feat_align_channel, decoder_input) + cb_cross_attn = cb_cross_attn + cb_feat_align_channel + cb_cross_attn = self.norm_cb(cb_cross_attn) + cb_attn, A = self.self_attn_cb(cb_cross_attn) + + cb_attn = cb_cross_attn + cb_attn + cb_attn = self.norm_cb(cb_attn) + decoder_input = decoder_input+cb_attn + + mask = decoder_input.new_zeros( + (batch_size, ) + multi_scale_memorys[i].shape[-2:], + dtype=torch.bool) + decoder_positional_encoding = self.decoder_positional_encoding(mask) + decoder_positional_encoding = decoder_positional_encoding.flatten( + 2).permute(0, 2, 1) + + decoder_inputs.append(decoder_input) + decoder_positional_encodings.append(decoder_positional_encoding) + + + + selected_q = select_top_k_features_from_regional_similarity(cb_multi_sclae_features[2], mask_features) + # Each item is [B, C, 1, 1]. squeeze() drops B when B==1 and breaks cat(dim=2). + _selected_q = [feat.reshape(feat.shape[0], feat.shape[1], 1) for feat in selected_q] + selected_q = torch.cat(_selected_q, dim=2) + selected_q = selected_q.permute(0, 2, 1) + + + query_feat = self.query_feat.weight.unsqueeze(0).repeat((batch_size, 1, 1)) + query_embed = self.query_embed.weight.unsqueeze(0).repeat((batch_size, 1, 1)) + query_feat = query_feat + selected_q + + cls_pred_list = [] + mask_pred_list = [] + cls_pred, mask_pred, attn_mask = self._forward_head( + query_feat, mask_features, multi_scale_memorys[0].shape[-2:]) + cls_pred_list.append(cls_pred) + mask_pred_list.append(mask_pred) + + for i in range(self.num_transformer_decoder_layers): + level_idx = i % self.num_transformer_feat_level + # if a mask is all True(all background), then set it all False. + mask_sum = (attn_mask.sum(-1) != attn_mask.shape[-1]).unsqueeze(-1) + attn_mask = attn_mask & mask_sum + # cross_attn + self_attn + layer = self.transformer_decoder.layers[i] + query_feat = layer( + query=query_feat, + key=decoder_inputs[level_idx], + value=decoder_inputs[level_idx], + query_pos=query_embed, + key_pos=decoder_positional_encodings[level_idx], + cross_attn_mask=attn_mask, + query_key_padding_mask=None, + # here we do not apply masking on padded region + key_padding_mask=None) + + cls_pred, mask_pred, attn_mask = self._forward_head( + query_feat, mask_features, multi_scale_memorys[(i + 1) % self.num_transformer_feat_level].shape[-2:]) + + + + cls_pred_list.append(cls_pred) + mask_pred_list.append(mask_pred) + + return cls_pred_list, mask_pred_list, cb_pred + + def predict(self, x: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tuple[Tensor]: + """Test without augmentaton. + + Args: + x (tuple[Tensor]): Multi-level features from the + upstream network, each is a 4D-tensor. + batch_img_metas (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + test_cfg (ConfigType): Test config. + + Returns: + Tensor: A tensor of segmentation mask. + """ + batch_data_samples = [ + SegDataSample(metainfo=metainfo) for metainfo in batch_img_metas + ] + + all_cls_scores, all_mask_preds, _ = self.forward(x, batch_data_samples) + mask_cls_results = all_cls_scores[-1] + mask_pred_results = all_mask_preds[-1] + if 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'] + else: + size = batch_img_metas[0]['img_shape'] + # upsample mask + mask_pred_results = F.interpolate( + mask_pred_results, size=size, mode='bilinear', align_corners=False) + cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1] + mask_pred = mask_pred_results.sigmoid() + seg_logits = torch.einsum('bqc, bqhw->bchw', cls_score, mask_pred) + return seg_logits diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/isa_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/isa_head.py new file mode 100644 index 0000000000000000000000000000000000000000..355f215f39007d0153c2fdb3b22a40e7f11a01e3 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/isa_head.py @@ -0,0 +1,143 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math + +import torch +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import SelfAttentionBlock as _SelfAttentionBlock +from .decode_head import BaseDecodeHead + + +class SelfAttentionBlock(_SelfAttentionBlock): + """Self-Attention Module. + + Args: + in_channels (int): Input channels of key/query feature. + channels (int): Output channels of key/query transform. + conv_cfg (dict | None): Config of conv layers. + norm_cfg (dict | None): Config of norm layers. + act_cfg (dict | None): Config of activation layers. + """ + + def __init__(self, in_channels, channels, conv_cfg, norm_cfg, act_cfg): + super().__init__( + key_in_channels=in_channels, + query_in_channels=in_channels, + channels=channels, + out_channels=in_channels, + share_key_query=False, + query_downsample=None, + key_downsample=None, + key_query_num_convs=2, + key_query_norm=True, + value_out_num_convs=1, + value_out_norm=False, + matmul_norm=True, + with_out=False, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + self.output_project = self.build_project( + in_channels, + in_channels, + num_convs=1, + use_conv_module=True, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, x): + """Forward function.""" + context = super().forward(x, x) + return self.output_project(context) + + +@MODELS.register_module() +class ISAHead(BaseDecodeHead): + """Interlaced Sparse Self-Attention for Semantic Segmentation. + + This head is the implementation of `ISA + `_. + + Args: + isa_channels (int): The channels of ISA Module. + down_factor (tuple[int]): The local group size of ISA. + """ + + def __init__(self, isa_channels, down_factor=(8, 8), **kwargs): + super().__init__(**kwargs) + self.down_factor = down_factor + + self.in_conv = ConvModule( + self.in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.global_relation = SelfAttentionBlock( + self.channels, + isa_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.local_relation = SelfAttentionBlock( + self.channels, + isa_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.out_conv = ConvModule( + self.channels * 2, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x_ = self._transform_inputs(inputs) + x = self.in_conv(x_) + residual = x + + n, c, h, w = x.size() + loc_h, loc_w = self.down_factor # size of local group in H- and W-axes + glb_h, glb_w = math.ceil(h / loc_h), math.ceil(w / loc_w) + pad_h, pad_w = glb_h * loc_h - h, glb_w * loc_w - w + if pad_h > 0 or pad_w > 0: # pad if the size is not divisible + padding = (pad_w // 2, pad_w - pad_w // 2, pad_h // 2, + pad_h - pad_h // 2) + x = F.pad(x, padding) + + # global relation + x = x.view(n, c, glb_h, loc_h, glb_w, loc_w) + # do permutation to gather global group + x = x.permute(0, 3, 5, 1, 2, 4) # (n, loc_h, loc_w, c, glb_h, glb_w) + x = x.reshape(-1, c, glb_h, glb_w) + # apply attention within each global group + x = self.global_relation(x) # (n * loc_h * loc_w, c, glb_h, glb_w) + + # local relation + x = x.view(n, loc_h, loc_w, c, glb_h, glb_w) + # do permutation to gather local group + x = x.permute(0, 4, 5, 3, 1, 2) # (n, glb_h, glb_w, c, loc_h, loc_w) + x = x.reshape(-1, c, loc_h, loc_w) + # apply attention within each local group + x = self.local_relation(x) # (n * glb_h * glb_w, c, loc_h, loc_w) + + # permute each pixel back to its original position + x = x.view(n, glb_h, glb_w, c, loc_h, loc_w) + x = x.permute(0, 3, 1, 4, 2, 5) # (n, c, glb_h, loc_h, glb_w, loc_w) + x = x.reshape(n, c, glb_h * loc_h, glb_w * loc_w) + if pad_h > 0 or pad_w > 0: # remove padding + x = x[:, :, pad_h // 2:pad_h // 2 + h, pad_w // 2:pad_w // 2 + w] + + x = self.out_conv(torch.cat([x, residual], dim=1)) + out = self.cls_seg(x) + + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/knet_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/knet_head.py new file mode 100644 index 0000000000000000000000000000000000000000..82d3a2807685cdc896c881095f46fd50a450018e --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/knet_head.py @@ -0,0 +1,461 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer +from mmcv.cnn.bricks.transformer import (FFN, MultiheadAttention, + build_transformer_layer) +from mmengine.logging import print_log +from torch import Tensor + +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.registry import MODELS +from mmseg.utils import SampleList + + +@MODELS.register_module() +class KernelUpdator(nn.Module): + """Dynamic Kernel Updator in Kernel Update Head. + + Args: + in_channels (int): The number of channels of input feature map. + Default: 256. + feat_channels (int): The number of middle-stage channels in + the kernel updator. Default: 64. + out_channels (int): The number of output channels. + gate_sigmoid (bool): Whether use sigmoid function in gate + mechanism. Default: True. + gate_norm_act (bool): Whether add normalization and activation + layer in gate mechanism. Default: False. + activate_out: Whether add activation after gate mechanism. + Default: False. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='LN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + """ + + def __init__( + self, + in_channels=256, + feat_channels=64, + out_channels=None, + gate_sigmoid=True, + gate_norm_act=False, + activate_out=False, + norm_cfg=dict(type='LN'), + act_cfg=dict(type='ReLU', inplace=True), + ): + super().__init__() + self.in_channels = in_channels + self.feat_channels = feat_channels + self.out_channels_raw = out_channels + self.gate_sigmoid = gate_sigmoid + self.gate_norm_act = gate_norm_act + self.activate_out = activate_out + self.act_cfg = act_cfg + self.norm_cfg = norm_cfg + self.out_channels = out_channels if out_channels else in_channels + + self.num_params_in = self.feat_channels + self.num_params_out = self.feat_channels + self.dynamic_layer = nn.Linear( + self.in_channels, self.num_params_in + self.num_params_out) + self.input_layer = nn.Linear(self.in_channels, + self.num_params_in + self.num_params_out, + 1) + self.input_gate = nn.Linear(self.in_channels, self.feat_channels, 1) + self.update_gate = nn.Linear(self.in_channels, self.feat_channels, 1) + if self.gate_norm_act: + self.gate_norm = build_norm_layer(norm_cfg, self.feat_channels)[1] + + self.norm_in = build_norm_layer(norm_cfg, self.feat_channels)[1] + self.norm_out = build_norm_layer(norm_cfg, self.feat_channels)[1] + self.input_norm_in = build_norm_layer(norm_cfg, self.feat_channels)[1] + self.input_norm_out = build_norm_layer(norm_cfg, self.feat_channels)[1] + + self.activation = build_activation_layer(act_cfg) + + self.fc_layer = nn.Linear(self.feat_channels, self.out_channels, 1) + self.fc_norm = build_norm_layer(norm_cfg, self.out_channels)[1] + + def forward(self, update_feature, input_feature): + """Forward function of KernelUpdator. + + Args: + update_feature (torch.Tensor): Feature map assembled from + each group. It would be reshaped with last dimension + shape: `self.in_channels`. + input_feature (torch.Tensor): Intermediate feature + with shape: (N, num_classes, conv_kernel_size**2, channels). + Returns: + Tensor: The output tensor of shape (N*C1/C2, K*K, C2), where N is + the number of classes, C1 and C2 are the feature map channels of + KernelUpdateHead and KernelUpdator, respectively. + """ + + update_feature = update_feature.reshape(-1, self.in_channels) + num_proposals = update_feature.size(0) + # dynamic_layer works for + # phi_1 and psi_3 in Eq.(4) and (5) of K-Net paper + parameters = self.dynamic_layer(update_feature) + param_in = parameters[:, :self.num_params_in].view( + -1, self.feat_channels) + param_out = parameters[:, -self.num_params_out:].view( + -1, self.feat_channels) + + # input_layer works for + # phi_2 and psi_4 in Eq.(4) and (5) of K-Net paper + input_feats = self.input_layer( + input_feature.reshape(num_proposals, -1, self.feat_channels)) + input_in = input_feats[..., :self.num_params_in] + input_out = input_feats[..., -self.num_params_out:] + + # `gate_feats` is F^G in K-Net paper + gate_feats = input_in * param_in.unsqueeze(-2) + if self.gate_norm_act: + gate_feats = self.activation(self.gate_norm(gate_feats)) + + input_gate = self.input_norm_in(self.input_gate(gate_feats)) + update_gate = self.norm_in(self.update_gate(gate_feats)) + if self.gate_sigmoid: + input_gate = input_gate.sigmoid() + update_gate = update_gate.sigmoid() + param_out = self.norm_out(param_out) + input_out = self.input_norm_out(input_out) + + if self.activate_out: + param_out = self.activation(param_out) + input_out = self.activation(input_out) + + # Gate mechanism. Eq.(5) in original paper. + # param_out has shape (batch_size, feat_channels, out_channels) + features = update_gate * param_out.unsqueeze( + -2) + input_gate * input_out + + features = self.fc_layer(features) + features = self.fc_norm(features) + features = self.activation(features) + + return features + + +@MODELS.register_module() +class KernelUpdateHead(nn.Module): + """Kernel Update Head in K-Net. + + Args: + num_classes (int): Number of classes. Default: 150. + num_ffn_fcs (int): The number of fully-connected layers in + FFNs. Default: 2. + num_heads (int): The number of parallel attention heads. + Default: 8. + num_mask_fcs (int): The number of fully connected layers for + mask prediction. Default: 3. + feedforward_channels (int): The hidden dimension of FFNs. + Defaults: 2048. + in_channels (int): The number of channels of input feature map. + Default: 256. + out_channels (int): The number of output channels. + Default: 256. + dropout (float): The Probability of an element to be + zeroed in MultiheadAttention and FFN. Default 0.0. + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + ffn_act_cfg (dict): Config of activation layers in FFN. + Default: dict(type='ReLU'). + conv_kernel_size (int): The kernel size of convolution in + Kernel Update Head for dynamic kernel updation. + Default: 1. + feat_transform_cfg (dict | None): Config of feature transform. + Default: None. + kernel_init (bool): Whether initiate mask kernel in mask head. + Default: False. + with_ffn (bool): Whether add FFN in kernel update head. + Default: True. + feat_gather_stride (int): Stride of convolution in feature transform. + Default: 1. + mask_transform_stride (int): Stride of mask transform. + Default: 1. + kernel_updator_cfg (dict): Config of kernel updator. + Default: dict( + type='DynamicConv', + in_channels=256, + feat_channels=64, + out_channels=256, + act_cfg=dict(type='ReLU', inplace=True), + norm_cfg=dict(type='LN')). + """ + + def __init__(self, + num_classes=150, + num_ffn_fcs=2, + num_heads=8, + num_mask_fcs=3, + feedforward_channels=2048, + in_channels=256, + out_channels=256, + dropout=0.0, + act_cfg=dict(type='ReLU', inplace=True), + ffn_act_cfg=dict(type='ReLU', inplace=True), + conv_kernel_size=1, + feat_transform_cfg=None, + kernel_init=False, + with_ffn=True, + feat_gather_stride=1, + mask_transform_stride=1, + kernel_updator_cfg=dict( + type='DynamicConv', + in_channels=256, + feat_channels=64, + out_channels=256, + act_cfg=dict(type='ReLU', inplace=True), + norm_cfg=dict(type='LN'))): + super().__init__() + self.num_classes = num_classes + self.in_channels = in_channels + self.out_channels = out_channels + self.fp16_enabled = False + self.dropout = dropout + self.num_heads = num_heads + self.kernel_init = kernel_init + self.with_ffn = with_ffn + self.conv_kernel_size = conv_kernel_size + self.feat_gather_stride = feat_gather_stride + self.mask_transform_stride = mask_transform_stride + + self.attention = MultiheadAttention(in_channels * conv_kernel_size**2, + num_heads, dropout) + self.attention_norm = build_norm_layer( + dict(type='LN'), in_channels * conv_kernel_size**2)[1] + self.kernel_update_conv = build_transformer_layer(kernel_updator_cfg) + + if feat_transform_cfg is not None: + kernel_size = feat_transform_cfg.pop('kernel_size', 1) + transform_channels = in_channels + self.feat_transform = ConvModule( + transform_channels, + in_channels, + kernel_size, + stride=feat_gather_stride, + padding=int(feat_gather_stride // 2), + **feat_transform_cfg) + else: + self.feat_transform = None + + if self.with_ffn: + self.ffn = FFN( + in_channels, + feedforward_channels, + num_ffn_fcs, + act_cfg=ffn_act_cfg, + dropout=dropout) + self.ffn_norm = build_norm_layer(dict(type='LN'), in_channels)[1] + + self.mask_fcs = nn.ModuleList() + for _ in range(num_mask_fcs): + self.mask_fcs.append( + nn.Linear(in_channels, in_channels, bias=False)) + self.mask_fcs.append( + build_norm_layer(dict(type='LN'), in_channels)[1]) + self.mask_fcs.append(build_activation_layer(act_cfg)) + + self.fc_mask = nn.Linear(in_channels, out_channels) + + def init_weights(self): + """Use xavier initialization for all weight parameter and set + classification head bias as a specific value when use focal loss.""" + for p in self.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + else: + # adopt the default initialization for + # the weight and bias of the layer norm + pass + if self.kernel_init: + print_log( + 'mask kernel in mask head is normal initialized by std 0.01') + nn.init.normal_(self.fc_mask.weight, mean=0, std=0.01) + + def forward(self, x, proposal_feat, mask_preds, mask_shape=None): + """Forward function of Dynamic Instance Interactive Head. + + Args: + x (Tensor): Feature map from FPN with shape + (batch_size, feature_dimensions, H , W). + proposal_feat (Tensor): Intermediate feature get from + diihead in last stage, has shape + (batch_size, num_proposals, feature_dimensions) + mask_preds (Tensor): mask prediction from the former stage in shape + (batch_size, num_proposals, H, W). + + Returns: + Tuple: The first tensor is predicted mask with shape + (N, num_classes, H, W), the second tensor is dynamic kernel + with shape (N, num_classes, channels, K, K). + """ + N, num_proposals = proposal_feat.shape[:2] + if self.feat_transform is not None: + x = self.feat_transform(x) + + C, H, W = x.shape[-3:] + + mask_h, mask_w = mask_preds.shape[-2:] + if mask_h != H or mask_w != W: + gather_mask = F.interpolate( + mask_preds, (H, W), align_corners=False, mode='bilinear') + else: + gather_mask = mask_preds + + sigmoid_masks = gather_mask.softmax(dim=1) + + # Group Feature Assembling. Eq.(3) in original paper. + # einsum is faster than bmm by 30% + x_feat = torch.einsum('bnhw,bchw->bnc', sigmoid_masks, x) + + # obj_feat in shape [B, N, C, K, K] -> [B, N, C, K*K] -> [B, N, K*K, C] + proposal_feat = proposal_feat.reshape(N, num_proposals, + self.in_channels, + -1).permute(0, 1, 3, 2) + obj_feat = self.kernel_update_conv(x_feat, proposal_feat) + + # [B, N, K*K, C] -> [B, N, K*K*C] -> [N, B, K*K*C] + obj_feat = obj_feat.reshape(N, num_proposals, -1).permute(1, 0, 2) + obj_feat = self.attention_norm(self.attention(obj_feat)) + # [N, B, K*K*C] -> [B, N, K*K*C] + obj_feat = obj_feat.permute(1, 0, 2) + + # obj_feat in shape [B, N, K*K*C] -> [B, N, K*K, C] + obj_feat = obj_feat.reshape(N, num_proposals, -1, self.in_channels) + + # FFN + if self.with_ffn: + obj_feat = self.ffn_norm(self.ffn(obj_feat)) + + mask_feat = obj_feat + + for reg_layer in self.mask_fcs: + mask_feat = reg_layer(mask_feat) + + # [B, N, K*K, C] -> [B, N, C, K*K] + mask_feat = self.fc_mask(mask_feat).permute(0, 1, 3, 2) + + if (self.mask_transform_stride == 2 and self.feat_gather_stride == 1): + mask_x = F.interpolate( + x, scale_factor=0.5, mode='bilinear', align_corners=False) + H, W = mask_x.shape[-2:] + else: + mask_x = x + # group conv is 5x faster than unfold and uses about 1/5 memory + # Group conv vs. unfold vs. concat batch, 2.9ms :13.5ms :3.8ms + # Group conv vs. unfold vs. concat batch, 278 : 1420 : 369 + # but in real training group conv is slower than concat batch + # so we keep using concat batch. + # fold_x = F.unfold( + # mask_x, + # self.conv_kernel_size, + # padding=int(self.conv_kernel_size // 2)) + # mask_feat = mask_feat.reshape(N, num_proposals, -1) + # new_mask_preds = torch.einsum('bnc,bcl->bnl', mask_feat, fold_x) + # [B, N, C, K*K] -> [B*N, C, K, K] + mask_feat = mask_feat.reshape(N, num_proposals, C, + self.conv_kernel_size, + self.conv_kernel_size) + # [B, C, H, W] -> [1, B*C, H, W] + new_mask_preds = [] + for i in range(N): + new_mask_preds.append( + F.conv2d( + mask_x[i:i + 1], + mask_feat[i], + padding=int(self.conv_kernel_size // 2))) + + new_mask_preds = torch.cat(new_mask_preds, dim=0) + new_mask_preds = new_mask_preds.reshape(N, num_proposals, H, W) + if self.mask_transform_stride == 2: + new_mask_preds = F.interpolate( + new_mask_preds, + scale_factor=2, + mode='bilinear', + align_corners=False) + + if mask_shape is not None and mask_shape[0] != H: + new_mask_preds = F.interpolate( + new_mask_preds, + mask_shape, + align_corners=False, + mode='bilinear') + + return new_mask_preds, obj_feat.permute(0, 1, 3, 2).reshape( + N, num_proposals, self.in_channels, self.conv_kernel_size, + self.conv_kernel_size) + + +@MODELS.register_module() +class IterativeDecodeHead(BaseDecodeHead): + """K-Net: Towards Unified Image Segmentation. + + This head is the implementation of + `K-Net: `_. + + Args: + num_stages (int): The number of stages (kernel update heads) + in IterativeDecodeHead. Default: 3. + kernel_generate_head:(dict): Config of kernel generate head which + generate mask predictions, dynamic kernels and class predictions + for next kernel update heads. + kernel_update_head (dict): Config of kernel update head which refine + dynamic kernels and class predictions iteratively. + + """ + + def __init__(self, num_stages, kernel_generate_head, kernel_update_head, + **kwargs): + # ``IterativeDecodeHead`` would skip initialization of + # ``BaseDecodeHead`` which would be called when building + # ``self.kernel_generate_head``. + super(BaseDecodeHead, self).__init__(**kwargs) + assert num_stages == len(kernel_update_head) + self.num_stages = num_stages + self.kernel_generate_head = MODELS.build(kernel_generate_head) + self.kernel_update_head = nn.ModuleList() + self.align_corners = self.kernel_generate_head.align_corners + self.num_classes = self.kernel_generate_head.num_classes + self.input_transform = self.kernel_generate_head.input_transform + self.ignore_index = self.kernel_generate_head.ignore_index + self.out_channels = self.num_classes + + for head_cfg in kernel_update_head: + self.kernel_update_head.append(MODELS.build(head_cfg)) + + def forward(self, inputs): + """Forward function.""" + feats = self.kernel_generate_head._forward_feature(inputs) + sem_seg = self.kernel_generate_head.cls_seg(feats) + seg_kernels = self.kernel_generate_head.conv_seg.weight.clone() + seg_kernels = seg_kernels[None].expand( + feats.size(0), *seg_kernels.size()) + + stage_segs = [sem_seg] + for i in range(self.num_stages): + sem_seg, seg_kernels = self.kernel_update_head[i](feats, + seg_kernels, + sem_seg) + stage_segs.append(sem_seg) + if self.training: + return stage_segs + # only return the prediction of the last stage during testing + return stage_segs[-1] + + def loss_by_feat(self, seg_logits: List[Tensor], + batch_data_samples: SampleList, **kwargs) -> dict: + losses = dict() + for i, logit in enumerate(seg_logits): + loss = self.kernel_generate_head.loss_by_feat( + logit, batch_data_samples) + for k, v in loss.items(): + losses[f'{k}.s{i}'] = v + + return losses diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/lraspp_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/lraspp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..ba2465f27522e6ff106fcdf94a46aab42881260a --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/lraspp_head.py @@ -0,0 +1,91 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.utils import is_tuple_of + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class LRASPPHead(BaseDecodeHead): + """Lite R-ASPP (LRASPP) head is proposed in Searching for MobileNetV3. + + This head is the improved implementation of `Searching for MobileNetV3 + `_. + + Args: + branch_channels (tuple[int]): The number of output channels in every + each branch. Default: (32, 64). + """ + + def __init__(self, branch_channels=(32, 64), **kwargs): + super().__init__(**kwargs) + if self.input_transform != 'multiple_select': + raise ValueError('in Lite R-ASPP (LRASPP) head, input_transform ' + f'must be \'multiple_select\'. But received ' + f'\'{self.input_transform}\'') + assert is_tuple_of(branch_channels, int) + assert len(branch_channels) == len(self.in_channels) - 1 + self.branch_channels = branch_channels + + self.convs = nn.Sequential() + self.conv_ups = nn.Sequential() + for i in range(len(branch_channels)): + self.convs.add_module( + f'conv{i}', + nn.Conv2d( + self.in_channels[i], branch_channels[i], 1, bias=False)) + self.conv_ups.add_module( + f'conv_up{i}', + ConvModule( + self.channels + branch_channels[i], + self.channels, + 1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + bias=False)) + + self.conv_up_input = nn.Conv2d(self.channels, self.channels, 1) + + self.aspp_conv = ConvModule( + self.in_channels[-1], + self.channels, + 1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + bias=False) + self.image_pool = nn.Sequential( + nn.AvgPool2d(kernel_size=49, stride=(16, 20)), + ConvModule( + self.in_channels[2], + self.channels, + 1, + act_cfg=dict(type='Sigmoid'), + bias=False)) + + def forward(self, inputs): + """Forward function.""" + inputs = self._transform_inputs(inputs) + + x = inputs[-1] + + x = self.aspp_conv(x) * resize( + self.image_pool(x), + size=x.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + x = self.conv_up_input(x) + + for i in range(len(self.branch_channels) - 1, -1, -1): + x = resize( + x, + size=inputs[i].size()[2:], + mode='bilinear', + align_corners=self.align_corners) + x = torch.cat([x, self.convs[i](inputs[i])], 1) + x = self.conv_ups[i](x) + + return self.cls_seg(x) diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/mask2former_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/mask2former_head.py new file mode 100644 index 0000000000000000000000000000000000000000..0135af0645830f5cf98595318c4bb20220e64b0b --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/mask2former_head.py @@ -0,0 +1,163 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.model import BaseModule + +try: + from mmdet.models.dense_heads import \ + Mask2FormerHead as MMDET_Mask2FormerHead +except ModuleNotFoundError: + MMDET_Mask2FormerHead = BaseModule + +from mmengine.structures import InstanceData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures.seg_data_sample import SegDataSample +from mmseg.utils import ConfigType, SampleList + + +@MODELS.register_module() +class Mask2FormerHead(MMDET_Mask2FormerHead): + """Implements the Mask2Former head. + + See `Mask2Former: Masked-attention Mask Transformer for Universal Image + Segmentation `_ for details. + + Args: + num_classes (int): Number of classes. Default: 150. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + ignore_index (int): The label index to be ignored. Default: 255. + """ + + def __init__(self, + num_classes, + align_corners=False, + ignore_index=255, + **kwargs): + super().__init__(**kwargs) + + self.num_classes = num_classes + self.align_corners = align_corners + self.out_channels = num_classes + self.ignore_index = ignore_index + + feat_channels = kwargs['feat_channels'] + self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1) + + def _seg_data_to_instance_data(self, batch_data_samples: SampleList): + """Perform forward propagation to convert paradigm from MMSegmentation + to MMDetection to ensure ``MMDET_Mask2FormerHead`` could be called + normally. Specifically, ``batch_gt_instances`` would be added. + + Args: + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + + Returns: + tuple[Tensor]: A tuple contains two lists. + + - batch_gt_instances (list[:obj:`InstanceData`]): Batch of + gt_instance. It usually includes ``labels``, each is + unique ground truth label id of images, with + shape (num_gt, ) and ``masks``, each is ground truth + masks of each instances of a image, shape (num_gt, h, w). + - batch_img_metas (list[dict]): List of image meta information. + """ + batch_img_metas = [] + batch_gt_instances = [] + + for data_sample in batch_data_samples: + batch_img_metas.append(data_sample.metainfo) + gt_sem_seg = data_sample.gt_sem_seg.data + classes = torch.unique( + gt_sem_seg, + sorted=False, + return_inverse=False, + return_counts=False) + + # remove ignored region + gt_labels = classes[classes != self.ignore_index] + + masks = [] + for class_id in gt_labels: + masks.append(gt_sem_seg == class_id) + + if len(masks) == 0: + gt_masks = torch.zeros( + (0, gt_sem_seg.shape[-2], + gt_sem_seg.shape[-1])).to(gt_sem_seg).long() + else: + gt_masks = torch.stack(masks).squeeze(1).long() + + instance_data = InstanceData(labels=gt_labels, masks=gt_masks) + batch_gt_instances.append(instance_data) + return batch_gt_instances, batch_img_metas + + def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + """Perform forward propagation and loss calculation of the decoder head + on the features of the upstream network. + + Args: + x (tuple[Tensor]): Multi-level features from the upstream + network, each is a 4D-tensor. + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + train_cfg (ConfigType): Training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components. + """ + # batch SegDataSample to InstanceDataSample + batch_gt_instances, batch_img_metas = self._seg_data_to_instance_data( + batch_data_samples) + + # forward + all_cls_scores, all_mask_preds = self(x, batch_data_samples) + + # loss + losses = self.loss_by_feat(all_cls_scores, all_mask_preds, + batch_gt_instances, batch_img_metas) + + return losses + + def predict(self, x: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tuple[Tensor]: + """Test without augmentaton. + + Args: + x (tuple[Tensor]): Multi-level features from the + upstream network, each is a 4D-tensor. + batch_img_metas (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + test_cfg (ConfigType): Test config. + + Returns: + Tensor: A tensor of segmentation mask. + """ + batch_data_samples = [ + SegDataSample(metainfo=metainfo) for metainfo in batch_img_metas + ] + + all_cls_scores, all_mask_preds = self(x, batch_data_samples) + mask_cls_results = all_cls_scores[-1] + mask_pred_results = all_mask_preds[-1] + if 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'] + else: + size = batch_img_metas[0]['img_shape'] + # upsample mask + mask_pred_results = F.interpolate( + mask_pred_results, size=size, mode='bilinear', align_corners=False) + cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1] + mask_pred = mask_pred_results.sigmoid() + seg_logits = torch.einsum('bqc, bqhw->bchw', cls_score, mask_pred) + return seg_logits diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/maskformer_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/maskformer_head.py new file mode 100644 index 0000000000000000000000000000000000000000..6e61a7f63a33a508955a866e57c139ce8c40e0f6 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/maskformer_head.py @@ -0,0 +1,174 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.model import BaseModule + +try: + from mmdet.models.dense_heads import MaskFormerHead as MMDET_MaskFormerHead +except ModuleNotFoundError: + MMDET_MaskFormerHead = BaseModule + +from mmengine.structures import InstanceData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures.seg_data_sample import SegDataSample +from mmseg.utils import ConfigType, SampleList + + +@MODELS.register_module() +class MaskFormerHead(MMDET_MaskFormerHead): + """Implements the MaskFormer head. + + See `Per-Pixel Classification is Not All You Need for Semantic Segmentation + `_ for details. + + Args: + num_classes (int): Number of classes. Default: 150. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + ignore_index (int): The label index to be ignored. Default: 255. + """ + + def __init__(self, + num_classes: int = 150, + align_corners: bool = False, + ignore_index: int = 255, + **kwargs) -> None: + super().__init__(**kwargs) + + self.out_channels = kwargs['out_channels'] + self.align_corners = True + self.num_classes = num_classes + self.align_corners = align_corners + self.out_channels = num_classes + self.ignore_index = ignore_index + + feat_channels = kwargs['feat_channels'] + self.cls_embed = nn.Linear(feat_channels, self.num_classes + 1) + + def _seg_data_to_instance_data(self, batch_data_samples: SampleList): + """Perform forward propagation to convert paradigm from MMSegmentation + to MMDetection to ensure ``MMDET_MaskFormerHead`` could be called + normally. Specifically, ``batch_gt_instances`` would be added. + + Args: + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + + Returns: + tuple[Tensor]: A tuple contains two lists. + + - batch_gt_instances (list[:obj:`InstanceData`]): Batch of + gt_instance. It usually includes ``labels``, each is + unique ground truth label id of images, with + shape (num_gt, ) and ``masks``, each is ground truth + masks of each instances of a image, shape (num_gt, h, w). + - batch_img_metas (list[dict]): List of image meta information. + """ + batch_img_metas = [] + batch_gt_instances = [] + for data_sample in batch_data_samples: + # Add `batch_input_shape` in metainfo of data_sample, which would + # be used in MaskFormerHead of MMDetection. + metainfo = data_sample.metainfo + metainfo['batch_input_shape'] = metainfo['img_shape'] + data_sample.set_metainfo(metainfo) + batch_img_metas.append(data_sample.metainfo) + gt_sem_seg = data_sample.gt_sem_seg.data + classes = torch.unique( + gt_sem_seg, + sorted=False, + return_inverse=False, + return_counts=False) + + # remove ignored region + gt_labels = classes[classes != self.ignore_index] + + masks = [] + for class_id in gt_labels: + masks.append(gt_sem_seg == class_id) + + if len(masks) == 0: + gt_masks = torch.zeros((0, gt_sem_seg.shape[-2], + gt_sem_seg.shape[-1])).to(gt_sem_seg) + else: + gt_masks = torch.stack(masks).squeeze(1) + + instance_data = InstanceData( + labels=gt_labels, masks=gt_masks.long()) + batch_gt_instances.append(instance_data) + return batch_gt_instances, batch_img_metas + + def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + """Perform forward propagation and loss calculation of the decoder head + on the features of the upstream network. + + Args: + x (tuple[Tensor]): Multi-level features from the upstream + network, each is a 4D-tensor. + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + train_cfg (ConfigType): Training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components. + """ + # batch SegDataSample to InstanceDataSample + batch_gt_instances, batch_img_metas = self._seg_data_to_instance_data( + batch_data_samples) + + # forward + all_cls_scores, all_mask_preds = self(x, batch_data_samples) + + # loss + losses = self.loss_by_feat(all_cls_scores, all_mask_preds, + batch_gt_instances, batch_img_metas) + + return losses + + def predict(self, x: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tuple[Tensor]: + """Test without augmentaton. + + Args: + x (tuple[Tensor]): Multi-level features from the + upstream network, each is a 4D-tensor. + batch_img_metas (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + test_cfg (ConfigType): Test config. + + Returns: + Tensor: A tensor of segmentation mask. + """ + + batch_data_samples = [] + for metainfo in batch_img_metas: + metainfo['batch_input_shape'] = metainfo['img_shape'] + batch_data_samples.append(SegDataSample(metainfo=metainfo)) + # Forward function of MaskFormerHead from MMDetection needs + # 'batch_data_samples' as inputs, which is image shape actually. + all_cls_scores, all_mask_preds = self(x, batch_data_samples) + mask_cls_results = all_cls_scores[-1] + mask_pred_results = all_mask_preds[-1] + + # upsample masks + img_shape = batch_img_metas[0]['batch_input_shape'] + mask_pred_results = F.interpolate( + mask_pred_results, + size=img_shape, + mode='bilinear', + align_corners=False) + + # semantic inference + cls_score = F.softmax(mask_cls_results, dim=-1)[..., :-1] + mask_pred = mask_pred_results.sigmoid() + seg_logits = torch.einsum('bqc,bqhw->bchw', cls_score, mask_pred) + return seg_logits diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/nl_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/nl_head.py new file mode 100644 index 0000000000000000000000000000000000000000..0ffcc2a2f081127f109deb0ad5bd1be0d6f50493 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/nl_head.py @@ -0,0 +1,50 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.cnn import NonLocal2d + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + + +@MODELS.register_module() +class NLHead(FCNHead): + """Non-local Neural Networks. + + This head is the implementation of `NLNet + `_. + + Args: + reduction (int): Reduction factor of projection transform. Default: 2. + use_scale (bool): Whether to scale pairwise_weight by + sqrt(1/inter_channels). Default: True. + mode (str): The nonlocal mode. Options are 'embedded_gaussian', + 'dot_product'. Default: 'embedded_gaussian.'. + """ + + def __init__(self, + reduction=2, + use_scale=True, + mode='embedded_gaussian', + **kwargs): + super().__init__(num_convs=2, **kwargs) + self.reduction = reduction + self.use_scale = use_scale + self.mode = mode + self.nl_block = NonLocal2d( + in_channels=self.channels, + reduction=self.reduction, + use_scale=self.use_scale, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + mode=self.mode) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + output = self.convs[0](x) + output = self.nl_block(output) + output = self.convs[1](output) + if self.concat_input: + output = self.conv_cat(torch.cat([x, output], dim=1)) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ocr_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ocr_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9afe37bebd6c16ff184dc482ae358eb7ae9a093a --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/ocr_head.py @@ -0,0 +1,127 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import SelfAttentionBlock as _SelfAttentionBlock +from ..utils import resize +from .cascade_decode_head import BaseCascadeDecodeHead + + +class SpatialGatherModule(nn.Module): + """Aggregate the context features according to the initial predicted + probability distribution. + + Employ the soft-weighted method to aggregate the context. + """ + + def __init__(self, scale): + super().__init__() + self.scale = scale + + def forward(self, feats, probs): + """Forward function.""" + batch_size, num_classes, height, width = probs.size() + channels = feats.size(1) + probs = probs.view(batch_size, num_classes, -1) + feats = feats.view(batch_size, channels, -1) + # [batch_size, height*width, num_classes] + feats = feats.permute(0, 2, 1) + # [batch_size, channels, height*width] + probs = F.softmax(self.scale * probs, dim=2) + # [batch_size, channels, num_classes] + ocr_context = torch.matmul(probs, feats) + ocr_context = ocr_context.permute(0, 2, 1).contiguous().unsqueeze(3) + return ocr_context + + +class ObjectAttentionBlock(_SelfAttentionBlock): + """Make a OCR used SelfAttentionBlock.""" + + def __init__(self, in_channels, channels, scale, conv_cfg, norm_cfg, + act_cfg): + if scale > 1: + query_downsample = nn.MaxPool2d(kernel_size=scale) + else: + query_downsample = None + super().__init__( + key_in_channels=in_channels, + query_in_channels=in_channels, + channels=channels, + out_channels=in_channels, + share_key_query=False, + query_downsample=query_downsample, + key_downsample=None, + key_query_num_convs=2, + key_query_norm=True, + value_out_num_convs=1, + value_out_norm=True, + matmul_norm=True, + with_out=True, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.bottleneck = ConvModule( + in_channels * 2, + in_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, query_feats, key_feats): + """Forward function.""" + context = super().forward(query_feats, key_feats) + output = self.bottleneck(torch.cat([context, query_feats], dim=1)) + if self.query_downsample is not None: + output = resize(query_feats) + + return output + + +@MODELS.register_module() +class OCRHead(BaseCascadeDecodeHead): + """Object-Contextual Representations for Semantic Segmentation. + + This head is the implementation of `OCRNet + `_. + + Args: + ocr_channels (int): The intermediate channels of OCR block. + scale (int): The scale of probability map in SpatialGatherModule in + Default: 1. + """ + + def __init__(self, ocr_channels, scale=1, **kwargs): + super().__init__(**kwargs) + self.ocr_channels = ocr_channels + self.scale = scale + self.object_context_block = ObjectAttentionBlock( + self.channels, + self.ocr_channels, + self.scale, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.spatial_gather_module = SpatialGatherModule(self.scale) + + self.bottleneck = ConvModule( + self.in_channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs, prev_output): + """Forward function.""" + x = self._transform_inputs(inputs) + feats = self.bottleneck(x) + context = self.spatial_gather_module(feats, prev_output) + object_context = self.object_context_block(feats, context) + output = self.cls_seg(object_context) + + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/pid_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/pid_head.py new file mode 100644 index 0000000000000000000000000000000000000000..c092cb32d07c279c1d6a45d2e02baccb8e5ffa33 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/pid_head.py @@ -0,0 +1,183 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional, Tuple, Union + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer +from mmengine.model import BaseModule +from torch import Tensor + +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.models.losses import accuracy +from mmseg.models.utils import resize +from mmseg.registry import MODELS +from mmseg.utils import OptConfigType, SampleList + + +class BasePIDHead(BaseModule): + """Base class for PID head. + + Args: + in_channels (int): Number of input channels. + channels (int): Number of output channels. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU', inplace=True). + init_cfg (dict or list[dict], optional): Init config dict. + Default: None. + """ + + def __init__(self, + in_channels: int, + channels: int, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + self.conv = ConvModule( + in_channels, + channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + order=('norm', 'act', 'conv')) + _, self.norm = build_norm_layer(norm_cfg, num_features=channels) + self.act = build_activation_layer(act_cfg) + + def forward(self, x: Tensor, cls_seg: Optional[nn.Module]) -> Tensor: + """Forward function. + Args: + x (Tensor): Input tensor. + cls_seg (nn.Module, optional): The classification head. + + Returns: + Tensor: Output tensor. + """ + x = self.conv(x) + x = self.norm(x) + x = self.act(x) + if cls_seg is not None: + x = cls_seg(x) + return x + + +@MODELS.register_module() +class PIDHead(BaseDecodeHead): + """Decode head for PIDNet. + + Args: + in_channels (int): Number of input channels. + channels (int): Number of output channels. + num_classes (int): Number of classes. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU', inplace=True). + """ + + def __init__(self, + in_channels: int, + channels: int, + num_classes: int, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + **kwargs): + super().__init__( + in_channels, + channels, + num_classes=num_classes, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **kwargs) + self.i_head = BasePIDHead(in_channels, channels, norm_cfg, act_cfg) + self.p_head = BasePIDHead(in_channels // 2, channels, norm_cfg, + act_cfg) + self.d_head = BasePIDHead( + in_channels // 2, + in_channels // 4, + norm_cfg, + ) + self.p_cls_seg = nn.Conv2d(channels, self.out_channels, kernel_size=1) + self.d_cls_seg = nn.Conv2d(in_channels // 4, 1, kernel_size=1) + + def init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_( + m.weight, mode='fan_out', nonlinearity='relu') + elif isinstance(m, nn.BatchNorm2d): + nn.init.constant_(m.weight, 1) + nn.init.constant_(m.bias, 0) + + def forward( + self, + inputs: Union[Tensor, + Tuple[Tensor]]) -> Union[Tensor, Tuple[Tensor]]: + """Forward function. + Args: + inputs (Tensor | tuple[Tensor]): Input tensor or tuple of + Tensor. When training, the input is a tuple of three tensors, + (p_feat, i_feat, d_feat), and the output is a tuple of three + tensors, (p_seg_logit, i_seg_logit, d_seg_logit). + When inference, only the head of integral branch is used, and + input is a tensor of integral feature map, and the output is + the segmentation logit. + + Returns: + Tensor | tuple[Tensor]: Output tensor or tuple of tensors. + """ + if self.training: + x_p, x_i, x_d = inputs + x_p = self.p_head(x_p, self.p_cls_seg) + x_i = self.i_head(x_i, self.cls_seg) + x_d = self.d_head(x_d, self.d_cls_seg) + return x_p, x_i, x_d + else: + return self.i_head(inputs, self.cls_seg) + + def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tuple[Tensor]: + gt_semantic_segs = [ + data_sample.gt_sem_seg.data for data_sample in batch_data_samples + ] + gt_edge_segs = [ + data_sample.gt_edge_map.data for data_sample in batch_data_samples + ] + gt_sem_segs = torch.stack(gt_semantic_segs, dim=0) + gt_edge_segs = torch.stack(gt_edge_segs, dim=0) + return gt_sem_segs, gt_edge_segs + + def loss_by_feat(self, seg_logits: Tuple[Tensor], + batch_data_samples: SampleList) -> dict: + loss = dict() + p_logit, i_logit, d_logit = seg_logits + sem_label, bd_label = self._stack_batch_gt(batch_data_samples) + p_logit = resize( + input=p_logit, + size=sem_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + i_logit = resize( + input=i_logit, + size=sem_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + d_logit = resize( + input=d_logit, + size=bd_label.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + sem_label = sem_label.squeeze(1) + bd_label = bd_label.squeeze(1) + loss['loss_sem_p'] = self.loss_decode[0]( + p_logit, sem_label, ignore_index=self.ignore_index) + loss['loss_sem_i'] = self.loss_decode[1](i_logit, sem_label) + loss['loss_bd'] = self.loss_decode[2](d_logit, bd_label) + filler = torch.ones_like(sem_label) * self.ignore_index + sem_bd_label = torch.where( + torch.sigmoid(d_logit[:, 0, :, :]) > 0.8, sem_label, filler) + loss['loss_sem_bd'] = self.loss_decode[3](i_logit, sem_bd_label) + loss['acc_seg'] = accuracy( + i_logit, sem_label, ignore_index=self.ignore_index) + return loss diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/point_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/point_head.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e433d66249a4690cea3e33e95ec54d58ee3a07 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/point_head.py @@ -0,0 +1,367 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Modified from https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend/point_head/point_head.py # noqa + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +try: + from mmcv.ops import point_sample +except ModuleNotFoundError: + point_sample = None + +from typing import List + +from mmseg.registry import MODELS +from mmseg.utils import SampleList +from ..losses import accuracy +from ..utils import resize +from .cascade_decode_head import BaseCascadeDecodeHead + + +def calculate_uncertainty(seg_logits): + """Estimate uncertainty based on seg logits. + + For each location of the prediction ``seg_logits`` we estimate + uncertainty as the difference between top first and top second + predicted logits. + + Args: + seg_logits (Tensor): Semantic segmentation logits, + shape (batch_size, num_classes, height, width). + + Returns: + scores (Tensor): T uncertainty scores with the most uncertain + locations having the highest uncertainty score, shape ( + batch_size, 1, height, width) + """ + top2_scores = torch.topk(seg_logits, k=2, dim=1)[0] + return (top2_scores[:, 1] - top2_scores[:, 0]).unsqueeze(1) + + +@MODELS.register_module() +class PointHead(BaseCascadeDecodeHead): + """A mask point head use in PointRend. + + This head is implemented of `PointRend: Image Segmentation as + Rendering `_. + ``PointHead`` use shared multi-layer perceptron (equivalent to + nn.Conv1d) to predict the logit of input points. The fine-grained feature + and coarse feature will be concatenate together for predication. + + Args: + num_fcs (int): Number of fc layers in the head. Default: 3. + in_channels (int): Number of input channels. Default: 256. + fc_channels (int): Number of fc channels. Default: 256. + num_classes (int): Number of classes for logits. Default: 80. + class_agnostic (bool): Whether use class agnostic classification. + If so, the output channels of logits will be 1. Default: False. + coarse_pred_each_layer (bool): Whether concatenate coarse feature with + the output of each fc layer. Default: True. + conv_cfg (dict|None): Dictionary to construct and config conv layer. + Default: dict(type='Conv1d')) + norm_cfg (dict|None): Dictionary to construct and config norm layer. + Default: None. + loss_point (dict): Dictionary to construct and config loss layer of + point head. Default: dict(type='CrossEntropyLoss', use_mask=True, + loss_weight=1.0). + """ + + def __init__(self, + num_fcs=3, + coarse_pred_each_layer=True, + conv_cfg=dict(type='Conv1d'), + norm_cfg=None, + act_cfg=dict(type='ReLU', inplace=False), + **kwargs): + super().__init__( + input_transform='multiple_select', + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + init_cfg=dict( + type='Normal', std=0.01, override=dict(name='fc_seg')), + **kwargs) + if point_sample is None: + raise RuntimeError('Please install mmcv-full for ' + 'point_sample ops') + + self.num_fcs = num_fcs + self.coarse_pred_each_layer = coarse_pred_each_layer + + fc_in_channels = sum(self.in_channels) + self.num_classes + fc_channels = self.channels + self.fcs = nn.ModuleList() + for k in range(num_fcs): + fc = ConvModule( + fc_in_channels, + fc_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.fcs.append(fc) + fc_in_channels = fc_channels + fc_in_channels += self.num_classes if self.coarse_pred_each_layer \ + else 0 + self.fc_seg = nn.Conv1d( + fc_in_channels, + self.num_classes, + kernel_size=1, + stride=1, + padding=0) + if self.dropout_ratio > 0: + self.dropout = nn.Dropout(self.dropout_ratio) + delattr(self, 'conv_seg') + + def cls_seg(self, feat): + """Classify each pixel with fc.""" + if self.dropout is not None: + feat = self.dropout(feat) + output = self.fc_seg(feat) + return output + + def forward(self, fine_grained_point_feats, coarse_point_feats): + x = torch.cat([fine_grained_point_feats, coarse_point_feats], dim=1) + for fc in self.fcs: + x = fc(x) + if self.coarse_pred_each_layer: + x = torch.cat((x, coarse_point_feats), dim=1) + return self.cls_seg(x) + + def _get_fine_grained_point_feats(self, x, points): + """Sample from fine grained features. + + Args: + x (list[Tensor]): Feature pyramid from by neck or backbone. + points (Tensor): Point coordinates, shape (batch_size, + num_points, 2). + + Returns: + fine_grained_feats (Tensor): Sampled fine grained feature, + shape (batch_size, sum(channels of x), num_points). + """ + + fine_grained_feats_list = [ + point_sample(_, points, align_corners=self.align_corners) + for _ in x + ] + if len(fine_grained_feats_list) > 1: + fine_grained_feats = torch.cat(fine_grained_feats_list, dim=1) + else: + fine_grained_feats = fine_grained_feats_list[0] + + return fine_grained_feats + + def _get_coarse_point_feats(self, prev_output, points): + """Sample from fine grained features. + + Args: + prev_output (list[Tensor]): Prediction of previous decode head. + points (Tensor): Point coordinates, shape (batch_size, + num_points, 2). + + Returns: + coarse_feats (Tensor): Sampled coarse feature, shape (batch_size, + num_classes, num_points). + """ + + coarse_feats = point_sample( + prev_output, points, align_corners=self.align_corners) + + return coarse_feats + + def loss(self, inputs, prev_output, batch_data_samples: SampleList, + train_cfg, **kwargs): + """Forward function for training. + Args: + inputs (list[Tensor]): List of multi-level img features. + prev_output (Tensor): The output of previous decode head. + batch_data_samples (list[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `img_metas` or `gt_semantic_seg`. + train_cfg (dict): The training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + x = self._transform_inputs(inputs) + with torch.no_grad(): + points = self.get_points_train( + prev_output, calculate_uncertainty, cfg=train_cfg) + fine_grained_point_feats = self._get_fine_grained_point_feats( + x, points) + coarse_point_feats = self._get_coarse_point_feats(prev_output, points) + point_logits = self.forward(fine_grained_point_feats, + coarse_point_feats) + + losses = self.loss_by_feat(point_logits, points, batch_data_samples) + + return losses + + def predict(self, inputs, prev_output, batch_img_metas: List[dict], + test_cfg, **kwargs): + """Forward function for testing. + + Args: + inputs (list[Tensor]): List of multi-level img features. + prev_output (Tensor): The output of previous decode head. + img_metas (list[dict]): List of image info dict where each dict + has: 'img_shape', 'scale_factor', 'flip', and may also contain + 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:Collect`. + test_cfg (dict): The testing config. + + Returns: + Tensor: Output segmentation map. + """ + + x = self._transform_inputs(inputs) + refined_seg_logits = prev_output.clone() + for _ in range(test_cfg.subdivision_steps): + refined_seg_logits = resize( + refined_seg_logits, + scale_factor=test_cfg.scale_factor, + mode='bilinear', + align_corners=self.align_corners) + batch_size, channels, height, width = refined_seg_logits.shape + point_indices, points = self.get_points_test( + refined_seg_logits, calculate_uncertainty, cfg=test_cfg) + fine_grained_point_feats = self._get_fine_grained_point_feats( + x, points) + coarse_point_feats = self._get_coarse_point_feats( + prev_output, points) + point_logits = self.forward(fine_grained_point_feats, + coarse_point_feats) + + point_indices = point_indices.unsqueeze(1).expand(-1, channels, -1) + refined_seg_logits = refined_seg_logits.reshape( + batch_size, channels, height * width) + refined_seg_logits = refined_seg_logits.scatter_( + 2, point_indices, point_logits) + refined_seg_logits = refined_seg_logits.view( + batch_size, channels, height, width) + + return self.predict_by_feat(refined_seg_logits, batch_img_metas, + **kwargs) + + def loss_by_feat(self, point_logits, points, batch_data_samples, **kwargs): + """Compute segmentation loss.""" + gt_semantic_seg = self._stack_batch_gt(batch_data_samples) + point_label = point_sample( + gt_semantic_seg.float(), + points, + mode='nearest', + align_corners=self.align_corners) + point_label = point_label.squeeze(1).long() + + loss = dict() + if not isinstance(self.loss_decode, nn.ModuleList): + losses_decode = [self.loss_decode] + else: + losses_decode = self.loss_decode + for loss_module in losses_decode: + loss['point' + loss_module.loss_name] = loss_module( + point_logits, point_label, ignore_index=self.ignore_index) + + loss['acc_point'] = accuracy( + point_logits, point_label, ignore_index=self.ignore_index) + return loss + + def get_points_train(self, seg_logits, uncertainty_func, cfg): + """Sample points for training. + + Sample points in [0, 1] x [0, 1] coordinate space based on their + uncertainty. The uncertainties are calculated for each point using + 'uncertainty_func' function that takes point's logit prediction as + input. + + Args: + seg_logits (Tensor): Semantic segmentation logits, shape ( + batch_size, num_classes, height, width). + uncertainty_func (func): uncertainty calculation function. + cfg (dict): Training config of point head. + + Returns: + point_coords (Tensor): A tensor of shape (batch_size, num_points, + 2) that contains the coordinates of ``num_points`` sampled + points. + """ + num_points = cfg.num_points + oversample_ratio = cfg.oversample_ratio + importance_sample_ratio = cfg.importance_sample_ratio + assert oversample_ratio >= 1 + assert 0 <= importance_sample_ratio <= 1 + batch_size = seg_logits.shape[0] + num_sampled = int(num_points * oversample_ratio) + point_coords = torch.rand( + batch_size, num_sampled, 2, device=seg_logits.device) + point_logits = point_sample(seg_logits, point_coords) + # It is crucial to calculate uncertainty based on the sampled + # prediction value for the points. Calculating uncertainties of the + # coarse predictions first and sampling them for points leads to + # incorrect results. To illustrate this: assume uncertainty func( + # logits)=-abs(logits), a sampled point between two coarse + # predictions with -1 and 1 logits has 0 logits, and therefore 0 + # uncertainty value. However, if we calculate uncertainties for the + # coarse predictions first, both will have -1 uncertainty, + # and sampled point will get -1 uncertainty. + point_uncertainties = uncertainty_func(point_logits) + num_uncertain_points = int(importance_sample_ratio * num_points) + num_random_points = num_points - num_uncertain_points + idx = torch.topk( + point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1] + shift = num_sampled * torch.arange( + batch_size, dtype=torch.long, device=seg_logits.device) + idx += shift[:, None] + point_coords = point_coords.view(-1, 2)[idx.view(-1), :].view( + batch_size, num_uncertain_points, 2) + if num_random_points > 0: + rand_point_coords = torch.rand( + batch_size, num_random_points, 2, device=seg_logits.device) + point_coords = torch.cat((point_coords, rand_point_coords), dim=1) + return point_coords + + def get_points_test(self, seg_logits, uncertainty_func, cfg): + """Sample points for testing. + + Find ``num_points`` most uncertain points from ``uncertainty_map``. + + Args: + seg_logits (Tensor): A tensor of shape (batch_size, num_classes, + height, width) for class-specific or class-agnostic prediction. + uncertainty_func (func): uncertainty calculation function. + cfg (dict): Testing config of point head. + + Returns: + point_indices (Tensor): A tensor of shape (batch_size, num_points) + that contains indices from [0, height x width) of the most + uncertain points. + point_coords (Tensor): A tensor of shape (batch_size, num_points, + 2) that contains [0, 1] x [0, 1] normalized coordinates of the + most uncertain points from the ``height x width`` grid . + """ + + num_points = cfg.subdivision_num_points + uncertainty_map = uncertainty_func(seg_logits) + batch_size, _, height, width = uncertainty_map.shape + h_step = 1.0 / height + w_step = 1.0 / width + + uncertainty_map = uncertainty_map.view(batch_size, height * width) + num_points = min(height * width, num_points) + point_indices = uncertainty_map.topk(num_points, dim=1)[1] + point_coords = torch.zeros( + batch_size, + num_points, + 2, + dtype=torch.float, + device=seg_logits.device) + point_coords[:, :, 0] = w_step / 2.0 + (point_indices % + width).float() * w_step + point_coords[:, :, 1] = h_step / 2.0 + (point_indices // + width).float() * h_step + return point_indices, point_coords diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/psa_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/psa_head.py new file mode 100644 index 0000000000000000000000000000000000000000..13ee5c58a569bb46612625b85685cd61b7e9df3e --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/psa_head.py @@ -0,0 +1,197 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + +try: + from mmcv.ops import PSAMask +except ModuleNotFoundError: + PSAMask = None + + +@MODELS.register_module() +class PSAHead(BaseDecodeHead): + """Point-wise Spatial Attention Network for Scene Parsing. + + This head is the implementation of `PSANet + `_. + + Args: + mask_size (tuple[int]): The PSA mask size. It usually equals input + size. + psa_type (str): The type of psa module. Options are 'collect', + 'distribute', 'bi-direction'. Default: 'bi-direction' + compact (bool): Whether use compact map for 'collect' mode. + Default: True. + shrink_factor (int): The downsample factors of psa mask. Default: 2. + normalization_factor (float): The normalize factor of attention. + psa_softmax (bool): Whether use softmax for attention. + """ + + def __init__(self, + mask_size, + psa_type='bi-direction', + compact=False, + shrink_factor=2, + normalization_factor=1.0, + psa_softmax=True, + **kwargs): + if PSAMask is None: + raise RuntimeError('Please install mmcv-full for PSAMask ops') + super().__init__(**kwargs) + assert psa_type in ['collect', 'distribute', 'bi-direction'] + self.psa_type = psa_type + self.compact = compact + self.shrink_factor = shrink_factor + self.mask_size = mask_size + mask_h, mask_w = mask_size + self.psa_softmax = psa_softmax + if normalization_factor is None: + normalization_factor = mask_h * mask_w + self.normalization_factor = normalization_factor + + self.reduce = ConvModule( + self.in_channels, + self.channels, + kernel_size=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.attention = nn.Sequential( + ConvModule( + self.channels, + self.channels, + kernel_size=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + nn.Conv2d( + self.channels, mask_h * mask_w, kernel_size=1, bias=False)) + if psa_type == 'bi-direction': + self.reduce_p = ConvModule( + self.in_channels, + self.channels, + kernel_size=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.attention_p = nn.Sequential( + ConvModule( + self.channels, + self.channels, + kernel_size=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + nn.Conv2d( + self.channels, mask_h * mask_w, kernel_size=1, bias=False)) + self.psamask_collect = PSAMask('collect', mask_size) + self.psamask_distribute = PSAMask('distribute', mask_size) + else: + self.psamask = PSAMask(psa_type, mask_size) + self.proj = ConvModule( + self.channels * (2 if psa_type == 'bi-direction' else 1), + self.in_channels, + kernel_size=1, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + self.bottleneck = ConvModule( + self.in_channels * 2, + self.channels, + kernel_size=3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + identity = x + align_corners = self.align_corners + if self.psa_type in ['collect', 'distribute']: + out = self.reduce(x) + n, c, h, w = out.size() + if self.shrink_factor != 1: + if h % self.shrink_factor and w % self.shrink_factor: + h = (h - 1) // self.shrink_factor + 1 + w = (w - 1) // self.shrink_factor + 1 + align_corners = True + else: + h = h // self.shrink_factor + w = w // self.shrink_factor + align_corners = False + out = resize( + out, + size=(h, w), + mode='bilinear', + align_corners=align_corners) + y = self.attention(out) + if self.compact: + if self.psa_type == 'collect': + y = y.view(n, h * w, + h * w).transpose(1, 2).view(n, h * w, h, w) + else: + y = self.psamask(y) + if self.psa_softmax: + y = F.softmax(y, dim=1) + out = torch.bmm( + out.view(n, c, h * w), y.view(n, h * w, h * w)).view( + n, c, h, w) * (1.0 / self.normalization_factor) + else: + x_col = self.reduce(x) + x_dis = self.reduce_p(x) + n, c, h, w = x_col.size() + if self.shrink_factor != 1: + if h % self.shrink_factor and w % self.shrink_factor: + h = (h - 1) // self.shrink_factor + 1 + w = (w - 1) // self.shrink_factor + 1 + align_corners = True + else: + h = h // self.shrink_factor + w = w // self.shrink_factor + align_corners = False + x_col = resize( + x_col, + size=(h, w), + mode='bilinear', + align_corners=align_corners) + x_dis = resize( + x_dis, + size=(h, w), + mode='bilinear', + align_corners=align_corners) + y_col = self.attention(x_col) + y_dis = self.attention_p(x_dis) + if self.compact: + y_dis = y_dis.view(n, h * w, + h * w).transpose(1, 2).view(n, h * w, h, w) + else: + y_col = self.psamask_collect(y_col) + y_dis = self.psamask_distribute(y_dis) + if self.psa_softmax: + y_col = F.softmax(y_col, dim=1) + y_dis = F.softmax(y_dis, dim=1) + x_col = torch.bmm( + x_col.view(n, c, h * w), y_col.view(n, h * w, h * w)).view( + n, c, h, w) * (1.0 / self.normalization_factor) + x_dis = torch.bmm( + x_dis.view(n, c, h * w), y_dis.view(n, h * w, h * w)).view( + n, c, h, w) * (1.0 / self.normalization_factor) + out = torch.cat([x_col, x_dis], 1) + out = self.proj(out) + out = resize( + out, + size=identity.shape[2:], + mode='bilinear', + align_corners=align_corners) + out = self.bottleneck(torch.cat((identity, out), dim=1)) + out = self.cls_seg(out) + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/psp_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/psp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..a40ec41dec281e53815e9753ee2ba1a5da76bd05 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/psp_head.py @@ -0,0 +1,117 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class PPM(nn.ModuleList): + """Pooling Pyramid Module used in PSPNet. + + Args: + pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module. + in_channels (int): Input channels. + channels (int): Channels after modules, before conv_seg. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict): Config of activation layers. + align_corners (bool): align_corners argument of F.interpolate. + """ + + def __init__(self, pool_scales, in_channels, channels, conv_cfg, norm_cfg, + act_cfg, align_corners, **kwargs): + super().__init__() + self.pool_scales = pool_scales + self.align_corners = align_corners + self.in_channels = in_channels + self.channels = channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + for pool_scale in pool_scales: + self.append( + nn.Sequential( + nn.AdaptiveAvgPool2d(pool_scale), + ConvModule( + self.in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + **kwargs))) + + def forward(self, x): + """Forward function.""" + ppm_outs = [] + for ppm in self: + ppm_out = ppm(x) + upsampled_ppm_out = resize( + ppm_out, + size=x.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + ppm_outs.append(upsampled_ppm_out) + return ppm_outs + + +@MODELS.register_module() +class PSPHead(BaseDecodeHead): + """Pyramid Scene Parsing Network. + + This head is the implementation of + `PSPNet `_. + + Args: + pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module. Default: (1, 2, 3, 6). + """ + + def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs): + super().__init__(**kwargs) + assert isinstance(pool_scales, (list, tuple)) + self.pool_scales = pool_scales + self.psp_modules = PPM( + self.pool_scales, + self.in_channels, + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=self.align_corners) + self.bottleneck = ConvModule( + self.in_channels + len(pool_scales) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def _forward_feature(self, inputs): + """Forward function for feature maps before classifying each pixel with + ``self.cls_seg`` fc. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + feats (Tensor): A tensor of shape (batch_size, self.channels, + H, W) which is feature map for last layer of decoder head. + """ + x = self._transform_inputs(inputs) + psp_outs = [x] + psp_outs.extend(self.psp_modules(x)) + psp_outs = torch.cat(psp_outs, dim=1) + feats = self.bottleneck(psp_outs) + return feats + + def forward(self, inputs): + """Forward function.""" + output = self._forward_feature(inputs) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/san_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/san_head.py new file mode 100644 index 0000000000000000000000000000000000000000..d20da801924080efeee30a246331af2e2e5df352 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/san_head.py @@ -0,0 +1,736 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from functools import partial +from typing import Dict, List, Tuple + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, build_norm_layer +from mmcv.cnn.bricks.transformer import BaseTransformerLayer +from mmcv.ops import point_sample +from mmengine.dist import all_reduce +from mmengine.model.weight_init import (caffe2_xavier_init, normal_init, + trunc_normal_) +from mmengine.runner.checkpoint import CheckpointLoader, load_state_dict +from mmengine.structures import InstanceData +from torch import Tensor +from torch.nn import functional as F + +from mmseg.models.backbones.vit import TransformerEncoderLayer +from mmseg.registry import MODELS +from mmseg.utils import (ConfigType, MatchMasks, SampleList, + seg_data_to_instance_data) +from ..utils import (MLP, LayerNorm2d, PatchEmbed, cross_attn_layer, + get_uncertain_point_coords_with_randomness, resize) +from .decode_head import BaseDecodeHead + + +class MLPMaskDecoder(nn.Module): + """Module for decoding query and visual features with MLP layers to + generate the attention biases and the mask proposals.""" + + def __init__( + self, + *, + in_channels: int, + total_heads: int = 1, + total_layers: int = 1, + embed_channels: int = 256, + mlp_channels: int = 256, + mlp_num_layers: int = 3, + rescale_attn_bias: bool = False, + ): + super().__init__() + self.total_heads = total_heads + self.total_layers = total_layers + + dense_affine_func = partial(nn.Conv2d, kernel_size=1) + # Query Branch + self.query_mlp = MLP(in_channels, mlp_channels, embed_channels, + mlp_num_layers) + # Pixel Branch + self.pix_mlp = MLP( + in_channels, + mlp_channels, + embed_channels, + mlp_num_layers, + affine_func=dense_affine_func, + ) + # Attention Bias Branch + self.attn_mlp = MLP( + in_channels, + mlp_channels, + embed_channels * self.total_heads * self.total_layers, + mlp_num_layers, + affine_func=dense_affine_func, + ) + if rescale_attn_bias: + self.bias_scaling = nn.Linear(1, 1) + else: + self.bias_scaling = nn.Identity() + + def forward(self, query: torch.Tensor, + x: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]: + """Forward function. + Args: + query (Tensor): Query Tokens [B,N,C]. + x (Tensor): Visual features [B,C,H,W] + + Return: + mask_preds (Tensor): Mask proposals. + attn_bias (List[Tensor]): List of attention bias. + """ + query = self.query_mlp(query) + pix = self.pix_mlp(x) + b, c, h, w = pix.shape + # preidict mask + mask_preds = torch.einsum('bqc,bchw->bqhw', query, pix) + # generate attn bias + attn = self.attn_mlp(x) + attn = attn.reshape(b, self.total_layers, self.total_heads, c, h, w) + attn_bias = torch.einsum('bqc,blnchw->blnqhw', query, attn) + attn_bias = self.bias_scaling(attn_bias[..., None]).squeeze(-1) + attn_bias = attn_bias.chunk(self.total_layers, dim=1) + attn_bias = [attn.squeeze(1) for attn in attn_bias] + return mask_preds, attn_bias + + +class SideAdapterNetwork(nn.Module): + """Side Adapter Network for predicting mask proposals and attention bias. + + Args: + in_channels (int): Number of input channels. Default: 3. + clip_channels (int): Number of channels of visual features. + Default: 768. + embed_dims (int): embedding dimension. Default: 240. + patch_size (int): The patch size. Default: 16. + patch_bias (bool): Whether use bias in patch embedding. + Default: True. + num_queries (int): Number of queries for mask proposals. + Default: 100. + fusion_index (List[int]): The layer number of the encode + transformer to fuse with the CLIP feature. + Default: [0, 1, 2, 3]. + cfg_encoder (ConfigType): Configs for the encode layers. + cfg_decoder (ConfigType): Configs for the decode layers. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + """ + + def __init__( + self, + in_channels: int = 3, + clip_channels: int = 768, + embed_dims: int = 240, + patch_size: int = 16, + patch_bias: bool = True, + num_queries: int = 100, + fusion_index: list = [0, 1, 2, 3], + cfg_encoder: ConfigType = ..., + cfg_decoder: ConfigType = ..., + norm_cfg: dict = dict(type='LN'), + ): + super().__init__() + + self.patch_embed = PatchEmbed( + in_channels=in_channels, + embed_dims=embed_dims, + conv_type='Conv2d', + kernel_size=patch_size, + stride=patch_size, + padding=0, + input_size=(640, 640), + bias=patch_bias, + norm_cfg=None, + init_cfg=None, + ) + ori_h, ori_w = self.patch_embed.init_out_size + num_patches = ori_h * ori_w + self.pos_embed = nn.Parameter( + torch.randn(1, num_patches, embed_dims) * .02) + self.query_pos_embed = nn.Parameter( + torch.zeros(1, num_queries, embed_dims)) + self.query_embed = nn.Parameter( + torch.zeros(1, num_queries, embed_dims)) + encode_layers = [] + for i in range(cfg_encoder.num_encode_layer): + encode_layers.append( + TransformerEncoderLayer( + embed_dims=embed_dims, + num_heads=cfg_encoder.num_heads, + feedforward_channels=cfg_encoder.mlp_ratio * embed_dims, + norm_cfg=norm_cfg)) + self.encode_layers = nn.ModuleList(encode_layers) + conv_clips = [] + for i in range(len(fusion_index)): + conv_clips.append( + nn.Sequential( + LayerNorm2d(clip_channels), + ConvModule( + clip_channels, + embed_dims, + kernel_size=1, + norm_cfg=None, + act_cfg=None))) + self.conv_clips = nn.ModuleList(conv_clips) + self.fusion_index = fusion_index + self.mask_decoder = MLPMaskDecoder( + in_channels=embed_dims, + total_heads=cfg_decoder.num_heads, + total_layers=cfg_decoder.num_layers, + embed_channels=cfg_decoder.embed_channels, + mlp_channels=cfg_decoder.mlp_channels, + mlp_num_layers=cfg_decoder.num_mlp, + rescale_attn_bias=cfg_decoder.rescale) + + def init_weights(self): + trunc_normal_(self.pos_embed, std=0.02) + nn.init.normal_(self.query_embed, std=0.02) + nn.init.normal_(self.query_pos_embed, std=0.02) + for i in range(len(self.conv_clips)): + caffe2_xavier_init(self.conv_clips[i][1].conv) + + def fuse_clip(self, fused_index: int, x: torch.Tensor, + clip_feature: torch.Tensor, hwshape: Tuple[int, + int], L: int): + """Fuse CLIP feature and visual tokens.""" + fused_clip = (resize( + self.conv_clips[fused_index](clip_feature.contiguous()), + size=hwshape, + mode='bilinear', + align_corners=False)).permute(0, 2, 3, 1).reshape(x[:, -L:, + ...].shape) + x = torch.cat([x[:, :-L, ...], x[:, -L:, ...] + fused_clip], dim=1) + return x + + def encode_feature(self, image: torch.Tensor, + clip_features: List[torch.Tensor], + deep_supervision_idxs: List[int]) -> List[List]: + """Encode images by a lightweight vision transformer.""" + assert len(self.fusion_index) == len(clip_features) + x, hwshape = self.patch_embed(image) + ori_h, ori_w = self.patch_embed.init_out_size + pos_embed = self.pos_embed + if self.pos_embed.shape[1] != x.shape[1]: + # resize the position embedding + pos_embed = ( + resize( + self.pos_embed.reshape(1, ori_h, ori_w, + -1).permute(0, 3, 1, 2), + size=hwshape, + mode='bicubic', + align_corners=False, + ).flatten(2).permute(0, 2, 1)) + pos_embed = torch.cat([ + self.query_pos_embed.expand(pos_embed.shape[0], -1, -1), pos_embed + ], + dim=1) + x = torch.cat([self.query_embed.expand(x.shape[0], -1, -1), x], dim=1) + x = x + pos_embed + L = hwshape[0] * hwshape[1] + fused_index = 0 + if self.fusion_index[fused_index] == 0: + x = self.fuse_clip(fused_index, x, clip_features[0][0], hwshape, L) + fused_index += 1 + outs = [] + for index, block in enumerate(self.encode_layers, start=1): + x = block(x) + if index < len(self.fusion_index + ) and index == self.fusion_index[fused_index]: + x = self.fuse_clip(fused_index, x, + clip_features[fused_index][0], hwshape, L) + fused_index += 1 + x_query = x[:, :-L, ...] + x_feat = x[:, -L:, ...].permute(0, 2, 1)\ + .reshape(x.shape[0], x.shape[-1], hwshape[0], hwshape[1]) + + if index in deep_supervision_idxs or index == len( + self.encode_layers): + outs.append({'query': x_query, 'x': x_feat}) + + if index < len(self.encode_layers): + x = x + pos_embed + return outs + + def decode_feature(self, features): + mask_embeds = [] + attn_biases = [] + for feature in features: + mask_embed, attn_bias = self.mask_decoder(**feature) + mask_embeds.append(mask_embed) + attn_biases.append(attn_bias) + return mask_embeds, attn_biases + + def forward( + self, image: torch.Tensor, clip_features: List[torch.Tensor], + deep_supervision_idxs: List[int] + ) -> Tuple[List[torch.Tensor], List[List[torch.Tensor]]]: + """Forward function.""" + features = self.encode_feature(image, clip_features, + deep_supervision_idxs) + mask_embeds, attn_biases = self.decode_feature(features) + return mask_embeds, attn_biases + + +class RecWithAttnbias(nn.Module): + """Mask recognition module by applying the attention biases to rest deeper + CLIP layers. + + Args: + sos_token_format (str): The format of sos token. It should be + chosen from ["cls_token", "learnable_token", "pos_embedding"]. + Default: 'cls_token'. + sos_token_num (int): Number of sos token. It should be equal to + the number of quries. Default: 100. + num_layers (int): Number of rest CLIP layers for mask recognition. + Default: 3. + cross_attn (bool): Whether use cross attention to update sos token. + Default: False. + embed_dims (int): The feature dimension of CLIP layers. + Default: 768. + num_heads (int): Parallel attention heads of CLIP layers. + Default: 768. + mlp_ratio (int): Ratio of mlp hidden dim to embedding dim. + Default: 4. + qkv_bias (bool): Whether to use bias in multihead-attention. + Default: True. + out_dims (int): Number of channels of the output mask proposals. + It should be equal to the out_dims of text_encoder. + Default: 512. + final_norm (True): Whether use norm layer for sos token. + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN'). + frozen_exclude (List): List of parameters that are not to be frozen. + """ + + def __init__(self, + sos_token_format: str = 'cls_token', + sos_token_num: int = 100, + num_layers: int = 3, + cross_attn: bool = False, + embed_dims: int = 768, + num_heads: int = 12, + mlp_ratio: int = 4, + num_fcs: int = 2, + qkv_bias: bool = True, + out_dims: int = 512, + final_norm: bool = True, + act_cfg: dict = dict(type='GELU'), + norm_cfg: dict = dict(type='LN'), + frozen_exclude: List = []): + super().__init__() + + assert sos_token_format in [ + 'cls_token', 'learnable_token', 'pos_embedding' + ] + self.sos_token_format = sos_token_format + self.sos_token_num = sos_token_num + self.frozen_exclude = frozen_exclude + self.cross_attn = cross_attn + self.num_layers = num_layers + self.num_heads = num_heads + if sos_token_format in ['learnable_token', 'pos_embedding']: + self.sos_token = nn.Parameter( + torch.randn(sos_token_num, 1, self.proj.shape[0])) + self.frozen.append('sos_token') + + layers = [] + for i in range(num_layers): + layers.append( + BaseTransformerLayer( + attn_cfgs=dict( + type='MultiheadAttention', + embed_dims=embed_dims, + num_heads=num_heads, + batch_first=False, + bias=qkv_bias), + ffn_cfgs=dict( + type='FFN', + embed_dims=embed_dims, + feedforward_channels=mlp_ratio * embed_dims, + act_cfg=act_cfg), + operation_order=('norm', 'self_attn', 'norm', 'ffn'))) + self.layers = nn.ModuleList(layers) + + self.ln_post = build_norm_layer(norm_cfg, embed_dims)[1] + self.proj = nn.Linear(embed_dims, out_dims, bias=False) + + self.final_norm = final_norm + self._freeze() + + def init_weights(self, rec_state_dict): + if hasattr(self, 'sos_token'): + normal_init(self.sos_token, std=0.02) + if rec_state_dict is not None: + load_state_dict(self, rec_state_dict, strict=False, logger=None) + else: + super().init_weights() + + def _freeze(self): + if 'all' in self.frozen_exclude: + return + for name, param in self.named_parameters(): + if not any([exclude in name for exclude in self.frozen_exclude]): + param.requires_grad = False + + def _build_attn_biases(self, attn_biases, target_shape): + formatted_attn_biases = [] + for attn_bias in attn_biases: + # convert it to proper format: N*num_head,L,L + # attn_bias: [N, num_head/1, num_sos,H,W] + n, num_head, num_sos, h, w = attn_bias.shape + # reshape and downsample + attn_bias = F.adaptive_max_pool2d( + attn_bias.reshape(n, num_head * num_sos, h, w), + output_size=target_shape) + attn_bias = attn_bias.reshape(n, num_head, num_sos, *target_shape) + + true_num_head = self.num_heads + assert (num_head == 1 or num_head + == true_num_head), f'num_head={num_head} is not supported.' + if num_head == 1: + attn_bias = attn_bias.repeat(1, true_num_head, 1, 1, 1) + attn_bias = attn_bias.reshape(n * true_num_head, num_sos, -1) + L = attn_bias.shape[-1] + if self.cross_attn: + # [n*num_head, num_sos, L] + formatted_attn_biases.append(attn_bias) + else: + # [n*num_head, num_sos+1+L, num_sos+1+L] + new_attn_bias = attn_bias.new_zeros(num_sos + 1 + L, + num_sos + 1 + L) + new_attn_bias[:, :num_sos] = -100 + new_attn_bias[torch.arange(num_sos), torch.arange(num_sos)] = 0 + new_attn_bias[:num_sos, num_sos] = -100 + new_attn_bias = ( + new_attn_bias[None, ...].expand(n * true_num_head, -1, + -1).clone()) + new_attn_bias[..., :num_sos, -L:] = attn_bias + formatted_attn_biases.append(new_attn_bias) + + if len(formatted_attn_biases) == 1: + formatted_attn_biases = [ + formatted_attn_biases[0] for _ in range(self.num_layers) + ] + return formatted_attn_biases + + def forward(self, bias: List[Tensor], feature: List[Tensor]): + """Forward function to recognize the category of masks + Args: + bias (List[Tensor]): Attention bias for transformer layers + feature (List[Tensor]): Output of the image encoder, + including cls_token and img_feature. + """ + cls_token = feature[1].unsqueeze(0) + img_feature = feature[0] + b, c, h, w = img_feature.shape + # construct clip shadow features + x = torch.cat( + [cls_token, + img_feature.reshape(b, c, -1).permute(2, 0, 1)]) + + # construct sos token + if self.sos_token_format == 'cls_token': + sos_token = cls_token.repeat(self.sos_token_num, 1, 1) + elif self.sos_token_format == 'learnable_token': + sos_token = self.sos_token.expand(-1, b, -1) + elif self.sos_token_format == 'pos_embedding': + sos_token = self.sos_token.expand(-1, b, -1) + cls_token + + # construct attn bias + attn_biases = self._build_attn_biases(bias, target_shape=(h, w)) + + if self.cross_attn: + for i, block in enumerate(self.layers): + if self.cross_attn: + sos_token = cross_attn_layer( + block, + sos_token, + x[1:, ], + attn_biases[i], + ) + if i < len(self.layers) - 1: + x = block(x) + else: + x = torch.cat([sos_token, x], dim=0) + for i, block in enumerate(self.layers): + x = block(x, attn_masks=[attn_biases[i]]) + sos_token = x[:self.sos_token_num] + + sos_token = sos_token.permute(1, 0, 2) # LND -> NLD + sos_token = self.ln_post(sos_token) + sos_token = self.proj(sos_token) + if self.final_norm: + sos_token = F.normalize(sos_token, dim=-1) + return sos_token + + +@MODELS.register_module() +class SideAdapterCLIPHead(BaseDecodeHead): + """Side Adapter Network (SAN) for open-vocabulary semantic segmentation + with pre-trained vision-language model. + + This decode head is the implementation of `Side Adapter Network + for Open-Vocabulary Semantic Segmentation` + . + Modified from https://github.com/MendelXu/SAN/blob/main/san/model/side_adapter/side_adapter.py # noqa:E501 + Copyright (c) 2023 MendelXu. + Licensed under the MIT License + + Args: + num_classes (int): the number of classes. + san_cfg (ConfigType): Configs for SideAdapterNetwork module + maskgen_cfg (ConfigType): Configs for RecWithAttnbias module + """ + + def __init__(self, num_classes: int, san_cfg: ConfigType, + maskgen_cfg: ConfigType, deep_supervision_idxs: List[int], + train_cfg: ConfigType, **kwargs): + super().__init__( + in_channels=san_cfg.in_channels, + channels=san_cfg.embed_dims, + num_classes=num_classes, + **kwargs) + assert san_cfg.num_queries == maskgen_cfg.sos_token_num, \ + 'num_queries in san_cfg should be equal to sos_token_num ' \ + 'in maskgen_cfg' + del self.conv_seg + self.side_adapter_network = SideAdapterNetwork(**san_cfg) + self.rec_with_attnbias = RecWithAttnbias(**maskgen_cfg) + self.deep_supervision_idxs = deep_supervision_idxs + self.train_cfg = train_cfg + if train_cfg: + self.match_masks = MatchMasks( + num_points=train_cfg.num_points, + num_queries=san_cfg.num_queries, + num_classes=num_classes, + assigner=train_cfg.assigner) + + def init_weights(self): + + rec_state_dict = None + if isinstance(self.init_cfg, dict) and \ + self.init_cfg.get('type') == 'Pretrained_Part': + checkpoint = CheckpointLoader.load_checkpoint( + self.init_cfg['checkpoint'], logger=None, map_location='cpu') + + rec_state_dict = checkpoint.copy() + para_prefix = 'decode_head.rec_with_attnbias' + prefix_len = len(para_prefix) + 1 + for k, v in checkpoint.items(): + rec_state_dict.pop(k) + if para_prefix in k: + rec_state_dict[k[prefix_len:]] = v + + self.side_adapter_network.init_weights() + self.rec_with_attnbias.init_weights(rec_state_dict) + + def forward(self, inputs: Tuple[Tensor], + deep_supervision_idxs) -> Tuple[List]: + """Forward function. + + Args: + inputs (Tuple[Tensor]): A triplet including images, + list of multi-level visual features from image encoder and + class embeddings from text_encoder. + + Returns: + mask_props (List[Tensor]): Mask proposals predicted by SAN. + mask_logits (List[Tensor]): Class logits of mask proposals. + """ + imgs, clip_feature, class_embeds = inputs + # predict mask proposals and attention bias + mask_props, attn_biases = self.side_adapter_network( + imgs, clip_feature, deep_supervision_idxs) + + # mask recognition with attention bias + mask_embeds = [ + self.rec_with_attnbias(att_bias, clip_feature[-1]) + for att_bias in attn_biases + ] + # Obtain class prediction of masks by comparing the similarity + # between the image token and the text embedding of class names. + mask_logits = [ + torch.einsum('bqc,nc->bqn', mask_embed, class_embeds) + for mask_embed in mask_embeds + ] + return mask_props, mask_logits + + def predict(self, inputs: Tuple[Tensor], batch_img_metas: List[dict], + test_cfg: ConfigType) -> Tensor: + """Forward function for prediction. + + Args: + inputs (Tuple[Tensor]): Images, visual features from image encoder + and class embedding from text encoder. + batch_img_metas (dict): List Image info where each dict may also + contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + test_cfg (dict): The testing config. + + Returns: + Tensor: Outputs segmentation logits map. + """ + mask_props, mask_logits = self.forward(inputs, []) + + return self.predict_by_feat([mask_props[-1], mask_logits[-1]], + batch_img_metas) + + def predict_by_feat(self, seg_logits: List[Tensor], + batch_img_metas: List[dict]) -> Tensor: + """1. Transform a batch of mask proposals to the input shape. + 2. Generate segmentation map with mask proposals and class logits. + """ + mask_pred = seg_logits[0] + cls_score = seg_logits[1] + if isinstance(batch_img_metas[0]['img_shape'], torch.Size): + # slide inference + size = batch_img_metas[0]['img_shape'] + elif 'pad_shape' in batch_img_metas[0]: + size = batch_img_metas[0]['pad_shape'][:2] + else: + size = batch_img_metas[0]['img_shape'] + # upsample mask + mask_pred = F.interpolate( + mask_pred, size=size, mode='bilinear', align_corners=False) + + mask_cls = F.softmax(cls_score, dim=-1)[..., :-1] + mask_pred = mask_pred.sigmoid() + seg_logits = torch.einsum('bqc,bqhw->bchw', mask_cls, mask_pred) + return seg_logits + + def loss(self, x: Tuple[Tensor], batch_data_samples: SampleList, + train_cfg: ConfigType) -> dict: + """Perform forward propagation and loss calculation of the decoder head + on the features of the upstream network. + + Args: + x (tuple[Tensor]): Multi-level features from the upstream + network, each is a 4D-tensor. + batch_data_samples (List[:obj:`SegDataSample`]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + train_cfg (ConfigType): Training config. + + Returns: + dict[str, Tensor]: a dictionary of loss components. + """ + # batch SegDataSample to InstanceDataSample + batch_gt_instances = seg_data_to_instance_data(self.ignore_index, + batch_data_samples) + + # forward + all_mask_props, all_mask_logits = self.forward( + x, self.deep_supervision_idxs) + + # loss + losses = self.loss_by_feat(all_mask_logits, all_mask_props, + batch_gt_instances) + + return losses + + def loss_by_feat( + self, all_cls_scores: Tensor, all_mask_preds: Tensor, + batch_gt_instances: List[InstanceData]) -> Dict[str, Tensor]: + """Loss function. + + Args: + all_cls_scores (Tensor): Classification scores for all decoder + layers with shape (num_decoder, batch_size, num_queries, + cls_out_channels). Note `cls_out_channels` should includes + background. + all_mask_preds (Tensor): Mask scores for all decoder layers with + shape (num_decoder, batch_size, num_queries, h, w). + batch_gt_instances (list[obj:`InstanceData`]): each contains + ``labels`` and ``masks``. + + Returns: + dict[str, Tensor]: A dictionary of loss components. + """ + num_dec_layers = len(all_cls_scores) + batch_gt_instances_list = [ + batch_gt_instances for _ in range(num_dec_layers) + ] + + losses = [] + for i in range(num_dec_layers): + cls_scores = all_cls_scores[i] + mask_preds = all_mask_preds[i] + # matching N mask predictions to K category labels + (labels, mask_targets, mask_weights, + avg_factor) = self.match_masks.get_targets( + cls_scores, mask_preds, batch_gt_instances_list[i]) + cls_scores = cls_scores.flatten(0, 1) + labels = labels.flatten(0, 1) + num_total_masks = cls_scores.new_tensor([avg_factor], + dtype=torch.float) + all_reduce(num_total_masks, op='mean') + num_total_masks = max(num_total_masks, 1) + + # extract positive ones + # shape (batch_size, num_queries, h, w) -> (num_total_gts, h, w) + mask_preds = mask_preds[mask_weights > 0] + + if mask_targets.shape[0] != 0: + with torch.no_grad(): + points_coords = get_uncertain_point_coords_with_randomness( + mask_preds.unsqueeze(1), None, + self.train_cfg.num_points, + self.train_cfg.oversample_ratio, + self.train_cfg.importance_sample_ratio) + # shape (num_total_gts, h, w) + # -> (num_total_gts, num_points) + mask_point_targets = point_sample( + mask_targets.unsqueeze(1).float(), + points_coords).squeeze(1) + # shape (num_queries, h, w) -> (num_queries, num_points) + mask_point_preds = point_sample( + mask_preds.unsqueeze(1), points_coords).squeeze(1) + + if not isinstance(self.loss_decode, nn.ModuleList): + losses_decode = [self.loss_decode] + else: + losses_decode = self.loss_decode + loss = dict() + for loss_decode in losses_decode: + if 'loss_cls' in loss_decode.loss_name: + if loss_decode.loss_name == 'loss_cls_ce': + loss[loss_decode.loss_name] = loss_decode( + cls_scores, labels) + else: + assert False, "Only support 'CrossEntropyLoss' in" \ + ' classification loss' + + elif 'loss_mask' in loss_decode.loss_name: + if mask_targets.shape[0] == 0: + loss[loss_decode.loss_name] = mask_preds.sum() + elif loss_decode.loss_name == 'loss_mask_ce': + loss[loss_decode.loss_name] = loss_decode( + mask_point_preds, + mask_point_targets, + avg_factor=num_total_masks * + self.train_cfg.num_points) + elif loss_decode.loss_name == 'loss_mask_dice': + loss[loss_decode.loss_name] = loss_decode( + mask_point_preds, + mask_point_targets, + avg_factor=num_total_masks) + else: + assert False, "Only support 'CrossEntropyLoss' and" \ + " 'DiceLoss' in mask loss" + else: + assert False, "Only support for 'loss_cls' and 'loss_mask'" + + losses.append(loss) + + loss_dict = dict() + # loss from the last decoder layer + loss_dict.update(losses[-1]) + # loss from other decoder layers + for i, loss in enumerate(losses[:-1]): + for k, v in loss.items(): + loss_dict[f'd{self.deep_supervision_idxs[i]}.{k}'] = v + return loss_dict diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/segformer_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/segformer_head.py new file mode 100644 index 0000000000000000000000000000000000000000..f9eb0b320b4e7b892e0540cea5ba5ea7054f8008 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/segformer_head.py @@ -0,0 +1,66 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.models.decode_heads.decode_head import BaseDecodeHead +from mmseg.registry import MODELS +from ..utils import resize + + +@MODELS.register_module() +class SegformerHead(BaseDecodeHead): + """The all mlp Head of segformer. + + This head is the implementation of + `Segformer ` _. + + Args: + interpolate_mode: The interpolate mode of MLP head upsample operation. + Default: 'bilinear'. + """ + + def __init__(self, interpolate_mode='bilinear', **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + + self.interpolate_mode = interpolate_mode + num_inputs = len(self.in_channels) + + assert num_inputs == len(self.in_index) + + self.convs = nn.ModuleList() + for i in range(num_inputs): + self.convs.append( + ConvModule( + in_channels=self.in_channels[i], + out_channels=self.channels, + kernel_size=1, + stride=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + + self.fusion_conv = ConvModule( + in_channels=self.channels * num_inputs, + out_channels=self.channels, + kernel_size=1, + norm_cfg=self.norm_cfg) + + def forward(self, inputs): + # Receive 4 stage backbone feature map: 1/4, 1/8, 1/16, 1/32 + inputs = self._transform_inputs(inputs) + outs = [] + for idx in range(len(inputs)): + x = inputs[idx] + conv = self.convs[idx] + outs.append( + resize( + input=conv(x), + size=inputs[0].shape[2:], + mode=self.interpolate_mode, + align_corners=self.align_corners)) + + out = self.fusion_conv(torch.cat(outs, dim=1)) + + out = self.cls_seg(out) + + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/segmenter_mask_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/segmenter_mask_head.py new file mode 100644 index 0000000000000000000000000000000000000000..85d27735ba8015772324177716b5e8d5f357295c --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/segmenter_mask_head.py @@ -0,0 +1,132 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import build_norm_layer +from mmengine.model import ModuleList +from mmengine.model.weight_init import (constant_init, trunc_normal_, + trunc_normal_init) + +from mmseg.models.backbones.vit import TransformerEncoderLayer +from mmseg.registry import MODELS +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class SegmenterMaskTransformerHead(BaseDecodeHead): + """Segmenter: Transformer for Semantic Segmentation. + + This head is the implementation of + `Segmenter: `_. + + Args: + backbone_cfg:(dict): Config of backbone of + Context Path. + in_channels (int): The number of channels of input image. + num_layers (int): The depth of transformer. + num_heads (int): The number of attention heads. + embed_dims (int): The number of embedding dimension. + mlp_ratio (int): ratio of mlp hidden dim to embedding dim. + Default: 4. + drop_path_rate (float): stochastic depth rate. Default 0.1. + drop_rate (float): Probability of an element to be zeroed. + Default 0.0 + attn_drop_rate (float): The drop out rate for attention layer. + Default 0.0 + num_fcs (int): The number of fully-connected layers for FFNs. + Default: 2. + qkv_bias (bool): Enable bias for qkv if True. Default: True. + act_cfg (dict): The activation config for FFNs. + Default: dict(type='GELU'). + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='LN') + init_std (float): The value of std in weight initialization. + Default: 0.02. + """ + + def __init__( + self, + in_channels, + num_layers, + num_heads, + embed_dims, + mlp_ratio=4, + drop_path_rate=0.1, + drop_rate=0.0, + attn_drop_rate=0.0, + num_fcs=2, + qkv_bias=True, + act_cfg=dict(type='GELU'), + norm_cfg=dict(type='LN'), + init_std=0.02, + **kwargs, + ): + super().__init__(in_channels=in_channels, **kwargs) + + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, num_layers)] + self.layers = ModuleList() + for i in range(num_layers): + self.layers.append( + TransformerEncoderLayer( + embed_dims=embed_dims, + num_heads=num_heads, + feedforward_channels=mlp_ratio * embed_dims, + attn_drop_rate=attn_drop_rate, + drop_rate=drop_rate, + drop_path_rate=dpr[i], + num_fcs=num_fcs, + qkv_bias=qkv_bias, + act_cfg=act_cfg, + norm_cfg=norm_cfg, + batch_first=True, + )) + + self.dec_proj = nn.Linear(in_channels, embed_dims) + + self.cls_emb = nn.Parameter( + torch.randn(1, self.num_classes, embed_dims)) + self.patch_proj = nn.Linear(embed_dims, embed_dims, bias=False) + self.classes_proj = nn.Linear(embed_dims, embed_dims, bias=False) + + self.decoder_norm = build_norm_layer( + norm_cfg, embed_dims, postfix=1)[1] + self.mask_norm = build_norm_layer( + norm_cfg, self.num_classes, postfix=2)[1] + + self.init_std = init_std + + delattr(self, 'conv_seg') + + def init_weights(self): + trunc_normal_(self.cls_emb, std=self.init_std) + trunc_normal_init(self.patch_proj, std=self.init_std) + trunc_normal_init(self.classes_proj, std=self.init_std) + for n, m in self.named_modules(): + if isinstance(m, nn.Linear): + trunc_normal_init(m, std=self.init_std, bias=0) + elif isinstance(m, nn.LayerNorm): + constant_init(m, val=1.0, bias=0.0) + + def forward(self, inputs): + x = self._transform_inputs(inputs) + b, c, h, w = x.shape + x = x.permute(0, 2, 3, 1).contiguous().view(b, -1, c) + + x = self.dec_proj(x) + cls_emb = self.cls_emb.expand(x.size(0), -1, -1) + x = torch.cat((x, cls_emb), 1) + for layer in self.layers: + x = layer(x) + x = self.decoder_norm(x) + + patches = self.patch_proj(x[:, :-self.num_classes]) + cls_seg_feat = self.classes_proj(x[:, -self.num_classes:]) + + patches = F.normalize(patches, dim=2, p=2) + cls_seg_feat = F.normalize(cls_seg_feat, dim=2, p=2) + + masks = patches @ cls_seg_feat.transpose(1, 2) + masks = self.mask_norm(masks) + masks = masks.permute(0, 2, 1).contiguous().view(b, -1, h, w) + + return masks diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_aspp_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_aspp_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9dba68c9ecc6909e47da4f2da6169d529910355d --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_aspp_head.py @@ -0,0 +1,102 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .aspp_head import ASPPHead, ASPPModule + + +class DepthwiseSeparableASPPModule(ASPPModule): + """Atrous Spatial Pyramid Pooling (ASPP) Module with depthwise separable + conv.""" + + def __init__(self, **kwargs): + super().__init__(**kwargs) + for i, dilation in enumerate(self.dilations): + if dilation > 1: + self[i] = DepthwiseSeparableConvModule( + self.in_channels, + self.channels, + 3, + dilation=dilation, + padding=dilation, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + +@MODELS.register_module() +class DepthwiseSeparableASPPHead(ASPPHead): + """Encoder-Decoder with Atrous Separable Convolution for Semantic Image + Segmentation. + + This head is the implementation of `DeepLabV3+ + `_. + + Args: + c1_in_channels (int): The input channels of c1 decoder. If is 0, + the no decoder will be used. + c1_channels (int): The intermediate channels of c1 decoder. + """ + + def __init__(self, c1_in_channels, c1_channels, **kwargs): + super().__init__(**kwargs) + assert c1_in_channels >= 0 + self.aspp_modules = DepthwiseSeparableASPPModule( + dilations=self.dilations, + in_channels=self.in_channels, + channels=self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + if c1_in_channels > 0: + self.c1_bottleneck = ConvModule( + c1_in_channels, + c1_channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + else: + self.c1_bottleneck = None + self.sep_bottleneck = nn.Sequential( + DepthwiseSeparableConvModule( + self.channels + c1_channels, + self.channels, + 3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + DepthwiseSeparableConvModule( + self.channels, + self.channels, + 3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg)) + + def forward(self, inputs): + """Forward function.""" + x = self._transform_inputs(inputs) + aspp_outs = [ + resize( + self.image_pool(x), + size=x.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + ] + aspp_outs.extend(self.aspp_modules(x)) + aspp_outs = torch.cat(aspp_outs, dim=1) + output = self.bottleneck(aspp_outs) + if self.c1_bottleneck is not None: + c1_output = self.c1_bottleneck(inputs[0]) + output = resize( + input=output, + size=c1_output.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + output = torch.cat([output, c1_output], dim=1) + output = self.sep_bottleneck(output) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_fcn_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_fcn_head.py new file mode 100644 index 0000000000000000000000000000000000000000..3b15983bceaeff48534bbceedfdf1c434a8d1d1f --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/sep_fcn_head.py @@ -0,0 +1,60 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.cnn import DepthwiseSeparableConvModule + +from mmseg.registry import MODELS +from .fcn_head import FCNHead + + +@MODELS.register_module() +class DepthwiseSeparableFCNHead(FCNHead): + """Depthwise-Separable Fully Convolutional Network for Semantic + Segmentation. + + This head is implemented according to `Fast-SCNN: Fast Semantic + Segmentation Network `_. + + Args: + in_channels(int): Number of output channels of FFM. + channels(int): Number of middle-stage channels in the decode head. + concat_input(bool): Whether to concatenate original decode input into + the result of several consecutive convolution layers. + Default: True. + num_classes(int): Used to determine the dimension of + final prediction tensor. + in_index(int): Correspond with 'out_indices' in FastSCNN backbone. + norm_cfg (dict | None): Config of norm layers. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + loss_decode(dict): Config of loss type and some + relevant additional options. + dw_act_cfg (dict):Activation config of depthwise ConvModule. If it is + 'default', it will be the same as `act_cfg`. Default: None. + """ + + def __init__(self, dw_act_cfg=None, **kwargs): + super().__init__(**kwargs) + self.convs[0] = DepthwiseSeparableConvModule( + self.in_channels, + self.channels, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + norm_cfg=self.norm_cfg, + dw_act_cfg=dw_act_cfg) + + for i in range(1, self.num_convs): + self.convs[i] = DepthwiseSeparableConvModule( + self.channels, + self.channels, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + norm_cfg=self.norm_cfg, + dw_act_cfg=dw_act_cfg) + + if self.concat_input: + self.conv_cat = DepthwiseSeparableConvModule( + self.in_channels + self.channels, + self.channels, + kernel_size=self.kernel_size, + padding=self.kernel_size // 2, + norm_cfg=self.norm_cfg, + dw_act_cfg=dw_act_cfg) diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_mla_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_mla_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1975991a60cc720650b880060efe10753f213131 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_mla_head.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import Upsample +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class SETRMLAHead(BaseDecodeHead): + """Multi level feature aggretation head of SETR. + + MLA head of `SETR `_. + + Args: + mlahead_channels (int): Channels of conv-conv-4x of multi-level feature + aggregation. Default: 128. + up_scale (int): The scale factor of interpolate. Default:4. + """ + + def __init__(self, mla_channels=128, up_scale=4, **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + self.mla_channels = mla_channels + + num_inputs = len(self.in_channels) + + # Refer to self.cls_seg settings of BaseDecodeHead + assert self.channels == num_inputs * mla_channels + + self.up_convs = nn.ModuleList() + for i in range(num_inputs): + self.up_convs.append( + nn.Sequential( + ConvModule( + in_channels=self.in_channels[i], + out_channels=mla_channels, + kernel_size=3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + ConvModule( + in_channels=mla_channels, + out_channels=mla_channels, + kernel_size=3, + padding=1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + Upsample( + scale_factor=up_scale, + mode='bilinear', + align_corners=self.align_corners))) + + def forward(self, inputs): + inputs = self._transform_inputs(inputs) + outs = [] + for x, up_conv in zip(inputs, self.up_convs): + outs.append(up_conv(x)) + out = torch.cat(outs, dim=1) + out = self.cls_seg(out) + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_up_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_up_head.py new file mode 100644 index 0000000000000000000000000000000000000000..9c796d8161088c2d7effe17f5ba71e43ff62e50c --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/setr_up_head.py @@ -0,0 +1,81 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import ConvModule, build_norm_layer + +from mmseg.registry import MODELS +from ..utils import Upsample +from .decode_head import BaseDecodeHead + + +@MODELS.register_module() +class SETRUPHead(BaseDecodeHead): + """Naive upsampling head and Progressive upsampling head of SETR. + + Naive or PUP head of `SETR `_. + + Args: + norm_layer (dict): Config dict for input normalization. + Default: norm_layer=dict(type='LN', eps=1e-6, requires_grad=True). + num_convs (int): Number of decoder convolutions. Default: 1. + up_scale (int): The scale factor of interpolate. Default:4. + kernel_size (int): The kernel size of convolution when decoding + feature information from backbone. Default: 3. + init_cfg (dict | list[dict] | None): Initialization config dict. + Default: dict( + type='Constant', val=1.0, bias=0, layer='LayerNorm'). + """ + + def __init__(self, + norm_layer=dict(type='LN', eps=1e-6, requires_grad=True), + num_convs=1, + up_scale=4, + kernel_size=3, + init_cfg=[ + dict(type='Constant', val=1.0, bias=0, layer='LayerNorm'), + dict( + type='Normal', + std=0.01, + override=dict(name='conv_seg')) + ], + **kwargs): + + assert kernel_size in [1, 3], 'kernel_size must be 1 or 3.' + + super().__init__(init_cfg=init_cfg, **kwargs) + + assert isinstance(self.in_channels, int) + + _, self.norm = build_norm_layer(norm_layer, self.in_channels) + + self.up_convs = nn.ModuleList() + in_channels = self.in_channels + out_channels = self.channels + for _ in range(num_convs): + self.up_convs.append( + nn.Sequential( + ConvModule( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=1, + padding=int(kernel_size - 1) // 2, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg), + Upsample( + scale_factor=up_scale, + mode='bilinear', + align_corners=self.align_corners))) + in_channels = out_channels + + def forward(self, x): + x = self._transform_inputs(x) + + n, c, h, w = x.shape + x = x.reshape(n, c, h * w).transpose(2, 1).contiguous() + x = self.norm(x) + x = x.transpose(1, 2).reshape(n, c, h, w).contiguous() + + for up_conv in self.up_convs: + x = up_conv(x) + out = self.cls_seg(x) + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/stdc_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/stdc_head.py new file mode 100644 index 0000000000000000000000000000000000000000..1c1c21e3083fcb5098d2458e44538c0cf5b8f0e4 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/stdc_head.py @@ -0,0 +1,97 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn.functional as F +from mmengine.structures import PixelData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures import SegDataSample +from mmseg.utils import SampleList +from .fcn_head import FCNHead + + +@MODELS.register_module() +class STDCHead(FCNHead): + """This head is the implementation of `Rethinking BiSeNet For Real-time + Semantic Segmentation `_. + + Args: + boundary_threshold (float): The threshold of calculating boundary. + Default: 0.1. + """ + + def __init__(self, boundary_threshold=0.1, **kwargs): + super().__init__(**kwargs) + self.boundary_threshold = boundary_threshold + # Using register buffer to make laplacian kernel on the same + # device of `seg_label`. + self.register_buffer( + 'laplacian_kernel', + torch.tensor([-1, -1, -1, -1, 8, -1, -1, -1, -1], + dtype=torch.float32, + requires_grad=False).reshape((1, 1, 3, 3))) + self.fusion_kernel = torch.nn.Parameter( + torch.tensor([[6. / 10], [3. / 10], [1. / 10]], + dtype=torch.float32).reshape(1, 3, 1, 1), + requires_grad=False) + + def loss_by_feat(self, seg_logits: Tensor, + batch_data_samples: SampleList) -> dict: + """Compute Detail Aggregation Loss.""" + # Note: The paper claims `fusion_kernel` is a trainable 1x1 conv + # parameters. However, it is a constant in original repo and other + # codebase because it would not be added into computation graph + # after threshold operation. + seg_label = self._stack_batch_gt(batch_data_samples).to( + self.laplacian_kernel) + boundary_targets = F.conv2d( + seg_label, self.laplacian_kernel, padding=1) + boundary_targets = boundary_targets.clamp(min=0) + boundary_targets[boundary_targets > self.boundary_threshold] = 1 + boundary_targets[boundary_targets <= self.boundary_threshold] = 0 + + boundary_targets_x2 = F.conv2d( + seg_label, self.laplacian_kernel, stride=2, padding=1) + boundary_targets_x2 = boundary_targets_x2.clamp(min=0) + + boundary_targets_x4 = F.conv2d( + seg_label, self.laplacian_kernel, stride=4, padding=1) + boundary_targets_x4 = boundary_targets_x4.clamp(min=0) + + boundary_targets_x4_up = F.interpolate( + boundary_targets_x4, boundary_targets.shape[2:], mode='nearest') + boundary_targets_x2_up = F.interpolate( + boundary_targets_x2, boundary_targets.shape[2:], mode='nearest') + + boundary_targets_x2_up[ + boundary_targets_x2_up > self.boundary_threshold] = 1 + boundary_targets_x2_up[ + boundary_targets_x2_up <= self.boundary_threshold] = 0 + + boundary_targets_x4_up[ + boundary_targets_x4_up > self.boundary_threshold] = 1 + boundary_targets_x4_up[ + boundary_targets_x4_up <= self.boundary_threshold] = 0 + + boundary_targets_pyramids = torch.stack( + (boundary_targets, boundary_targets_x2_up, boundary_targets_x4_up), + dim=1) + + boundary_targets_pyramids = boundary_targets_pyramids.squeeze(2) + boudary_targets_pyramid = F.conv2d(boundary_targets_pyramids, + self.fusion_kernel) + + boudary_targets_pyramid[ + boudary_targets_pyramid > self.boundary_threshold] = 1 + boudary_targets_pyramid[ + boudary_targets_pyramid <= self.boundary_threshold] = 0 + + seg_labels = boudary_targets_pyramid.long() + batch_sample_list = [] + for label in seg_labels: + seg_data_sample = SegDataSample() + seg_data_sample.gt_sem_seg = PixelData(data=label) + batch_sample_list.append(seg_data_sample) + + loss = super().loss_by_feat(seg_logits, batch_sample_list) + return loss diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/uper_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/uper_head.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ccc3173c0f1193e89ad48861aa7b5ee3b329cc --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/uper_head.py @@ -0,0 +1,139 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule + +from mmseg.registry import MODELS +from ..utils import resize +from .decode_head import BaseDecodeHead +from .psp_head import PPM + + +@MODELS.register_module() +class UPerHead(BaseDecodeHead): + """Unified Perceptual Parsing for Scene Understanding. + + This head is the implementation of `UPerNet + `_. + + Args: + pool_scales (tuple[int]): Pooling scales used in Pooling Pyramid + Module applied on the last feature. Default: (1, 2, 3, 6). + """ + + def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs): + super().__init__(input_transform='multiple_select', **kwargs) + # PSP Module + self.psp_modules = PPM( + pool_scales, + self.in_channels[-1], + self.channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=self.align_corners) + self.bottleneck = ConvModule( + self.in_channels[-1] + len(pool_scales) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + # FPN Module + self.lateral_convs = nn.ModuleList() + self.fpn_convs = nn.ModuleList() + for in_channels in self.in_channels[:-1]: # skip the top layer + l_conv = ConvModule( + in_channels, + self.channels, + 1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + inplace=False) + fpn_conv = ConvModule( + self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + inplace=False) + self.lateral_convs.append(l_conv) + self.fpn_convs.append(fpn_conv) + + self.fpn_bottleneck = ConvModule( + len(self.in_channels) * self.channels, + self.channels, + 3, + padding=1, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg) + + def psp_forward(self, inputs): + """Forward function of PSP module.""" + x = inputs[-1] + psp_outs = [x] + psp_outs.extend(self.psp_modules(x)) + psp_outs = torch.cat(psp_outs, dim=1) + output = self.bottleneck(psp_outs) + + return output + + def _forward_feature(self, inputs): + """Forward function for feature maps before classifying each pixel with + ``self.cls_seg`` fc. + + Args: + inputs (list[Tensor]): List of multi-level img features. + + Returns: + feats (Tensor): A tensor of shape (batch_size, self.channels, + H, W) which is feature map for last layer of decoder head. + """ + inputs = self._transform_inputs(inputs) + + # build laterals + laterals = [ + lateral_conv(inputs[i]) + for i, lateral_conv in enumerate(self.lateral_convs) + ] + + laterals.append(self.psp_forward(inputs)) + + # build top-down path + used_backbone_levels = len(laterals) + for i in range(used_backbone_levels - 1, 0, -1): + prev_shape = laterals[i - 1].shape[2:] + laterals[i - 1] = laterals[i - 1] + resize( + laterals[i], + size=prev_shape, + mode='bilinear', + align_corners=self.align_corners) + + # build outputs + fpn_outs = [ + self.fpn_convs[i](laterals[i]) + for i in range(used_backbone_levels - 1) + ] + # append psp feature + fpn_outs.append(laterals[-1]) + + for i in range(used_backbone_levels - 1, 0, -1): + fpn_outs[i] = resize( + fpn_outs[i], + size=fpn_outs[0].shape[2:], + mode='bilinear', + align_corners=self.align_corners) + fpn_outs = torch.cat(fpn_outs, dim=1) + feats = self.fpn_bottleneck(fpn_outs) + return feats + + def forward(self, inputs): + """Forward function.""" + output = self._forward_feature(inputs) + output = self.cls_seg(output) + return output diff --git a/reconstruction/modules/InterFormer/mmseg/models/decode_heads/vpd_depth_head.py b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/vpd_depth_head.py new file mode 100644 index 0000000000000000000000000000000000000000..65bdfbd8d9065c158f4f6a147cd8c06ae1dfd961 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/decode_heads/vpd_depth_head.py @@ -0,0 +1,253 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Dict, List, Optional, Sequence, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import build_conv_layer, build_norm_layer, build_upsample_layer +from mmengine.model import BaseModule +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import SampleList +from ..utils import resize +from .decode_head import BaseDecodeHead + + +class VPDDepthDecoder(BaseModule): + """VPD Depth Decoder class. + + Args: + in_channels (int): Number of input channels. + out_channels (int): Number of output channels. + num_deconv_layers (int): Number of deconvolution layers. + num_deconv_filters (List[int]): List of output channels for + deconvolution layers. + init_cfg (Optional[Union[Dict, List[Dict]]], optional): Configuration + for weight initialization. Defaults to Normal for Conv2d and + ConvTranspose2d layers. + """ + + def __init__(self, + in_channels: int, + out_channels: int, + num_deconv_layers: int, + num_deconv_filters: List[int], + init_cfg: Optional[Union[Dict, List[Dict]]] = dict( + type='Normal', + std=0.001, + layer=['Conv2d', 'ConvTranspose2d'])): + super().__init__(init_cfg=init_cfg) + self.in_channels = in_channels + + self.deconv_layers = self._make_deconv_layer( + num_deconv_layers, + num_deconv_filters, + ) + + conv_layers = [] + conv_layers.append( + build_conv_layer( + dict(type='Conv2d'), + in_channels=num_deconv_filters[-1], + out_channels=out_channels, + kernel_size=3, + stride=1, + padding=1)) + conv_layers.append(build_norm_layer(dict(type='BN'), out_channels)[1]) + conv_layers.append(nn.ReLU(inplace=True)) + self.conv_layers = nn.Sequential(*conv_layers) + + self.up_sample = nn.Upsample( + scale_factor=2, mode='bilinear', align_corners=False) + + def forward(self, x): + """Forward pass through the decoder network.""" + out = self.deconv_layers(x) + out = self.conv_layers(out) + + out = self.up_sample(out) + out = self.up_sample(out) + + return out + + def _make_deconv_layer(self, num_layers, num_deconv_filters): + """Make deconv layers.""" + + layers = [] + in_channels = self.in_channels + for i in range(num_layers): + + num_channels = num_deconv_filters[i] + layers.append( + build_upsample_layer( + dict(type='deconv'), + in_channels=in_channels, + out_channels=num_channels, + kernel_size=2, + stride=2, + padding=0, + output_padding=0, + bias=False)) + layers.append(nn.BatchNorm2d(num_channels)) + layers.append(nn.ReLU(inplace=True)) + in_channels = num_channels + + return nn.Sequential(*layers) + + +@MODELS.register_module() +class VPDDepthHead(BaseDecodeHead): + """Depth Prediction Head for VPD. + + .. _`VPD`: https://arxiv.org/abs/2303.02153 + + Args: + max_depth (float): Maximum depth value. Defaults to 10.0. + in_channels (Sequence[int]): Number of input channels for each + convolutional layer. + embed_dim (int): Dimension of embedding. Defaults to 192. + feature_dim (int): Dimension of aggregated feature. Defaults to 1536. + num_deconv_layers (int): Number of deconvolution layers in the + decoder. Defaults to 3. + num_deconv_filters (Sequence[int]): Number of filters for each deconv + layer. Defaults to (32, 32, 32). + fmap_border (Union[int, Sequence[int]]): Feature map border for + cropping. Defaults to 0. + align_corners (bool): Flag for align_corners in interpolation. + Defaults to False. + loss_decode (dict): Configurations for the loss function. Defaults to + dict(type='SiLogLoss'). + init_cfg (dict): Initialization configurations. Defaults to + dict(type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']). + """ + + num_classes = 1 + out_channels = 1 + input_transform = None + + def __init__( + self, + max_depth: float = 10.0, + in_channels: Sequence[int] = [320, 640, 1280, 1280], + embed_dim: int = 192, + feature_dim: int = 1536, + num_deconv_layers: int = 3, + num_deconv_filters: Sequence[int] = (32, 32, 32), + fmap_border: Union[int, Sequence[int]] = 0, + align_corners: bool = False, + loss_decode: dict = dict(type='SiLogLoss'), + init_cfg=dict( + type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']), + ): + + super(BaseDecodeHead, self).__init__(init_cfg=init_cfg) + + # initialize parameters + self.in_channels = in_channels + self.max_depth = max_depth + self.align_corners = align_corners + + # feature map border + if isinstance(fmap_border, int): + fmap_border = (fmap_border, fmap_border) + self.fmap_border = fmap_border + + # define network layers + self.conv1 = nn.Sequential( + nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1), + nn.GroupNorm(16, in_channels[0]), + nn.ReLU(), + nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1), + ) + self.conv2 = nn.Conv2d( + in_channels[1], in_channels[1], 3, stride=2, padding=1) + + self.conv_aggregation = nn.Sequential( + nn.Conv2d(sum(in_channels), feature_dim, 1), + nn.GroupNorm(16, feature_dim), + nn.ReLU(), + ) + + self.decoder = VPDDepthDecoder( + in_channels=embed_dim * 8, + out_channels=embed_dim, + num_deconv_layers=num_deconv_layers, + num_deconv_filters=num_deconv_filters) + + self.depth_pred_layer = nn.Sequential( + nn.Conv2d( + embed_dim, embed_dim, kernel_size=3, stride=1, padding=1), + nn.ReLU(inplace=False), + nn.Conv2d(embed_dim, 1, kernel_size=3, stride=1, padding=1)) + + # build loss + if isinstance(loss_decode, dict): + self.loss_decode = MODELS.build(loss_decode) + elif isinstance(loss_decode, (list, tuple)): + self.loss_decode = nn.ModuleList() + for loss in loss_decode: + self.loss_decode.append(MODELS.build(loss)) + else: + raise TypeError(f'loss_decode must be a dict or sequence of dict,\ + but got {type(loss_decode)}') + + def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tensor: + gt_depth_maps = [ + data_sample.gt_depth_map.data for data_sample in batch_data_samples + ] + return torch.stack(gt_depth_maps, dim=0) + + def forward(self, x): + x = [ + x[0], x[1], + torch.cat([x[2], F.interpolate(x[3], scale_factor=2)], dim=1) + ] + x = torch.cat([self.conv1(x[0]), self.conv2(x[1]), x[2]], dim=1) + x = self.conv_aggregation(x) + + x = x[:, :, :x.size(2) - self.fmap_border[0], :x.size(3) - + self.fmap_border[1]].contiguous() + x = self.decoder(x) + out = self.depth_pred_layer(x) + + depth = torch.sigmoid(out) * self.max_depth + + return depth + + def loss_by_feat(self, pred_depth_map: Tensor, + batch_data_samples: SampleList) -> dict: + """Compute depth estimation loss. + + Args: + pred_depth_map (Tensor): The output from decode head forward + function. + batch_data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_dpeth_map`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + + gt_depth_map = self._stack_batch_gt(batch_data_samples) + loss = dict() + pred_depth_map = resize( + input=pred_depth_map, + size=gt_depth_map.shape[2:], + mode='bilinear', + align_corners=self.align_corners) + + if not isinstance(self.loss_decode, nn.ModuleList): + losses_decode = [self.loss_decode] + else: + losses_decode = self.loss_decode + for loss_decode in losses_decode: + if loss_decode.loss_name not in loss: + loss[loss_decode.loss_name] = loss_decode( + pred_depth_map, gt_depth_map) + else: + loss[loss_decode.loss_name] += loss_decode( + pred_depth_map, gt_depth_map) + + return loss diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__init__.py b/reconstruction/modules/InterFormer/mmseg/models/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0467cb3ad89b8c0c57f7f8eb58cbc2e23f50cdb4 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/__init__.py @@ -0,0 +1,21 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .accuracy import Accuracy, accuracy +from .boundary_loss import BoundaryLoss +from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy, + cross_entropy, mask_cross_entropy) +from .dice_loss import DiceLoss +from .focal_loss import FocalLoss +from .huasdorff_distance_loss import HuasdorffDisstanceLoss +from .lovasz_loss import LovaszLoss +from .ohem_cross_entropy_loss import OhemCrossEntropy +from .silog_loss import SiLogLoss +from .tversky_loss import TverskyLoss +from .utils import reduce_loss, weight_reduce_loss, weighted_loss + +__all__ = [ + 'accuracy', 'Accuracy', 'cross_entropy', 'binary_cross_entropy', + 'mask_cross_entropy', 'CrossEntropyLoss', 'reduce_loss', + 'weight_reduce_loss', 'weighted_loss', 'LovaszLoss', 'DiceLoss', + 'FocalLoss', 'TverskyLoss', 'OhemCrossEntropy', 'BoundaryLoss', + 'HuasdorffDisstanceLoss', 'SiLogLoss' +] diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d9368091eea71bcfbfbd10e79988e93e279af4b Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9747958dcb80baf3b7dab5e05f87601c9a645cb8 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39d031f71032e6c5a646e342c141ffa1a3965f84 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b66404b08692387d697d4b570eb174eda171344 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/accuracy.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f275b92bb3f1dd5a409cb64f8fda8db662a4bc3 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c01349750b5c17a1c8998489f7d2f6973ba8f5b5 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/boundary_loss.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/cross_entropy_loss.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/cross_entropy_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5d5f5cc31aefc8d8bcdba8b119ca40e6d4b3287 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/cross_entropy_loss.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/cross_entropy_loss.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/cross_entropy_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dbb82becb90555a78cb29662914bc1fcc5aacdc Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/cross_entropy_loss.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/dice_loss.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/dice_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f42ad3c25e76bc3db8bc740b32b5aaa4bfefd56 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/dice_loss.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/dice_loss.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/dice_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..670d78baabba0922ccd4be1c6080abcbe7705f4b Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/dice_loss.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/focal_loss.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/focal_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..355a07ce19b2a8905ed05a50d830db2ccf5b6f4a Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/focal_loss.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/focal_loss.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/focal_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45e15bcf89da1ac014dbeada7173f849cb2c3720 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/focal_loss.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/huasdorff_distance_loss.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/huasdorff_distance_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52e42d22fd3162ed18356922f8b97a92827a9bb2 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/huasdorff_distance_loss.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/huasdorff_distance_loss.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/huasdorff_distance_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8764f89761a9ee1d51f755d110e724000353a0e Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/huasdorff_distance_loss.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/lovasz_loss.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/lovasz_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e62c22ed2390169fa4e994c9984d95fb2e057cc Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/lovasz_loss.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/lovasz_loss.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/lovasz_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..152f51884868b4af45a66fcada4fd9f10cdb08d3 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/lovasz_loss.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/ohem_cross_entropy_loss.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/ohem_cross_entropy_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cf88151ca529aa12b5e05b7cf3c64ecab0c07a0 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/ohem_cross_entropy_loss.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/ohem_cross_entropy_loss.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/ohem_cross_entropy_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baeaabd07115760f4ec9fe6c983e7dd475074b10 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/ohem_cross_entropy_loss.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/silog_loss.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/silog_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5241aa6302020972c2519634053e97416b63e41d Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/silog_loss.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/silog_loss.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/silog_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b24dc174fc5e53de646f61aa358cf417633305a Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/silog_loss.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/tversky_loss.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/tversky_loss.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e89b77f702f972e8ad25b381988f7363bbb225d7 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/tversky_loss.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/tversky_loss.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/tversky_loss.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3de70327a491b57dd7f45d2529f8d0866279247e Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/tversky_loss.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/utils.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d13a7d56256df5a19f0d255f56aac102cd17ef85 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/utils.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/utils.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/utils.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85496dc9205702f97131a23afb783cfd3f4db774 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/losses/__pycache__/utils.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/accuracy.py b/reconstruction/modules/InterFormer/mmseg/models/losses/accuracy.py new file mode 100644 index 0000000000000000000000000000000000000000..1d9e2d7701088adadd5b6bb71c718c986b87a066 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/accuracy.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn + + +def accuracy(pred, target, topk=1, thresh=None, ignore_index=None): + """Calculate accuracy according to the prediction and target. + + Args: + pred (torch.Tensor): The model prediction, shape (N, num_class, ...) + target (torch.Tensor): The target of each prediction, shape (N, , ...) + ignore_index (int | None): The label index to be ignored. Default: None + topk (int | tuple[int], optional): If the predictions in ``topk`` + matches the target, the predictions will be regarded as + correct ones. Defaults to 1. + thresh (float, optional): If not None, predictions with scores under + this threshold are considered incorrect. Default to None. + + Returns: + float | tuple[float]: If the input ``topk`` is a single integer, + the function will return a single float as accuracy. If + ``topk`` is a tuple containing multiple integers, the + function will return a tuple containing accuracies of + each ``topk`` number. + """ + assert isinstance(topk, (int, tuple)) + if isinstance(topk, int): + topk = (topk, ) + return_single = True + else: + return_single = False + + maxk = max(topk) + if pred.size(0) == 0: + accu = [pred.new_tensor(0.) for i in range(len(topk))] + return accu[0] if return_single else accu + assert pred.ndim == target.ndim + 1 + assert pred.size(0) == target.size(0) + assert maxk <= pred.size(1), \ + f'maxk {maxk} exceeds pred dimension {pred.size(1)}' + pred_value, pred_label = pred.topk(maxk, dim=1) + # transpose to shape (maxk, N, ...) + pred_label = pred_label.transpose(0, 1) + correct = pred_label.eq(target.unsqueeze(0).expand_as(pred_label)) + if thresh is not None: + # Only prediction values larger than thresh are counted as correct + correct = correct & (pred_value > thresh).t() + if ignore_index is not None: + correct = correct[:, target != ignore_index] + res = [] + eps = torch.finfo(torch.float32).eps + for k in topk: + # Avoid causing ZeroDivisionError when all pixels + # of an image are ignored + correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) + eps + if ignore_index is not None: + total_num = target[target != ignore_index].numel() + eps + else: + total_num = target.numel() + eps + res.append(correct_k.mul_(100.0 / total_num)) + return res[0] if return_single else res + + +class Accuracy(nn.Module): + """Accuracy calculation module.""" + + def __init__(self, topk=(1, ), thresh=None, ignore_index=None): + """Module to calculate the accuracy. + + Args: + topk (tuple, optional): The criterion used to calculate the + accuracy. Defaults to (1,). + thresh (float, optional): If not None, predictions with scores + under this threshold are considered incorrect. Default to None. + """ + super().__init__() + self.topk = topk + self.thresh = thresh + self.ignore_index = ignore_index + + def forward(self, pred, target): + """Forward function to calculate accuracy. + + Args: + pred (torch.Tensor): Prediction of models. + target (torch.Tensor): Target for each prediction. + + Returns: + tuple[float]: The accuracies under different topk criterions. + """ + return accuracy(pred, target, self.topk, self.thresh, + self.ignore_index) diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/boundary_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/boundary_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..e86b850d87e1d26be8cbb700758dae8dead82c58 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/boundary_loss.py @@ -0,0 +1,62 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor + +from mmseg.registry import MODELS + + +@MODELS.register_module() +class BoundaryLoss(nn.Module): + """Boundary loss. + + This function is modified from + `PIDNet `_. # noqa + Licensed under the MIT License. + + + Args: + loss_weight (float): Weight of the loss. Defaults to 1.0. + loss_name (str): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_boundary'. + """ + + def __init__(self, + loss_weight: float = 1.0, + loss_name: str = 'loss_boundary'): + super().__init__() + self.loss_weight = loss_weight + self.loss_name_ = loss_name + + def forward(self, bd_pre: Tensor, bd_gt: Tensor) -> Tensor: + """Forward function. + Args: + bd_pre (Tensor): Predictions of the boundary head. + bd_gt (Tensor): Ground truth of the boundary. + + Returns: + Tensor: Loss tensor. + """ + log_p = bd_pre.permute(0, 2, 3, 1).contiguous().view(1, -1) + target_t = bd_gt.view(1, -1).float() + + pos_index = (target_t == 1) + neg_index = (target_t == 0) + + weight = torch.zeros_like(log_p) + pos_num = pos_index.sum() + neg_num = neg_index.sum() + sum_num = pos_num + neg_num + weight[pos_index] = neg_num * 1.0 / sum_num + weight[neg_index] = pos_num * 1.0 / sum_num + + loss = F.binary_cross_entropy_with_logits( + log_p, target_t, weight, reduction='mean') + + return self.loss_weight * loss + + @property + def loss_name(self): + return self.loss_name_ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/cross_entropy_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/cross_entropy_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..988fb789c11eca9d002b2c02f227450d704aeaef --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/cross_entropy_loss.py @@ -0,0 +1,311 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from mmseg.registry import MODELS +from .utils import get_class_weight, weight_reduce_loss + + +def cross_entropy(pred, + label, + weight=None, + class_weight=None, + reduction='mean', + avg_factor=None, + ignore_index=-100, + avg_non_ignore=False): + """cross_entropy. The wrapper function for :func:`F.cross_entropy` + + Args: + pred (torch.Tensor): The prediction with shape (N, 1). + label (torch.Tensor): The learning label of the prediction. + weight (torch.Tensor, optional): Sample-wise loss weight. + Default: None. + class_weight (list[float], optional): The weight for each class. + Default: None. + reduction (str, optional): The method used to reduce the loss. + Options are 'none', 'mean' and 'sum'. Default: 'mean'. + avg_factor (int, optional): Average factor that is used to average + the loss. Default: None. + ignore_index (int): Specifies a target value that is ignored and + does not contribute to the input gradients. When + ``avg_non_ignore `` is ``True``, and the ``reduction`` is + ``''mean''``, the loss is averaged over non-ignored targets. + Defaults: -100. + avg_non_ignore (bool): The flag decides to whether the loss is + only averaged over non-ignored targets. Default: False. + `New in version 0.23.0.` + """ + + # class_weight is a manual rescaling weight given to each class. + # If given, has to be a Tensor of size C element-wise losses + loss = F.cross_entropy( + pred, + label, + weight=class_weight, + reduction='none', + ignore_index=ignore_index) + + # apply weights and do the reduction + # average loss over non-ignored elements + # pytorch's official cross_entropy average loss over non-ignored elements + # refer to https://github.com/pytorch/pytorch/blob/56b43f4fec1f76953f15a627694d4bba34588969/torch/nn/functional.py#L2660 # noqa + if (avg_factor is None) and reduction == 'mean': + if class_weight is None: + if avg_non_ignore: + avg_factor = label.numel() - (label + == ignore_index).sum().item() + else: + avg_factor = label.numel() + + else: + # the average factor should take the class weights into account + label_weights = torch.stack([class_weight[cls] for cls in label + ]).to(device=class_weight.device) + + if avg_non_ignore: + label_weights[label == ignore_index] = 0 + avg_factor = label_weights.sum() + + if weight is not None: + weight = weight.float() + loss = weight_reduce_loss( + loss, weight=weight, reduction=reduction, avg_factor=avg_factor) + + return loss + + +def _expand_onehot_labels(labels, label_weights, target_shape, ignore_index): + """Expand onehot labels to match the size of prediction.""" + bin_labels = labels.new_zeros(target_shape) + valid_mask = (labels >= 0) & (labels != ignore_index) + inds = torch.nonzero(valid_mask, as_tuple=True) + + if inds[0].numel() > 0: + if labels.dim() == 3: + bin_labels[inds[0], labels[valid_mask], inds[1], inds[2]] = 1 + else: + bin_labels[inds[0], labels[valid_mask]] = 1 + + valid_mask = valid_mask.unsqueeze(1).expand(target_shape).float() + + if label_weights is None: + bin_label_weights = valid_mask + else: + bin_label_weights = label_weights.unsqueeze(1).expand(target_shape) + bin_label_weights = bin_label_weights * valid_mask + + return bin_labels, bin_label_weights, valid_mask + + +def binary_cross_entropy(pred, + label, + weight=None, + reduction='mean', + avg_factor=None, + class_weight=None, + ignore_index=-100, + avg_non_ignore=False, + **kwargs): + """Calculate the binary CrossEntropy loss. + + Args: + pred (torch.Tensor): The prediction with shape (N, 1). + label (torch.Tensor): The learning label of the prediction. + Note: In bce loss, label < 0 is invalid. + weight (torch.Tensor, optional): Sample-wise loss weight. + reduction (str, optional): The method used to reduce the loss. + Options are "none", "mean" and "sum". + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + class_weight (list[float], optional): The weight for each class. + ignore_index (int): The label index to be ignored. Default: -100. + avg_non_ignore (bool): The flag decides to whether the loss is + only averaged over non-ignored targets. Default: False. + `New in version 0.23.0.` + + Returns: + torch.Tensor: The calculated loss + """ + if pred.size(1) == 1: + # For binary class segmentation, the shape of pred is + # [N, 1, H, W] and that of label is [N, H, W]. + # As the ignore_index often set as 255, so the + # binary class label check should mask out + # ignore_index + assert label[label != ignore_index].max() <= 1, \ + 'For pred with shape [N, 1, H, W], its label must have at ' \ + 'most 2 classes' + pred = pred.squeeze(1) + if pred.dim() != label.dim(): + assert (pred.dim() == 2 and label.dim() == 1) or ( + pred.dim() == 4 and label.dim() == 3), \ + 'Only pred shape [N, C], label shape [N] or pred shape [N, C, ' \ + 'H, W], label shape [N, H, W] are supported' + # `weight` returned from `_expand_onehot_labels` + # has been treated for valid (non-ignore) pixels + label, weight, valid_mask = _expand_onehot_labels( + label, weight, pred.shape, ignore_index) + else: + # should mask out the ignored elements + valid_mask = ((label >= 0) & (label != ignore_index)).float() + if weight is not None: + weight = weight * valid_mask + else: + weight = valid_mask + # average loss over non-ignored and valid elements + if reduction == 'mean' and avg_factor is None and avg_non_ignore: + avg_factor = valid_mask.sum().item() + + loss = F.binary_cross_entropy_with_logits( + pred, label.float(), pos_weight=class_weight, reduction='none') + # do the reduction for the weighted loss + loss = weight_reduce_loss( + loss, weight, reduction=reduction, avg_factor=avg_factor) + + return loss + + +def mask_cross_entropy(pred, + target, + label, + reduction='mean', + avg_factor=None, + class_weight=None, + ignore_index=None, + **kwargs): + """Calculate the CrossEntropy loss for masks. + + Args: + pred (torch.Tensor): The prediction with shape (N, C), C is the number + of classes. + target (torch.Tensor): The learning label of the prediction. + label (torch.Tensor): ``label`` indicates the class label of the mask' + corresponding object. This will be used to select the mask in the + of the class which the object belongs to when the mask prediction + if not class-agnostic. + reduction (str, optional): The method used to reduce the loss. + Options are "none", "mean" and "sum". + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + class_weight (list[float], optional): The weight for each class. + ignore_index (None): Placeholder, to be consistent with other loss. + Default: None. + + Returns: + torch.Tensor: The calculated loss + """ + assert ignore_index is None, 'BCE loss does not support ignore_index' + # TODO: handle these two reserved arguments + assert reduction == 'mean' and avg_factor is None + num_rois = pred.size()[0] + inds = torch.arange(0, num_rois, dtype=torch.long, device=pred.device) + pred_slice = pred[inds, label].squeeze(1) + return F.binary_cross_entropy_with_logits( + pred_slice, target, weight=class_weight, reduction='mean')[None] + + +@MODELS.register_module() +class CrossEntropyLoss(nn.Module): + """CrossEntropyLoss. + + Args: + use_sigmoid (bool, optional): Whether the prediction uses sigmoid + of softmax. Defaults to False. + use_mask (bool, optional): Whether to use mask cross entropy loss. + Defaults to False. + reduction (str, optional): . Defaults to 'mean'. + Options are "none", "mean" and "sum". + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_weight (float, optional): Weight of the loss. Defaults to 1.0. + loss_name (str, optional): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_ce'. + avg_non_ignore (bool): The flag decides to whether the loss is + only averaged over non-ignored targets. Default: False. + `New in version 0.23.0.` + """ + + def __init__(self, + use_sigmoid=False, + use_mask=False, + reduction='mean', + class_weight=None, + loss_weight=1.0, + loss_name='loss_ce', + avg_non_ignore=False): + super().__init__() + assert (use_sigmoid is False) or (use_mask is False) + self.use_sigmoid = use_sigmoid + self.use_mask = use_mask + self.reduction = reduction + self.loss_weight = loss_weight + self.class_weight = get_class_weight(class_weight) + self.avg_non_ignore = avg_non_ignore + if not self.avg_non_ignore and self.reduction == 'mean': + warnings.warn( + 'Default ``avg_non_ignore`` is False, if you would like to ' + 'ignore the certain label and average loss over non-ignore ' + 'labels, which is the same with PyTorch official ' + 'cross_entropy, set ``avg_non_ignore=True``.') + + if self.use_sigmoid: + self.cls_criterion = binary_cross_entropy + elif self.use_mask: + self.cls_criterion = mask_cross_entropy + else: + self.cls_criterion = cross_entropy + self._loss_name = loss_name + + def extra_repr(self): + """Extra repr.""" + s = f'avg_non_ignore={self.avg_non_ignore}' + return s + + def forward(self, + cls_score, + label, + weight=None, + avg_factor=None, + reduction_override=None, + ignore_index=-100, + **kwargs): + """Forward function.""" + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.class_weight is not None: + class_weight = cls_score.new_tensor(self.class_weight) + else: + class_weight = None + # Note: for BCE loss, label < 0 is invalid. + loss_cls = self.loss_weight * self.cls_criterion( + cls_score, + label, + weight, + class_weight=class_weight, + reduction=reduction, + avg_factor=avg_factor, + avg_non_ignore=self.avg_non_ignore, + ignore_index=ignore_index, + **kwargs) + return loss_cls + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/dice_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/dice_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..fb2ffdba8daf867032b6d7b4e0d70a9b7a0c50fe --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/dice_loss.py @@ -0,0 +1,202 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Union + +import torch +import torch.nn as nn + +from mmseg.registry import MODELS +from .utils import weight_reduce_loss + + +def _expand_onehot_labels_dice(pred: torch.Tensor, + target: torch.Tensor) -> torch.Tensor: + """Expand onehot labels to match the size of prediction. + + Args: + pred (torch.Tensor): The prediction, has a shape (N, num_class, H, W). + target (torch.Tensor): The learning label of the prediction, + has a shape (N, H, W). + + Returns: + torch.Tensor: The target after one-hot encoding, + has a shape (N, num_class, H, W). + """ + num_classes = pred.shape[1] + one_hot_target = torch.clamp(target, min=0, max=num_classes) + one_hot_target = torch.nn.functional.one_hot(one_hot_target, + num_classes + 1) + one_hot_target = one_hot_target[..., :num_classes].permute(0, 3, 1, 2) + return one_hot_target + + +def dice_loss(pred: torch.Tensor, + target: torch.Tensor, + weight: Union[torch.Tensor, None], + eps: float = 1e-3, + reduction: Union[str, None] = 'mean', + naive_dice: Union[bool, None] = False, + avg_factor: Union[int, None] = None, + ignore_index: Union[int, None] = 255) -> float: + """Calculate dice loss, there are two forms of dice loss is supported: + + - the one proposed in `V-Net: Fully Convolutional Neural + Networks for Volumetric Medical Image Segmentation + `_. + - the dice loss in which the power of the number in the + denominator is the first power instead of the second + power. + + Args: + pred (torch.Tensor): The prediction, has a shape (n, *) + target (torch.Tensor): The learning label of the prediction, + shape (n, *), same shape of pred. + weight (torch.Tensor, optional): The weight of loss for each + prediction, has a shape (n,). Defaults to None. + eps (float): Avoid dividing by zero. Default: 1e-3. + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. + Options are "none", "mean" and "sum". + naive_dice (bool, optional): If false, use the dice + loss defined in the V-Net paper, otherwise, use the + naive dice loss in which the power of the number in the + denominator is the first power instead of the second + power.Defaults to False. + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + ignore_index (int, optional): The label index to be ignored. + Defaults to 255. + """ + if ignore_index is not None: + num_classes = pred.shape[1] + pred = pred[:, torch.arange(num_classes) != ignore_index, :, :] + target = target[:, torch.arange(num_classes) != ignore_index, :, :] + assert pred.shape[1] != 0 # if the ignored index is the only class + input = pred.flatten(1) + target = target.flatten(1).float() + a = torch.sum(input * target, 1) + if naive_dice: + b = torch.sum(input, 1) + c = torch.sum(target, 1) + d = (2 * a + eps) / (b + c + eps) + else: + b = torch.sum(input * input, 1) + eps + c = torch.sum(target * target, 1) + eps + d = (2 * a) / (b + c) + + loss = 1 - d + if weight is not None: + assert weight.ndim == loss.ndim + assert len(weight) == len(pred) + loss = weight_reduce_loss(loss, weight, reduction, avg_factor) + return loss + + +@MODELS.register_module() +class DiceLoss(nn.Module): + + def __init__(self, + use_sigmoid=True, + activate=True, + reduction='mean', + naive_dice=False, + loss_weight=1.0, + ignore_index=255, + eps=1e-3, + loss_name='loss_dice'): + """Compute dice loss. + + Args: + use_sigmoid (bool, optional): Whether to the prediction is + used for sigmoid or softmax. Defaults to True. + activate (bool): Whether to activate the predictions inside, + this will disable the inside sigmoid operation. + Defaults to True. + reduction (str, optional): The method used + to reduce the loss. Options are "none", + "mean" and "sum". Defaults to 'mean'. + naive_dice (bool, optional): If false, use the dice + loss defined in the V-Net paper, otherwise, use the + naive dice loss in which the power of the number in the + denominator is the first power instead of the second + power. Defaults to False. + loss_weight (float, optional): Weight of loss. Defaults to 1.0. + ignore_index (int, optional): The label index to be ignored. + Default: 255. + eps (float): Avoid dividing by zero. Defaults to 1e-3. + loss_name (str, optional): Name of the loss item. If you want this + loss item to be included into the backward graph, `loss_` must + be the prefix of the name. Defaults to 'loss_dice'. + """ + + super().__init__() + self.use_sigmoid = use_sigmoid + self.reduction = reduction + self.naive_dice = naive_dice + self.loss_weight = loss_weight + self.eps = eps + self.activate = activate + self.ignore_index = ignore_index + self._loss_name = loss_name + + def forward(self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None, + ignore_index=255, + **kwargs): + """Forward function. + + Args: + pred (torch.Tensor): The prediction, has a shape (n, *). + target (torch.Tensor): The label of the prediction, + shape (n, *), same shape of pred. + weight (torch.Tensor, optional): The weight of loss for each + prediction, has a shape (n,). Defaults to None. + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + reduction_override (str, optional): The reduction method used to + override the original reduction method of the loss. + Options are "none", "mean" and "sum". + + Returns: + torch.Tensor: The calculated loss + """ + one_hot_target = target + if (pred.shape != target.shape): + one_hot_target = _expand_onehot_labels_dice(pred, target) + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.activate: + if self.use_sigmoid: + pred = pred.sigmoid() + elif pred.shape[1] != 1: + # softmax does not work when there is only 1 class + pred = pred.softmax(dim=1) + loss = self.loss_weight * dice_loss( + pred, + one_hot_target, + weight, + eps=self.eps, + reduction=reduction, + naive_dice=self.naive_dice, + avg_factor=avg_factor, + ignore_index=self.ignore_index) + + return loss + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/focal_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/focal_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..6507ed7a9112993733ac25bc095da0b571e14363 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/focal_loss.py @@ -0,0 +1,337 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Modified from https://github.com/open-mmlab/mmdetection +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.ops import sigmoid_focal_loss as _sigmoid_focal_loss + +from mmseg.registry import MODELS +from .utils import weight_reduce_loss + + +# This method is used when cuda is not available +def py_sigmoid_focal_loss(pred, + target, + one_hot_target=None, + weight=None, + gamma=2.0, + alpha=0.5, + class_weight=None, + valid_mask=None, + reduction='mean', + avg_factor=None): + """PyTorch version of `Focal Loss `_. + + Args: + pred (torch.Tensor): The prediction with shape (N, C), C is the + number of classes + target (torch.Tensor): The learning label of the prediction with + shape (N, C) + one_hot_target (None): Placeholder. It should be None. + weight (torch.Tensor, optional): Sample-wise loss weight. + gamma (float, optional): The gamma for calculating the modulating + factor. Defaults to 2.0. + alpha (float | list[float], optional): A balanced form for Focal Loss. + Defaults to 0.5. + class_weight (list[float], optional): Weight of each class. + Defaults to None. + valid_mask (torch.Tensor, optional): A mask uses 1 to mark the valid + samples and uses 0 to mark the ignored samples. Default: None. + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + """ + if isinstance(alpha, list): + alpha = pred.new_tensor(alpha) + pred_sigmoid = pred.sigmoid() + target = target.type_as(pred) + one_minus_pt = (1 - pred_sigmoid) * target + pred_sigmoid * (1 - target) + focal_weight = (alpha * target + (1 - alpha) * + (1 - target)) * one_minus_pt.pow(gamma) + + loss = F.binary_cross_entropy_with_logits( + pred, target, reduction='none') * focal_weight + final_weight = torch.ones(1, pred.size(1)).type_as(loss) + if weight is not None: + if weight.shape != loss.shape and weight.size(0) == loss.size(0): + # For most cases, weight is of shape (N, ), + # which means it does not have the second axis num_class + weight = weight.view(-1, 1) + assert weight.dim() == loss.dim() + final_weight = final_weight * weight + if class_weight is not None: + final_weight = final_weight * pred.new_tensor(class_weight) + if valid_mask is not None: + final_weight = final_weight * valid_mask + loss = weight_reduce_loss(loss, final_weight, reduction, avg_factor) + return loss + + +def sigmoid_focal_loss(pred, + target, + one_hot_target, + weight=None, + gamma=2.0, + alpha=0.5, + class_weight=None, + valid_mask=None, + reduction='mean', + avg_factor=None): + r"""A wrapper of cuda version `Focal Loss + `_. + Args: + pred (torch.Tensor): The prediction with shape (N, C), C is the number + of classes. + target (torch.Tensor): The learning label of the prediction. It's shape + should be (N, ) + one_hot_target (torch.Tensor): The learning label with shape (N, C) + weight (torch.Tensor, optional): Sample-wise loss weight. + gamma (float, optional): The gamma for calculating the modulating + factor. Defaults to 2.0. + alpha (float | list[float], optional): A balanced form for Focal Loss. + Defaults to 0.5. + class_weight (list[float], optional): Weight of each class. + Defaults to None. + valid_mask (torch.Tensor, optional): A mask uses 1 to mark the valid + samples and uses 0 to mark the ignored samples. Default: None. + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. Options are "none", "mean" and "sum". + avg_factor (int, optional): Average factor that is used to average + the loss. Defaults to None. + """ + # Function.apply does not accept keyword arguments, so the decorator + # "weighted_loss" is not applicable + final_weight = torch.ones(1, pred.size(1)).type_as(pred) + if isinstance(alpha, list): + # _sigmoid_focal_loss doesn't accept alpha of list type. Therefore, if + # a list is given, we set the input alpha as 0.5. This means setting + # equal weight for foreground class and background class. By + # multiplying the loss by 2, the effect of setting alpha as 0.5 is + # undone. The alpha of type list is used to regulate the loss in the + # post-processing process. + loss = _sigmoid_focal_loss(pred.contiguous(), target.contiguous(), + gamma, 0.5, None, 'none') * 2 + alpha = pred.new_tensor(alpha) + final_weight = final_weight * ( + alpha * one_hot_target + (1 - alpha) * (1 - one_hot_target)) + else: + loss = _sigmoid_focal_loss(pred.contiguous(), target.contiguous(), + gamma, alpha, None, 'none') + if weight is not None: + if weight.shape != loss.shape and weight.size(0) == loss.size(0): + # For most cases, weight is of shape (N, ), + # which means it does not have the second axis num_class + weight = weight.view(-1, 1) + assert weight.dim() == loss.dim() + final_weight = final_weight * weight + if class_weight is not None: + final_weight = final_weight * pred.new_tensor(class_weight) + if valid_mask is not None: + final_weight = final_weight * valid_mask + loss = weight_reduce_loss(loss, final_weight, reduction, avg_factor) + return loss + + +@MODELS.register_module() +class FocalLoss(nn.Module): + + def __init__(self, + use_sigmoid=True, + gamma=2.0, + alpha=0.5, + reduction='mean', + class_weight=None, + loss_weight=1.0, + loss_name='loss_focal'): + """`Focal Loss `_ + Args: + use_sigmoid (bool, optional): Whether to the prediction is + used for sigmoid or softmax. Defaults to True. + gamma (float, optional): The gamma for calculating the modulating + factor. Defaults to 2.0. + alpha (float | list[float], optional): A balanced form for Focal + Loss. Defaults to 0.5. When a list is provided, the length + of the list should be equal to the number of classes. + Please be careful that this parameter is not the + class-wise weight but the weight of a binary classification + problem. This binary classification problem regards the + pixels which belong to one class as the foreground + and the other pixels as the background, each element in + the list is the weight of the corresponding foreground class. + The value of alpha or each element of alpha should be a float + in the interval [0, 1]. If you want to specify the class-wise + weight, please use `class_weight` parameter. + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. Options are "none", "mean" and + "sum". + class_weight (list[float], optional): Weight of each class. + Defaults to None. + loss_weight (float, optional): Weight of loss. Defaults to 1.0. + loss_name (str, optional): Name of the loss item. If you want this + loss item to be included into the backward graph, `loss_` must + be the prefix of the name. Defaults to 'loss_focal'. + """ + super().__init__() + assert use_sigmoid is True, \ + 'AssertionError: Only sigmoid focal loss supported now.' + assert reduction in ('none', 'mean', 'sum'), \ + "AssertionError: reduction should be 'none', 'mean' or " \ + "'sum'" + assert isinstance(alpha, (float, list)), \ + 'AssertionError: alpha should be of type float' + assert isinstance(gamma, float), \ + 'AssertionError: gamma should be of type float' + assert isinstance(loss_weight, float), \ + 'AssertionError: loss_weight should be of type float' + assert isinstance(loss_name, str), \ + 'AssertionError: loss_name should be of type str' + assert isinstance(class_weight, list) or class_weight is None, \ + 'AssertionError: class_weight must be None or of type list' + self.use_sigmoid = use_sigmoid + self.gamma = gamma + self.alpha = alpha + self.reduction = reduction + self.class_weight = class_weight + self.loss_weight = loss_weight + self._loss_name = loss_name + + def forward(self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None, + ignore_index=255, + **kwargs): + """Forward function. + + Args: + pred (torch.Tensor): The prediction with shape + (N, C) where C = number of classes, or + (N, C, d_1, d_2, ..., d_K) with K≥1 in the + case of K-dimensional loss. + target (torch.Tensor): The ground truth. If containing class + indices, shape (N) where each value is 0≤targets[i]≤C−1, + or (N, d_1, d_2, ..., d_K) with K≥1 in the case of + K-dimensional loss. If containing class probabilities, + same shape as the input. + weight (torch.Tensor, optional): The weight of loss for each + prediction. Defaults to None. + avg_factor (int, optional): Average factor that is used to + average the loss. Defaults to None. + reduction_override (str, optional): The reduction method used + to override the original reduction method of the loss. + Options are "none", "mean" and "sum". + ignore_index (int, optional): The label index to be ignored. + Default: 255 + Returns: + torch.Tensor: The calculated loss + """ + assert isinstance(ignore_index, int), \ + 'ignore_index must be of type int' + assert reduction_override in (None, 'none', 'mean', 'sum'), \ + "AssertionError: reduction should be 'none', 'mean' or " \ + "'sum'" + assert pred.shape == target.shape or \ + (pred.size(0) == target.size(0) and + pred.shape[2:] == target.shape[1:]), \ + "The shape of pred doesn't match the shape of target" + + original_shape = pred.shape + + # [B, C, d_1, d_2, ..., d_k] -> [C, B, d_1, d_2, ..., d_k] + pred = pred.transpose(0, 1) + # [C, B, d_1, d_2, ..., d_k] -> [C, N] + pred = pred.reshape(pred.size(0), -1) + # [C, N] -> [N, C] + pred = pred.transpose(0, 1).contiguous() + + if original_shape == target.shape: + # target with shape [B, C, d_1, d_2, ...] + # transform it's shape into [N, C] + # [B, C, d_1, d_2, ...] -> [C, B, d_1, d_2, ..., d_k] + target = target.transpose(0, 1) + # [C, B, d_1, d_2, ..., d_k] -> [C, N] + target = target.reshape(target.size(0), -1) + # [C, N] -> [N, C] + target = target.transpose(0, 1).contiguous() + else: + # target with shape [B, d_1, d_2, ...] + # transform it's shape into [N, ] + target = target.view(-1).contiguous() + valid_mask = (target != ignore_index).view(-1, 1) + # avoid raising error when using F.one_hot() + target = torch.where(target == ignore_index, target.new_tensor(0), + target) + + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.use_sigmoid: + num_classes = pred.size(1) + if torch.cuda.is_available() and pred.is_cuda: + if target.dim() == 1: + one_hot_target = F.one_hot( + target, num_classes=num_classes + 1) + if num_classes == 1: + one_hot_target = one_hot_target[:, 1] + target = 1 - target + else: + one_hot_target = one_hot_target[:, :num_classes] + else: + one_hot_target = target + target = target.argmax(dim=1) + valid_mask = (target != ignore_index).view(-1, 1) + calculate_loss_func = sigmoid_focal_loss + else: + one_hot_target = None + if target.dim() == 1: + target = F.one_hot(target, num_classes=num_classes + 1) + if num_classes == 1: + target = target[:, 1] + else: + target = target[:, num_classes] + else: + valid_mask = (target.argmax(dim=1) != ignore_index).view( + -1, 1) + calculate_loss_func = py_sigmoid_focal_loss + + loss_cls = self.loss_weight * calculate_loss_func( + pred, + target, + one_hot_target, + weight, + gamma=self.gamma, + alpha=self.alpha, + class_weight=self.class_weight, + valid_mask=valid_mask, + reduction=reduction, + avg_factor=avg_factor) + + if reduction == 'none': + # [N, C] -> [C, N] + loss_cls = loss_cls.transpose(0, 1) + # [C, N] -> [C, B, d1, d2, ...] + # original_shape: [B, C, d1, d2, ...] + loss_cls = loss_cls.reshape(original_shape[1], + original_shape[0], + *original_shape[2:]) + # [C, B, d1, d2, ...] -> [B, C, d1, d2, ...] + loss_cls = loss_cls.transpose(0, 1).contiguous() + else: + raise NotImplementedError + return loss_cls + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/huasdorff_distance_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/huasdorff_distance_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..d950ba728f8d419ea2b291e2159b926aca44038c --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/huasdorff_distance_loss.py @@ -0,0 +1,160 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from https://github.com/JunMa11/SegWithDistMap/blob/ +master/code/train_LA_HD.py (Apache-2.0 License)""" +import torch +import torch.nn as nn +import torch.nn.functional as F +from scipy.ndimage import distance_transform_edt as distance +from torch import Tensor + +from mmseg.registry import MODELS +from .utils import get_class_weight, weighted_loss + + +def compute_dtm(img_gt: Tensor, pred: Tensor) -> Tensor: + """ + compute the distance transform map of foreground in mask + Args: + img_gt: Ground truth of the image, (b, h, w) + pred: Predictions of the segmentation head after softmax, (b, c, h, w) + + Returns: + output: the foreground Distance Map (SDM) + dtm(x) = 0; x in segmentation boundary + inf|x-y|; x in segmentation + """ + + fg_dtm = torch.zeros_like(pred) + out_shape = pred.shape + for b in range(out_shape[0]): # batch size + for c in range(1, out_shape[1]): # default 0 channel is background + posmask = img_gt[b].byte() + if posmask.any(): + posdis = distance(posmask) + fg_dtm[b][c] = torch.from_numpy(posdis) + + return fg_dtm + + +@weighted_loss +def hd_loss(seg_soft: Tensor, + gt: Tensor, + seg_dtm: Tensor, + gt_dtm: Tensor, + class_weight=None, + ignore_index=255) -> Tensor: + """ + compute huasdorff distance loss for segmentation + Args: + seg_soft: softmax results, shape=(b,c,x,y) + gt: ground truth, shape=(b,x,y) + seg_dtm: segmentation distance transform map, shape=(b,c,x,y) + gt_dtm: ground truth distance transform map, shape=(b,c,x,y) + + Returns: + output: hd_loss + """ + assert seg_soft.shape[0] == gt.shape[0] + total_loss = 0 + num_class = seg_soft.shape[1] + if class_weight is not None: + assert class_weight.ndim == num_class + for i in range(1, num_class): + if i != ignore_index: + delta_s = (seg_soft[:, i, ...] - gt.float())**2 + s_dtm = seg_dtm[:, i, ...]**2 + g_dtm = gt_dtm[:, i, ...]**2 + dtm = s_dtm + g_dtm + multiplied = torch.einsum('bxy, bxy->bxy', delta_s, dtm) + hd_loss = multiplied.mean() + if class_weight is not None: + hd_loss *= class_weight[i] + total_loss += hd_loss + + return total_loss / num_class + + +@MODELS.register_module() +class HuasdorffDisstanceLoss(nn.Module): + """HuasdorffDisstanceLoss. This loss is proposed in `How Distance Transform + Maps Boost Segmentation CNNs: An Empirical Study. + + `_. + Args: + reduction (str, optional): The method used to reduce the loss into + a scalar. Defaults to 'mean'. + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_weight (float): Weight of the loss. Defaults to 1.0. + ignore_index (int | None): The label index to be ignored. Default: 255. + loss_name (str): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_boundary'. + """ + + def __init__(self, + reduction='mean', + class_weight=None, + loss_weight=1.0, + ignore_index=255, + loss_name='loss_huasdorff_disstance', + **kwargs): + super().__init__() + self.reduction = reduction + self.loss_weight = loss_weight + self.class_weight = get_class_weight(class_weight) + self._loss_name = loss_name + self.ignore_index = ignore_index + + def forward(self, + pred: Tensor, + target: Tensor, + avg_factor=None, + reduction_override=None, + **kwargs) -> Tensor: + """Forward function. + + Args: + pred (Tensor): Predictions of the segmentation head. (B, C, H, W) + target (Tensor): Ground truth of the image. (B, H, W) + avg_factor (int, optional): Average factor that is used to + average the loss. Defaults to None. + reduction_override (str, optional): The reduction method used + to override the original reduction method of the loss. + Options are "none", "mean" and "sum". + Returns: + Tensor: Loss tensor. + """ + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.class_weight is not None: + class_weight = pred.new_tensor(self.class_weight) + else: + class_weight = None + + pred_soft = F.softmax(pred, dim=1) + valid_mask = (target != self.ignore_index).long() + target = target * valid_mask + + with torch.no_grad(): + gt_dtm = compute_dtm(target.cpu(), pred_soft) + gt_dtm = gt_dtm.float() + seg_dtm2 = compute_dtm( + pred_soft.argmax(dim=1, keepdim=False).cpu(), pred_soft) + seg_dtm2 = seg_dtm2.float() + + loss_hd = self.loss_weight * hd_loss( + pred_soft, + target, + seg_dtm=seg_dtm2, + gt_dtm=gt_dtm, + reduction=reduction, + avg_factor=avg_factor, + class_weight=class_weight, + ignore_index=self.ignore_index) + return loss_hd + + @property + def loss_name(self): + return self._loss_name diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/kldiv_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/kldiv_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..496ef9713f085a36d46837ac0b51d4cb9f956fce --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/kldiv_loss.py @@ -0,0 +1,99 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F + +from mmseg.registry import MODELS + + +@MODELS.register_module() +class KLDivLoss(nn.Module): + + def __init__(self, + temperature: float = 1.0, + reduction: str = 'mean', + loss_name: str = 'loss_kld'): + """Kullback-Leibler divergence Loss. + + + + Args: + temperature (float, optional): Temperature param + reduction (str, optional): The method to reduce the loss into a + scalar. Default is "mean". Options are "none", "sum", + and "mean" + """ + + assert isinstance(temperature, (float, int)), \ + 'Expected temperature to be' \ + f'float or int, but got {temperature.__class__.__name__} instead' + assert temperature != 0., 'Temperature must not be zero' + + assert reduction in ['mean', 'none', 'sum'], \ + 'Reduction must be one of the options ("mean", ' \ + f'"sum", "none"), but got {reduction}' + + super().__init__() + self.temperature = temperature + self.reduction = reduction + self._loss_name = loss_name + + def forward(self, input: torch.Tensor, target: torch.Tensor): + """Forward function. Calculate KL divergence Loss. + + Args: + input (Tensor): Logit tensor, + the data type is float32 or float64. + The shape is (N, C) where N is batchsize and C is number of + channels. + If there more than 2 dimensions, shape is (N, C, D1, D2, ... + Dk), k>= 1 + target (Tensor): Logit tensor, + the data type is float32 or float64. + input and target must be with the same shape. + + Returns: + (Tensor): Reduced loss. + """ + assert isinstance(input, torch.Tensor), 'Expected input to' \ + f'be Tensor, but got {input.__class__.__name__} instead' + assert isinstance(target, torch.Tensor), 'Expected target to' \ + f'be Tensor, but got {target.__class__.__name__} instead' + + assert input.shape == target.shape, 'Input and target ' \ + 'must have same shape,' \ + f'but got shapes {input.shape} and {target.shape}' + + input = F.softmax(input / self.temperature, dim=1) + target = F.softmax(target / self.temperature, dim=1) + + loss = F.kl_div(input, target, reduction='none', log_target=False) + loss = loss * self.temperature**2 + + batch_size = input.shape[0] + + if self.reduction == 'sum': + # Change view to calculate instance-wise sum + loss = loss.view(batch_size, -1) + return torch.sum(loss, dim=1) + + elif self.reduction == 'mean': + # Change view to calculate instance-wise mean + loss = loss.view(batch_size, -1) + return torch.mean(loss, dim=1) + + return loss + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/lovasz_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/lovasz_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..b47f9d8a15330a45d0d2d25f3c18d9386e2b335e --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/lovasz_loss.py @@ -0,0 +1,323 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from https://github.com/bermanmaxim/LovaszSoftmax/blob/master/pytor +ch/lovasz_losses.py Lovasz-Softmax and Jaccard hinge loss in PyTorch Maxim +Berman 2018 ESAT-PSI KU Leuven (MIT License)""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.utils import is_list_of + +from mmseg.registry import MODELS +from .utils import get_class_weight, weight_reduce_loss + + +def lovasz_grad(gt_sorted): + """Computes gradient of the Lovasz extension w.r.t sorted errors. + + See Alg. 1 in paper. + """ + p = len(gt_sorted) + gts = gt_sorted.sum() + intersection = gts - gt_sorted.float().cumsum(0) + union = gts + (1 - gt_sorted).float().cumsum(0) + jaccard = 1. - intersection / union + if p > 1: # cover 1-pixel case + jaccard[1:p] = jaccard[1:p] - jaccard[0:-1] + return jaccard + + +def flatten_binary_logits(logits, labels, ignore_index=None): + """Flattens predictions in the batch (binary case) Remove labels equal to + 'ignore_index'.""" + logits = logits.view(-1) + labels = labels.view(-1) + if ignore_index is None: + return logits, labels + valid = (labels != ignore_index) + vlogits = logits[valid] + vlabels = labels[valid] + return vlogits, vlabels + + +def flatten_probs(probs, labels, ignore_index=None): + """Flattens predictions in the batch.""" + if probs.dim() == 3: + # assumes output of a sigmoid layer + B, H, W = probs.size() + probs = probs.view(B, 1, H, W) + B, C, H, W = probs.size() + probs = probs.permute(0, 2, 3, 1).contiguous().view(-1, C) # B*H*W, C=P,C + labels = labels.view(-1) + if ignore_index is None: + return probs, labels + valid = (labels != ignore_index) + vprobs = probs[valid.nonzero().squeeze()] + vlabels = labels[valid] + return vprobs, vlabels + + +def lovasz_hinge_flat(logits, labels): + """Binary Lovasz hinge loss. + + Args: + logits (torch.Tensor): [P], logits at each prediction + (between -infty and +infty). + labels (torch.Tensor): [P], binary ground truth labels (0 or 1). + + Returns: + torch.Tensor: The calculated loss. + """ + if len(labels) == 0: + # only void pixels, the gradients should be 0 + return logits.sum() * 0. + signs = 2. * labels.float() - 1. + errors = (1. - logits * signs) + errors_sorted, perm = torch.sort(errors, dim=0, descending=True) + perm = perm.data + gt_sorted = labels[perm] + grad = lovasz_grad(gt_sorted) + loss = torch.dot(F.relu(errors_sorted), grad) + return loss + + +def lovasz_hinge(logits, + labels, + classes='present', + per_image=False, + class_weight=None, + reduction='mean', + avg_factor=None, + ignore_index=255): + """Binary Lovasz hinge loss. + + Args: + logits (torch.Tensor): [B, H, W], logits at each pixel + (between -infty and +infty). + labels (torch.Tensor): [B, H, W], binary ground truth masks (0 or 1). + classes (str | list[int], optional): Placeholder, to be consistent with + other loss. Default: None. + per_image (bool, optional): If per_image is True, compute the loss per + image instead of per batch. Default: False. + class_weight (list[float], optional): Placeholder, to be consistent + with other loss. Default: None. + reduction (str, optional): The method used to reduce the loss. Options + are "none", "mean" and "sum". This parameter only works when + per_image is True. Default: 'mean'. + avg_factor (int, optional): Average factor that is used to average + the loss. This parameter only works when per_image is True. + Default: None. + ignore_index (int | None): The label index to be ignored. Default: 255. + + Returns: + torch.Tensor: The calculated loss. + """ + if per_image: + loss = [ + lovasz_hinge_flat(*flatten_binary_logits( + logit.unsqueeze(0), label.unsqueeze(0), ignore_index)) + for logit, label in zip(logits, labels) + ] + loss = weight_reduce_loss( + torch.stack(loss), None, reduction, avg_factor) + else: + loss = lovasz_hinge_flat( + *flatten_binary_logits(logits, labels, ignore_index)) + return loss + + +def lovasz_softmax_flat(probs, labels, classes='present', class_weight=None): + """Multi-class Lovasz-Softmax loss. + + Args: + probs (torch.Tensor): [P, C], class probabilities at each prediction + (between 0 and 1). + labels (torch.Tensor): [P], ground truth labels (between 0 and C - 1). + classes (str | list[int], optional): Classes chosen to calculate loss. + 'all' for all classes, 'present' for classes present in labels, or + a list of classes to average. Default: 'present'. + class_weight (list[float], optional): The weight for each class. + Default: None. + + Returns: + torch.Tensor: The calculated loss. + """ + if probs.numel() == 0: + # only void pixels, the gradients should be 0 + return probs * 0. + C = probs.size(1) + losses = [] + class_to_sum = list(range(C)) if classes in ['all', 'present'] else classes + for c in class_to_sum: + fg = (labels == c).float() # foreground for class c + if (classes == 'present' and fg.sum() == 0): + continue + if C == 1: + if len(classes) > 1: + raise ValueError('Sigmoid output possible only with 1 class') + class_pred = probs[:, 0] + else: + class_pred = probs[:, c] + errors = (fg - class_pred).abs() + errors_sorted, perm = torch.sort(errors, 0, descending=True) + perm = perm.data + fg_sorted = fg[perm] + loss = torch.dot(errors_sorted, lovasz_grad(fg_sorted)) + if class_weight is not None: + loss *= class_weight[c] + losses.append(loss) + return torch.stack(losses).mean() + + +def lovasz_softmax(probs, + labels, + classes='present', + per_image=False, + class_weight=None, + reduction='mean', + avg_factor=None, + ignore_index=255): + """Multi-class Lovasz-Softmax loss. + + Args: + probs (torch.Tensor): [B, C, H, W], class probabilities at each + prediction (between 0 and 1). + labels (torch.Tensor): [B, H, W], ground truth labels (between 0 and + C - 1). + classes (str | list[int], optional): Classes chosen to calculate loss. + 'all' for all classes, 'present' for classes present in labels, or + a list of classes to average. Default: 'present'. + per_image (bool, optional): If per_image is True, compute the loss per + image instead of per batch. Default: False. + class_weight (list[float], optional): The weight for each class. + Default: None. + reduction (str, optional): The method used to reduce the loss. Options + are "none", "mean" and "sum". This parameter only works when + per_image is True. Default: 'mean'. + avg_factor (int, optional): Average factor that is used to average + the loss. This parameter only works when per_image is True. + Default: None. + ignore_index (int | None): The label index to be ignored. Default: 255. + + Returns: + torch.Tensor: The calculated loss. + """ + + if per_image: + loss = [ + lovasz_softmax_flat( + *flatten_probs( + prob.unsqueeze(0), label.unsqueeze(0), ignore_index), + classes=classes, + class_weight=class_weight) + for prob, label in zip(probs, labels) + ] + loss = weight_reduce_loss( + torch.stack(loss), None, reduction, avg_factor) + else: + loss = lovasz_softmax_flat( + *flatten_probs(probs, labels, ignore_index), + classes=classes, + class_weight=class_weight) + return loss + + +@MODELS.register_module() +class LovaszLoss(nn.Module): + """LovaszLoss. + + This loss is proposed in `The Lovasz-Softmax loss: A tractable surrogate + for the optimization of the intersection-over-union measure in neural + networks `_. + + Args: + loss_type (str, optional): Binary or multi-class loss. + Default: 'multi_class'. Options are "binary" and "multi_class". + classes (str | list[int], optional): Classes chosen to calculate loss. + 'all' for all classes, 'present' for classes present in labels, or + a list of classes to average. Default: 'present'. + per_image (bool, optional): If per_image is True, compute the loss per + image instead of per batch. Default: False. + reduction (str, optional): The method used to reduce the loss. Options + are "none", "mean" and "sum". This parameter only works when + per_image is True. Default: 'mean'. + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_weight (float, optional): Weight of the loss. Defaults to 1.0. + loss_name (str, optional): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_lovasz'. + """ + + def __init__(self, + loss_type='multi_class', + classes='present', + per_image=False, + reduction='mean', + class_weight=None, + loss_weight=1.0, + loss_name='loss_lovasz'): + super().__init__() + assert loss_type in ('binary', 'multi_class'), "loss_type should be \ + 'binary' or 'multi_class'." + + if loss_type == 'binary': + self.cls_criterion = lovasz_hinge + else: + self.cls_criterion = lovasz_softmax + assert classes in ('all', 'present') or is_list_of(classes, int) + if not per_image: + assert reduction == 'none', "reduction should be 'none' when \ + per_image is False." + + self.classes = classes + self.per_image = per_image + self.reduction = reduction + self.loss_weight = loss_weight + self.class_weight = get_class_weight(class_weight) + self._loss_name = loss_name + + def forward(self, + cls_score, + label, + weight=None, + avg_factor=None, + reduction_override=None, + **kwargs): + """Forward function.""" + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + if self.class_weight is not None: + class_weight = cls_score.new_tensor(self.class_weight) + else: + class_weight = None + + # if multi-class loss, transform logits to probs + if self.cls_criterion == lovasz_softmax: + cls_score = F.softmax(cls_score, dim=1) + + loss_cls = self.loss_weight * self.cls_criterion( + cls_score, + label, + self.classes, + self.per_image, + class_weight=class_weight, + reduction=reduction, + avg_factor=avg_factor, + **kwargs) + return loss_cls + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/ohem_cross_entropy_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/ohem_cross_entropy_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a519b4d84e1dbf86ebc7ad07372ddbdfb0ff3d13 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/ohem_cross_entropy_loss.py @@ -0,0 +1,94 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional, Union + +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor + +from mmseg.registry import MODELS + + +@MODELS.register_module() +class OhemCrossEntropy(nn.Module): + """OhemCrossEntropy loss. + + This func is modified from + `PIDNet `_. # noqa + + Licensed under the MIT License. + + Args: + ignore_label (int): Labels to ignore when computing the loss. + Default: 255 + thresh (float, optional): The threshold for hard example selection. + Below which, are prediction with low confidence. If not + specified, the hard examples will be pixels of top ``min_kept`` + loss. Default: 0.7. + min_kept (int, optional): The minimum number of predictions to keep. + Default: 100000. + loss_weight (float): Weight of the loss. Defaults to 1.0. + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_name (str): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_boundary'. + """ + + def __init__(self, + ignore_label: int = 255, + thres: float = 0.7, + min_kept: int = 100000, + loss_weight: float = 1.0, + class_weight: Optional[Union[List[float], str]] = None, + loss_name: str = 'loss_ohem'): + super().__init__() + self.thresh = thres + self.min_kept = max(1, min_kept) + self.ignore_label = ignore_label + self.loss_weight = loss_weight + self.loss_name_ = loss_name + self.class_weight = class_weight + + def forward(self, score: Tensor, target: Tensor) -> Tensor: + """Forward function. + Args: + score (Tensor): Predictions of the segmentation head. + target (Tensor): Ground truth of the image. + + Returns: + Tensor: Loss tensor. + """ + # score: (N, C, H, W) + pred = F.softmax(score, dim=1) + if self.class_weight is not None: + class_weight = score.new_tensor(self.class_weight) + else: + class_weight = None + + pixel_losses = F.cross_entropy( + score, + target, + weight=class_weight, + ignore_index=self.ignore_label, + reduction='none').contiguous().view(-1) # (N*H*W) + mask = target.contiguous().view(-1) != self.ignore_label # (N*H*W) + + tmp_target = target.clone() # (N, H, W) + tmp_target[tmp_target == self.ignore_label] = 0 + # pred: (N, C, H, W) -> (N*H*W, C) + pred = pred.gather(1, tmp_target.unsqueeze(1)) + # pred: (N*H*W, C) -> (N*H*W), ind: (N*H*W) + pred, ind = pred.contiguous().view(-1, )[mask].contiguous().sort() + if pred.numel() > 0: + min_value = pred[min(self.min_kept, pred.numel() - 1)] + else: + return score.new_tensor(0.0) + threshold = max(min_value, self.thresh) + + pixel_losses = pixel_losses[mask][ind] + pixel_losses = pixel_losses[pred < threshold] + return self.loss_weight * pixel_losses.mean() + + @property + def loss_name(self): + return self.loss_name_ diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/silog_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/silog_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..ecc07aac424a9308bce33e00c621369ac555f4ba --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/silog_loss.py @@ -0,0 +1,122 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional, Union + +import torch +import torch.nn as nn +from torch import Tensor + +from mmseg.registry import MODELS +from .utils import weight_reduce_loss + + +def silog_loss(pred: Tensor, + target: Tensor, + weight: Optional[Tensor] = None, + eps: float = 1e-4, + reduction: Union[str, None] = 'mean', + avg_factor: Optional[int] = None) -> Tensor: + """Computes the Scale-Invariant Logarithmic (SI-Log) loss between + prediction and target. + + Args: + pred (Tensor): Predicted output. + target (Tensor): Ground truth. + weight (Optional[Tensor]): Optional weight to apply on the loss. + eps (float): Epsilon value to avoid division and log(0). + reduction (Union[str, None]): Specifies the reduction to apply to the + output: 'mean', 'sum' or None. + avg_factor (Optional[int]): Optional average factor for the loss. + + Returns: + Tensor: The calculated SI-Log loss. + """ + pred, target = pred.flatten(1), target.flatten(1) + valid_mask = (target > eps).detach().float() + + diff_log = torch.log(target.clamp(min=eps)) - torch.log( + pred.clamp(min=eps)) + + valid_mask = (target > eps).detach() & (~torch.isnan(diff_log)) + diff_log[~valid_mask] = 0.0 + valid_mask = valid_mask.float() + + diff_log_sq_mean = (diff_log.pow(2) * valid_mask).sum( + dim=1) / valid_mask.sum(dim=1).clamp(min=eps) + diff_log_mean = (diff_log * valid_mask).sum(dim=1) / valid_mask.sum( + dim=1).clamp(min=eps) + + loss = torch.sqrt(diff_log_sq_mean - 0.5 * diff_log_mean.pow(2)) + + if weight is not None: + weight = weight.float() + + loss = weight_reduce_loss(loss, weight, reduction, avg_factor) + return loss + + +@MODELS.register_module() +class SiLogLoss(nn.Module): + """Compute SiLog loss. + + Args: + reduction (str, optional): The method used + to reduce the loss. Options are "none", + "mean" and "sum". Defaults to 'mean'. + loss_weight (float, optional): Weight of loss. Defaults to 1.0. + eps (float): Avoid dividing by zero. Defaults to 1e-3. + loss_name (str, optional): Name of the loss item. If you want this + loss item to be included into the backward graph, `loss_` must + be the prefix of the name. Defaults to 'loss_silog'. + """ + + def __init__(self, + reduction='mean', + loss_weight=1.0, + eps=1e-6, + loss_name='loss_silog'): + super().__init__() + self.reduction = reduction + self.loss_weight = loss_weight + self.eps = eps + self._loss_name = loss_name + + def forward( + self, + pred, + target, + weight=None, + avg_factor=None, + reduction_override=None, + ): + + assert pred.shape == target.shape, 'the shapes of pred ' \ + f'({pred.shape}) and target ({target.shape}) are mismatch' + + assert reduction_override in (None, 'none', 'mean', 'sum') + reduction = ( + reduction_override if reduction_override else self.reduction) + + loss = self.loss_weight * silog_loss( + pred, + target, + weight, + eps=self.eps, + reduction=reduction, + avg_factor=avg_factor, + ) + + return loss + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/tversky_loss.py b/reconstruction/modules/InterFormer/mmseg/models/losses/tversky_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..bfca1af6669e3ac328492da11758a084999ef906 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/tversky_loss.py @@ -0,0 +1,137 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from +https://github.com/JunMa11/SegLoss/blob/master/losses_pytorch/dice_loss.py#L333 +(Apache-2.0 License)""" +import torch +import torch.nn as nn +import torch.nn.functional as F + +from ..builder import LOSSES +from .utils import get_class_weight, weighted_loss + + +@weighted_loss +def tversky_loss(pred, + target, + valid_mask, + alpha=0.3, + beta=0.7, + smooth=1, + class_weight=None, + ignore_index=255): + assert pred.shape[0] == target.shape[0] + total_loss = 0 + num_classes = pred.shape[1] + for i in range(num_classes): + if i != ignore_index: + tversky_loss = binary_tversky_loss( + pred[:, i], + target[..., i], + valid_mask=valid_mask, + alpha=alpha, + beta=beta, + smooth=smooth) + if class_weight is not None: + tversky_loss *= class_weight[i] + total_loss += tversky_loss + return total_loss / num_classes + + +@weighted_loss +def binary_tversky_loss(pred, + target, + valid_mask, + alpha=0.3, + beta=0.7, + smooth=1): + assert pred.shape[0] == target.shape[0] + pred = pred.reshape(pred.shape[0], -1) + target = target.reshape(target.shape[0], -1) + valid_mask = valid_mask.reshape(valid_mask.shape[0], -1) + + TP = torch.sum(torch.mul(pred, target) * valid_mask, dim=1) + FP = torch.sum(torch.mul(pred, 1 - target) * valid_mask, dim=1) + FN = torch.sum(torch.mul(1 - pred, target) * valid_mask, dim=1) + tversky = (TP + smooth) / (TP + alpha * FP + beta * FN + smooth) + + return 1 - tversky + + +@LOSSES.register_module() +class TverskyLoss(nn.Module): + """TverskyLoss. This loss is proposed in `Tversky loss function for image + segmentation using 3D fully convolutional deep networks. + + `_. + Args: + smooth (float): A float number to smooth loss, and avoid NaN error. + Default: 1. + class_weight (list[float] | str, optional): Weight of each class. If in + str format, read them from a file. Defaults to None. + loss_weight (float, optional): Weight of the loss. Default to 1.0. + ignore_index (int | None): The label index to be ignored. Default: 255. + alpha(float, in [0, 1]): + The coefficient of false positives. Default: 0.3. + beta (float, in [0, 1]): + The coefficient of false negatives. Default: 0.7. + Note: alpha + beta = 1. + loss_name (str, optional): Name of the loss item. If you want this loss + item to be included into the backward graph, `loss_` must be the + prefix of the name. Defaults to 'loss_tversky'. + """ + + def __init__(self, + smooth=1, + class_weight=None, + loss_weight=1.0, + ignore_index=255, + alpha=0.3, + beta=0.7, + loss_name='loss_tversky'): + super().__init__() + self.smooth = smooth + self.class_weight = get_class_weight(class_weight) + self.loss_weight = loss_weight + self.ignore_index = ignore_index + assert (alpha + beta == 1.0), 'Sum of alpha and beta but be 1.0!' + self.alpha = alpha + self.beta = beta + self._loss_name = loss_name + + def forward(self, pred, target, **kwargs): + if self.class_weight is not None: + class_weight = pred.new_tensor(self.class_weight) + else: + class_weight = None + + pred = F.softmax(pred, dim=1) + num_classes = pred.shape[1] + one_hot_target = F.one_hot( + torch.clamp(target.long(), 0, num_classes - 1), + num_classes=num_classes) + valid_mask = (target != self.ignore_index).long() + + loss = self.loss_weight * tversky_loss( + pred, + one_hot_target, + valid_mask=valid_mask, + alpha=self.alpha, + beta=self.beta, + smooth=self.smooth, + class_weight=class_weight, + ignore_index=self.ignore_index) + return loss + + @property + def loss_name(self): + """Loss Name. + + This function must be implemented and will return the name of this + loss function. This name will be used to combine different loss items + by simple sum operation. In addition, if you want this loss item to be + included into the backward graph, `loss_` must be the prefix of the + name. + Returns: + str: The name of this loss item. + """ + return self._loss_name diff --git a/reconstruction/modules/InterFormer/mmseg/models/losses/utils.py b/reconstruction/modules/InterFormer/mmseg/models/losses/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..047803473316ff5fc58de2b8e35ef0087bc3b624 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/losses/utils.py @@ -0,0 +1,129 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import functools + +import numpy as np +import torch +import torch.nn.functional as F +from mmengine.fileio import load + + +def get_class_weight(class_weight): + """Get class weight for loss function. + + Args: + class_weight (list[float] | str | None): If class_weight is a str, + take it as a file name and read from it. + """ + if isinstance(class_weight, str): + # take it as a file path + if class_weight.endswith('.npy'): + class_weight = np.load(class_weight) + else: + # pkl, json or yaml + class_weight = load(class_weight) + + return class_weight + + +def reduce_loss(loss, reduction) -> torch.Tensor: + """Reduce loss as specified. + + Args: + loss (Tensor): Elementwise loss tensor. + reduction (str): Options are "none", "mean" and "sum". + + Return: + Tensor: Reduced loss tensor. + """ + reduction_enum = F._Reduction.get_enum(reduction) + # none: 0, elementwise_mean:1, sum: 2 + if reduction_enum == 0: + return loss + elif reduction_enum == 1: + return loss.mean() + elif reduction_enum == 2: + return loss.sum() + + +def weight_reduce_loss(loss, + weight=None, + reduction='mean', + avg_factor=None) -> torch.Tensor: + """Apply element-wise weight and reduce loss. + + Args: + loss (Tensor): Element-wise loss. + weight (Tensor): Element-wise weights. + reduction (str): Same as built-in losses of PyTorch. + avg_factor (float): Average factor when computing the mean of losses. + + Returns: + Tensor: Processed loss values. + """ + # if weight is specified, apply element-wise weight + if weight is not None: + assert weight.dim() == loss.dim() + if weight.dim() > 1: + assert weight.size(1) == 1 or weight.size(1) == loss.size(1) + loss = loss * weight + + # if avg_factor is not specified, just reduce the loss + if avg_factor is None: + loss = reduce_loss(loss, reduction) + else: + # if reduction is mean, then average the loss by avg_factor + if reduction == 'mean': + # Avoid causing ZeroDivisionError when avg_factor is 0.0, + # i.e., all labels of an image belong to ignore index. + eps = torch.finfo(torch.float32).eps + loss = loss.sum() / (avg_factor + eps) + # if reduction is 'none', then do nothing, otherwise raise an error + elif reduction != 'none': + raise ValueError('avg_factor can not be used with reduction="sum"') + return loss + + +def weighted_loss(loss_func): + """Create a weighted version of a given loss function. + + To use this decorator, the loss function must have the signature like + `loss_func(pred, target, **kwargs)`. The function only needs to compute + element-wise loss without any reduction. This decorator will add weight + and reduction arguments to the function. The decorated function will have + the signature like `loss_func(pred, target, weight=None, reduction='mean', + avg_factor=None, **kwargs)`. + + :Example: + + >>> import torch + >>> @weighted_loss + >>> def l1_loss(pred, target): + >>> return (pred - target).abs() + + >>> pred = torch.Tensor([0, 2, 3]) + >>> target = torch.Tensor([1, 1, 1]) + >>> weight = torch.Tensor([1, 0, 1]) + + >>> l1_loss(pred, target) + tensor(1.3333) + >>> l1_loss(pred, target, weight) + tensor(1.) + >>> l1_loss(pred, target, reduction='none') + tensor([1., 1., 2.]) + >>> l1_loss(pred, target, weight, avg_factor=2) + tensor(1.5000) + """ + + @functools.wraps(loss_func) + def wrapper(pred, + target, + weight=None, + reduction='mean', + avg_factor=None, + **kwargs): + # get element-wise loss + loss = loss_func(pred, target, **kwargs) + loss = weight_reduce_loss(loss, weight, reduction, avg_factor) + return loss + + return wrapper diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__init__.py b/reconstruction/modules/InterFormer/mmseg/models/necks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff03186a92b78f942e79cff9eec9f5e2784c359a --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/necks/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .featurepyramid import Feature2Pyramid +from .fpn import FPN +from .ic_neck import ICNeck +from .jpu import JPU +from .mla_neck import MLANeck +from .multilevel_neck import MultiLevelNeck + +__all__ = [ + 'FPN', 'MultiLevelNeck', 'MLANeck', 'ICNeck', 'JPU', 'Feature2Pyramid' +] diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b33541fed3908c15b3479f2874ffb3a075d1ff70 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3477f13a4fd7dea15251eb0f87e71689dc64b1b Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/featurepyramid.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/featurepyramid.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38ec4302aa0ca5a4aadcb8e4ad8ae00acd0d1bd3 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/featurepyramid.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/featurepyramid.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/featurepyramid.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3911d3224fdbe86e4afac9bee50ede3770778a59 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/featurepyramid.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/fpn.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/fpn.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f24c3ee10fa8639f8b45234aebac350c8a69b5f1 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/fpn.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/fpn.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/fpn.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26df1d6f086136dff02f64bb7fc7ea8e5298e126 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/fpn.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/ic_neck.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/ic_neck.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f64a517a9d62ab380f707860d0c236c78dc9e2ea Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/ic_neck.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/ic_neck.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/ic_neck.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12f6aa6ff0ac3865b437f0a0c70bb8b76124bb65 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/ic_neck.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/jpu.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/jpu.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14f8c3f66987923a58ba98686b8b4c56add16c45 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/jpu.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/jpu.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/jpu.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..962b026cb6e62c03280e84e15468e43e6f9d7692 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/jpu.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/mla_neck.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/mla_neck.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef9fa0352fdbed5d4ecbcdbcef6c6be8199edc9e Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/mla_neck.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/mla_neck.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/mla_neck.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bb1909329e2bc0bffc27abcd2c47e590c6f4726 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/mla_neck.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/multilevel_neck.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/multilevel_neck.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ae3f1a7e1c02eecc9f2502fe255656798475d19 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/multilevel_neck.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/multilevel_neck.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/multilevel_neck.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3660261060da21771eed6d9564684e741de634a2 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/necks/__pycache__/multilevel_neck.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/featurepyramid.py b/reconstruction/modules/InterFormer/mmseg/models/necks/featurepyramid.py new file mode 100644 index 0000000000000000000000000000000000000000..dc1250d39dafcf78880aa282bcba4215520ad94e --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/necks/featurepyramid.py @@ -0,0 +1,67 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import build_norm_layer + +from mmseg.registry import MODELS + + +@MODELS.register_module() +class Feature2Pyramid(nn.Module): + """Feature2Pyramid. + + A neck structure connect ViT backbone and decoder_heads. + + Args: + embed_dims (int): Embedding dimension. + rescales (list[float]): Different sampling multiples were + used to obtain pyramid features. Default: [4, 2, 1, 0.5]. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='SyncBN', requires_grad=True). + """ + + def __init__(self, + embed_dim, + rescales=[4, 2, 1, 0.5], + norm_cfg=dict(type='SyncBN', requires_grad=True)): + super().__init__() + self.rescales = rescales + self.upsample_4x = None + for k in self.rescales: + if k == 4: + self.upsample_4x = nn.Sequential( + nn.ConvTranspose2d( + embed_dim, embed_dim, kernel_size=2, stride=2), + build_norm_layer(norm_cfg, embed_dim)[1], + nn.GELU(), + nn.ConvTranspose2d( + embed_dim, embed_dim, kernel_size=2, stride=2), + ) + elif k == 2: + self.upsample_2x = nn.Sequential( + nn.ConvTranspose2d( + embed_dim, embed_dim, kernel_size=2, stride=2)) + elif k == 1: + self.identity = nn.Identity() + elif k == 0.5: + self.downsample_2x = nn.MaxPool2d(kernel_size=2, stride=2) + elif k == 0.25: + self.downsample_4x = nn.MaxPool2d(kernel_size=4, stride=4) + else: + raise KeyError(f'invalid {k} for feature2pyramid') + + def forward(self, inputs): + assert len(inputs) == len(self.rescales) + outputs = [] + if self.upsample_4x is not None: + ops = [ + self.upsample_4x, self.upsample_2x, self.identity, + self.downsample_2x + ] + else: + ops = [ + self.upsample_2x, self.identity, self.downsample_2x, + self.downsample_4x + ] + for i in range(len(inputs)): + outputs.append(ops[i](inputs[i])) + return tuple(outputs) diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/fpn.py b/reconstruction/modules/InterFormer/mmseg/models/necks/fpn.py new file mode 100644 index 0000000000000000000000000000000000000000..ddab74c00a262a89031fda44824c5de0e2e9a362 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/necks/fpn.py @@ -0,0 +1,212 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize + + +@MODELS.register_module() +class FPN(BaseModule): + """Feature Pyramid Network. + + This neck is the implementation of `Feature Pyramid Networks for Object + Detection `_. + + Args: + in_channels (list[int]): Number of input channels per scale. + out_channels (int): Number of output channels (used at each scale). + num_outs (int): Number of output scales. + start_level (int): Index of the start input backbone level used to + build the feature pyramid. Default: 0. + end_level (int): Index of the end input backbone level (exclusive) to + build the feature pyramid. Default: -1, which means the last level. + add_extra_convs (bool | str): If bool, it decides whether to add conv + layers on top of the original feature maps. Default to False. + If True, its actual mode is specified by `extra_convs_on_inputs`. + If str, it specifies the source feature map of the extra convs. + Only the following options are allowed + + - 'on_input': Last feat map of neck inputs (i.e. backbone feature). + - 'on_lateral': Last feature map after lateral convs. + - 'on_output': The last output feature map after fpn convs. + extra_convs_on_inputs (bool, deprecated): Whether to apply extra convs + on the original feature from the backbone. If True, + it is equivalent to `add_extra_convs='on_input'`. If False, it is + equivalent to set `add_extra_convs='on_output'`. Default to True. + relu_before_extra_convs (bool): Whether to apply relu before the extra + conv. Default: False. + no_norm_on_lateral (bool): Whether to apply norm on lateral. + Default: False. + conv_cfg (dict): Config dict for convolution layer. Default: None. + norm_cfg (dict): Config dict for normalization layer. Default: None. + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: None. + upsample_cfg (dict): Config dict for interpolate layer. + Default: dict(mode='nearest'). + init_cfg (dict or list[dict], optional): Initialization config dict. + + Example: + >>> import torch + >>> in_channels = [2, 3, 5, 7] + >>> scales = [340, 170, 84, 43] + >>> inputs = [torch.rand(1, c, s, s) + ... for c, s in zip(in_channels, scales)] + >>> self = FPN(in_channels, 11, len(in_channels)).eval() + >>> outputs = self.forward(inputs) + >>> for i in range(len(outputs)): + ... print(f'outputs[{i}].shape = {outputs[i].shape}') + outputs[0].shape = torch.Size([1, 11, 340, 340]) + outputs[1].shape = torch.Size([1, 11, 170, 170]) + outputs[2].shape = torch.Size([1, 11, 84, 84]) + outputs[3].shape = torch.Size([1, 11, 43, 43]) + """ + + def __init__(self, + in_channels, + out_channels, + num_outs, + start_level=0, + end_level=-1, + add_extra_convs=False, + extra_convs_on_inputs=False, + relu_before_extra_convs=False, + no_norm_on_lateral=False, + conv_cfg=None, + norm_cfg=None, + act_cfg=None, + upsample_cfg=dict(mode='nearest'), + init_cfg=dict( + type='Xavier', layer='Conv2d', distribution='uniform')): + super().__init__(init_cfg) + assert isinstance(in_channels, list) + self.in_channels = in_channels + self.out_channels = out_channels + self.num_ins = len(in_channels) + self.num_outs = num_outs + self.relu_before_extra_convs = relu_before_extra_convs + self.no_norm_on_lateral = no_norm_on_lateral + self.fp16_enabled = False + self.upsample_cfg = upsample_cfg.copy() + + if end_level == -1: + self.backbone_end_level = self.num_ins + assert num_outs >= self.num_ins - start_level + else: + # if end_level < inputs, no extra level is allowed + self.backbone_end_level = end_level + assert end_level <= len(in_channels) + assert num_outs == end_level - start_level + self.start_level = start_level + self.end_level = end_level + self.add_extra_convs = add_extra_convs + assert isinstance(add_extra_convs, (str, bool)) + if isinstance(add_extra_convs, str): + # Extra_convs_source choices: 'on_input', 'on_lateral', 'on_output' + assert add_extra_convs in ('on_input', 'on_lateral', 'on_output') + elif add_extra_convs: # True + if extra_convs_on_inputs: + # For compatibility with previous release + # TODO: deprecate `extra_convs_on_inputs` + self.add_extra_convs = 'on_input' + else: + self.add_extra_convs = 'on_output' + + self.lateral_convs = nn.ModuleList() + self.fpn_convs = nn.ModuleList() + + for i in range(self.start_level, self.backbone_end_level): + l_conv = ConvModule( + in_channels[i], + out_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg if not self.no_norm_on_lateral else None, + act_cfg=act_cfg, + inplace=False) + fpn_conv = ConvModule( + out_channels, + out_channels, + 3, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + inplace=False) + + self.lateral_convs.append(l_conv) + self.fpn_convs.append(fpn_conv) + + # add extra conv layers (e.g., RetinaNet) + extra_levels = num_outs - self.backbone_end_level + self.start_level + if self.add_extra_convs and extra_levels >= 1: + for i in range(extra_levels): + if i == 0 and self.add_extra_convs == 'on_input': + in_channels = self.in_channels[self.backbone_end_level - 1] + else: + in_channels = out_channels + extra_fpn_conv = ConvModule( + in_channels, + out_channels, + 3, + stride=2, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + inplace=False) + self.fpn_convs.append(extra_fpn_conv) + + def forward(self, inputs): + assert len(inputs) == len(self.in_channels) + + # build laterals + laterals = [ + lateral_conv(inputs[i + self.start_level]) + for i, lateral_conv in enumerate(self.lateral_convs) + ] + + # build top-down path + used_backbone_levels = len(laterals) + for i in range(used_backbone_levels - 1, 0, -1): + # In some cases, fixing `scale factor` (e.g. 2) is preferred, but + # it cannot co-exist with `size` in `F.interpolate`. + if 'scale_factor' in self.upsample_cfg: + laterals[i - 1] = laterals[i - 1] + resize( + laterals[i], **self.upsample_cfg) + else: + prev_shape = laterals[i - 1].shape[2:] + laterals[i - 1] = laterals[i - 1] + resize( + laterals[i], size=prev_shape, **self.upsample_cfg) + + # build outputs + # part 1: from original levels + outs = [ + self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels) + ] + # part 2: add extra levels + if self.num_outs > len(outs): + # use max pool to get more levels on top of outputs + # (e.g., Faster R-CNN, Mask R-CNN) + if not self.add_extra_convs: + for i in range(self.num_outs - used_backbone_levels): + outs.append(F.max_pool2d(outs[-1], 1, stride=2)) + # add conv layers on top of original feature maps (RetinaNet) + else: + if self.add_extra_convs == 'on_input': + extra_source = inputs[self.backbone_end_level - 1] + elif self.add_extra_convs == 'on_lateral': + extra_source = laterals[-1] + elif self.add_extra_convs == 'on_output': + extra_source = outs[-1] + else: + raise NotImplementedError + outs.append(self.fpn_convs[used_backbone_levels](extra_source)) + for i in range(used_backbone_levels + 1, self.num_outs): + if self.relu_before_extra_convs: + outs.append(self.fpn_convs[i](F.relu(outs[-1]))) + else: + outs.append(self.fpn_convs[i](outs[-1])) + return tuple(outs) diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/ic_neck.py b/reconstruction/modules/InterFormer/mmseg/models/necks/ic_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..9763541e0980cb0ec53a342b656e64c99d87ed7e --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/necks/ic_neck.py @@ -0,0 +1,148 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize + + +class CascadeFeatureFusion(BaseModule): + """Cascade Feature Fusion Unit in ICNet. + + Args: + low_channels (int): The number of input channels for + low resolution feature map. + high_channels (int): The number of input channels for + high resolution feature map. + out_channels (int): The number of output channels. + conv_cfg (dict): Dictionary to construct and config conv layer. + Default: None. + norm_cfg (dict): Dictionary to construct and config norm layer. + Default: dict(type='BN'). + act_cfg (dict): Dictionary to construct and config act layer. + Default: dict(type='ReLU'). + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + + Returns: + x (Tensor): The output tensor of shape (N, out_channels, H, W). + x_low (Tensor): The output tensor of shape (N, out_channels, H, W) + for Cascade Label Guidance in auxiliary heads. + """ + + def __init__(self, + low_channels, + high_channels, + out_channels, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.align_corners = align_corners + self.conv_low = ConvModule( + low_channels, + out_channels, + 3, + padding=2, + dilation=2, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.conv_high = ConvModule( + high_channels, + out_channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, x_low, x_high): + x_low = resize( + x_low, + size=x_high.size()[2:], + mode='bilinear', + align_corners=self.align_corners) + # Note: Different from original paper, `x_low` is underwent + # `self.conv_low` rather than another 1x1 conv classifier + # before being used for auxiliary head. + x_low = self.conv_low(x_low) + x_high = self.conv_high(x_high) + x = x_low + x_high + x = F.relu(x, inplace=True) + return x, x_low + + +@MODELS.register_module() +class ICNeck(BaseModule): + """ICNet for Real-Time Semantic Segmentation on High-Resolution Images. + + This head is the implementation of `ICHead + `_. + + Args: + in_channels (int): The number of input image channels. Default: 3. + out_channels (int): The numbers of output feature channels. + Default: 128. + conv_cfg (dict): Dictionary to construct and config conv layer. + Default: None. + norm_cfg (dict): Dictionary to construct and config norm layer. + Default: dict(type='BN'). + act_cfg (dict): Dictionary to construct and config act layer. + Default: dict(type='ReLU'). + align_corners (bool): align_corners argument of F.interpolate. + Default: False. + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels=(64, 256, 256), + out_channels=128, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + align_corners=False, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + assert len(in_channels) == 3, 'Length of input channels \ + must be 3!' + + self.in_channels = in_channels + self.out_channels = out_channels + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.align_corners = align_corners + self.cff_24 = CascadeFeatureFusion( + self.in_channels[2], + self.in_channels[1], + self.out_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=self.align_corners) + + self.cff_12 = CascadeFeatureFusion( + self.out_channels, + self.in_channels[0], + self.out_channels, + conv_cfg=self.conv_cfg, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + align_corners=self.align_corners) + + def forward(self, inputs): + assert len(inputs) == 3, 'Length of input feature \ + maps must be 3!' + + x_sub1, x_sub2, x_sub4 = inputs + x_cff_24, x_24 = self.cff_24(x_sub4, x_sub2) + x_cff_12, x_12 = self.cff_12(x_cff_24, x_sub1) + # Note: `x_cff_12` is used for decode_head, + # `x_24` and `x_12` are used for auxiliary head. + return x_24, x_12, x_cff_12 diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/jpu.py b/reconstruction/modules/InterFormer/mmseg/models/necks/jpu.py new file mode 100644 index 0000000000000000000000000000000000000000..3ea0fe2183377d3e3c1a87ca8a0df909b123cdfa --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/necks/jpu.py @@ -0,0 +1,131 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule +from mmengine.model import BaseModule + +from mmseg.registry import MODELS +from ..utils import resize + + +@MODELS.register_module() +class JPU(BaseModule): + """FastFCN: Rethinking Dilated Convolution in the Backbone + for Semantic Segmentation. + + This Joint Pyramid Upsampling (JPU) neck is the implementation of + `FastFCN `_. + + Args: + in_channels (Tuple[int], optional): The number of input channels + for each convolution operations before upsampling. + Default: (512, 1024, 2048). + mid_channels (int): The number of output channels of JPU. + Default: 512. + start_level (int): Index of the start input backbone level used to + build the feature pyramid. Default: 0. + end_level (int): Index of the end input backbone level (exclusive) to + build the feature pyramid. Default: -1, which means the last level. + dilations (tuple[int]): Dilation rate of each Depthwise + Separable ConvModule. Default: (1, 2, 4, 8). + align_corners (bool, optional): The align_corners argument of + resize operation. Default: False. + conv_cfg (dict | None): Config of conv layers. + Default: None. + norm_cfg (dict | None): Config of norm layers. + Default: dict(type='BN'). + act_cfg (dict): Config of activation layers. + Default: dict(type='ReLU'). + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + in_channels=(512, 1024, 2048), + mid_channels=512, + start_level=0, + end_level=-1, + dilations=(1, 2, 4, 8), + align_corners=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + assert isinstance(in_channels, tuple) + assert isinstance(dilations, tuple) + self.in_channels = in_channels + self.mid_channels = mid_channels + self.start_level = start_level + self.num_ins = len(in_channels) + if end_level == -1: + self.backbone_end_level = self.num_ins + else: + self.backbone_end_level = end_level + assert end_level <= len(in_channels) + + self.dilations = dilations + self.align_corners = align_corners + + self.conv_layers = nn.ModuleList() + self.dilation_layers = nn.ModuleList() + for i in range(self.start_level, self.backbone_end_level): + conv_layer = nn.Sequential( + ConvModule( + self.in_channels[i], + self.mid_channels, + kernel_size=3, + padding=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.conv_layers.append(conv_layer) + for i in range(len(dilations)): + dilation_layer = nn.Sequential( + DepthwiseSeparableConvModule( + in_channels=(self.backbone_end_level - self.start_level) * + self.mid_channels, + out_channels=self.mid_channels, + kernel_size=3, + stride=1, + padding=dilations[i], + dilation=dilations[i], + dw_norm_cfg=norm_cfg, + dw_act_cfg=None, + pw_norm_cfg=norm_cfg, + pw_act_cfg=act_cfg)) + self.dilation_layers.append(dilation_layer) + + def forward(self, inputs): + """Forward function.""" + assert len(inputs) == len(self.in_channels), 'Length of inputs must \ + be the same with self.in_channels!' + + feats = [ + self.conv_layers[i - self.start_level](inputs[i]) + for i in range(self.start_level, self.backbone_end_level) + ] + + h, w = feats[0].shape[2:] + for i in range(1, len(feats)): + feats[i] = resize( + feats[i], + size=(h, w), + mode='bilinear', + align_corners=self.align_corners) + + feat = torch.cat(feats, dim=1) + concat_feat = torch.cat([ + self.dilation_layers[i](feat) for i in range(len(self.dilations)) + ], + dim=1) + + outs = [] + + # Default: outs[2] is the output of JPU for decoder head, outs[1] is + # the feature map from backbone for auxiliary head. Additionally, + # outs[0] can also be used for auxiliary head. + for i in range(self.start_level, self.backbone_end_level - 1): + outs.append(inputs[i]) + outs.append(concat_feat) + return tuple(outs) diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/mla_neck.py b/reconstruction/modules/InterFormer/mmseg/models/necks/mla_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..db250aefbfa45beaa98855be79ddc7f5e7276cca --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/necks/mla_neck.py @@ -0,0 +1,118 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import ConvModule, build_norm_layer + +from mmseg.registry import MODELS + + +class MLAModule(nn.Module): + + def __init__(self, + in_channels=[1024, 1024, 1024, 1024], + out_channels=256, + norm_cfg=None, + act_cfg=None): + super().__init__() + self.channel_proj = nn.ModuleList() + for i in range(len(in_channels)): + self.channel_proj.append( + ConvModule( + in_channels=in_channels[i], + out_channels=out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + self.feat_extract = nn.ModuleList() + for i in range(len(in_channels)): + self.feat_extract.append( + ConvModule( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + def forward(self, inputs): + + # feat_list -> [p2, p3, p4, p5] + feat_list = [] + for x, conv in zip(inputs, self.channel_proj): + feat_list.append(conv(x)) + + # feat_list -> [p5, p4, p3, p2] + # mid_list -> [m5, m4, m3, m2] + feat_list = feat_list[::-1] + mid_list = [] + for feat in feat_list: + if len(mid_list) == 0: + mid_list.append(feat) + else: + mid_list.append(mid_list[-1] + feat) + + # mid_list -> [m5, m4, m3, m2] + # out_list -> [o2, o3, o4, o5] + out_list = [] + for mid, conv in zip(mid_list, self.feat_extract): + out_list.append(conv(mid)) + + return tuple(out_list) + + +@MODELS.register_module() +class MLANeck(nn.Module): + """Multi-level Feature Aggregation. + + This neck is `The Multi-level Feature Aggregation construction of + SETR `_. + + + Args: + in_channels (List[int]): Number of input channels per scale. + out_channels (int): Number of output channels (used at each scale). + norm_layer (dict): Config dict for input normalization. + Default: norm_layer=dict(type='LN', eps=1e-6, requires_grad=True). + norm_cfg (dict): Config dict for normalization layer. Default: None. + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + norm_layer=dict(type='LN', eps=1e-6, requires_grad=True), + norm_cfg=None, + act_cfg=None): + super().__init__() + assert isinstance(in_channels, list) + self.in_channels = in_channels + self.out_channels = out_channels + + # In order to build general vision transformer backbone, we have to + # move MLA to neck. + self.norm = nn.ModuleList([ + build_norm_layer(norm_layer, in_channels[i])[1] + for i in range(len(in_channels)) + ]) + + self.mla = MLAModule( + in_channels=in_channels, + out_channels=out_channels, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, inputs): + assert len(inputs) == len(self.in_channels) + + # Convert from nchw to nlc + outs = [] + for i in range(len(inputs)): + x = inputs[i] + n, c, h, w = x.shape + x = x.reshape(n, c, h * w).transpose(2, 1).contiguous() + x = self.norm[i](x) + x = x.transpose(1, 2).reshape(n, c, h, w).contiguous() + outs.append(x) + + outs = self.mla(outs) + return tuple(outs) diff --git a/reconstruction/modules/InterFormer/mmseg/models/necks/multilevel_neck.py b/reconstruction/modules/InterFormer/mmseg/models/necks/multilevel_neck.py new file mode 100644 index 0000000000000000000000000000000000000000..c997125f24791b1c01248c60a27fa37a986c6c82 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/necks/multilevel_neck.py @@ -0,0 +1,79 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model.weight_init import xavier_init + +from mmseg.registry import MODELS +from ..utils import resize + + +@MODELS.register_module() +class MultiLevelNeck(nn.Module): + """MultiLevelNeck. + + A neck structure connect vit backbone and decoder_heads. + + Args: + in_channels (List[int]): Number of input channels per scale. + out_channels (int): Number of output channels (used at each scale). + scales (List[float]): Scale factors for each input feature map. + Default: [0.5, 1, 2, 4] + norm_cfg (dict): Config dict for normalization layer. Default: None. + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + scales=[0.5, 1, 2, 4], + norm_cfg=None, + act_cfg=None): + super().__init__() + assert isinstance(in_channels, list) + self.in_channels = in_channels + self.out_channels = out_channels + self.scales = scales + self.num_outs = len(scales) + self.lateral_convs = nn.ModuleList() + self.convs = nn.ModuleList() + for in_channel in in_channels: + self.lateral_convs.append( + ConvModule( + in_channel, + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + for _ in range(self.num_outs): + self.convs.append( + ConvModule( + out_channels, + out_channels, + kernel_size=3, + padding=1, + stride=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + # default init_weights for conv(msra) and norm in ConvModule + def init_weights(self): + for m in self.modules(): + if isinstance(m, nn.Conv2d): + xavier_init(m, distribution='uniform') + + def forward(self, inputs): + assert len(inputs) == len(self.in_channels) + inputs = [ + lateral_conv(inputs[i]) + for i, lateral_conv in enumerate(self.lateral_convs) + ] + # for len(inputs) not equal to self.num_outs + if len(inputs) == 1: + inputs = [inputs[0] for _ in range(self.num_outs)] + outs = [] + for i in range(self.num_outs): + x_resize = resize( + inputs[i], scale_factor=self.scales[i], mode='bilinear') + outs.append(self.convs[i](x_resize)) + return tuple(outs) diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__init__.py b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59b012f41725d26d099b8f890630d1dc04019ba5 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__init__.py @@ -0,0 +1,12 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .base import BaseSegmentor +from .cascade_encoder_decoder import CascadeEncoderDecoder +from .depth_estimator import DepthEstimator +from .encoder_decoder import EncoderDecoder +from .multimodal_encoder_decoder import MultimodalEncoderDecoder +from .seg_tta import SegTTAModel + +__all__ = [ + 'BaseSegmentor', 'EncoderDecoder', 'CascadeEncoderDecoder', 'SegTTAModel', + 'MultimodalEncoderDecoder', 'DepthEstimator' +] diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..718e5460eda862fe1d0f3e946cd74eaf7ba02b3c Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be9b139301597c27ae4b445eaa42165bcca8bee1 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/base.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acf2fb3cc44a7a8b198362e059304456fe46c54c Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/base.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/base.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/base.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40d1eea4451079037481043d6d6cab931ec54bcc Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/base.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/cascade_encoder_decoder.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/cascade_encoder_decoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8d4936063416634957bed47add57d29f80d12cb Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/cascade_encoder_decoder.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/cascade_encoder_decoder.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/cascade_encoder_decoder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed6a18bc9a4ea83c927f42f670b3136150ae8f51 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/cascade_encoder_decoder.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/depth_estimator.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/depth_estimator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f26b9097b037102d4aa1a9b54b861ad957021ec9 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/depth_estimator.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/depth_estimator.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/depth_estimator.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4237a96807892538f8fe4ac9bd61c8009e78c67 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/depth_estimator.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/encoder_decoder.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/encoder_decoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc5187d382b8ce0ee712d4130ef860700409ce35 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/encoder_decoder.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/encoder_decoder.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/encoder_decoder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..756aa4bde3201ce29986519ee17412337a9f2de7 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/encoder_decoder.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/multimodal_encoder_decoder.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/multimodal_encoder_decoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a78d19e5d16a40eb6cac8742cf53705c5e7a021 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/multimodal_encoder_decoder.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/multimodal_encoder_decoder.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/multimodal_encoder_decoder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b087ddf5bd4df9b38aaf3ecb1d088a2f4c411d8 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/multimodal_encoder_decoder.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/seg_tta.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/seg_tta.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..04a7bca41bf39801984d261767950f646e84dd44 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/seg_tta.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/seg_tta.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/seg_tta.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7852561d351729941b62078d90a2fae7af7f0bb8 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/segmentors/__pycache__/seg_tta.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/base.py b/reconstruction/modules/InterFormer/mmseg/models/segmentors/base.py new file mode 100644 index 0000000000000000000000000000000000000000..17a0bb2b33e57684bccaaf892af69bcba69dd773 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/segmentors/base.py @@ -0,0 +1,200 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from abc import ABCMeta, abstractmethod +from typing import List, Tuple + +from mmengine.model import BaseModel +from mmengine.structures import PixelData +from torch import Tensor + +from mmseg.structures import SegDataSample +from mmseg.utils import (ForwardResults, OptConfigType, OptMultiConfig, + OptSampleList, SampleList) +from ..utils import resize + + +class BaseSegmentor(BaseModel, metaclass=ABCMeta): + """Base class for segmentors. + + Args: + data_preprocessor (dict, optional): Model preprocessing config + for processing the input data. it usually includes + ``to_rgb``, ``pad_size_divisor``, ``pad_val``, + ``mean`` and ``std``. Default to None. + init_cfg (dict, optional): the config to control the + initialization. Default to None. + """ + + def __init__(self, + data_preprocessor: OptConfigType = None, + init_cfg: OptMultiConfig = None): + super().__init__( + data_preprocessor=data_preprocessor, init_cfg=init_cfg) + + @property + def with_neck(self) -> bool: + """bool: whether the segmentor has neck""" + return hasattr(self, 'neck') and self.neck is not None + + @property + def with_auxiliary_head(self) -> bool: + """bool: whether the segmentor has auxiliary head""" + return hasattr(self, + 'auxiliary_head') and self.auxiliary_head is not None + + @property + def with_decode_head(self) -> bool: + """bool: whether the segmentor has decode head""" + return hasattr(self, 'decode_head') and self.decode_head is not None + + @abstractmethod + def extract_feat(self, inputs: Tensor) -> bool: + """Placeholder for extract features from images.""" + pass + + @abstractmethod + def encode_decode(self, inputs: Tensor, batch_data_samples: SampleList): + """Placeholder for encode images with backbone and decode into a + semantic segmentation map of the same size as input.""" + pass + + def forward(self, + inputs: Tensor, + data_samples: OptSampleList = None, + mode: str = 'tensor') -> ForwardResults: + """The unified entry for a forward process in both training and test. + + The method should accept three modes: "tensor", "predict" and "loss": + + - "tensor": Forward the whole network and return tensor or tuple of + tensor without any post-processing, same as a common nn.Module. + - "predict": Forward and return the predictions, which are fully + processed to a list of :obj:`SegDataSample`. + - "loss": Forward and return a dict of losses according to the given + inputs and data samples. + + Note that this method doesn't handle neither back propagation nor + optimizer updating, which are done in the :meth:`train_step`. + + Args: + inputs (torch.Tensor): The input tensor with shape (N, C, ...) in + general. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_sem_seg`. Default to None. + mode (str): Return what kind of value. Defaults to 'tensor'. + + Returns: + The return type depends on ``mode``. + + - If ``mode="tensor"``, return a tensor or a tuple of tensor. + - If ``mode="predict"``, return a list of :obj:`DetDataSample`. + - If ``mode="loss"``, return a dict of tensor. + """ + if mode == 'loss': + return self.loss(inputs, data_samples) + elif mode == 'predict': + return self.predict(inputs, data_samples) + elif mode == 'tensor': + return self._forward(inputs, data_samples) + else: + raise RuntimeError(f'Invalid mode "{mode}". ' + 'Only supports loss, predict and tensor mode') + + @abstractmethod + def loss(self, inputs: Tensor, data_samples: SampleList) -> dict: + """Calculate losses from a batch of inputs and data samples.""" + pass + + @abstractmethod + def predict(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """Predict results from a batch of inputs and data samples with post- + processing.""" + pass + + @abstractmethod + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tuple[List[Tensor]]: + """Network forward process. + + Usually includes backbone, neck and head forward without any post- + processing. + """ + pass + + def postprocess_result(self, + seg_logits: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """ Convert results list to `SegDataSample`. + Args: + seg_logits (Tensor): The segmentation results, seg_logits from + model of each input image. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_sem_seg`. Default to None. + Returns: + list[:obj:`SegDataSample`]: Segmentation results of the + input images. Each SegDataSample usually contain: + + - ``pred_sem_seg``(PixelData): Prediction of semantic segmentation. + - ``seg_logits``(PixelData): Predicted logits of semantic + segmentation before normalization. + """ + batch_size, C, H, W = seg_logits.shape + + if data_samples is None: + data_samples = [SegDataSample() for _ in range(batch_size)] + only_prediction = True + else: + only_prediction = False + + for i in range(batch_size): + if not only_prediction: + img_meta = data_samples[i].metainfo + # remove padding area + if 'img_padding_size' not in img_meta: + padding_size = img_meta.get('padding_size', [0] * 4) + else: + padding_size = img_meta['img_padding_size'] + padding_left, padding_right, padding_top, padding_bottom =\ + padding_size + # i_seg_logits shape is 1, C, H, W after remove padding + i_seg_logits = seg_logits[i:i + 1, :, + padding_top:H - padding_bottom, + padding_left:W - padding_right] + + flip = img_meta.get('flip', None) + if flip: + flip_direction = img_meta.get('flip_direction', None) + assert flip_direction in ['horizontal', 'vertical'] + if flip_direction == 'horizontal': + i_seg_logits = i_seg_logits.flip(dims=(3, )) + else: + i_seg_logits = i_seg_logits.flip(dims=(2, )) + + # resize as original shape + i_seg_logits = resize( + i_seg_logits, + size=img_meta['ori_shape'], + mode='bilinear', + align_corners=self.align_corners, + warning=False).squeeze(0) + else: + i_seg_logits = seg_logits[i] + + if C > 1: + i_seg_pred = i_seg_logits.argmax(dim=0, keepdim=True) + else: + i_seg_logits = i_seg_logits.sigmoid() + i_seg_pred = (i_seg_logits > + self.decode_head.threshold).to(i_seg_logits) + data_samples[i].set_data({ + 'seg_logits': + PixelData(**{'data': i_seg_logits}), + 'pred_sem_seg': + PixelData(**{'data': i_seg_pred}) + }) + + return data_samples diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/cascade_encoder_decoder.py b/reconstruction/modules/InterFormer/mmseg/models/segmentors/cascade_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..0184a3533a18cbe96a28bbb645c3e73bbffcdeee --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/segmentors/cascade_encoder_decoder.py @@ -0,0 +1,138 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional + +from torch import Tensor, nn + +from mmseg.registry import MODELS +from mmseg.utils import (ConfigType, OptConfigType, OptMultiConfig, + OptSampleList, SampleList, add_prefix) +from .encoder_decoder import EncoderDecoder + + +@MODELS.register_module() +class CascadeEncoderDecoder(EncoderDecoder): + """Cascade Encoder Decoder segmentors. + + CascadeEncoderDecoder almost the same as EncoderDecoder, while decoders of + CascadeEncoderDecoder are cascaded. The output of previous decoder_head + will be the input of next decoder_head. + + Args: + + num_stages (int): How many stages will be cascaded. + backbone (ConfigType): The config for the backnone of segmentor. + decode_head (ConfigType): The config for the decode head of segmentor. + neck (OptConfigType): The config for the neck of segmentor. + Defaults to None. + auxiliary_head (OptConfigType): The config for the auxiliary head of + segmentor. Defaults to None. + train_cfg (OptConfigType): The config for training. Defaults to None. + test_cfg (OptConfigType): The config for testing. Defaults to None. + data_preprocessor (dict, optional): The pre-process config of + :class:`BaseDataPreprocessor`. + pretrained (str, optional): The path for pretrained model. + Defaults to None. + init_cfg (dict, optional): The weight initialized config for + :class:`BaseModule`. + """ + + def __init__(self, + num_stages: int, + backbone: ConfigType, + decode_head: ConfigType, + neck: OptConfigType = None, + auxiliary_head: OptConfigType = None, + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + data_preprocessor: OptConfigType = None, + pretrained: Optional[str] = None, + init_cfg: OptMultiConfig = None): + self.num_stages = num_stages + super().__init__( + backbone=backbone, + decode_head=decode_head, + neck=neck, + auxiliary_head=auxiliary_head, + train_cfg=train_cfg, + test_cfg=test_cfg, + data_preprocessor=data_preprocessor, + pretrained=pretrained, + init_cfg=init_cfg) + + def _init_decode_head(self, decode_head: ConfigType) -> None: + """Initialize ``decode_head``""" + assert isinstance(decode_head, list) + assert len(decode_head) == self.num_stages + self.decode_head = nn.ModuleList() + for i in range(self.num_stages): + self.decode_head.append(MODELS.build(decode_head[i])) + self.align_corners = self.decode_head[-1].align_corners + self.num_classes = self.decode_head[-1].num_classes + self.out_channels = self.decode_head[-1].out_channels + + def encode_decode(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Encode images with backbone and decode into a semantic segmentation + map of the same size as input.""" + x = self.extract_feat(inputs) + out = self.decode_head[0].forward(x) + for i in range(1, self.num_stages - 1): + out = self.decode_head[i].forward(x, out) + seg_logits_list = self.decode_head[-1].predict(x, out, batch_img_metas, + self.test_cfg) + + return seg_logits_list + + def _decode_head_forward_train(self, inputs: Tensor, + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for decode head in + training.""" + losses = dict() + + loss_decode = self.decode_head[0].loss(inputs, data_samples, + self.train_cfg) + + losses.update(add_prefix(loss_decode, 'decode_0')) + # get batch_img_metas + batch_size = len(data_samples) + batch_img_metas = [] + for batch_index in range(batch_size): + metainfo = data_samples[batch_index].metainfo + batch_img_metas.append(metainfo) + + for i in range(1, self.num_stages): + # forward test again, maybe unnecessary for most methods. + if i == 1: + prev_outputs = self.decode_head[0].forward(inputs) + else: + prev_outputs = self.decode_head[i - 1].forward( + inputs, prev_outputs) + loss_decode = self.decode_head[i].loss(inputs, prev_outputs, + data_samples, + self.train_cfg) + losses.update(add_prefix(loss_decode, f'decode_{i}')) + + return losses + + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tensor: + """Network forward process. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_semantic_seg`. + + Returns: + Tensor: Forward output of model without any post-processes. + """ + x = self.extract_feat(inputs) + + out = self.decode_head[0].forward(x) + for i in range(1, self.num_stages): + # TODO support PointRend tensor mode + out = self.decode_head[i].forward(x, out) + + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/depth_estimator.py b/reconstruction/modules/InterFormer/mmseg/models/segmentors/depth_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..1020637e737a3c72ba6a48f2d1228717470ba862 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/segmentors/depth_estimator.py @@ -0,0 +1,392 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import logging +from typing import List, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmengine.logging import print_log +from mmengine.structures import PixelData +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.structures import SegDataSample +from mmseg.utils import (ConfigType, OptConfigType, OptMultiConfig, + OptSampleList, SampleList, add_prefix) +from ..utils import resize +from .encoder_decoder import EncoderDecoder + + +@MODELS.register_module() +class DepthEstimator(EncoderDecoder): + """Encoder Decoder depth estimator. + + EncoderDecoder typically consists of backbone, decode_head, auxiliary_head. + Note that auxiliary_head is only used for deep supervision during training, + which could be dumped during inference. + + 1. The ``loss`` method is used to calculate the loss of model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2) Call the decode head loss function to forward decode head model and + calculate losses. + + .. code:: text + + loss(): extract_feat() -> _decode_head_forward_train() -> _auxiliary_head_forward_train (optional) + _decode_head_forward_train(): decode_head.loss() + _auxiliary_head_forward_train(): auxiliary_head.loss (optional) + + 2. The ``predict`` method is used to predict depth estimation results, + which includes two steps: (1) Run inference function to obtain the list of + depth (2) Call post-processing function to obtain list of + ``SegDataSample`` including ``pred_depth_map``. + + .. code:: text + + predict(): inference() -> postprocess_result() + inference(): whole_inference()/slide_inference() + whole_inference()/slide_inference(): encoder_decoder() + encoder_decoder(): extract_feat() -> decode_head.predict() + + 3. The ``_forward`` method is used to output the tensor by running the model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2)Call the decode head forward function to forward decode head model. + + .. code:: text + + _forward(): extract_feat() -> _decode_head.forward() + + Args: + + backbone (ConfigType): The config for the backnone of depth estimator. + decode_head (ConfigType): The config for the decode head of depth estimator. + neck (OptConfigType): The config for the neck of depth estimator. + Defaults to None. + auxiliary_head (OptConfigType): The config for the auxiliary head of + depth estimator. Defaults to None. + train_cfg (OptConfigType): The config for training. Defaults to None. + test_cfg (OptConfigType): The config for testing. Defaults to None. + data_preprocessor (dict, optional): The pre-process config of + :class:`BaseDataPreprocessor`. + pretrained (str, optional): The path for pretrained model. + Defaults to None. + init_cfg (dict, optional): The weight initialized config for + :class:`BaseModule`. + """ # noqa: E501 + + def __init__(self, + backbone: ConfigType, + decode_head: ConfigType, + neck: OptConfigType = None, + auxiliary_head: OptConfigType = None, + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + data_preprocessor: OptConfigType = None, + pretrained: Optional[str] = None, + init_cfg: OptMultiConfig = None): + super().__init__( + backbone=backbone, + decode_head=decode_head, + neck=neck, + auxiliary_head=auxiliary_head, + train_cfg=train_cfg, + test_cfg=test_cfg, + data_preprocessor=data_preprocessor, + pretrained=pretrained, + init_cfg=init_cfg) + + def extract_feat(self, + inputs: Tensor, + batch_img_metas: Optional[List[dict]] = None) -> Tensor: + """Extract features from images.""" + + if getattr(self.backbone, 'class_embed_select', False) and \ + isinstance(batch_img_metas, list) and \ + 'category_id' in batch_img_metas[0]: + cat_ids = [meta['category_id'] for meta in batch_img_metas] + cat_ids = torch.tensor(cat_ids).to(inputs.device) + inputs = (inputs, cat_ids) + + x = self.backbone(inputs) + if self.with_neck: + x = self.neck(x) + return x + + def encode_decode(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Encode images with backbone and decode into a depth map of the same + size as input.""" + x = self.extract_feat(inputs, batch_img_metas) + depth = self.decode_head.predict(x, batch_img_metas, self.test_cfg) + + return depth + + def _decode_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for decode head in + training.""" + losses = dict() + loss_decode = self.decode_head.loss(inputs, data_samples, + self.train_cfg) + + losses.update(add_prefix(loss_decode, 'decode')) + return losses + + def _auxiliary_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for auxiliary head in + training.""" + losses = dict() + if isinstance(self.auxiliary_head, nn.ModuleList): + for idx, aux_head in enumerate(self.auxiliary_head): + loss_aux = aux_head.loss(inputs, data_samples, self.train_cfg) + losses.update(add_prefix(loss_aux, f'aux_{idx}')) + else: + loss_aux = self.auxiliary_head.loss(inputs, data_samples, + self.train_cfg) + losses.update(add_prefix(loss_aux, 'aux')) + + return losses + + def loss(self, inputs: Tensor, data_samples: SampleList) -> dict: + """Calculate losses from a batch of inputs and data samples. + + Args: + inputs (Tensor): Input images. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_depth_map`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + if data_samples is not None: + batch_img_metas = [ + data_sample.metainfo for data_sample in data_samples + ] + else: + batch_img_metas = [ + dict( + ori_shape=inputs.shape[2:], + img_shape=inputs.shape[2:], + pad_shape=inputs.shape[2:], + padding_size=[0, 0, 0, 0]) + ] * inputs.shape[0] + + x = self.extract_feat(inputs, batch_img_metas) + + losses = dict() + + loss_decode = self._decode_head_forward_train(x, data_samples) + losses.update(loss_decode) + + if self.with_auxiliary_head: + loss_aux = self._auxiliary_head_forward_train(x, data_samples) + losses.update(loss_aux) + + return losses + + def predict(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """Predict results from a batch of inputs and data samples with post- + processing. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`], optional): The seg data + samples. It usually includes information such as `metainfo` + and `gt_depth_map`. + + Returns: + list[:obj:`SegDataSample`]: Depth estimation results of the + input images. Each SegDataSample usually contain: + + - ``pred_depth_max``(PixelData): Prediction of depth estimation. + """ + if data_samples is not None: + batch_img_metas = [ + data_sample.metainfo for data_sample in data_samples + ] + else: + batch_img_metas = [ + dict( + ori_shape=inputs.shape[2:], + img_shape=inputs.shape[2:], + pad_shape=inputs.shape[2:], + padding_size=[0, 0, 0, 0]) + ] * inputs.shape[0] + + depth = self.inference(inputs, batch_img_metas) + + return self.postprocess_result(depth, data_samples) + + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tensor: + """Network forward process. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_depth_map`. + + Returns: + Tensor: Forward output of model without any post-processes. + """ + x = self.extract_feat(inputs) + return self.decode_head.forward(x) + + def slide_flip_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference by sliding-window with overlap and flip. + + If h_crop > h_img or w_crop > w_img, the small patch will be used to + decode without padding. + + Args: + inputs (tensor): the tensor should have a shape NxCxHxW, + which contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The depth estimation results. + """ + + h_stride, w_stride = self.test_cfg.stride + h_crop, w_crop = self.test_cfg.crop_size + batch_size, _, h_img, w_img = inputs.size() + out_channels = self.out_channels + h_grids = max(h_img - h_crop + h_stride - 1, 0) // h_stride + 1 + w_grids = max(w_img - w_crop + w_stride - 1, 0) // w_stride + 1 + preds = inputs.new_zeros((batch_size, out_channels, h_img, w_img)) + count_mat = inputs.new_zeros((batch_size, 1, h_img, w_img)) + for h_idx in range(h_grids): + for w_idx in range(w_grids): + y1 = h_idx * h_stride + x1 = w_idx * w_stride + y2 = min(y1 + h_crop, h_img) + x2 = min(x1 + w_crop, w_img) + y1 = max(y2 - h_crop, 0) + x1 = max(x2 - w_crop, 0) + crop_img = inputs[:, :, y1:y2, x1:x2] + # change the image shape to patch shape + batch_img_metas[0]['img_shape'] = crop_img.shape[2:] + # the output of encode_decode is depth tensor map + # with shape [N, C, H, W] + crop_depth_map = self.encode_decode(crop_img, batch_img_metas) + + # average out the original and flipped prediction + crop_depth_map_flip = self.encode_decode( + crop_img.flip(dims=(3, )), batch_img_metas) + crop_depth_map_flip = crop_depth_map_flip.flip(dims=(3, )) + crop_depth_map = (crop_depth_map + crop_depth_map_flip) / 2.0 + + preds += F.pad(crop_depth_map, + (int(x1), int(preds.shape[3] - x2), int(y1), + int(preds.shape[2] - y2))) + + count_mat[:, :, y1:y2, x1:x2] += 1 + assert (count_mat == 0).sum() == 0 + depth = preds / count_mat + + return depth + + def inference(self, inputs: Tensor, batch_img_metas: List[dict]) -> Tensor: + """Inference with slide/whole style. + + Args: + inputs (Tensor): The input image of shape (N, 3, H, W). + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', 'pad_shape', and 'padding_size'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The depth estimation results. + """ + assert self.test_cfg.get('mode', 'whole') in ['slide', 'whole', + 'slide_flip'], \ + f'Only "slide", "slide_flip" or "whole" test mode are ' \ + f'supported, but got {self.test_cfg["mode"]}.' + ori_shape = batch_img_metas[0]['ori_shape'] + if not all(_['ori_shape'] == ori_shape for _ in batch_img_metas): + print_log( + 'Image shapes are different in the batch.', + logger='current', + level=logging.WARN) + if self.test_cfg.mode == 'slide': + depth_map = self.slide_inference(inputs, batch_img_metas) + if self.test_cfg.mode == 'slide_flip': + depth_map = self.slide_flip_inference(inputs, batch_img_metas) + else: + depth_map = self.whole_inference(inputs, batch_img_metas) + + return depth_map + + def postprocess_result(self, + depth: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """ Convert results list to `SegDataSample`. + Args: + depth (Tensor): The depth estimation results. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_depth_map`. Default to None. + Returns: + list[:obj:`SegDataSample`]: Depth estomation results of the + input images. Each SegDataSample usually contain: + + - ``pred_depth_map``(PixelData): Prediction of depth estimation. + """ + batch_size, C, H, W = depth.shape + + if data_samples is None: + data_samples = [SegDataSample() for _ in range(batch_size)] + only_prediction = True + else: + only_prediction = False + + for i in range(batch_size): + if not only_prediction: + img_meta = data_samples[i].metainfo + # remove padding area + if 'img_padding_size' not in img_meta: + padding_size = img_meta.get('padding_size', [0] * 4) + else: + padding_size = img_meta['img_padding_size'] + padding_left, padding_right, padding_top, padding_bottom =\ + padding_size + # i_depth shape is 1, C, H, W after remove padding + i_depth = depth[i:i + 1, :, padding_top:H - padding_bottom, + padding_left:W - padding_right] + + flip = img_meta.get('flip', None) + if flip: + flip_direction = img_meta.get('flip_direction', None) + assert flip_direction in ['horizontal', 'vertical'] + if flip_direction == 'horizontal': + i_depth = i_depth.flip(dims=(3, )) + else: + i_depth = i_depth.flip(dims=(2, )) + + # resize as original shape + i_depth = resize( + i_depth, + size=img_meta['ori_shape'], + mode='bilinear', + align_corners=self.align_corners, + warning=False).squeeze(0) + else: + i_depth = depth[i] + + data_samples[i].set_data( + {'pred_depth_map': PixelData(**{'data': i_depth})}) + + return data_samples diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/encoder_decoder.py b/reconstruction/modules/InterFormer/mmseg/models/segmentors/encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4050e0b736f98c17629a93e2f70be1d7e84fbb --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/segmentors/encoder_decoder.py @@ -0,0 +1,364 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import logging +from typing import List, Optional + +import torch.nn as nn +import torch.nn.functional as F +from mmengine.logging import print_log +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import (ConfigType, OptConfigType, OptMultiConfig, + OptSampleList, SampleList, add_prefix) +from .base import BaseSegmentor + + +@MODELS.register_module() +class EncoderDecoder(BaseSegmentor): + """Encoder Decoder segmentors. + + EncoderDecoder typically consists of backbone, decode_head, auxiliary_head. + Note that auxiliary_head is only used for deep supervision during training, + which could be dumped during inference. + + 1. The ``loss`` method is used to calculate the loss of model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2) Call the decode head loss function to forward decode head model and + calculate losses. + + .. code:: text + + loss(): extract_feat() -> _decode_head_forward_train() -> _auxiliary_head_forward_train (optional) + _decode_head_forward_train(): decode_head.loss() + _auxiliary_head_forward_train(): auxiliary_head.loss (optional) + + 2. The ``predict`` method is used to predict segmentation results, + which includes two steps: (1) Run inference function to obtain the list of + seg_logits (2) Call post-processing function to obtain list of + ``SegDataSample`` including ``pred_sem_seg`` and ``seg_logits``. + + .. code:: text + + predict(): inference() -> postprocess_result() + infercen(): whole_inference()/slide_inference() + whole_inference()/slide_inference(): encoder_decoder() + encoder_decoder(): extract_feat() -> decode_head.predict() + + 3. The ``_forward`` method is used to output the tensor by running the model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2)Call the decode head forward function to forward decode head model. + + .. code:: text + + _forward(): extract_feat() -> _decode_head.forward() + + Args: + + backbone (ConfigType): The config for the backnone of segmentor. + decode_head (ConfigType): The config for the decode head of segmentor. + neck (OptConfigType): The config for the neck of segmentor. + Defaults to None. + auxiliary_head (OptConfigType): The config for the auxiliary head of + segmentor. Defaults to None. + train_cfg (OptConfigType): The config for training. Defaults to None. + test_cfg (OptConfigType): The config for testing. Defaults to None. + data_preprocessor (dict, optional): The pre-process config of + :class:`BaseDataPreprocessor`. + pretrained (str, optional): The path for pretrained model. + Defaults to None. + init_cfg (dict, optional): The weight initialized config for + :class:`BaseModule`. + """ # noqa: E501 + + def __init__(self, + backbone: ConfigType, + decode_head: ConfigType, + neck: OptConfigType = None, + auxiliary_head: OptConfigType = None, + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + data_preprocessor: OptConfigType = None, + pretrained: Optional[str] = None, + init_cfg: OptMultiConfig = None): + super().__init__( + data_preprocessor=data_preprocessor, init_cfg=init_cfg) + if pretrained is not None: + assert backbone.get('pretrained') is None, \ + 'both backbone and segmentor set pretrained weight' + backbone.pretrained = pretrained + self.backbone = MODELS.build(backbone) + if neck is not None: + self.neck = MODELS.build(neck) + self._init_decode_head(decode_head) + self._init_auxiliary_head(auxiliary_head) + + self.train_cfg = train_cfg + self.test_cfg = test_cfg + + assert self.with_decode_head + + def _init_decode_head(self, decode_head: ConfigType) -> None: + """Initialize ``decode_head``""" + self.decode_head = MODELS.build(decode_head) + self.align_corners = self.decode_head.align_corners + self.num_classes = self.decode_head.num_classes + self.out_channels = self.decode_head.out_channels + + def _init_auxiliary_head(self, auxiliary_head: ConfigType) -> None: + """Initialize ``auxiliary_head``""" + if auxiliary_head is not None: + if isinstance(auxiliary_head, list): + self.auxiliary_head = nn.ModuleList() + for head_cfg in auxiliary_head: + self.auxiliary_head.append(MODELS.build(head_cfg)) + else: + self.auxiliary_head = MODELS.build(auxiliary_head) + + def extract_feat(self, inputs: Tensor) -> List[Tensor]: + """Extract features from images.""" + x = self.backbone(inputs) + if self.with_neck: + x = self.neck(x) + return x + + def encode_decode(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Encode images with backbone and decode into a semantic segmentation + map of the same size as input.""" + x = self.extract_feat(inputs) + seg_logits = self.decode_head.predict(x, batch_img_metas, + self.test_cfg) + + return seg_logits + + def _decode_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for decode head in + training.""" + losses = dict() + loss_decode = self.decode_head.loss(inputs, data_samples, + self.train_cfg) + + losses.update(add_prefix(loss_decode, 'decode')) + return losses + + def _auxiliary_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for auxiliary head in + training.""" + losses = dict() + if isinstance(self.auxiliary_head, nn.ModuleList): + for idx, aux_head in enumerate(self.auxiliary_head): + loss_aux = aux_head.loss(inputs, data_samples, self.train_cfg) + losses.update(add_prefix(loss_aux, f'aux_{idx}')) + else: + loss_aux = self.auxiliary_head.loss(inputs, data_samples, + self.train_cfg) + losses.update(add_prefix(loss_aux, 'aux')) + + return losses + + def loss(self, inputs: Tensor, data_samples: SampleList) -> dict: + """Calculate losses from a batch of inputs and data samples. + + Args: + inputs (Tensor): Input images. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_sem_seg`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + + x = self.extract_feat(inputs) + + losses = dict() + + loss_decode = self._decode_head_forward_train(x, data_samples) + losses.update(loss_decode) + + if self.with_auxiliary_head: + loss_aux = self._auxiliary_head_forward_train(x, data_samples) + losses.update(loss_aux) + + return losses + + def predict(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """Predict results from a batch of inputs and data samples with post- + processing. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`], optional): The seg data + samples. It usually includes information such as `metainfo` + and `gt_sem_seg`. + + Returns: + list[:obj:`SegDataSample`]: Segmentation results of the + input images. Each SegDataSample usually contain: + + - ``pred_sem_seg``(PixelData): Prediction of semantic segmentation. + - ``seg_logits``(PixelData): Predicted logits of semantic + segmentation before normalization. + """ + if data_samples is not None: + batch_img_metas = [ + data_sample.metainfo for data_sample in data_samples + ] + else: + batch_img_metas = [ + dict( + ori_shape=inputs.shape[2:], + img_shape=inputs.shape[2:], + pad_shape=inputs.shape[2:], + padding_size=[0, 0, 0, 0]) + ] * inputs.shape[0] + + seg_logits = self.inference(inputs, batch_img_metas) + + return self.postprocess_result(seg_logits, data_samples) + + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tensor: + """Network forward process. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_sem_seg`. + + Returns: + Tensor: Forward output of model without any post-processes. + """ + x = self.extract_feat(inputs) + return self.decode_head.forward(x) + + def slide_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference by sliding-window with overlap. + + If h_crop > h_img or w_crop > w_img, the small patch will be used to + decode without padding. + + Args: + inputs (tensor): the tensor should have a shape NxCxHxW, + which contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + h_stride, w_stride = self.test_cfg.stride + h_crop, w_crop = self.test_cfg.crop_size + batch_size, _, h_img, w_img = inputs.size() + out_channels = self.out_channels + h_grids = max(h_img - h_crop + h_stride - 1, 0) // h_stride + 1 + w_grids = max(w_img - w_crop + w_stride - 1, 0) // w_stride + 1 + preds = inputs.new_zeros((batch_size, out_channels, h_img, w_img)) + count_mat = inputs.new_zeros((batch_size, 1, h_img, w_img)) + for h_idx in range(h_grids): + for w_idx in range(w_grids): + y1 = h_idx * h_stride + x1 = w_idx * w_stride + y2 = min(y1 + h_crop, h_img) + x2 = min(x1 + w_crop, w_img) + y1 = max(y2 - h_crop, 0) + x1 = max(x2 - w_crop, 0) + crop_img = inputs[:, :, y1:y2, x1:x2] + # change the image shape to patch shape + batch_img_metas[0]['img_shape'] = crop_img.shape[2:] + # the output of encode_decode is seg logits tensor map + # with shape [N, C, H, W] + crop_seg_logit = self.encode_decode(crop_img, batch_img_metas) + preds += F.pad(crop_seg_logit, + (int(x1), int(preds.shape[3] - x2), int(y1), + int(preds.shape[2] - y2))) + + count_mat[:, :, y1:y2, x1:x2] += 1 + assert (count_mat == 0).sum() == 0 + seg_logits = preds / count_mat + + return seg_logits + + def whole_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference with full image. + + Args: + inputs (Tensor): The tensor should have a shape NxCxHxW, which + contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + seg_logits = self.encode_decode(inputs, batch_img_metas) + + return seg_logits + + def inference(self, inputs: Tensor, batch_img_metas: List[dict]) -> Tensor: + """Inference with slide/whole style. + + Args: + inputs (Tensor): The input image of shape (N, 3, H, W). + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', 'pad_shape', and 'padding_size'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + assert self.test_cfg.get('mode', 'whole') in ['slide', 'whole'], \ + f'Only "slide" or "whole" test mode are supported, but got ' \ + f'{self.test_cfg["mode"]}.' + ori_shape = batch_img_metas[0]['ori_shape'] + if not all(_['ori_shape'] == ori_shape for _ in batch_img_metas): + print_log( + 'Image shapes are different in the batch.', + logger='current', + level=logging.WARN) + if self.test_cfg.mode == 'slide': + seg_logit = self.slide_inference(inputs, batch_img_metas) + else: + seg_logit = self.whole_inference(inputs, batch_img_metas) + + return seg_logit + + def aug_test(self, inputs, batch_img_metas, rescale=True): + """Test with augmentations. + + Only rescale=True is supported. + """ + # aug_test rescale all imgs back to ori_shape for now + assert rescale + # to save memory, we get augmented seg logit inplace + seg_logit = self.inference(inputs[0], batch_img_metas[0], rescale) + for i in range(1, len(inputs)): + cur_seg_logit = self.inference(inputs[i], batch_img_metas[i], + rescale) + seg_logit += cur_seg_logit + seg_logit /= len(inputs) + seg_pred = seg_logit.argmax(dim=1) + # unravel batch dim + seg_pred = list(seg_pred) + return seg_pred diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/multimodal_encoder_decoder.py b/reconstruction/modules/InterFormer/mmseg/models/segmentors/multimodal_encoder_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..75aa8b9b17688cb5f54da08f9300af82b3339967 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/segmentors/multimodal_encoder_decoder.py @@ -0,0 +1,350 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional + +import torch.nn.functional as F +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import (ConfigType, OptConfigType, OptMultiConfig, + OptSampleList, SampleList, add_prefix) +from .base import BaseSegmentor + + +@MODELS.register_module() +class MultimodalEncoderDecoder(BaseSegmentor): + """Multimodal Encoder-Decoder segmentors. + + Multimodal segmentation architecture is used for open-vocabulary + semantic segmentation with combining the visual and language + pretrain models. It consists of a image_encoder (backbone) to extract + visual feature, a text encoder to extract text feature, and a decode + head to generate semantic maps. + Note that the deep supervision during training is implemented in decode head. + + 1. The ``loss`` method is used to calculate the loss of model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2) Call the decode head loss function to forward decode head model and + calculate losses. + + .. code:: text + + loss(): extract_feat() -> _decode_head_forward_train() + _decode_head_forward_train(): decode_head.loss() + + 2. The ``predict`` method is used to predict segmentation results, + which includes two steps: (1) Run inference function to obtain the list of + seg_logits (2) Call post-processing function to obtain list of + ``SegDataSampel`` including ``pred_sem_seg`` and ``seg_logits``. + + .. code:: text + + predict(): inference() -> postprocess_result() + inference(): whole_inference()/slide_inference() + whole_inference()/slide_inference(): encoder_decoder() + encoder_decoder(): extract_feat() -> decode_head.predict() + + 3. The ``_forward`` method is used to output the tensor by running the model, + which includes two steps: (1) Extracts features to obtain the feature maps + (2)Call the decode head forward function to forward decode head model. + + .. code:: text + + _forward(): extract_feat() -> _decode_head.forward() + + Args: + + image_encoder (ConfigType): The config for the visual encoder of segmentor. + text_encoder ((ConfigType): The config for the text encoder of segmentor. + decode_head (ConfigType): The config for the decode head of segmentor. + train_cfg (OptConfigType): The config for training. Defaults to None. + test_cfg (OptConfigType): The config for testing. Defaults to None. + data_preprocessor (dict, optional): The pre-process config of + :class:`BaseDataPreprocessor`. + pretrained (str, optional): The path for pretrained model. + Defaults to None. + asymetric_input (bool): whether to use different size of input for image encoder + and decode head. Defaults to False. + encoder_resolution (float): resize scale of input images for image encoder. + Defaults to None. + init_cfg (dict, optional): The weight initialized config for + :class:`BaseModule`. + """ # noqa: E501 + + def __init__(self, + image_encoder: ConfigType, + text_encoder: ConfigType, + decode_head: ConfigType, + train_cfg: OptConfigType = None, + test_cfg: OptConfigType = None, + data_preprocessor: OptConfigType = None, + pretrained: Optional[str] = None, + asymetric_input: bool = True, + encoder_resolution: float = None, + init_cfg: OptMultiConfig = None): + super().__init__( + data_preprocessor=data_preprocessor, init_cfg=init_cfg) + if pretrained is not None: + image_encoder.init_cfg = dict( + type='Pretrained_Part', checkpoint=pretrained) + text_encoder.init_cfg = dict( + type='Pretrained_Part', checkpoint=pretrained) + decode_head.init_cfg = dict( + type='Pretrained_Part', checkpoint=pretrained) + + if asymetric_input: + assert encoder_resolution is not None, \ + 'if asymetric_input set True, ' \ + 'clip_resolution must be a certain value' + self.asymetric_input = asymetric_input + self.encoder_resolution = encoder_resolution + self.image_encoder = MODELS.build(image_encoder) + self.text_encoder = MODELS.build(text_encoder) + self._init_decode_head(decode_head) + + self.train_cfg = train_cfg + self.test_cfg = test_cfg + + assert self.with_decode_head + + def _init_decode_head(self, decode_head: ConfigType) -> None: + """Initialize ``decode_head``""" + self.decode_head = MODELS.build(decode_head) + self.align_corners = self.decode_head.align_corners + self.num_classes = self.decode_head.num_classes + self.out_channels = self.decode_head.out_channels + + def extract_feat(self, inputs: Tensor) -> List[Tensor]: + """Extract visual features from images.""" + x = self.image_encoder(inputs) + return x + + def encode_decode(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Encode the name of classes with text_encoder and encode images with + image_encoder. + + Then decode the class embedding and visual feature into a semantic + segmentation map of the same size as input. + """ + classifier_embeds = self.text_encoder() + clip_inputs = inputs + if self.asymetric_input: + clip_inputs = F.interpolate( + inputs, scale_factor=self.encoder_resolution, mode='bilinear') + x = self.image_encoder(clip_inputs) + seg_logits = self.decode_head.predict([inputs, x, classifier_embeds], + batch_img_metas, self.test_cfg) + + return seg_logits + + def _decode_head_forward_train(self, inputs: List[Tensor], + data_samples: SampleList) -> dict: + """Run forward function and calculate loss for decode head in + training.""" + losses = dict() + loss_decode = self.decode_head.loss(inputs, data_samples, + self.train_cfg) + + losses.update(add_prefix(loss_decode, 'decode')) + return losses + + def loss(self, inputs: Tensor, data_samples: SampleList) -> dict: + """Calculate losses from a batch of inputs and data samples. + + Args: + inputs (Tensor): Input images. + data_samples (list[:obj:`SegDataSample`]): The seg data samples. + It usually includes information such as `metainfo` and + `gt_sem_seg`. + + Returns: + dict[str, Tensor]: a dictionary of loss components + """ + classifier_embeds = self.text_encoder() + clip_inputs = inputs + if self.asymetric_input: + clip_inputs = F.interpolate( + inputs, scale_factor=self.encoder_resolution, mode='bilinear') + x = self.image_encoder(clip_inputs) + + losses = dict() + + loss_decode = self._decode_head_forward_train( + [inputs, x, classifier_embeds], data_samples) + losses.update(loss_decode) + + return losses + + def predict(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> SampleList: + """Predict results from a batch of inputs and data samples with post- + processing. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`], optional): The seg data + samples. It usually includes information such as `metainfo` + and `gt_sem_seg`. + + Returns: + list[:obj:`SegDataSample`]: Segmentation results of the + input images. Each SegDataSample usually contain: + + - ``pred_sem_seg``(PixelData): Prediction of semantic segmentation. + - ``seg_logits``(PixelData): Predicted logits of semantic + segmentation before normalization. + """ + if data_samples is not None: + batch_img_metas = [ + data_sample.metainfo for data_sample in data_samples + ] + else: + batch_img_metas = [ + dict( + ori_shape=inputs.shape[2:], + img_shape=inputs.shape[2:], + pad_shape=inputs.shape[2:], + padding_size=[0, 0, 0, 0]) + ] * inputs.shape[0] + + seg_logits = self.inference(inputs, batch_img_metas) + + return self.postprocess_result(seg_logits, data_samples) + + def _forward(self, + inputs: Tensor, + data_samples: OptSampleList = None) -> Tensor: + """Network forward process. + + Args: + inputs (Tensor): Inputs with shape (N, C, H, W). + data_samples (List[:obj:`SegDataSample`]): The seg + data samples. It usually includes information such + as `metainfo` and `gt_sem_seg`. + + Returns: + Tensor: Forward output of model without any post-processes. + """ + x = self.extract_feat(inputs) + return self.decode_head.forward(x) + + def slide_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference by sliding-window with overlap. + + If h_crop > h_img or w_crop > w_img, the small patch will be used to + decode without padding. + + Args: + inputs (tensor): the tensor should have a shape NxCxHxW, + which contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + h_stride, w_stride = self.test_cfg.stride + h_crop, w_crop = self.test_cfg.crop_size + batch_size, _, h_img, w_img = inputs.size() + out_channels = self.out_channels + h_grids = max(h_img - h_crop + h_stride - 1, 0) // h_stride + 1 + w_grids = max(w_img - w_crop + w_stride - 1, 0) // w_stride + 1 + preds = inputs.new_zeros((batch_size, out_channels, h_img, w_img)) + count_mat = inputs.new_zeros((batch_size, 1, h_img, w_img)) + for h_idx in range(h_grids): + for w_idx in range(w_grids): + y1 = h_idx * h_stride + x1 = w_idx * w_stride + y2 = min(y1 + h_crop, h_img) + x2 = min(x1 + w_crop, w_img) + y1 = max(y2 - h_crop, 0) + x1 = max(x2 - w_crop, 0) + crop_img = inputs[:, :, y1:y2, x1:x2] + # change the image shape to patch shape + batch_img_metas[0]['img_shape'] = crop_img.shape[2:] + # the output of encode_decode is seg logits tensor map + # with shape [N, C, H, W] + crop_seg_logit = self.encode_decode(crop_img, batch_img_metas) + preds += F.pad(crop_seg_logit, + (int(x1), int(preds.shape[3] - x2), int(y1), + int(preds.shape[2] - y2))) + + count_mat[:, :, y1:y2, x1:x2] += 1 + assert (count_mat == 0).sum() == 0 + seg_logits = preds / count_mat + + return seg_logits + + def whole_inference(self, inputs: Tensor, + batch_img_metas: List[dict]) -> Tensor: + """Inference with full image. + + Args: + inputs (Tensor): The tensor should have a shape NxCxHxW, which + contains all images in the batch. + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', and 'pad_shape'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + seg_logits = self.encode_decode(inputs, batch_img_metas) + + return seg_logits + + def inference(self, inputs: Tensor, batch_img_metas: List[dict]) -> Tensor: + """Inference with slide/whole style. + + Args: + inputs (Tensor): The input image of shape (N, 3, H, W). + batch_img_metas (List[dict]): List of image metainfo where each may + also contain: 'img_shape', 'scale_factor', 'flip', 'img_path', + 'ori_shape', 'pad_shape', and 'padding_size'. + For details on the values of these keys see + `mmseg/datasets/pipelines/formatting.py:PackSegInputs`. + + Returns: + Tensor: The segmentation results, seg_logits from model of each + input image. + """ + + assert self.test_cfg.mode in ['slide', 'whole'] + ori_shape = batch_img_metas[0]['ori_shape'] + assert all(_['ori_shape'] == ori_shape for _ in batch_img_metas) + if self.test_cfg.mode == 'slide': + seg_logit = self.slide_inference(inputs, batch_img_metas) + else: + seg_logit = self.whole_inference(inputs, batch_img_metas) + + return seg_logit + + def aug_test(self, inputs, batch_img_metas, rescale=True): + """Test with augmentations. + + Only rescale=True is supported. + """ + # aug_test rescale all imgs back to ori_shape for now + assert rescale + # to save memory, we get augmented seg logit inplace + seg_logit = self.inference(inputs[0], batch_img_metas[0], rescale) + for i in range(1, len(inputs)): + cur_seg_logit = self.inference(inputs[i], batch_img_metas[i], + rescale) + seg_logit += cur_seg_logit + seg_logit /= len(inputs) + seg_pred = seg_logit.argmax(dim=1) + # unravel batch dim + seg_pred = list(seg_pred) + return seg_pred diff --git a/reconstruction/modules/InterFormer/mmseg/models/segmentors/seg_tta.py b/reconstruction/modules/InterFormer/mmseg/models/segmentors/seg_tta.py new file mode 100644 index 0000000000000000000000000000000000000000..63ef61d223a572dec4fc3e43e1550b98cd2e7302 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/segmentors/seg_tta.py @@ -0,0 +1,47 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List + +import torch +from mmengine.model import BaseTTAModel +from mmengine.structures import PixelData + +from mmseg.registry import MODELS +from mmseg.utils import SampleList + + +@MODELS.register_module() +class SegTTAModel(BaseTTAModel): + + def merge_preds(self, data_samples_list: List[SampleList]) -> SampleList: + """Merge predictions of enhanced data to one prediction. + + Args: + data_samples_list (List[SampleList]): List of predictions + of all enhanced data. + + Returns: + SampleList: Merged prediction. + """ + predictions = [] + for data_samples in data_samples_list: + seg_logits = data_samples[0].seg_logits.data + logits = torch.zeros(seg_logits.shape).to(seg_logits) + for data_sample in data_samples: + seg_logit = data_sample.seg_logits.data + if self.module.out_channels > 1: + logits += seg_logit.softmax(dim=0) + else: + logits += seg_logit.sigmoid() + logits /= len(data_samples) + if self.module.out_channels == 1: + seg_pred = (logits > self.module.decode_head.threshold + ).to(logits).squeeze(1) + else: + seg_pred = logits.argmax(dim=0) + data_sample.set_data({'pred_sem_seg': PixelData(data=seg_pred)}) + if hasattr(data_samples[0], 'gt_sem_seg'): + data_sample.set_data( + {'gt_sem_seg': data_samples[0].gt_sem_seg}) + data_sample.set_metainfo({'img_path': data_samples[0].img_path}) + predictions.append(data_sample) + return predictions diff --git a/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__init__.py b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..199856d9d79800cbcd9aa7b77223a6528c6b7e0a --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .clip_text_encoder import CLIPTextEncoder + +__all__ = ['CLIPTextEncoder'] diff --git a/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6aa548136baeb862c6ebb1020e3f8d347979f67 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d45675ab07ea223d98813767e15d7f69148c3c9a Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/clip_text_encoder.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/clip_text_encoder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..526511bbaf676f49aa03935c65eadd92fd5d9a81 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/clip_text_encoder.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/clip_text_encoder.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/clip_text_encoder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20c61a4eb99ed5dab10a4534a1c5fdeaf40b1953 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/__pycache__/clip_text_encoder.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/text_encoder/clip_text_encoder.py b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/clip_text_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..1a18b86395ebcf0443e9aab05f4454acada98990 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/text_encoder/clip_text_encoder.py @@ -0,0 +1,229 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List + +import numpy as np +import torch +import torch.nn as nn +from mmcv.cnn import build_norm_layer +from mmcv.cnn.bricks.transformer import BaseTransformerLayer +from mmengine.model import BaseModule, ModuleList +from mmengine.runner.checkpoint import CheckpointLoader, load_state_dict +from torch.nn import functional as F + +from mmseg.registry import MODELS +from mmseg.utils import get_classes, get_predefined_templates, tokenizer + + +@MODELS.register_module() +class CLIPTextEncoder(BaseModule): + """A text encoder with transformer architecture to encode the label text. + + Modified from https://github.com/MendelXu/SAN/blob/main/san/model/clip_utils/classifier.py # noqa:E501 + Copyright (c) 2023 MendelXu. + Licensed under the MIT License + + Args: + dataset_name: (str|None): The name of the dataset to which + the data belongs. + vocabulary: (List[str]|None): The list of class names. Default: None. + templates: (List[str]|None): The prompt template used for labels. + Default: None. + total_vocab_size: (int): Number of all words used by the pre-trained + model. Default: 49408 (CLIP). + context_length: (int): The max length of prompt text. + Default: 77 (CLIP). + embed_dims: (int): Width of transformer model. Default: 512. + num_layers: (int): Depth of transformer. Default: 12, + num_heads: (int): Number of attention heads in transformer. + Default: 8, + mlp_ratio: (int) Ratio of mlp hidden dim to embedding dim in + transformer. Default: 4, + output_dims: (int) Dim of output text embeddings. Default: 512, + cache_feature: (bool) Whether to save class embeddings in cache. + Default: True, + cat_bg: (bool) Whether to add background embedding. Default: True. + norm_cfg (dict|None): Config for norm layer. Default: dict(type='LN') + init_cfg (dict or list[dict], optional): Initialization config dict. + Default: None. + """ + + def __init__(self, + dataset_name: str = None, + vocabulary: List[str] = None, + templates: str = 'vild', + total_vocab_size: int = 49408, + context_length: int = 77, + embed_dims: int = 512, + num_layers: int = 12, + num_heads: int = 8, + mlp_ratio: int = 4, + output_dims: int = 512, + cache_feature: bool = True, + cat_bg: bool = True, + norm_cfg: dict = dict(type='LN'), + init_cfg: dict = None): + super().__init__(init_cfg) + if isinstance(templates, List): + self.templates = templates + else: + self.templates = get_predefined_templates(templates) + + assert dataset_name is not None or vocabulary is not None, \ + "text_encoder required either 'dataset_name' or 'vocabulary'" + assert dataset_name is None or vocabulary is None, \ + "there is conflict between 'dataset_name' and 'vocabulary'" + self.dataset_name = dataset_name + self.vocabulary = vocabulary + self.num_pos = context_length + self.token_embedding = nn.Embedding(total_vocab_size, embed_dims) + self.positional_embedding = nn.Parameter( + torch.empty(context_length, embed_dims)) + self.text_projection = nn.Parameter( + torch.empty(embed_dims, output_dims)) + self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) + self.transformer = ModuleList() + self.register_buffer( + 'attn_mask', self.build_attention_mask(), persistent=False) + for i in range(num_layers): + self.transformer.append( + BaseTransformerLayer( + attn_cfgs=dict( + type='MultiheadAttention', + embed_dims=embed_dims, + num_heads=num_heads, + batch_first=False, + bias=True), + ffn_cfgs=dict( + type='FFN', + embed_dims=embed_dims, + feedforward_channels=mlp_ratio * embed_dims, + act_cfg=dict(type='QuickGELU')), + operation_order=('norm', 'self_attn', 'norm', 'ffn'))) + self.ln_final = build_norm_layer( + norm_cfg, embed_dims, postfix='_final')[1] + + self.cache_feature = cache_feature + if self.cache_feature: + self.cache = {} + + self._freeze() + + self.cat_bg = cat_bg + if self.cat_bg: + self.bg_embed = nn.Parameter( + torch.randn(1, self.text_projection.shape[1])) + + @property + def ln_final(self): + return getattr(self, self.final_name) + + def build_attention_mask(self): + """lazily create causal attention mask, with full attention between the + tokens. + + pytorch uses additive attention mask; fill with -inf + """ + mask = torch.empty(self.num_pos, self.num_pos) + mask.fill_(float('-inf')) + mask.triu_(1) # zero out the lower diagonal + return mask + + def _freeze(self): + for param in self.parameters(): + param.requires_grad = False + + def init_weights(self): + if self.cat_bg: + nn.init.normal_( + self.bg_embed, + std=self.bg_embed.shape[1]**-0.5, + ) + if isinstance(self.init_cfg, dict) and \ + self.init_cfg.get('type') == 'Pretrained_Part': + checkpoint = CheckpointLoader.load_checkpoint( + self.init_cfg['checkpoint'], logger=None, map_location='cpu') + + state_dict = checkpoint.copy() + para_prefix = 'text_encoder' + prefix_len = len(para_prefix) + 1 + for k, v in checkpoint.items(): + state_dict.pop(k) + if para_prefix in k: + state_dict[k[prefix_len:]] = v + + load_state_dict(self, state_dict, strict=False, logger=None) + + else: + super().init_weights() + + @torch.no_grad() + def encode_text(self, text, normalize=False): + """encode class token.""" + + embed_device = self.token_embedding.weight.device + x = self.token_embedding( + text.to(embed_device)) # [batch_size, n_ctx, d_model] + x = x + self.positional_embedding + x = x.permute(1, 0, 2) # NLD -> LND + for block in self.transformer: + x = block(query=x, attn_masks=self.attn_mask) + x = x.permute(1, 0, 2) # LND -> NLD + x = self.ln_final(x) # [batch_size, n_ctx, transformer.width] + # take features from the eot embedding + # (eot_token is the highest number in each sequence) + x = x[torch.arange(x.shape[0]), + text.argmax(dim=-1)] @ self.text_projection + return F.normalize(x, dim=-1) if normalize else x + + def template_encode(self, vocabulary): + """Prompt engineering.""" + text_embed_bucket = [] + for template in self.templates: + text_inputs = tokenizer.tokenize( + [template.format(noun) for noun in vocabulary]) + text_embed = self.encode_text(text_inputs, normalize=True) + text_embed_bucket.append(text_embed) + text_embed = torch.stack(text_embed_bucket).mean(dim=0) + text_embed = text_embed / text_embed.norm(dim=-1, keepdim=True) + return text_embed + + def forward(self): + """Forward function.""" + if self.dataset_name is None: # encoding vocabulary directly + class_names = self.vocabulary + if self.cache_feature: + new_classes = [ + word for word in class_names if word not in self.cache + ] + if len(new_classes) > 0: + class_embeds = self.template_encode(new_classes) + self.cache.update(dict(zip(new_classes, class_embeds))) + class_embeds = torch.stack( + [self.cache[word] for word in class_names]) + else: + class_embeds = self.template_encode(class_names) + + else: # encoding the classes of the dataset + class_names = get_classes(self.dataset_name) + if class_names[0] == 'background': + class_names = class_names[1:] + if self.cache_feature: + if self.dataset_name not in self.cache: + class_embeds = self.template_encode(class_names) + self.cache[self.dataset_name] = class_embeds + else: + class_embeds = self.cache[self.dataset_name] + else: + class_embeds = self.template_encode(class_names) + + if self.cat_bg: + class_embeds = torch.cat([class_embeds, self.bg_embed]) + class_embeds = F.normalize(class_embeds, p=2, dim=-1) + return self.logit_scale.exp() * class_embeds + + +@MODELS.register_module() +class QuickGELU(nn.Module): + # From https://github.com/openai/CLIP/blob/main/clip/model.py + def forward(self, x: torch.Tensor): + return x * torch.sigmoid(1.702 * x) diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__init__.py b/reconstruction/modules/InterFormer/mmseg/models/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c0751b17c02de14e9bf1bfc02230d507a143e9c0 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/__init__.py @@ -0,0 +1,27 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .basic_block import BasicBlock, Bottleneck +from .embed import PatchEmbed +from .encoding import Encoding +from .inverted_residual import InvertedResidual, InvertedResidualV3 +from .make_divisible import make_divisible +from .point_sample import get_uncertain_point_coords_with_randomness +from .ppm import DAPPM, PAPPM +from .res_layer import ResLayer +from .se_layer import SELayer +from .self_attention_block import SelfAttentionBlock +from .shape_convert import (nchw2nlc2nchw, nchw_to_nlc, nlc2nchw2nlc, + nlc_to_nchw) +from .up_conv_block import UpConvBlock + +# isort: off +from .wrappers import Upsample, resize +from .san_layers import MLP, LayerNorm2d, cross_attn_layer + +__all__ = [ + 'ResLayer', 'SelfAttentionBlock', 'make_divisible', 'InvertedResidual', + 'UpConvBlock', 'InvertedResidualV3', 'SELayer', 'PatchEmbed', + 'nchw_to_nlc', 'nlc_to_nchw', 'nchw2nlc2nchw', 'nlc2nchw2nlc', 'Encoding', + 'Upsample', 'resize', 'DAPPM', 'PAPPM', 'BasicBlock', 'Bottleneck', + 'cross_attn_layer', 'LayerNorm2d', 'MLP', + 'get_uncertain_point_coords_with_randomness' +] diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d0f07b2fa48c665be52fd8f075b4d2c014ae8fe Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f127211d782727026bdd292869f47fe4a555afc1 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/basic_block.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/basic_block.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..427902511679a9f05e5517683bef25da4eec3fe5 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/basic_block.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/basic_block.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/basic_block.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e7d9c35cac58976f8d5de1b2d3ad423cffd4c2c Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/basic_block.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/embed.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/embed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b67419a5e6811727376765a6dc216c3c97059dc Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/embed.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/embed.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/embed.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68f1b5e266c93036b1ca322826248024f0f24fe7 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/embed.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/encoding.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/encoding.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd441c9aea16668954159c7bc68d4c900fc74be7 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/encoding.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/encoding.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/encoding.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cd1b8d0079942ac8cfd0eac815ec013296d6da6 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/encoding.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/inverted_residual.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/inverted_residual.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83518c6da0fdeea240b4f2d826d6669e17b83e79 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/inverted_residual.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/inverted_residual.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/inverted_residual.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..048b27a4679f70790d19dcff7de2ea2534c0d0d2 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/inverted_residual.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/make_divisible.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/make_divisible.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a3151d28259cf79f93284b8619272ccea18dd686 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/make_divisible.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/make_divisible.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/make_divisible.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97239b8f895a3fe460bef08258e1009f187d98f4 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/make_divisible.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/point_sample.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/point_sample.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b10d736123897ad538e590e7b52aa6077cc084f3 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/point_sample.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/point_sample.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/point_sample.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1036cbfd38a82e3a128a990ead6d29ea285dd689 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/point_sample.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/ppm.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/ppm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4da01fb9782d48d86de49f1baa4275b30a8131d2 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/ppm.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/ppm.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/ppm.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9febdd2c7de1a188acf4353efbca6ca25023cca2 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/ppm.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/res_layer.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/res_layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..711100596b37481421914eba83e37000e3230a34 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/res_layer.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/res_layer.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/res_layer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60c5591569c849de73bf63ed0b91a2a2d4a5737f Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/res_layer.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/san_layers.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/san_layers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b75f7a1c8c5379c64ceee9567be82d48562ae2eb Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/san_layers.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/san_layers.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/san_layers.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d47f77bfe3cd902af6223db682ee9c225d199b76 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/san_layers.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/se_layer.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/se_layer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a1729e2b52bddee83219188e20c722ab2c152af Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/se_layer.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/se_layer.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/se_layer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe59de13b5ad7adb7dcd6faade1fd614b7d578cd Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/se_layer.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/self_attention_block.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/self_attention_block.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e82baf0a7b95994b1407b49f145da103f8670f63 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/self_attention_block.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/self_attention_block.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/self_attention_block.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd8d7808911b26771d2612551f11d4bee2b07b81 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/self_attention_block.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/shape_convert.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/shape_convert.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ab9fedc55d97a111bc6235111045f4007a238c0 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/shape_convert.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/shape_convert.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/shape_convert.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..770835513d3eaaa51b67c32b852873cd6188e93f Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/shape_convert.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/up_conv_block.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/up_conv_block.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b487c6e86e65c26af08b40c0d4c2a45aae1b3f2 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/up_conv_block.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/up_conv_block.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/up_conv_block.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..510fe17e48b0c130e52368b010bb373fbf44757e Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/up_conv_block.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/wrappers.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/wrappers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac57b5d15f60c2e13ab0fbf085fb94486716626a Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/wrappers.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/wrappers.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/wrappers.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6113f3fbdb3e38912999583d1b91e8c606ca954e Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/models/utils/__pycache__/wrappers.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/basic_block.py b/reconstruction/modules/InterFormer/mmseg/models/utils/basic_block.py new file mode 100644 index 0000000000000000000000000000000000000000..4e1ad8146dd200c5f1e543adf22ada654ee196a4 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/basic_block.py @@ -0,0 +1,143 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Optional + +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule +from torch import Tensor + +from mmseg.registry import MODELS +from mmseg.utils import OptConfigType + + +class BasicBlock(BaseModule): + """Basic block from `ResNet `_. + + Args: + in_channels (int): Input channels. + channels (int): Output channels. + stride (int): Stride of the first block. Default: 1. + downsample (nn.Module, optional): Downsample operation on identity. + Default: None. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict, optional): Config dict for activation layer in + ConvModule. Default: dict(type='ReLU', inplace=True). + act_cfg_out (dict, optional): Config dict for activation layer at the + last of the block. Default: None. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + expansion = 1 + + def __init__(self, + in_channels: int, + channels: int, + stride: int = 1, + downsample: nn.Module = None, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + act_cfg_out: OptConfigType = dict(type='ReLU', inplace=True), + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + self.conv1 = ConvModule( + in_channels, + channels, + kernel_size=3, + stride=stride, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.conv2 = ConvModule( + channels, + channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=None) + self.downsample = downsample + if act_cfg_out: + self.act = MODELS.build(act_cfg_out) + + def forward(self, x: Tensor) -> Tensor: + residual = x + out = self.conv1(x) + out = self.conv2(out) + + if self.downsample: + residual = self.downsample(x) + + out += residual + + if hasattr(self, 'act'): + out = self.act(out) + + return out + + +class Bottleneck(BaseModule): + """Bottleneck block from `ResNet `_. + + Args: + in_channels (int): Input channels. + channels (int): Output channels. + stride (int): Stride of the first block. Default: 1. + downsample (nn.Module, optional): Downsample operation on identity. + Default: None. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict, optional): Config dict for activation layer in + ConvModule. Default: dict(type='ReLU', inplace=True). + act_cfg_out (dict, optional): Config dict for activation layer at + the last of the block. Default: None. + init_cfg (dict, optional): Initialization config dict. Default: None. + """ + + expansion = 2 + + def __init__(self, + in_channels: int, + channels: int, + stride: int = 1, + downsample: Optional[nn.Module] = None, + norm_cfg: OptConfigType = dict(type='BN'), + act_cfg: OptConfigType = dict(type='ReLU', inplace=True), + act_cfg_out: OptConfigType = None, + init_cfg: OptConfigType = None): + super().__init__(init_cfg) + self.conv1 = ConvModule( + in_channels, channels, 1, norm_cfg=norm_cfg, act_cfg=act_cfg) + self.conv2 = ConvModule( + channels, + channels, + 3, + stride, + 1, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.conv3 = ConvModule( + channels, + channels * self.expansion, + 1, + norm_cfg=norm_cfg, + act_cfg=None) + if act_cfg_out: + self.act = MODELS.build(act_cfg_out) + self.downsample = downsample + + def forward(self, x: Tensor) -> Tensor: + residual = x + + out = self.conv1(x) + out = self.conv2(out) + out = self.conv3(out) + + if self.downsample: + residual = self.downsample(x) + + out += residual + + if hasattr(self, 'act'): + out = self.act(out) + + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/embed.py b/reconstruction/modules/InterFormer/mmseg/models/utils/embed.py new file mode 100644 index 0000000000000000000000000000000000000000..aef0a40b0a87bb6616db96fe2c72c19cc6f5b366 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/embed.py @@ -0,0 +1,330 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import math +from typing import Sequence + +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import build_conv_layer, build_norm_layer +from mmengine.model import BaseModule +from mmengine.utils import to_2tuple + + +class AdaptivePadding(nn.Module): + """Applies padding to input (if needed) so that input can get fully covered + by filter you specified. It support two modes "same" and "corner". The + "same" mode is same with "SAME" padding mode in TensorFlow, pad zero around + input. The "corner" mode would pad zero to bottom right. + + Args: + kernel_size (int | tuple): Size of the kernel: + stride (int | tuple): Stride of the filter. Default: 1: + dilation (int | tuple): Spacing between kernel elements. + Default: 1. + padding (str): Support "same" and "corner", "corner" mode + would pad zero to bottom right, and "same" mode would + pad zero around input. Default: "corner". + Example: + >>> kernel_size = 16 + >>> stride = 16 + >>> dilation = 1 + >>> input = torch.rand(1, 1, 15, 17) + >>> adap_pad = AdaptivePadding( + >>> kernel_size=kernel_size, + >>> stride=stride, + >>> dilation=dilation, + >>> padding="corner") + >>> out = adap_pad(input) + >>> assert (out.shape[2], out.shape[3]) == (16, 32) + >>> input = torch.rand(1, 1, 16, 17) + >>> out = adap_pad(input) + >>> assert (out.shape[2], out.shape[3]) == (16, 32) + """ + + def __init__(self, kernel_size=1, stride=1, dilation=1, padding='corner'): + + super().__init__() + + assert padding in ('same', 'corner') + + kernel_size = to_2tuple(kernel_size) + stride = to_2tuple(stride) + dilation = to_2tuple(dilation) + + self.padding = padding + self.kernel_size = kernel_size + self.stride = stride + self.dilation = dilation + + def get_pad_shape(self, input_shape): + input_h, input_w = input_shape + kernel_h, kernel_w = self.kernel_size + stride_h, stride_w = self.stride + output_h = math.ceil(input_h / stride_h) + output_w = math.ceil(input_w / stride_w) + pad_h = max((output_h - 1) * stride_h + + (kernel_h - 1) * self.dilation[0] + 1 - input_h, 0) + pad_w = max((output_w - 1) * stride_w + + (kernel_w - 1) * self.dilation[1] + 1 - input_w, 0) + return pad_h, pad_w + + def forward(self, x): + pad_h, pad_w = self.get_pad_shape(x.size()[-2:]) + if pad_h > 0 or pad_w > 0: + if self.padding == 'corner': + x = F.pad(x, [0, pad_w, 0, pad_h]) + elif self.padding == 'same': + x = F.pad(x, [ + pad_w // 2, pad_w - pad_w // 2, pad_h // 2, + pad_h - pad_h // 2 + ]) + return x + + +class PatchEmbed(BaseModule): + """Image to Patch Embedding. + + We use a conv layer to implement PatchEmbed. + + Args: + in_channels (int): The num of input channels. Default: 3 + embed_dims (int): The dimensions of embedding. Default: 768 + conv_type (str): The config dict for embedding + conv layer type selection. Default: "Conv2d". + kernel_size (int): The kernel_size of embedding conv. Default: 16. + stride (int, optional): The slide stride of embedding conv. + Default: None (Would be set as `kernel_size`). + padding (int | tuple | string ): The padding length of + embedding conv. When it is a string, it means the mode + of adaptive padding, support "same" and "corner" now. + Default: "corner". + dilation (int): The dilation rate of embedding conv. Default: 1. + bias (bool): Bias of embed conv. Default: True. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: None. + input_size (int | tuple | None): The size of input, which will be + used to calculate the out size. Only work when `dynamic_size` + is False. Default: None. + init_cfg (`mmengine.ConfigDict`, optional): The Config for + initialization. Default: None. + """ + + def __init__(self, + in_channels=3, + embed_dims=768, + conv_type='Conv2d', + kernel_size=16, + stride=None, + padding='corner', + dilation=1, + bias=True, + norm_cfg=None, + input_size=None, + init_cfg=None): + super().__init__(init_cfg=init_cfg) + + self.embed_dims = embed_dims + if stride is None: + stride = kernel_size + + kernel_size = to_2tuple(kernel_size) + stride = to_2tuple(stride) + dilation = to_2tuple(dilation) + + if isinstance(padding, str): + self.adap_padding = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + # disable the padding of conv + padding = 0 + else: + self.adap_padding = None + padding = to_2tuple(padding) + + self.projection = build_conv_layer( + dict(type=conv_type), + in_channels=in_channels, + out_channels=embed_dims, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + bias=bias) + + if norm_cfg is not None: + self.norm = build_norm_layer(norm_cfg, embed_dims)[1] + else: + self.norm = None + + if input_size: + input_size = to_2tuple(input_size) + # `init_out_size` would be used outside to + # calculate the num_patches + # when `use_abs_pos_embed` outside + self.init_input_size = input_size + if self.adap_padding: + pad_h, pad_w = self.adap_padding.get_pad_shape(input_size) + input_h, input_w = input_size + input_h = input_h + pad_h + input_w = input_w + pad_w + input_size = (input_h, input_w) + + # https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html + h_out = (input_size[0] + 2 * padding[0] - dilation[0] * + (kernel_size[0] - 1) - 1) // stride[0] + 1 + w_out = (input_size[1] + 2 * padding[1] - dilation[1] * + (kernel_size[1] - 1) - 1) // stride[1] + 1 + self.init_out_size = (h_out, w_out) + else: + self.init_input_size = None + self.init_out_size = None + + def forward(self, x): + """ + Args: + x (Tensor): Has shape (B, C, H, W). In most case, C is 3. + + Returns: + tuple: Contains merged results and its spatial shape. + + - x (Tensor): Has shape (B, out_h * out_w, embed_dims) + - out_size (tuple[int]): Spatial shape of x, arrange as + (out_h, out_w). + """ + + if self.adap_padding: + x = self.adap_padding(x) + + x = self.projection(x) + out_size = (x.shape[2], x.shape[3]) + x = x.flatten(2).transpose(1, 2) + if self.norm is not None: + x = self.norm(x) + return x, out_size + + +class PatchMerging(BaseModule): + """Merge patch feature map. + + This layer groups feature map by kernel_size, and applies norm and linear + layers to the grouped feature map. Our implementation uses `nn.Unfold` to + merge patch, which is about 25% faster than original implementation. + Instead, we need to modify pretrained models for compatibility. + + Args: + in_channels (int): The num of input channels. + out_channels (int): The num of output channels. + kernel_size (int | tuple, optional): the kernel size in the unfold + layer. Defaults to 2. + stride (int | tuple, optional): the stride of the sliding blocks in the + unfold layer. Default: None. (Would be set as `kernel_size`) + padding (int | tuple | string ): The padding length of + embedding conv. When it is a string, it means the mode + of adaptive padding, support "same" and "corner" now. + Default: "corner". + dilation (int | tuple, optional): dilation parameter in the unfold + layer. Default: 1. + bias (bool, optional): Whether to add bias in linear layer or not. + Defaults: False. + norm_cfg (dict, optional): Config dict for normalization layer. + Default: dict(type='LN'). + init_cfg (dict, optional): The extra config for initialization. + Default: None. + """ + + def __init__(self, + in_channels, + out_channels, + kernel_size=2, + stride=None, + padding='corner', + dilation=1, + bias=False, + norm_cfg=dict(type='LN'), + init_cfg=None): + super().__init__(init_cfg=init_cfg) + self.in_channels = in_channels + self.out_channels = out_channels + if stride: + stride = stride + else: + stride = kernel_size + + kernel_size = to_2tuple(kernel_size) + stride = to_2tuple(stride) + dilation = to_2tuple(dilation) + + if isinstance(padding, str): + self.adap_padding = AdaptivePadding( + kernel_size=kernel_size, + stride=stride, + dilation=dilation, + padding=padding) + # disable the padding of unfold + padding = 0 + else: + self.adap_padding = None + + padding = to_2tuple(padding) + self.sampler = nn.Unfold( + kernel_size=kernel_size, + dilation=dilation, + padding=padding, + stride=stride) + + sample_dim = kernel_size[0] * kernel_size[1] * in_channels + + if norm_cfg is not None: + self.norm = build_norm_layer(norm_cfg, sample_dim)[1] + else: + self.norm = None + + self.reduction = nn.Linear(sample_dim, out_channels, bias=bias) + + def forward(self, x, input_size): + """ + Args: + x (Tensor): Has shape (B, H*W, C_in). + input_size (tuple[int]): The spatial shape of x, arrange as (H, W). + Default: None. + + Returns: + tuple: Contains merged results and its spatial shape. + + - x (Tensor): Has shape (B, Merged_H * Merged_W, C_out) + - out_size (tuple[int]): Spatial shape of x, arrange as + (Merged_H, Merged_W). + """ + B, L, C = x.shape + assert isinstance(input_size, Sequence), f'Expect ' \ + f'input_size is ' \ + f'`Sequence` ' \ + f'but get {input_size}' + + H, W = input_size + assert L == H * W, 'input feature has wrong size' + + x = x.view(B, H, W, C).permute([0, 3, 1, 2]) # B, C, H, W + # Use nn.Unfold to merge patch. About 25% faster than original method, + # but need to modify pretrained model for compatibility + + if self.adap_padding: + x = self.adap_padding(x) + H, W = x.shape[-2:] + + x = self.sampler(x) + # if kernel_size=2 and stride=2, x should has shape (B, 4*C, H/2*W/2) + + out_h = (H + 2 * self.sampler.padding[0] - self.sampler.dilation[0] * + (self.sampler.kernel_size[0] - 1) - + 1) // self.sampler.stride[0] + 1 + out_w = (W + 2 * self.sampler.padding[1] - self.sampler.dilation[1] * + (self.sampler.kernel_size[1] - 1) - + 1) // self.sampler.stride[1] + 1 + + output_size = (out_h, out_w) + x = x.transpose(1, 2) # B, H/2*W/2, 4*C + x = self.norm(x) if self.norm else x + x = self.reduction(x) + return x, output_size diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/encoding.py b/reconstruction/modules/InterFormer/mmseg/models/utils/encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..ee4f0574fbc1957cf8da591a0e4befd6d8a125d3 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/encoding.py @@ -0,0 +1,75 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from torch import nn +from torch.nn import functional as F + + +class Encoding(nn.Module): + """Encoding Layer: a learnable residual encoder. + + Input is of shape (batch_size, channels, height, width). + Output is of shape (batch_size, num_codes, channels). + + Args: + channels: dimension of the features or feature channels + num_codes: number of code words + """ + + def __init__(self, channels, num_codes): + super().__init__() + # init codewords and smoothing factor + self.channels, self.num_codes = channels, num_codes + std = 1. / ((num_codes * channels)**0.5) + # [num_codes, channels] + self.codewords = nn.Parameter( + torch.empty(num_codes, channels, + dtype=torch.float).uniform_(-std, std), + requires_grad=True) + # [num_codes] + self.scale = nn.Parameter( + torch.empty(num_codes, dtype=torch.float).uniform_(-1, 0), + requires_grad=True) + + @staticmethod + def scaled_l2(x, codewords, scale): + num_codes, channels = codewords.size() + batch_size = x.size(0) + reshaped_scale = scale.view((1, 1, num_codes)) + expanded_x = x.unsqueeze(2).expand( + (batch_size, x.size(1), num_codes, channels)) + reshaped_codewords = codewords.view((1, 1, num_codes, channels)) + + scaled_l2_norm = reshaped_scale * ( + expanded_x - reshaped_codewords).pow(2).sum(dim=3) + return scaled_l2_norm + + @staticmethod + def aggregate(assignment_weights, x, codewords): + num_codes, channels = codewords.size() + reshaped_codewords = codewords.view((1, 1, num_codes, channels)) + batch_size = x.size(0) + + expanded_x = x.unsqueeze(2).expand( + (batch_size, x.size(1), num_codes, channels)) + encoded_feat = (assignment_weights.unsqueeze(3) * + (expanded_x - reshaped_codewords)).sum(dim=1) + return encoded_feat + + def forward(self, x): + assert x.dim() == 4 and x.size(1) == self.channels + # [batch_size, channels, height, width] + batch_size = x.size(0) + # [batch_size, height x width, channels] + x = x.view(batch_size, self.channels, -1).transpose(1, 2).contiguous() + # assignment_weights: [batch_size, channels, num_codes] + assignment_weights = F.softmax( + self.scaled_l2(x, self.codewords, self.scale), dim=2) + # aggregate + encoded_feat = self.aggregate(assignment_weights, x, self.codewords) + return encoded_feat + + def __repr__(self): + repr_str = self.__class__.__name__ + repr_str += f'(Nx{self.channels}xHxW =>Nx{self.num_codes}' \ + f'x{self.channels})' + return repr_str diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/inverted_residual.py b/reconstruction/modules/InterFormer/mmseg/models/utils/inverted_residual.py new file mode 100644 index 0000000000000000000000000000000000000000..56190b3bfe7cc8fe98bf34c3812db18dd34a8f02 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/inverted_residual.py @@ -0,0 +1,213 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.cnn import ConvModule +from torch import nn +from torch.utils import checkpoint as cp + +from .se_layer import SELayer + + +class InvertedResidual(nn.Module): + """InvertedResidual block for MobileNetV2. + + Args: + in_channels (int): The input channels of the InvertedResidual block. + out_channels (int): The output channels of the InvertedResidual block. + stride (int): Stride of the middle (first) 3x3 convolution. + expand_ratio (int): Adjusts number of channels of the hidden layer + in InvertedResidual by this amount. + dilation (int): Dilation rate of depthwise conv. Default: 1 + conv_cfg (dict): Config dict for convolution layer. + Default: None, which means using conv2d. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU6'). + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + + Returns: + Tensor: The output tensor. + """ + + def __init__(self, + in_channels, + out_channels, + stride, + expand_ratio, + dilation=1, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU6'), + with_cp=False, + **kwargs): + super().__init__() + self.stride = stride + assert stride in [1, 2], f'stride must in [1, 2]. ' \ + f'But received {stride}.' + self.with_cp = with_cp + self.use_res_connect = self.stride == 1 and in_channels == out_channels + hidden_dim = int(round(in_channels * expand_ratio)) + + layers = [] + if expand_ratio != 1: + layers.append( + ConvModule( + in_channels=in_channels, + out_channels=hidden_dim, + kernel_size=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **kwargs)) + layers.extend([ + ConvModule( + in_channels=hidden_dim, + out_channels=hidden_dim, + kernel_size=3, + stride=stride, + padding=dilation, + dilation=dilation, + groups=hidden_dim, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **kwargs), + ConvModule( + in_channels=hidden_dim, + out_channels=out_channels, + kernel_size=1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None, + **kwargs) + ]) + self.conv = nn.Sequential(*layers) + + def forward(self, x): + + def _inner_forward(x): + if self.use_res_connect: + return x + self.conv(x) + else: + return self.conv(x) + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + return out + + +class InvertedResidualV3(nn.Module): + """Inverted Residual Block for MobileNetV3. + + Args: + in_channels (int): The input channels of this Module. + out_channels (int): The output channels of this Module. + mid_channels (int): The input channels of the depthwise convolution. + kernel_size (int): The kernel size of the depthwise convolution. + Default: 3. + stride (int): The stride of the depthwise convolution. Default: 1. + se_cfg (dict): Config dict for se layer. Default: None, which means no + se layer. + with_expand_conv (bool): Use expand conv or not. If set False, + mid_channels must be the same with in_channels. Default: True. + conv_cfg (dict): Config dict for convolution layer. Default: None, + which means using conv2d. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer. + Default: dict(type='ReLU'). + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + + Returns: + Tensor: The output tensor. + """ + + def __init__(self, + in_channels, + out_channels, + mid_channels, + kernel_size=3, + stride=1, + se_cfg=None, + with_expand_conv=True, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + with_cp=False): + super().__init__() + self.with_res_shortcut = (stride == 1 and in_channels == out_channels) + assert stride in [1, 2] + self.with_cp = with_cp + self.with_se = se_cfg is not None + self.with_expand_conv = with_expand_conv + + if self.with_se: + assert isinstance(se_cfg, dict) + if not self.with_expand_conv: + assert mid_channels == in_channels + + if self.with_expand_conv: + self.expand_conv = ConvModule( + in_channels=in_channels, + out_channels=mid_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.depthwise_conv = ConvModule( + in_channels=mid_channels, + out_channels=mid_channels, + kernel_size=kernel_size, + stride=stride, + padding=kernel_size // 2, + groups=mid_channels, + conv_cfg=dict( + type='Conv2dAdaptivePadding') if stride == 2 else conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + if self.with_se: + self.se = SELayer(**se_cfg) + + self.linear_conv = ConvModule( + in_channels=mid_channels, + out_channels=out_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=None) + + def forward(self, x): + + def _inner_forward(x): + out = x + + if self.with_expand_conv: + out = self.expand_conv(out) + + out = self.depthwise_conv(out) + + if self.with_se: + out = self.se(out) + + out = self.linear_conv(out) + + if self.with_res_shortcut: + return x + out + else: + return out + + if self.with_cp and x.requires_grad: + out = cp.checkpoint(_inner_forward, x) + else: + out = _inner_forward(x) + + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/make_divisible.py b/reconstruction/modules/InterFormer/mmseg/models/utils/make_divisible.py new file mode 100644 index 0000000000000000000000000000000000000000..ed42c2eeea2a6aed03a0be5516b8d1ef1139e486 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/make_divisible.py @@ -0,0 +1,28 @@ +# Copyright (c) OpenMMLab. All rights reserved. +def make_divisible(value, divisor, min_value=None, min_ratio=0.9): + """Make divisible function. + + This function rounds the channel number to the nearest value that can be + divisible by the divisor. It is taken from the original tf repo. It ensures + that all layers have a channel number that is divisible by divisor. It can + be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py # noqa + + Args: + value (int): The original channel number. + divisor (int): The divisor to fully divide the channel number. + min_value (int): The minimum value of the output channel. + Default: None, means that the minimum value equal to the divisor. + min_ratio (float): The minimum ratio of the rounded channel number to + the original channel number. Default: 0.9. + + Returns: + int: The modified output channel number. + """ + + if min_value is None: + min_value = divisor + new_value = max(min_value, int(value + divisor / 2) // divisor * divisor) + # Make sure that round down does not go down by more than (1-min_ratio). + if new_value < min_ratio * value: + new_value += divisor + return new_value diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/point_sample.py b/reconstruction/modules/InterFormer/mmseg/models/utils/point_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..1afc957f3da7d1dc030c21d40311c768c6952ea4 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/point_sample.py @@ -0,0 +1,88 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.ops import point_sample +from torch import Tensor + + +def get_uncertainty(mask_preds: Tensor, labels: Tensor) -> Tensor: + """Estimate uncertainty based on pred logits. + + We estimate uncertainty as L1 distance between 0.0 and the logits + prediction in 'mask_preds' for the foreground class in `classes`. + + Args: + mask_preds (Tensor): mask predication logits, shape (num_rois, + num_classes, mask_height, mask_width). + + labels (Tensor): Either predicted or ground truth label for + each predicted mask, of length num_rois. + + Returns: + scores (Tensor): Uncertainty scores with the most uncertain + locations having the highest uncertainty score, + shape (num_rois, 1, mask_height, mask_width) + """ + if mask_preds.shape[1] == 1: + gt_class_logits = mask_preds.clone() + else: + inds = torch.arange(mask_preds.shape[0], device=mask_preds.device) + gt_class_logits = mask_preds[inds, labels].unsqueeze(1) + return -torch.abs(gt_class_logits) + + +def get_uncertain_point_coords_with_randomness( + mask_preds: Tensor, labels: Tensor, num_points: int, + oversample_ratio: float, importance_sample_ratio: float) -> Tensor: + """Get ``num_points`` most uncertain points with random points during + train. + + Sample points in [0, 1] x [0, 1] coordinate space based on their + uncertainty. The uncertainties are calculated for each point using + 'get_uncertainty()' function that takes point's logit prediction as + input. + + Args: + mask_preds (Tensor): A tensor of shape (num_rois, num_classes, + mask_height, mask_width) for class-specific or class-agnostic + prediction. + labels (Tensor): The ground truth class for each instance. + num_points (int): The number of points to sample. + oversample_ratio (float): Oversampling parameter. + importance_sample_ratio (float): Ratio of points that are sampled + via importnace sampling. + + Returns: + point_coords (Tensor): A tensor of shape (num_rois, num_points, 2) + that contains the coordinates sampled points. + """ + assert oversample_ratio >= 1 + assert 0 <= importance_sample_ratio <= 1 + batch_size = mask_preds.shape[0] + num_sampled = int(num_points * oversample_ratio) + point_coords = torch.rand( + batch_size, num_sampled, 2, device=mask_preds.device) + point_logits = point_sample(mask_preds, point_coords) + # It is crucial to calculate uncertainty based on the sampled + # prediction value for the points. Calculating uncertainties of the + # coarse predictions first and sampling them for points leads to + # incorrect results. To illustrate this: assume uncertainty func( + # logits)=-abs(logits), a sampled point between two coarse + # predictions with -1 and 1 logits has 0 logits, and therefore 0 + # uncertainty value. However, if we calculate uncertainties for the + # coarse predictions first, both will have -1 uncertainty, + # and sampled point will get -1 uncertainty. + point_uncertainties = get_uncertainty(point_logits, labels) + num_uncertain_points = int(importance_sample_ratio * num_points) + num_random_points = num_points - num_uncertain_points + idx = torch.topk( + point_uncertainties[:, 0, :], k=num_uncertain_points, dim=1)[1] + shift = num_sampled * torch.arange( + batch_size, dtype=torch.long, device=mask_preds.device) + idx += shift[:, None] + point_coords = point_coords.view(-1, 2)[idx.view(-1), :].view( + batch_size, num_uncertain_points, 2) + if num_random_points > 0: + rand_roi_coords = torch.rand( + batch_size, num_random_points, 2, device=mask_preds.device) + point_coords = torch.cat((point_coords, rand_roi_coords), dim=1) + return point_coords diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/ppm.py b/reconstruction/modules/InterFormer/mmseg/models/utils/ppm.py new file mode 100644 index 0000000000000000000000000000000000000000..5fe6ff26fae6869b989cecde96af3ceff1a37b38 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/ppm.py @@ -0,0 +1,193 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Dict, List + +import torch +import torch.nn as nn +import torch.nn.functional as F +from mmcv.cnn import ConvModule +from mmengine.model import BaseModule, ModuleList, Sequential +from torch import Tensor + + +class DAPPM(BaseModule): + """DAPPM module in `DDRNet `_. + + Args: + in_channels (int): Input channels. + branch_channels (int): Branch channels. + out_channels (int): Output channels. + num_scales (int): Number of scales. + kernel_sizes (list[int]): Kernel sizes of each scale. + strides (list[int]): Strides of each scale. + paddings (list[int]): Paddings of each scale. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU', inplace=True). + conv_cfg (dict): Config dict for convolution layer in ConvModule. + Default: dict(order=('norm', 'act', 'conv'), bias=False). + upsample_mode (str): Upsample mode. Default: 'bilinear'. + """ + + def __init__(self, + in_channels: int, + branch_channels: int, + out_channels: int, + num_scales: int, + kernel_sizes: List[int] = [5, 9, 17], + strides: List[int] = [2, 4, 8], + paddings: List[int] = [2, 4, 8], + norm_cfg: Dict = dict(type='BN', momentum=0.1), + act_cfg: Dict = dict(type='ReLU', inplace=True), + conv_cfg: Dict = dict( + order=('norm', 'act', 'conv'), bias=False), + upsample_mode: str = 'bilinear'): + super().__init__() + + self.num_scales = num_scales + self.unsample_mode = upsample_mode + self.in_channels = in_channels + self.branch_channels = branch_channels + self.out_channels = out_channels + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.conv_cfg = conv_cfg + + self.scales = ModuleList([ + ConvModule( + in_channels, + branch_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + ]) + for i in range(1, num_scales - 1): + self.scales.append( + Sequential(*[ + nn.AvgPool2d( + kernel_size=kernel_sizes[i - 1], + stride=strides[i - 1], + padding=paddings[i - 1]), + ConvModule( + in_channels, + branch_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + ])) + self.scales.append( + Sequential(*[ + nn.AdaptiveAvgPool2d((1, 1)), + ConvModule( + in_channels, + branch_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + ])) + self.processes = ModuleList() + for i in range(num_scales - 1): + self.processes.append( + ConvModule( + branch_channels, + branch_channels, + kernel_size=3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg)) + + self.compression = ConvModule( + branch_channels * num_scales, + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + + self.shortcut = ConvModule( + in_channels, + out_channels, + kernel_size=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + **conv_cfg) + + def forward(self, inputs: Tensor): + feats = [] + feats.append(self.scales[0](inputs)) + + for i in range(1, self.num_scales): + feat_up = F.interpolate( + self.scales[i](inputs), + size=inputs.shape[2:], + mode=self.unsample_mode) + feats.append(self.processes[i - 1](feat_up + feats[i - 1])) + + return self.compression(torch.cat(feats, + dim=1)) + self.shortcut(inputs) + + +class PAPPM(DAPPM): + """PAPPM module in `PIDNet `_. + + Args: + in_channels (int): Input channels. + branch_channels (int): Branch channels. + out_channels (int): Output channels. + num_scales (int): Number of scales. + kernel_sizes (list[int]): Kernel sizes of each scale. + strides (list[int]): Strides of each scale. + paddings (list[int]): Paddings of each scale. + norm_cfg (dict): Config dict for normalization layer. + Default: dict(type='BN', momentum=0.1). + act_cfg (dict): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU', inplace=True). + conv_cfg (dict): Config dict for convolution layer in ConvModule. + Default: dict(order=('norm', 'act', 'conv'), bias=False). + upsample_mode (str): Upsample mode. Default: 'bilinear'. + """ + + def __init__(self, + in_channels: int, + branch_channels: int, + out_channels: int, + num_scales: int, + kernel_sizes: List[int] = [5, 9, 17], + strides: List[int] = [2, 4, 8], + paddings: List[int] = [2, 4, 8], + norm_cfg: Dict = dict(type='BN', momentum=0.1), + act_cfg: Dict = dict(type='ReLU', inplace=True), + conv_cfg: Dict = dict( + order=('norm', 'act', 'conv'), bias=False), + upsample_mode: str = 'bilinear'): + super().__init__(in_channels, branch_channels, out_channels, + num_scales, kernel_sizes, strides, paddings, norm_cfg, + act_cfg, conv_cfg, upsample_mode) + + self.processes = ConvModule( + self.branch_channels * (self.num_scales - 1), + self.branch_channels * (self.num_scales - 1), + kernel_size=3, + padding=1, + groups=self.num_scales - 1, + norm_cfg=self.norm_cfg, + act_cfg=self.act_cfg, + **self.conv_cfg) + + def forward(self, inputs: Tensor): + x_ = self.scales[0](inputs) + feats = [] + for i in range(1, self.num_scales): + feat_up = F.interpolate( + self.scales[i](inputs), + size=inputs.shape[2:], + mode=self.unsample_mode, + align_corners=False) + feats.append(feat_up + x_) + scale_out = self.processes(torch.cat(feats, dim=1)) + return self.compression(torch.cat([x_, scale_out], + dim=1)) + self.shortcut(inputs) diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/res_layer.py b/reconstruction/modules/InterFormer/mmseg/models/utils/res_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd7a6f75a168f2f7e3c61f82d309b1cf0d502bc --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/res_layer.py @@ -0,0 +1,96 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmcv.cnn import build_conv_layer, build_norm_layer +from mmengine.model import Sequential +from torch import nn as nn + + +class ResLayer(Sequential): + """ResLayer to build ResNet style backbone. + + Args: + block (nn.Module): block used to build ResLayer. + inplanes (int): inplanes of block. + planes (int): planes of block. + num_blocks (int): number of blocks. + stride (int): stride of the first block. Default: 1 + avg_down (bool): Use AvgPool instead of stride conv when + downsampling in the bottleneck. Default: False + conv_cfg (dict): dictionary to construct and config conv layer. + Default: None + norm_cfg (dict): dictionary to construct and config norm layer. + Default: dict(type='BN') + multi_grid (int | None): Multi grid dilation rates of last + stage. Default: None + contract_dilation (bool): Whether contract first dilation of each layer + Default: False + """ + + def __init__(self, + block, + inplanes, + planes, + num_blocks, + stride=1, + dilation=1, + avg_down=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + multi_grid=None, + contract_dilation=False, + **kwargs): + self.block = block + + downsample = None + if stride != 1 or inplanes != planes * block.expansion: + downsample = [] + conv_stride = stride + if avg_down: + conv_stride = 1 + downsample.append( + nn.AvgPool2d( + kernel_size=stride, + stride=stride, + ceil_mode=True, + count_include_pad=False)) + downsample.extend([ + build_conv_layer( + conv_cfg, + inplanes, + planes * block.expansion, + kernel_size=1, + stride=conv_stride, + bias=False), + build_norm_layer(norm_cfg, planes * block.expansion)[1] + ]) + downsample = nn.Sequential(*downsample) + + layers = [] + if multi_grid is None: + if dilation > 1 and contract_dilation: + first_dilation = dilation // 2 + else: + first_dilation = dilation + else: + first_dilation = multi_grid[0] + layers.append( + block( + inplanes=inplanes, + planes=planes, + stride=stride, + dilation=first_dilation, + downsample=downsample, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + **kwargs)) + inplanes = planes * block.expansion + for i in range(1, num_blocks): + layers.append( + block( + inplanes=inplanes, + planes=planes, + stride=1, + dilation=dilation if multi_grid is None else multi_grid[i], + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + **kwargs)) + super().__init__(*layers) diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/san_layers.py b/reconstruction/modules/InterFormer/mmseg/models/utils/san_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..2267686daf62658c5dc81408e0a399c43aee83aa --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/san_layers.py @@ -0,0 +1,418 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# Modified from https://github.com/MendelXu/SAN/blob/main/san/model/attn_helper.py # noqa: E501 +# Copyright (c) 2023 MendelXu. +# Licensed under the MIT License + +import warnings +from typing import Optional + +import torch +from mmcv.cnn.bricks.transformer import BaseTransformerLayer +from torch import Tensor, nn +from torch.nn import functional as F + + +def cross_attn_with_self_bias( + query: Tensor, + key: Tensor, + value: Tensor, + embed_dim_to_check: int, + num_heads: int, + in_proj_weight: Tensor, + in_proj_bias: Tensor, + bias_k: Optional[Tensor], + bias_v: Optional[Tensor], + add_zero_attn: bool, + dropout_p: float, + out_proj_weight: Tensor, + out_proj_bias: Tensor, + training: bool = True, + key_padding_mask: Optional[Tensor] = None, + need_weights: bool = True, + attn_mask: Optional[Tensor] = None, + use_separate_proj_weight: bool = False, + q_proj_weight: Optional[Tensor] = None, + k_proj_weight: Optional[Tensor] = None, + v_proj_weight: Optional[Tensor] = None, + static_k: Optional[Tensor] = None, + static_v: Optional[Tensor] = None, +): + """Forward function of multi-head attention. Modified from + multi_head_attention_forward in + https://github.com/pytorch/pytorch/blob/main/torch/nn/functional.py. + + Args: + query, key, value: map a query and a set of key-value pairs to an output. + See "Attention Is All You Need" for more details. + embed_dim_to_check: total dimension of the model. + num_heads: parallel attention heads. + in_proj_weight, in_proj_bias: input projection weight and bias. + bias_k, bias_v: bias of the key and value sequences to be added at dim=0. + add_zero_attn: add a new batch of zeros to the key and + value sequences at dim=1. + dropout_p: probability of an element to be zeroed. + out_proj_weight, out_proj_bias: the output projection weight and bias. + training: apply dropout if is ``True``. + key_padding_mask: if provided, specified padding elements in the key will + be ignored by the attention. This is an binary mask. When the value is True, + the corresponding value on the attention layer will be filled with -inf. + need_weights: output attn_output_weights. + Default: `True` + Note: `needs_weight` defaults to `True`, but should be set to `False` + For best performance when attention weights are not needed. + *Setting needs_weights to `True` + leads to a significant performance degradation.* + attn_mask: 2D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all + the batches while a 3D mask allows to specify a different mask for the entries of each batch. + use_separate_proj_weight: the function accept the proj. weights for query, key, + and value in different forms. If false, in_proj_weight will be used, which is + a combination of q_proj_weight, k_proj_weight, v_proj_weight. + q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias. + static_k, static_v: static key and value used for attention operators. + """ # noqa: E501 + tgt_len, bsz, embed_dim = query.size() + assert embed_dim == embed_dim_to_check + # allow MHA to have different sizes for the feature dimension + assert key.size(0) == value.size(0) and key.size(1) == value.size(1) + + head_dim = embed_dim // num_heads + assert head_dim * num_heads == embed_dim, \ + 'embed_dim must be divisible by num_heads' + scaling = float(head_dim)**-0.5 + + if not use_separate_proj_weight: + if (query is key or torch.equal( + query, key)) and (key is value or torch.equal(key, value)): + # self-attention + raise NotImplementedError('self-attention is not implemented') + + elif key is value or torch.equal(key, value): + # encoder-decoder attention + # This is inline in_proj function + # with in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = 0 + _end = embed_dim + _w = in_proj_weight[_start:_end, :] + if _b is not None: + _b = _b[_start:_end] + q = F.linear(query, _w, _b) + + if key is None: + assert value is None + k = None + v = None + q_k = None + q_v = None + else: + # This is inline in_proj function with + # in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = embed_dim + _end = None + _w = in_proj_weight[_start:, :] + if _b is not None: + _b = _b[_start:] + k, v = F.linear(key, _w, _b).chunk(2, dim=-1) + q_k, q_v = F.linear(query, _w, _b).chunk(2, dim=-1) + else: + # This is inline in_proj function with + # in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = 0 + _end = embed_dim + _w = in_proj_weight[_start:_end, :] + if _b is not None: + _b = _b[_start:_end] + q = F.linear(query, _w, _b) + + # This is inline in_proj function with + # in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = embed_dim + _end = embed_dim * 2 + _w = in_proj_weight[_start:_end, :] + if _b is not None: + _b = _b[_start:_end] + k = F.linear(key, _w, _b) + q_k = F.linear(query, _w, _b) + # This is inline in_proj function with + # in_proj_weight and in_proj_bias + _b = in_proj_bias + _start = embed_dim * 2 + _end = None + _w = in_proj_weight[_start:, :] + if _b is not None: + _b = _b[_start:] + v = F.linear(value, _w, _b) + q_v = F.linear(query, _w, _b) + else: + q_proj_weight_non_opt = \ + torch.jit._unwrap_optional(q_proj_weight) + len1, len2 = q_proj_weight_non_opt.size() + assert len1 == embed_dim and len2 == query.size(-1) + + k_proj_weight_non_opt = \ + torch.jit._unwrap_optional(k_proj_weight) + len1, len2 = k_proj_weight_non_opt.size() + assert len1 == embed_dim and len2 == key.size(-1) + + v_proj_weight_non_opt = \ + torch.jit._unwrap_optional(v_proj_weight) + len1, len2 = v_proj_weight_non_opt.size() + assert len1 == embed_dim and len2 == value.size(-1) + + if in_proj_bias is not None: + q = F.linear(query, q_proj_weight_non_opt, + in_proj_bias[0:embed_dim]) + k = F.linear(key, k_proj_weight_non_opt, + in_proj_bias[embed_dim:(embed_dim * 2)]) + v = F.linear(value, v_proj_weight_non_opt, + in_proj_bias[(embed_dim * 2):]) + else: + q = F.linear(query, q_proj_weight_non_opt, in_proj_bias) + k = F.linear(key, k_proj_weight_non_opt, in_proj_bias) + v = F.linear(value, v_proj_weight_non_opt, in_proj_bias) + q = q * scaling + + if attn_mask is not None: + assert ( + attn_mask.dtype == torch.float32 + or attn_mask.dtype == torch.float64 + or attn_mask.dtype == torch.float16 + or attn_mask.dtype == torch.uint8 or attn_mask.dtype == torch.bool + ), 'Only float, byte, and bool types are supported for ' \ + 'attn_mask, not {}'.format(attn_mask.dtype) + if attn_mask.dtype == torch.uint8: + warnings.warn('Byte tensor for attn_mask in nn.MultiheadAttention ' + 'is deprecated. Use bool tensor instead.') + attn_mask = attn_mask.to(torch.bool) + + if attn_mask.dim() == 2: + attn_mask = attn_mask.unsqueeze(0) + if list(attn_mask.size()) != [1, query.size(0), key.size(0)]: + raise RuntimeError( + 'The size of the 2D attn_mask is not correct.') + elif attn_mask.dim() == 3: + if list(attn_mask.size()) != [ + bsz * num_heads, + query.size(0), key.size(0) + ]: + raise RuntimeError( + 'The size of the 3D attn_mask is not correct.') + else: + raise RuntimeError( + "attn_mask's dimension {} is not supported".format( + attn_mask.dim())) + # attn_mask's dim is 3 now. + + # convert ByteTensor key_padding_mask to bool + if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8: + warnings.warn( + 'Byte tensor for key_padding_mask in nn.MultiheadAttention ' + 'is deprecated. Use bool tensor instead.') + key_padding_mask = key_padding_mask.to(torch.bool) + + if bias_k is not None and bias_v is not None: + if static_k is None and static_v is None: + k = torch.cat([k, bias_k.repeat(1, bsz, 1)]) + v = torch.cat([v, bias_v.repeat(1, bsz, 1)]) + if attn_mask is not None: + attn_mask = F.pad(attn_mask, (0, 1)) + if key_padding_mask is not None: + key_padding_mask = F.pad(key_padding_mask, (0, 1)) + else: + assert static_k is None, 'bias cannot be added to static key.' + assert static_v is None, 'bias cannot be added to static value.' + else: + assert bias_k is None + assert bias_v is None + + q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1) + if k is not None: + k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + q_k = q_k.contiguous().view(tgt_len, bsz * num_heads, + head_dim).transpose(0, 1) + if v is not None: + v = v.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1) + q_v = q_v.contiguous().view(tgt_len, bsz * num_heads, + head_dim).transpose(0, 1) + + if static_k is not None: + assert static_k.size(0) == bsz * num_heads + assert static_k.size(2) == head_dim + k = static_k + + if static_v is not None: + assert static_v.size(0) == bsz * num_heads + assert static_v.size(2) == head_dim + v = static_v + + src_len = k.size(1) + + if key_padding_mask is not None: + assert key_padding_mask.size(0) == bsz + assert key_padding_mask.size(1) == src_len + + if add_zero_attn: + src_len += 1 + k = torch.cat( + [ + k, + torch.zeros( + (k.size(0), 1) + k.size()[2:], + dtype=k.dtype, + device=k.device), + ], + dim=1, + ) + v = torch.cat( + [ + v, + torch.zeros( + (v.size(0), 1) + v.size()[2:], + dtype=v.dtype, + device=v.device), + ], + dim=1, + ) + if attn_mask is not None: + attn_mask = F.pad(attn_mask, (0, 1)) + if key_padding_mask is not None: + key_padding_mask = F.pad(key_padding_mask, (0, 1)) + + attn_output_weights = torch.bmm(q, k.transpose(1, 2)) + assert list( + attn_output_weights.size()) == [bsz * num_heads, tgt_len, src_len] + + if attn_mask is not None: + if attn_mask.dtype == torch.bool: + attn_output_weights.masked_fill_(attn_mask, float('-inf')) + else: + attn_output_weights += attn_mask + + if key_padding_mask is not None: + attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, + src_len) + attn_output_weights = attn_output_weights.masked_fill( + key_padding_mask.unsqueeze(1).unsqueeze(2), + float('-inf'), + ) + attn_output_weights = attn_output_weights.view(bsz * num_heads, + tgt_len, src_len) + # attn_out_weights: [bsz * num_heads, tgt_len, src_len] + # ->[bsz * num_heads, tgt_len, src_len+1] + self_weight = (q * q_k).sum( + dim=-1, keepdim=True) # [bsz * num_heads, tgt_len, 1] + total_attn_output_weights = torch.cat([attn_output_weights, self_weight], + dim=-1) + total_attn_output_weights = F.softmax(total_attn_output_weights, dim=-1) + total_attn_output_weights = F.dropout( + total_attn_output_weights, p=dropout_p, training=training) + attn_output_weights = \ + total_attn_output_weights[:, :, : -1] + # [bsz * num_heads, tgt_len, src_len] + self_weight = \ + total_attn_output_weights[:, :, -1:] # [bsz * num_heads, tgt_len, 1] + + attn_output = torch.bmm(attn_output_weights, + v) # [bsz * num_heads, tgt_len, head_dim] + attn_output = (attn_output + self_weight * q_v + ) # [bsz * num_heads, tgt_len, head_dim] + assert list(attn_output.size()) == [bsz * num_heads, tgt_len, head_dim] + attn_output = attn_output.transpose(0, 1).contiguous().view( + tgt_len, bsz, embed_dim) + attn_output = F.linear(attn_output, out_proj_weight, out_proj_bias) + + if need_weights: + # average attention weights over heads + attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, + src_len) + return attn_output, attn_output_weights # .sum(dim=1) / num_heads + else: + return attn_output, None + + +def cross_attn_layer(tf_layer: BaseTransformerLayer, x, mem, attn_bias): + """Implementation of transformer layer with cross attention. The cross + attention shares the embedding weights with self-attention of tf_layer. + Args: + tf_layer: (TransformerEncoderLayer): The Module of transformer layer. + x (Tensor): query [K,N,C] + mem (Tensor): key and value [L,N,C] + attn_bias (Tensor): attention bias [N*num_head,K,L] + + Return: + x (Tensor): cross attention output [K,N,C] + """ + self_attn_layer = tf_layer.attentions[0].attn + attn_layer_paras = { + 'embed_dim_to_check': self_attn_layer.embed_dim, + 'num_heads': self_attn_layer.num_heads, + 'in_proj_weight': self_attn_layer.in_proj_weight, + 'in_proj_bias': self_attn_layer.in_proj_bias, + 'bias_k': self_attn_layer.bias_k, + 'bias_v': self_attn_layer.bias_v, + 'add_zero_attn': self_attn_layer.add_zero_attn, + 'dropout_p': self_attn_layer.dropout, + 'out_proj_weight': self_attn_layer.out_proj.weight, + 'out_proj_bias': self_attn_layer.out_proj.bias, + 'training': self_attn_layer.training + } + + q_x = tf_layer.norms[0](x) + k_x = v_x = tf_layer.norms[0](mem) + x = x + cross_attn_with_self_bias( + q_x, + k_x, + v_x, + attn_mask=attn_bias, + need_weights=False, + **attn_layer_paras)[0] + x = tf_layer.ffns[0](tf_layer.norms[1](x), identity=x) + return x + + +class LayerNorm2d(nn.Module): + """A LayerNorm variant, popularized by Transformers, that performs point- + wise mean and variance normalization over the channel dimension for inputs + that have shape (batch_size, channels, height, width). + + https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa B950 + """ + + def __init__(self, normalized_shape, eps=1e-6): + super().__init__() + self.weight = nn.Parameter(torch.ones(normalized_shape)) + self.bias = nn.Parameter(torch.zeros(normalized_shape)) + self.eps = eps + self.normalized_shape = (normalized_shape, ) + + def forward(self, x: torch.Tensor): + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +class MLP(nn.Module): + """Very simple multi-layer perceptron (also called FFN)""" + + def __init__(self, + input_dim, + hidden_dim, + output_dim, + num_layers, + affine_func=nn.Linear): + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + affine_func(n, k) + for n, k in zip([input_dim] + h, h + [output_dim])) + + def forward(self, x: torch.Tensor): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + return x diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/se_layer.py b/reconstruction/modules/InterFormer/mmseg/models/utils/se_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff632cfea728a7ffd99f1578c828c588d78f3db --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/se_layer.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch.nn as nn +from mmcv.cnn import ConvModule +from mmengine.utils import is_tuple_of + +from .make_divisible import make_divisible + + +class SELayer(nn.Module): + """Squeeze-and-Excitation Module. + + Args: + channels (int): The input (and output) channels of the SE layer. + ratio (int): Squeeze ratio in SELayer, the intermediate channel will be + ``int(channels/ratio)``. Default: 16. + conv_cfg (None or dict): Config dict for convolution layer. + Default: None, which means using conv2d. + act_cfg (dict or Sequence[dict]): Config dict for activation layer. + If act_cfg is a dict, two activation layers will be configured + by this dict. If act_cfg is a sequence of dicts, the first + activation layer will be configured by the first dict and the + second activation layer will be configured by the second dict. + Default: (dict(type='ReLU'), dict(type='HSigmoid', bias=3.0, + divisor=6.0)). + """ + + def __init__(self, + channels, + ratio=16, + conv_cfg=None, + act_cfg=(dict(type='ReLU'), + dict(type='HSigmoid', bias=3.0, divisor=6.0))): + super().__init__() + if isinstance(act_cfg, dict): + act_cfg = (act_cfg, act_cfg) + assert len(act_cfg) == 2 + assert is_tuple_of(act_cfg, dict) + self.global_avgpool = nn.AdaptiveAvgPool2d(1) + self.conv1 = ConvModule( + in_channels=channels, + out_channels=make_divisible(channels // ratio, 8), + kernel_size=1, + stride=1, + conv_cfg=conv_cfg, + act_cfg=act_cfg[0]) + self.conv2 = ConvModule( + in_channels=make_divisible(channels // ratio, 8), + out_channels=channels, + kernel_size=1, + stride=1, + conv_cfg=conv_cfg, + act_cfg=act_cfg[1]) + + def forward(self, x): + out = self.global_avgpool(x) + out = self.conv1(out) + out = self.conv2(out) + return x * out diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/self_attention_block.py b/reconstruction/modules/InterFormer/mmseg/models/utils/self_attention_block.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb6e8284e599637c12553e27199338a820709e3 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/self_attention_block.py @@ -0,0 +1,161 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +from mmcv.cnn import ConvModule +from mmengine.model.weight_init import constant_init +from torch import nn as nn +from torch.nn import functional as F + + +class SelfAttentionBlock(nn.Module): + """General self-attention block/non-local block. + + Please refer to https://arxiv.org/abs/1706.03762 for details about key, + query and value. + + Args: + key_in_channels (int): Input channels of key feature. + query_in_channels (int): Input channels of query feature. + channels (int): Output channels of key/query transform. + out_channels (int): Output channels. + share_key_query (bool): Whether share projection weight between key + and query projection. + query_downsample (nn.Module): Query downsample module. + key_downsample (nn.Module): Key downsample module. + key_query_num_convs (int): Number of convs for key/query projection. + value_num_convs (int): Number of convs for value projection. + matmul_norm (bool): Whether normalize attention map with sqrt of + channels + with_out (bool): Whether use out projection. + conv_cfg (dict|None): Config of conv layers. + norm_cfg (dict|None): Config of norm layers. + act_cfg (dict|None): Config of activation layers. + """ + + def __init__(self, key_in_channels, query_in_channels, channels, + out_channels, share_key_query, query_downsample, + key_downsample, key_query_num_convs, value_out_num_convs, + key_query_norm, value_out_norm, matmul_norm, with_out, + conv_cfg, norm_cfg, act_cfg): + super().__init__() + if share_key_query: + assert key_in_channels == query_in_channels + self.key_in_channels = key_in_channels + self.query_in_channels = query_in_channels + self.out_channels = out_channels + self.channels = channels + self.share_key_query = share_key_query + self.conv_cfg = conv_cfg + self.norm_cfg = norm_cfg + self.act_cfg = act_cfg + self.key_project = self.build_project( + key_in_channels, + channels, + num_convs=key_query_num_convs, + use_conv_module=key_query_norm, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + if share_key_query: + self.query_project = self.key_project + else: + self.query_project = self.build_project( + query_in_channels, + channels, + num_convs=key_query_num_convs, + use_conv_module=key_query_norm, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + self.value_project = self.build_project( + key_in_channels, + channels if with_out else out_channels, + num_convs=value_out_num_convs, + use_conv_module=value_out_norm, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + if with_out: + self.out_project = self.build_project( + channels, + out_channels, + num_convs=value_out_num_convs, + use_conv_module=value_out_norm, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + else: + self.out_project = None + + self.query_downsample = query_downsample + self.key_downsample = key_downsample + self.matmul_norm = matmul_norm + + self.init_weights() + + def init_weights(self): + """Initialize weight of later layer.""" + if self.out_project is not None: + if not isinstance(self.out_project, ConvModule): + constant_init(self.out_project, 0) + + def build_project(self, in_channels, channels, num_convs, use_conv_module, + conv_cfg, norm_cfg, act_cfg): + """Build projection layer for key/query/value/out.""" + if use_conv_module: + convs = [ + ConvModule( + in_channels, + channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + ] + for _ in range(num_convs - 1): + convs.append( + ConvModule( + channels, + channels, + 1, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + else: + convs = [nn.Conv2d(in_channels, channels, 1)] + for _ in range(num_convs - 1): + convs.append(nn.Conv2d(channels, channels, 1)) + if len(convs) > 1: + convs = nn.Sequential(*convs) + else: + convs = convs[0] + return convs + + def forward(self, query_feats, key_feats): + """Forward function.""" + batch_size = query_feats.size(0) + query = self.query_project(query_feats) + if self.query_downsample is not None: + query = self.query_downsample(query) + query = query.reshape(*query.shape[:2], -1) + query = query.permute(0, 2, 1).contiguous() + + key = self.key_project(key_feats) + value = self.value_project(key_feats) + if self.key_downsample is not None: + key = self.key_downsample(key) + value = self.key_downsample(value) + key = key.reshape(*key.shape[:2], -1) + value = value.reshape(*value.shape[:2], -1) + value = value.permute(0, 2, 1).contiguous() + + sim_map = torch.matmul(query, key) + if self.matmul_norm: + sim_map = (self.channels**-.5) * sim_map + sim_map = F.softmax(sim_map, dim=-1) + + context = torch.matmul(sim_map, value) + context = context.permute(0, 2, 1).contiguous() + context = context.reshape(batch_size, -1, *query_feats.shape[2:]) + if self.out_project is not None: + context = self.out_project(context) + return context diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/shape_convert.py b/reconstruction/modules/InterFormer/mmseg/models/utils/shape_convert.py new file mode 100644 index 0000000000000000000000000000000000000000..cce1e220b645d4b02df1ec2d9ed3137c8acba707 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/shape_convert.py @@ -0,0 +1,107 @@ +# Copyright (c) OpenMMLab. All rights reserved. +def nlc_to_nchw(x, hw_shape): + """Convert [N, L, C] shape tensor to [N, C, H, W] shape tensor. + + Args: + x (Tensor): The input tensor of shape [N, L, C] before conversion. + hw_shape (Sequence[int]): The height and width of output feature map. + + Returns: + Tensor: The output tensor of shape [N, C, H, W] after conversion. + """ + H, W = hw_shape + assert len(x.shape) == 3 + B, L, C = x.shape + assert L == H * W, 'The seq_len doesn\'t match H, W' + return x.transpose(1, 2).reshape(B, C, H, W) + + +def nchw_to_nlc(x): + """Flatten [N, C, H, W] shape tensor to [N, L, C] shape tensor. + + Args: + x (Tensor): The input tensor of shape [N, C, H, W] before conversion. + + Returns: + Tensor: The output tensor of shape [N, L, C] after conversion. + """ + assert len(x.shape) == 4 + return x.flatten(2).transpose(1, 2).contiguous() + + +def nchw2nlc2nchw(module, x, contiguous=False, **kwargs): + """Flatten [N, C, H, W] shape tensor `x` to [N, L, C] shape tensor. Use the + reshaped tensor as the input of `module`, and the convert the output of + `module`, whose shape is. + + [N, L, C], to [N, C, H, W]. + + Args: + module (Callable): A callable object the takes a tensor + with shape [N, L, C] as input. + x (Tensor): The input tensor of shape [N, C, H, W]. + contiguous: + contiguous (Bool): Whether to make the tensor contiguous + after each shape transform. + + Returns: + Tensor: The output tensor of shape [N, C, H, W]. + + Example: + >>> import torch + >>> import torch.nn as nn + >>> norm = nn.LayerNorm(4) + >>> feature_map = torch.rand(4, 4, 5, 5) + >>> output = nchw2nlc2nchw(norm, feature_map) + """ + B, C, H, W = x.shape + if not contiguous: + x = x.flatten(2).transpose(1, 2) + x = module(x, **kwargs) + x = x.transpose(1, 2).reshape(B, C, H, W) + else: + x = x.flatten(2).transpose(1, 2).contiguous() + x = module(x, **kwargs) + x = x.transpose(1, 2).reshape(B, C, H, W).contiguous() + return x + + +def nlc2nchw2nlc(module, x, hw_shape, contiguous=False, **kwargs): + """Convert [N, L, C] shape tensor `x` to [N, C, H, W] shape tensor. Use the + reshaped tensor as the input of `module`, and convert the output of + `module`, whose shape is. + + [N, C, H, W], to [N, L, C]. + + Args: + module (Callable): A callable object the takes a tensor + with shape [N, C, H, W] as input. + x (Tensor): The input tensor of shape [N, L, C]. + hw_shape: (Sequence[int]): The height and width of the + feature map with shape [N, C, H, W]. + contiguous (Bool): Whether to make the tensor contiguous + after each shape transform. + + Returns: + Tensor: The output tensor of shape [N, L, C]. + + Example: + >>> import torch + >>> import torch.nn as nn + >>> conv = nn.Conv2d(16, 16, 3, 1, 1) + >>> feature_map = torch.rand(4, 25, 16) + >>> output = nlc2nchw2nlc(conv, feature_map, (5, 5)) + """ + H, W = hw_shape + assert len(x.shape) == 3 + B, L, C = x.shape + assert L == H * W, 'The seq_len doesn\'t match H, W' + if not contiguous: + x = x.transpose(1, 2).reshape(B, C, H, W) + x = module(x, **kwargs) + x = x.flatten(2).transpose(1, 2) + else: + x = x.transpose(1, 2).reshape(B, C, H, W).contiguous() + x = module(x, **kwargs) + x = x.flatten(2).transpose(1, 2).contiguous() + return x diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/up_conv_block.py b/reconstruction/modules/InterFormer/mmseg/models/utils/up_conv_block.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa3b598de96d53c169232d9c89ac458f6921e8d --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/up_conv_block.py @@ -0,0 +1,102 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, build_upsample_layer + + +class UpConvBlock(nn.Module): + """Upsample convolution block in decoder for UNet. + + This upsample convolution block consists of one upsample module + followed by one convolution block. The upsample module expands the + high-level low-resolution feature map and the convolution block fuses + the upsampled high-level low-resolution feature map and the low-level + high-resolution feature map from encoder. + + Args: + conv_block (nn.Sequential): Sequential of convolutional layers. + in_channels (int): Number of input channels of the high-level + skip_channels (int): Number of input channels of the low-level + high-resolution feature map from encoder. + out_channels (int): Number of output channels. + num_convs (int): Number of convolutional layers in the conv_block. + Default: 2. + stride (int): Stride of convolutional layer in conv_block. Default: 1. + dilation (int): Dilation rate of convolutional layer in conv_block. + Default: 1. + with_cp (bool): Use checkpoint or not. Using checkpoint will save some + memory while slowing down the training speed. Default: False. + conv_cfg (dict | None): Config dict for convolution layer. + Default: None. + norm_cfg (dict | None): Config dict for normalization layer. + Default: dict(type='BN'). + act_cfg (dict | None): Config dict for activation layer in ConvModule. + Default: dict(type='ReLU'). + upsample_cfg (dict): The upsample config of the upsample module in + decoder. Default: dict(type='InterpConv'). If the size of + high-level feature map is the same as that of skip feature map + (low-level feature map from encoder), it does not need upsample the + high-level feature map and the upsample_cfg is None. + dcn (bool): Use deformable convolution in convolutional layer or not. + Default: None. + plugins (dict): plugins for convolutional layers. Default: None. + """ + + def __init__(self, + conv_block, + in_channels, + skip_channels, + out_channels, + num_convs=2, + stride=1, + dilation=1, + with_cp=False, + conv_cfg=None, + norm_cfg=dict(type='BN'), + act_cfg=dict(type='ReLU'), + upsample_cfg=dict(type='InterpConv'), + dcn=None, + plugins=None): + super().__init__() + assert dcn is None, 'Not implemented yet.' + assert plugins is None, 'Not implemented yet.' + + self.conv_block = conv_block( + in_channels=2 * skip_channels, + out_channels=out_channels, + num_convs=num_convs, + stride=stride, + dilation=dilation, + with_cp=with_cp, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + dcn=None, + plugins=None) + if upsample_cfg is not None: + self.upsample = build_upsample_layer( + cfg=upsample_cfg, + in_channels=in_channels, + out_channels=skip_channels, + with_cp=with_cp, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + else: + self.upsample = ConvModule( + in_channels, + skip_channels, + kernel_size=1, + stride=1, + padding=0, + conv_cfg=conv_cfg, + norm_cfg=norm_cfg, + act_cfg=act_cfg) + + def forward(self, skip, x): + """Forward function.""" + + x = self.upsample(x) + out = torch.cat([skip, x], dim=1) + out = self.conv_block(out) + + return out diff --git a/reconstruction/modules/InterFormer/mmseg/models/utils/wrappers.py b/reconstruction/modules/InterFormer/mmseg/models/utils/wrappers.py new file mode 100644 index 0000000000000000000000000000000000000000..abbd0c029623b4f480a067e4b78adfec234ef8d0 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/models/utils/wrappers.py @@ -0,0 +1,51 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +import torch.nn as nn +import torch.nn.functional as F + + +def resize(input, + size=None, + scale_factor=None, + mode='nearest', + align_corners=None, + warning=True): + if warning: + if size is not None and align_corners: + input_h, input_w = tuple(int(x) for x in input.shape[2:]) + output_h, output_w = tuple(int(x) for x in size) + if output_h > input_h or output_w > output_h: + if ((output_h > 1 and output_w > 1 and input_h > 1 + and input_w > 1) and (output_h - 1) % (input_h - 1) + and (output_w - 1) % (input_w - 1)): + warnings.warn( + f'When align_corners={align_corners}, ' + 'the output would more aligned if ' + f'input size {(input_h, input_w)} is `x+1` and ' + f'out size {(output_h, output_w)} is `nx+1`') + return F.interpolate(input, size, scale_factor, mode, align_corners) + + +class Upsample(nn.Module): + + def __init__(self, + size=None, + scale_factor=None, + mode='nearest', + align_corners=None): + super().__init__() + self.size = size + if isinstance(scale_factor, tuple): + self.scale_factor = tuple(float(factor) for factor in scale_factor) + else: + self.scale_factor = float(scale_factor) if scale_factor else None + self.mode = mode + self.align_corners = align_corners + + def forward(self, x): + if not self.size: + size = [int(t * self.scale_factor) for t in x.shape[-2:]] + else: + size = self.size + return resize(x, size, None, self.mode, self.align_corners) diff --git a/reconstruction/modules/InterFormer/mmseg/registry/__init__.py b/reconstruction/modules/InterFormer/mmseg/registry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee514d1a2a2bdd54a0a9b017ec227160ee502be5 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/registry/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .registry import (DATA_SAMPLERS, DATASETS, EVALUATOR, HOOKS, INFERENCERS, + LOG_PROCESSORS, LOOPS, METRICS, MODEL_WRAPPERS, MODELS, + OPTIM_WRAPPER_CONSTRUCTORS, OPTIM_WRAPPERS, OPTIMIZERS, + PARAM_SCHEDULERS, RUNNER_CONSTRUCTORS, RUNNERS, + TASK_UTILS, TRANSFORMS, VISBACKENDS, VISUALIZERS, + WEIGHT_INITIALIZERS) + +__all__ = [ + 'HOOKS', 'DATASETS', 'DATA_SAMPLERS', 'TRANSFORMS', 'MODELS', + 'WEIGHT_INITIALIZERS', 'OPTIMIZERS', 'OPTIM_WRAPPER_CONSTRUCTORS', + 'TASK_UTILS', 'PARAM_SCHEDULERS', 'METRICS', 'MODEL_WRAPPERS', + 'VISBACKENDS', 'VISUALIZERS', 'RUNNERS', 'RUNNER_CONSTRUCTORS', 'LOOPS', + 'EVALUATOR', 'LOG_PROCESSORS', 'OPTIM_WRAPPERS', 'INFERENCERS' +] diff --git a/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..397395104c7bc149a202532f17324800e2c0b09c Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0947432081db26154e2e11478b99688f2869e1f0 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/registry.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/registry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4916b90e89868689e5dcfb21d4d2be1750dcc86 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/registry.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/registry.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/registry.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..daaa210119596af30e090344cdc7692c2cfe13f2 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/registry/__pycache__/registry.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/registry/registry.py b/reconstruction/modules/InterFormer/mmseg/registry/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..37b6a776095856c2fab0101b5b0ec8ed7e8fa8f2 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/registry/registry.py @@ -0,0 +1,118 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""MMSegmentation provides 21 registry nodes to support using modules across +projects. Each node is a child of the root registry in MMEngine. + +More details can be found at +https://mmengine.readthedocs.io/en/latest/advanced_tutorials/registry.html. +""" + +from mmengine.registry import DATA_SAMPLERS as MMENGINE_DATA_SAMPLERS +from mmengine.registry import DATASETS as MMENGINE_DATASETS +from mmengine.registry import EVALUATOR as MMENGINE_EVALUATOR +from mmengine.registry import HOOKS as MMENGINE_HOOKS +from mmengine.registry import INFERENCERS as MMENGINE_INFERENCERS +from mmengine.registry import LOG_PROCESSORS as MMENGINE_LOG_PROCESSORS +from mmengine.registry import LOOPS as MMENGINE_LOOPS +from mmengine.registry import METRICS as MMENGINE_METRICS +from mmengine.registry import MODEL_WRAPPERS as MMENGINE_MODEL_WRAPPERS +from mmengine.registry import MODELS as MMENGINE_MODELS +from mmengine.registry import \ + OPTIM_WRAPPER_CONSTRUCTORS as MMENGINE_OPTIM_WRAPPER_CONSTRUCTORS +from mmengine.registry import OPTIM_WRAPPERS as MMENGINE_OPTIM_WRAPPERS +from mmengine.registry import OPTIMIZERS as MMENGINE_OPTIMIZERS +from mmengine.registry import PARAM_SCHEDULERS as MMENGINE_PARAM_SCHEDULERS +from mmengine.registry import \ + RUNNER_CONSTRUCTORS as MMENGINE_RUNNER_CONSTRUCTORS +from mmengine.registry import RUNNERS as MMENGINE_RUNNERS +from mmengine.registry import TASK_UTILS as MMENGINE_TASK_UTILS +from mmengine.registry import TRANSFORMS as MMENGINE_TRANSFORMS +from mmengine.registry import VISBACKENDS as MMENGINE_VISBACKENDS +from mmengine.registry import VISUALIZERS as MMENGINE_VISUALIZERS +from mmengine.registry import \ + WEIGHT_INITIALIZERS as MMENGINE_WEIGHT_INITIALIZERS +from mmengine.registry import Registry + +# manage all kinds of runners like `EpochBasedRunner` and `IterBasedRunner` +RUNNERS = Registry('runner', parent=MMENGINE_RUNNERS) +# manage runner constructors that define how to initialize runners +RUNNER_CONSTRUCTORS = Registry( + 'runner constructor', parent=MMENGINE_RUNNER_CONSTRUCTORS) +# manage all kinds of loops like `EpochBasedTrainLoop` +LOOPS = Registry('loop', parent=MMENGINE_LOOPS) +# manage all kinds of hooks like `CheckpointHook` +HOOKS = Registry( + 'hook', parent=MMENGINE_HOOKS, locations=['mmseg.engine.hooks']) + +# manage data-related modules +DATASETS = Registry( + 'dataset', parent=MMENGINE_DATASETS, locations=['mmseg.datasets']) +DATA_SAMPLERS = Registry('data sampler', parent=MMENGINE_DATA_SAMPLERS) +TRANSFORMS = Registry( + 'transform', + parent=MMENGINE_TRANSFORMS, + locations=['mmseg.datasets.transforms']) + +# mangage all kinds of modules inheriting `nn.Module` +MODELS = Registry('model', parent=MMENGINE_MODELS, locations=['mmseg.models']) +# mangage all kinds of model wrappers like 'MMDistributedDataParallel' +MODEL_WRAPPERS = Registry( + 'model_wrapper', + parent=MMENGINE_MODEL_WRAPPERS, + locations=['mmseg.models']) +# mangage all kinds of weight initialization modules like `Uniform` +WEIGHT_INITIALIZERS = Registry( + 'weight initializer', + parent=MMENGINE_WEIGHT_INITIALIZERS, + locations=['mmseg.models']) + +# mangage all kinds of optimizers like `SGD` and `Adam` +OPTIMIZERS = Registry( + 'optimizer', + parent=MMENGINE_OPTIMIZERS, + locations=['mmseg.engine.optimizers']) +# manage optimizer wrapper +OPTIM_WRAPPERS = Registry( + 'optim_wrapper', + parent=MMENGINE_OPTIM_WRAPPERS, + locations=['mmseg.engine.optimizers']) +# manage constructors that customize the optimization hyperparameters. +OPTIM_WRAPPER_CONSTRUCTORS = Registry( + 'optimizer wrapper constructor', + parent=MMENGINE_OPTIM_WRAPPER_CONSTRUCTORS, + locations=['mmseg.engine.optimizers']) +# mangage all kinds of parameter schedulers like `MultiStepLR` +PARAM_SCHEDULERS = Registry( + 'parameter scheduler', + parent=MMENGINE_PARAM_SCHEDULERS, + locations=['mmseg.engine.schedulers']) + +# manage all kinds of metrics +METRICS = Registry( + 'metric', parent=MMENGINE_METRICS, locations=['mmseg.evaluation']) +# manage evaluator +EVALUATOR = Registry( + 'evaluator', parent=MMENGINE_EVALUATOR, locations=['mmseg.evaluation']) + +# manage task-specific modules like ohem pixel sampler +TASK_UTILS = Registry( + 'task util', parent=MMENGINE_TASK_UTILS, locations=['mmseg.models']) + +# manage visualizer +VISUALIZERS = Registry( + 'visualizer', + parent=MMENGINE_VISUALIZERS, + locations=['mmseg.visualization']) +# manage visualizer backend +VISBACKENDS = Registry( + 'vis_backend', + parent=MMENGINE_VISBACKENDS, + locations=['mmseg.visualization']) + +# manage logprocessor +LOG_PROCESSORS = Registry( + 'log_processor', + parent=MMENGINE_LOG_PROCESSORS, + locations=['mmseg.visualization']) + +# manage inferencer +INFERENCERS = Registry('inferencer', parent=MMENGINE_INFERENCERS) diff --git a/reconstruction/modules/InterFormer/mmseg/structures/__init__.py b/reconstruction/modules/InterFormer/mmseg/structures/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63d118dca3ebcff30ca241f9378475bcce072627 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/structures/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .sampler import BasePixelSampler, OHEMPixelSampler, build_pixel_sampler +from .seg_data_sample import SegDataSample + +__all__ = [ + 'SegDataSample', 'BasePixelSampler', 'OHEMPixelSampler', + 'build_pixel_sampler' +] diff --git a/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd43c9bc2eac8ffbb0c7fb0521f1c32f65daebcf Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaae3728fe7b5ec77e2d79ae091c87f869dff13c Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/seg_data_sample.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/seg_data_sample.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60e7c4d1358a689f680a4b9eadf24f9ac56e6879 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/seg_data_sample.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/seg_data_sample.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/seg_data_sample.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..093ffc399952185fa09a4843ce29f4d7335e700a Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/__pycache__/seg_data_sample.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/__init__.py b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91d762d1b4552b391ece046fa3d094409011bcec --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .base_pixel_sampler import BasePixelSampler +from .builder import build_pixel_sampler +from .ohem_pixel_sampler import OHEMPixelSampler + +__all__ = ['build_pixel_sampler', 'BasePixelSampler', 'OHEMPixelSampler'] diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a3a3d582a0ef853f8d3859c601af4de2fa7b581 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3b1e5d406653a3ef25f80ccf46449d8f12c30cb Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/base_pixel_sampler.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/base_pixel_sampler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..383dd6920da90e7d4ec13b24103c6c83a94dafe6 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/base_pixel_sampler.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/base_pixel_sampler.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/base_pixel_sampler.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50e08e76d210f63c953ea49ad7e091f95b704b11 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/base_pixel_sampler.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/builder.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7eacebdef23847dcbb6e432fd84fb9ad7dc34ce9 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/builder.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/builder.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/builder.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0672a86d14d3c49c3c00845cdbf4c37d945fd8c7 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/builder.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/ohem_pixel_sampler.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/ohem_pixel_sampler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7187de64b326e6db91c6791079aef6c9c7740906 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/ohem_pixel_sampler.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/ohem_pixel_sampler.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/ohem_pixel_sampler.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cda913de0f1951a3f1321d349e34a2b7186cc705 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/structures/sampler/__pycache__/ohem_pixel_sampler.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/base_pixel_sampler.py b/reconstruction/modules/InterFormer/mmseg/structures/sampler/base_pixel_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..03672cd478a2e464cc734ae92686c86f219da0a9 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/structures/sampler/base_pixel_sampler.py @@ -0,0 +1,13 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from abc import ABCMeta, abstractmethod + + +class BasePixelSampler(metaclass=ABCMeta): + """Base class of pixel sampler.""" + + def __init__(self, **kwargs): + pass + + @abstractmethod + def sample(self, seg_logit, seg_label): + """Placeholder for sample function.""" diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/builder.py b/reconstruction/modules/InterFormer/mmseg/structures/sampler/builder.py new file mode 100644 index 0000000000000000000000000000000000000000..48e14790264a3d4c4ff54d84e5bab67b1623a1df --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/structures/sampler/builder.py @@ -0,0 +1,14 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import warnings + +from mmseg.registry import TASK_UTILS + +PIXEL_SAMPLERS = TASK_UTILS + + +def build_pixel_sampler(cfg, **default_args): + """Build pixel sampler for segmentation map.""" + warnings.warn( + '``build_pixel_sampler`` would be deprecated soon, please use ' + '``mmseg.registry.TASK_UTILS.build()`` ') + return TASK_UTILS.build(cfg, default_args=default_args) diff --git a/reconstruction/modules/InterFormer/mmseg/structures/sampler/ohem_pixel_sampler.py b/reconstruction/modules/InterFormer/mmseg/structures/sampler/ohem_pixel_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..a974273cab504be269e7f391e23a521b97bd8588 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/structures/sampler/ohem_pixel_sampler.py @@ -0,0 +1,85 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .base_pixel_sampler import BasePixelSampler +from .builder import PIXEL_SAMPLERS + + +@PIXEL_SAMPLERS.register_module() +class OHEMPixelSampler(BasePixelSampler): + """Online Hard Example Mining Sampler for segmentation. + + Args: + context (nn.Module): The context of sampler, subclass of + :obj:`BaseDecodeHead`. + thresh (float, optional): The threshold for hard example selection. + Below which, are prediction with low confidence. If not + specified, the hard examples will be pixels of top ``min_kept`` + loss. Default: None. + min_kept (int, optional): The minimum number of predictions to keep. + Default: 100000. + """ + + def __init__(self, context, thresh=None, min_kept=100000): + super().__init__() + self.context = context + assert min_kept > 1 + self.thresh = thresh + self.min_kept = min_kept + + def sample(self, seg_logit, seg_label): + """Sample pixels that have high loss or with low prediction confidence. + + Args: + seg_logit (torch.Tensor): segmentation logits, shape (N, C, H, W) + seg_label (torch.Tensor): segmentation label, shape (N, 1, H, W) + + Returns: + torch.Tensor: segmentation weight, shape (N, H, W) + """ + with torch.no_grad(): + assert seg_logit.shape[2:] == seg_label.shape[2:] + assert seg_label.shape[1] == 1 + seg_label = seg_label.squeeze(1).long() + batch_kept = self.min_kept * seg_label.size(0) + valid_mask = seg_label != self.context.ignore_index + seg_weight = seg_logit.new_zeros(size=seg_label.size()) + valid_seg_weight = seg_weight[valid_mask] + if self.thresh is not None: + seg_prob = F.softmax(seg_logit, dim=1) + + tmp_seg_label = seg_label.clone().unsqueeze(1) + tmp_seg_label[tmp_seg_label == self.context.ignore_index] = 0 + seg_prob = seg_prob.gather(1, tmp_seg_label).squeeze(1) + sort_prob, sort_indices = seg_prob[valid_mask].sort() + + if sort_prob.numel() > 0: + min_threshold = sort_prob[min(batch_kept, + sort_prob.numel() - 1)] + else: + min_threshold = 0.0 + threshold = max(min_threshold, self.thresh) + valid_seg_weight[seg_prob[valid_mask] < threshold] = 1. + else: + if not isinstance(self.context.loss_decode, nn.ModuleList): + losses_decode = [self.context.loss_decode] + else: + losses_decode = self.context.loss_decode + losses = 0.0 + for loss_module in losses_decode: + losses += loss_module( + seg_logit, + seg_label, + weight=None, + ignore_index=self.context.ignore_index, + reduction_override='none') + + # faster than topk according to https://github.com/pytorch/pytorch/issues/22812 # noqa + _, sort_indices = losses[valid_mask].sort(descending=True) + valid_seg_weight[sort_indices[:batch_kept]] = 1. + + seg_weight[valid_mask] = valid_seg_weight + + return seg_weight diff --git a/reconstruction/modules/InterFormer/mmseg/structures/seg_data_sample.py b/reconstruction/modules/InterFormer/mmseg/structures/seg_data_sample.py new file mode 100644 index 0000000000000000000000000000000000000000..ce68b5474330e2149d7d1c4de2d2406ae5b0345e --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/structures/seg_data_sample.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmengine.structures import BaseDataElement, PixelData + + +class SegDataSample(BaseDataElement): + """A data structure interface of MMSegmentation. They are used as + interfaces between different components. + + The attributes in ``SegDataSample`` are divided into several parts: + + - ``gt_sem_seg``(PixelData): Ground truth of semantic segmentation. + - ``pred_sem_seg``(PixelData): Prediction of semantic segmentation. + - ``seg_logits``(PixelData): Predicted logits of semantic segmentation. + + Examples: + >>> import torch + >>> import numpy as np + >>> from mmengine.structures import PixelData + >>> from mmseg.structures import SegDataSample + + >>> data_sample = SegDataSample() + >>> img_meta = dict(img_shape=(4, 4, 3), + ... pad_shape=(4, 4, 3)) + >>> gt_segmentations = PixelData(metainfo=img_meta) + >>> gt_segmentations.data = torch.randint(0, 2, (1, 4, 4)) + >>> data_sample.gt_sem_seg = gt_segmentations + >>> assert 'img_shape' in data_sample.gt_sem_seg.metainfo_keys() + >>> data_sample.gt_sem_seg.shape + (4, 4) + >>> print(data_sample) + + ) at 0x1c2aae44d60> + + >>> data_sample = SegDataSample() + >>> gt_sem_seg_data = dict(sem_seg=torch.rand(1, 4, 4)) + >>> gt_sem_seg = PixelData(**gt_sem_seg_data) + >>> data_sample.gt_sem_seg = gt_sem_seg + >>> assert 'gt_sem_seg' in data_sample + >>> assert 'sem_seg' in data_sample.gt_sem_seg + """ + + @property + def gt_sem_seg(self) -> PixelData: + return self._gt_sem_seg + + @gt_sem_seg.setter + def gt_sem_seg(self, value: PixelData) -> None: + self.set_field(value, '_gt_sem_seg', dtype=PixelData) + + @gt_sem_seg.deleter + def gt_sem_seg(self) -> None: + del self._gt_sem_seg + + @property + def pred_sem_seg(self) -> PixelData: + return self._pred_sem_seg + + @pred_sem_seg.setter + def pred_sem_seg(self, value: PixelData) -> None: + self.set_field(value, '_pred_sem_seg', dtype=PixelData) + + @pred_sem_seg.deleter + def pred_sem_seg(self) -> None: + del self._pred_sem_seg + + @property + def seg_logits(self) -> PixelData: + return self._seg_logits + + @seg_logits.setter + def seg_logits(self, value: PixelData) -> None: + self.set_field(value, '_seg_logits', dtype=PixelData) + + @seg_logits.deleter + def seg_logits(self) -> None: + del self._seg_logits diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__init__.py b/reconstruction/modules/InterFormer/mmseg/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0a2af58c6e0316d6f961df81160f3fc61a8a29e3 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/__init__.py @@ -0,0 +1,70 @@ +# Copyright (c) OpenMMLab. All rights reserved. +# yapf: disable +from .class_names import (ade_classes, ade_palette, bdd100k_classes, + bdd100k_palette, cityscapes_classes, + cityscapes_palette, cocostuff_classes, + cocostuff_palette, dataset_aliases, get_classes, + get_palette, isaid_classes, isaid_palette, + loveda_classes, loveda_palette, potsdam_classes, + potsdam_palette, stare_classes, stare_palette, + synapse_classes, synapse_palette, vaihingen_classes, + vaihingen_palette, voc_classes, voc_palette) +# yapf: enable +from .collect_env import collect_env +from .get_templates import get_predefined_templates +from .io import datafrombytes +from .misc import add_prefix, stack_batch +from .set_env import register_all_modules +from .tokenizer import tokenize +from .typing_utils import (ConfigType, ForwardResults, MultiConfig, + OptConfigType, OptMultiConfig, OptSampleList, + SampleList, TensorDict, TensorList) + +# isort: off +from .mask_classification import MatchMasks, seg_data_to_instance_data + +__all__ = [ + 'collect_env', + 'register_all_modules', + 'stack_batch', + 'add_prefix', + 'ConfigType', + 'OptConfigType', + 'MultiConfig', + 'OptMultiConfig', + 'SampleList', + 'OptSampleList', + 'TensorDict', + 'TensorList', + 'ForwardResults', + 'cityscapes_classes', + 'ade_classes', + 'voc_classes', + 'cocostuff_classes', + 'loveda_classes', + 'potsdam_classes', + 'vaihingen_classes', + 'isaid_classes', + 'stare_classes', + 'cityscapes_palette', + 'ade_palette', + 'voc_palette', + 'cocostuff_palette', + 'loveda_palette', + 'potsdam_palette', + 'vaihingen_palette', + 'isaid_palette', + 'stare_palette', + 'dataset_aliases', + 'get_classes', + 'get_palette', + 'datafrombytes', + 'synapse_palette', + 'synapse_classes', + 'get_predefined_templates', + 'tokenize', + 'seg_data_to_instance_data', + 'MatchMasks', + 'bdd100k_classes', + 'bdd100k_palette', +] diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef127f132b394beedca78c1ae14d817ccf1bdfe5 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bbb74281f672a20ed185d1ca262fbc1a81263c7 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/class_names.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/class_names.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dcf2c12ddf0ffa02886cf0f2e44fe9bffcc0790 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/class_names.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/class_names.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/class_names.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54733045a807af0b441fd2215655384c6678fb24 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/class_names.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/collect_env.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/collect_env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..053c4bb862ccd240f2b6725172b7ae4b8ddb96b7 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/collect_env.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/collect_env.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/collect_env.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..883d09cb80aafea086851358de2d0a7c5ed899b6 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/collect_env.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/get_templates.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/get_templates.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf7d537dc891b3b5144c50de8b76884aad4e69ff Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/get_templates.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/get_templates.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/get_templates.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..601d81ae230683f2c9262856c0d273abd2bfd681 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/get_templates.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/io.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/io.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e3f1e45b9d6ae1f8fb2b8e3ce8f2916bd13bc49 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/io.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/io.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/io.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b3a349ac63ab4e06b026d99d4a323e1fb7012b7 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/io.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/mask_classification.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/mask_classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b012412ceb68a179811f6927d653f71327b8720a Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/mask_classification.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/mask_classification.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/mask_classification.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..408a1bca881e3b1a999cdd59ba824fd67fa49c1f Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/mask_classification.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/misc.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/misc.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b952916a4c6cffcd39622b37ea0fa07dd70f6799 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/misc.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/misc.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/misc.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d44213ffb07ef9ac41b61fd755202db5ec5a365f Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/misc.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/set_env.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/set_env.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abf8e0cbced350e3b22fc1e1e5ddb5b8db6e2e82 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/set_env.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/set_env.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/set_env.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e87dd522e41119cad5f9856d14085fc28a5103e3 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/set_env.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/tokenizer.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/tokenizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a951699c45190c95c390c8f276a729f26d7ab7e0 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/tokenizer.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/tokenizer.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/tokenizer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d501605f44b1d7d68edafd9722333c04194d4a7a Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/tokenizer.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/typing_utils.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/typing_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c18c130e6c1e04a31e99d0c62e06666d86adeb9 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/typing_utils.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/typing_utils.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/typing_utils.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c92d18d22b157286274fe0025745d348729b2c0 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/utils/__pycache__/typing_utils.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/utils/bpe_simple_vocab_16e6.txt.gz b/reconstruction/modules/InterFormer/mmseg/utils/bpe_simple_vocab_16e6.txt.gz new file mode 100644 index 0000000000000000000000000000000000000000..36a15856e00a06a9fbed8cdd34d2393fea4a3113 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/bpe_simple_vocab_16e6.txt.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:924691ac288e54409236115652ad4aa250f48203de50a9e4722a6ecd48d6804a +size 1356917 diff --git a/reconstruction/modules/InterFormer/mmseg/utils/class_names.py b/reconstruction/modules/InterFormer/mmseg/utils/class_names.py new file mode 100644 index 0000000000000000000000000000000000000000..644e955966ce81fca6a82ffb0bd6d9781eae61bc --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/class_names.py @@ -0,0 +1,548 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmengine.utils import is_str + + +def cityscapes_classes(): + """Cityscapes class names for external use.""" + return [ + 'road', 'sidewalk', 'building', 'wall', 'fence', 'pole', + 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', + 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', + 'bicycle' + ] + + +def ade_classes(): + """ADE20K class names for external use.""" + return [ + 'wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed ', + 'windowpane', 'grass', 'cabinet', 'sidewalk', 'person', 'earth', + 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', + 'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mirror', 'rug', + 'field', 'armchair', 'seat', 'fence', 'desk', 'rock', 'wardrobe', + 'lamp', 'bathtub', 'railing', 'cushion', 'base', 'box', 'column', + 'signboard', 'chest of drawers', 'counter', 'sand', 'sink', + 'skyscraper', 'fireplace', 'refrigerator', 'grandstand', 'path', + 'stairs', 'runway', 'case', 'pool table', 'pillow', 'screen door', + 'stairway', 'river', 'bridge', 'bookcase', 'blind', 'coffee table', + 'toilet', 'flower', 'book', 'hill', 'bench', 'countertop', 'stove', + 'palm', 'kitchen island', 'computer', 'swivel chair', 'boat', 'bar', + 'arcade machine', 'hovel', 'bus', 'towel', 'light', 'truck', 'tower', + 'chandelier', 'awning', 'streetlight', 'booth', 'television receiver', + 'airplane', 'dirt track', 'apparel', 'pole', 'land', 'bannister', + 'escalator', 'ottoman', 'bottle', 'buffet', 'poster', 'stage', 'van', + 'ship', 'fountain', 'conveyer belt', 'canopy', 'washer', 'plaything', + 'swimming pool', 'stool', 'barrel', 'basket', 'waterfall', 'tent', + 'bag', 'minibike', 'cradle', 'oven', 'ball', 'food', 'step', 'tank', + 'trade name', 'microwave', 'pot', 'animal', 'bicycle', 'lake', + 'dishwasher', 'screen', 'blanket', 'sculpture', 'hood', 'sconce', + 'vase', 'traffic light', 'tray', 'ashcan', 'fan', 'pier', 'crt screen', + 'plate', 'monitor', 'bulletin board', 'shower', 'radiator', 'glass', + 'clock', 'flag' + ] + + +def voc_classes(): + """Pascal VOC class names for external use.""" + return [ + 'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', + 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', + 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', + 'tvmonitor' + ] + + +def pcontext_classes(): + """Pascal Context class names for external use.""" + return [ + 'aeroplane', 'bag', 'bed', 'bedclothes', 'bench', 'bicycle', 'bird', + 'boat', 'book', 'bottle', 'building', 'bus', 'cabinet', 'car', 'cat', + 'ceiling', 'chair', 'cloth', 'computer', 'cow', 'cup', 'curtain', + 'dog', 'door', 'fence', 'floor', 'flower', 'food', 'grass', 'ground', + 'horse', 'keyboard', 'light', 'motorbike', 'mountain', 'mouse', + 'person', 'plate', 'platform', 'pottedplant', 'road', 'rock', 'sheep', + 'shelves', 'sidewalk', 'sign', 'sky', 'snow', 'sofa', 'table', 'track', + 'train', 'tree', 'truck', 'tvmonitor', 'wall', 'water', 'window', + 'wood' + ] + + +def cocostuff_classes(): + """CocoStuff class names for external use.""" + return [ + 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', + 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', + 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', + 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', + 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', + 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', + 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', + 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', + 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', + 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', + 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', + 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', + 'scissors', 'teddy bear', 'hair drier', 'toothbrush', 'banner', + 'blanket', 'branch', 'bridge', 'building-other', 'bush', 'cabinet', + 'cage', 'cardboard', 'carpet', 'ceiling-other', 'ceiling-tile', + 'cloth', 'clothes', 'clouds', 'counter', 'cupboard', 'curtain', + 'desk-stuff', 'dirt', 'door-stuff', 'fence', 'floor-marble', + 'floor-other', 'floor-stone', 'floor-tile', 'floor-wood', 'flower', + 'fog', 'food-other', 'fruit', 'furniture-other', 'grass', 'gravel', + 'ground-other', 'hill', 'house', 'leaves', 'light', 'mat', 'metal', + 'mirror-stuff', 'moss', 'mountain', 'mud', 'napkin', 'net', 'paper', + 'pavement', 'pillow', 'plant-other', 'plastic', 'platform', + 'playingfield', 'railing', 'railroad', 'river', 'road', 'rock', 'roof', + 'rug', 'salad', 'sand', 'sea', 'shelf', 'sky-other', 'skyscraper', + 'snow', 'solid-other', 'stairs', 'stone', 'straw', 'structural-other', + 'table', 'tent', 'textile-other', 'towel', 'tree', 'vegetable', + 'wall-brick', 'wall-concrete', 'wall-other', 'wall-panel', + 'wall-stone', 'wall-tile', 'wall-wood', 'water-other', 'waterdrops', + 'window-blind', 'window-other', 'wood' + ] + + +def loveda_classes(): + """LoveDA class names for external use.""" + return [ + 'background', 'building', 'road', 'water', 'barren', 'forest', + 'agricultural' + ] + + +def potsdam_classes(): + """Potsdam class names for external use.""" + return [ + 'impervious_surface', 'building', 'low_vegetation', 'tree', 'car', + 'clutter' + ] + + +def vaihingen_classes(): + """Vaihingen class names for external use.""" + return [ + 'impervious_surface', 'building', 'low_vegetation', 'tree', 'car', + 'clutter' + ] + + +def isaid_classes(): + """iSAID class names for external use.""" + return [ + 'background', 'ship', 'store_tank', 'baseball_diamond', 'tennis_court', + 'basketball_court', 'Ground_Track_Field', 'Bridge', 'Large_Vehicle', + 'Small_Vehicle', 'Helicopter', 'Swimming_pool', 'Roundabout', + 'Soccer_ball_field', 'plane', 'Harbor' + ] + + +def stare_classes(): + """stare class names for external use.""" + return ['background', 'vessel'] + + +def mapillary_v1_classes(): + """mapillary_v1 class names for external use.""" + return [ + 'Bird', 'Ground Animal', 'Curb', 'Fence', 'Guard Rail', 'Barrier', + 'Wall', 'Bike Lane', 'Crosswalk - Plain', 'Curb Cut', 'Parking', + 'Pedestrian Area', 'Rail Track', 'Road', 'Service Lane', 'Sidewalk', + 'Bridge', 'Building', 'Tunnel', 'Person', 'Bicyclist', 'Motorcyclist', + 'Other Rider', 'Lane Marking - Crosswalk', 'Lane Marking - General', + 'Mountain', 'Sand', 'Sky', 'Snow', 'Terrain', 'Vegetation', 'Water', + 'Banner', 'Bench', 'Bike Rack', 'Billboard', 'Catch Basin', + 'CCTV Camera', 'Fire Hydrant', 'Junction Box', 'Mailbox', 'Manhole', + 'Phone Booth', 'Pothole', 'Street Light', 'Pole', 'Traffic Sign Frame', + 'Utility Pole', 'Traffic Light', 'Traffic Sign (Back)', + 'Traffic Sign (Front)', 'Trash Can', 'Bicycle', 'Boat', 'Bus', 'Car', + 'Caravan', 'Motorcycle', 'On Rails', 'Other Vehicle', 'Trailer', + 'Truck', 'Wheeled Slow', 'Car Mount', 'Ego Vehicle', 'Unlabeled' + ] + + +def mapillary_v1_palette(): + """mapillary_v1_ palette for external use.""" + return [[165, 42, 42], [0, 192, 0], [196, 196, 196], [190, 153, 153], + [180, 165, 180], [90, 120, 150], [102, 102, 156], [128, 64, 255], + [140, 140, 200], [170, 170, 170], [250, 170, 160], [96, 96, 96], + [230, 150, 140], [128, 64, 128], [110, 110, 110], [244, 35, 232], + [150, 100, 100], [70, 70, 70], [150, 120, 90], [220, 20, 60], + [255, 0, 0], [255, 0, 100], [255, 0, 200], [200, 128, 128], + [255, 255, 255], [64, 170, 64], [230, 160, 50], [70, 130, 180], + [190, 255, 255], [152, 251, 152], [107, 142, 35], [0, 170, 30], + [255, 255, 128], [250, 0, 30], [100, 140, 180], [220, 220, 220], + [220, 128, 128], [222, 40, 40], [100, 170, 30], [40, 40, 40], + [33, 33, 33], [100, 128, 160], [142, 0, 0], [70, 100, 150], + [210, 170, 100], [153, 153, 153], [128, 128, 128], [0, 0, 80], + [250, 170, 30], [192, 192, 192], [220, 220, 0], [140, 140, 20], + [119, 11, 32], [150, 0, 255], [0, 60, 100], [0, 0, 142], + [0, 0, 90], [0, 0, 230], [0, 80, 100], [128, 64, 64], [0, 0, 110], + [0, 0, 70], [0, 0, 192], [32, 32, 32], [120, 10, 10], [0, 0, 0]] + + +def mapillary_v2_classes(): + """mapillary_v2 class names for external use.""" + return [ + 'Bird', 'Ground Animal', 'Ambiguous Barrier', 'Concrete Block', 'Curb', + 'Fence', 'Guard Rail', 'Barrier', 'Road Median', 'Road Side', + 'Lane Separator', 'Temporary Barrier', 'Wall', 'Bike Lane', + 'Crosswalk - Plain', 'Curb Cut', 'Driveway', 'Parking', + 'Parking Aisle', 'Pedestrian Area', 'Rail Track', 'Road', + 'Road Shoulder', 'Service Lane', 'Sidewalk', 'Traffic Island', + 'Bridge', 'Building', 'Garage', 'Tunnel', 'Person', 'Person Group', + 'Bicyclist', 'Motorcyclist', 'Other Rider', + 'Lane Marking - Dashed Line', 'Lane Marking - Straight Line', + 'Lane Marking - Zigzag Line', 'Lane Marking - Ambiguous', + 'Lane Marking - Arrow (Left)', 'Lane Marking - Arrow (Other)', + 'Lane Marking - Arrow (Right)', + 'Lane Marking - Arrow (Split Left or Straight)', + 'Lane Marking - Arrow (Split Right or Straight)', + 'Lane Marking - Arrow (Straight)', 'Lane Marking - Crosswalk', + 'Lane Marking - Give Way (Row)', 'Lane Marking - Give Way (Single)', + 'Lane Marking - Hatched (Chevron)', + 'Lane Marking - Hatched (Diagonal)', 'Lane Marking - Other', + 'Lane Marking - Stop Line', 'Lane Marking - Symbol (Bicycle)', + 'Lane Marking - Symbol (Other)', 'Lane Marking - Text', + 'Lane Marking (only) - Dashed Line', 'Lane Marking (only) - Crosswalk', + 'Lane Marking (only) - Other', 'Lane Marking (only) - Test', + 'Mountain', 'Sand', 'Sky', 'Snow', 'Terrain', 'Vegetation', 'Water', + 'Banner', 'Bench', 'Bike Rack', 'Catch Basin', 'CCTV Camera', + 'Fire Hydrant', 'Junction Box', 'Mailbox', 'Manhole', 'Parking Meter', + 'Phone Booth', 'Pothole', 'Signage - Advertisement', + 'Signage - Ambiguous', 'Signage - Back', 'Signage - Information', + 'Signage - Other', 'Signage - Store', 'Street Light', 'Pole', + 'Pole Group', 'Traffic Sign Frame', 'Utility Pole', 'Traffic Cone', + 'Traffic Light - General (Single)', 'Traffic Light - Pedestrians', + 'Traffic Light - General (Upright)', + 'Traffic Light - General (Horizontal)', 'Traffic Light - Cyclists', + 'Traffic Light - Other', 'Traffic Sign - Ambiguous', + 'Traffic Sign (Back)', 'Traffic Sign - Direction (Back)', + 'Traffic Sign - Direction (Front)', 'Traffic Sign (Front)', + 'Traffic Sign - Parking', 'Traffic Sign - Temporary (Back)', + 'Traffic Sign - Temporary (Front)', 'Trash Can', 'Bicycle', 'Boat', + 'Bus', 'Car', 'Caravan', 'Motorcycle', 'On Rails', 'Other Vehicle', + 'Trailer', 'Truck', 'Vehicle Group', 'Wheeled Slow', 'Water Valve', + 'Car Mount', 'Dynamic', 'Ego Vehicle', 'Ground', 'Static', 'Unlabeled' + ] + + +def mapillary_v2_palette(): + """mapillary_v2_ palette for external use.""" + return [[165, 42, 42], [0, 192, 0], [250, 170, 31], [250, 170, 32], + [196, 196, 196], [190, 153, 153], [180, 165, 180], [90, 120, 150], + [250, 170, 33], [250, 170, 34], [128, 128, 128], [250, 170, 35], + [102, 102, 156], [128, 64, 255], [140, 140, 200], [170, 170, 170], + [250, 170, 36], [250, 170, 160], [250, 170, 37], [96, 96, 96], + [230, 150, 140], [128, 64, 128], [110, 110, 110], [110, 110, 110], + [244, 35, 232], [128, 196, 128], [150, 100, 100], [70, 70, 70], + [150, 150, 150], [150, 120, 90], [220, 20, 60], [220, 20, 60], + [255, 0, 0], [255, 0, 100], [255, 0, 200], [255, 255, 255], + [255, 255, 255], [250, 170, 29], [250, 170, 28], [250, 170, 26], + [250, 170, 25], [250, 170, 24], [250, 170, 22], [250, 170, 21], + [250, 170, 20], [255, 255, 255], [250, 170, 19], [250, 170, 18], + [250, 170, 12], [250, 170, 11], [255, 255, 255], [255, 255, 255], + [250, 170, 16], [250, 170, 15], [250, 170, 15], [255, 255, 255], + [255, 255, 255], [255, 255, 255], [255, 255, 255], [64, 170, 64], + [230, 160, 50], [70, 130, 180], [190, 255, 255], [152, 251, 152], + [107, 142, 35], [0, 170, 30], [255, 255, 128], [250, 0, 30], + [100, 140, 180], [220, 128, 128], [222, 40, 40], [100, 170, 30], + [40, 40, 40], [33, 33, 33], [100, 128, 160], [20, 20, 255], + [142, 0, 0], [70, 100, 150], [250, 171, 30], [250, 172, 30], + [250, 173, 30], [250, 174, 30], [250, 175, 30], [250, 176, 30], + [210, 170, 100], [153, 153, 153], [153, 153, 153], [128, 128, 128], + [0, 0, 80], [210, 60, 60], [250, 170, 30], [250, 170, 30], + [250, 170, 30], [250, 170, 30], [250, 170, 30], [250, 170, 30], + [192, 192, 192], [192, 192, 192], [192, 192, 192], [220, 220, 0], + [220, 220, 0], [0, 0, 196], [192, 192, 192], [220, 220, 0], + [140, 140, 20], [119, 11, 32], [150, 0, 255], [0, 60, 100], + [0, 0, 142], [0, 0, 90], [0, 0, 230], [0, 80, 100], [128, 64, 64], + [0, 0, 110], [0, 0, 70], [0, 0, 142], [0, 0, 192], [170, 170, 170], + [32, 32, 32], [111, 74, 0], [120, 10, 10], [81, 0, 81], + [111, 111, 0], [0, 0, 0]] + + +def cityscapes_palette(): + """Cityscapes palette for external use.""" + return [[128, 64, 128], [244, 35, 232], [70, 70, 70], [102, 102, 156], + [190, 153, 153], [153, 153, 153], [250, 170, 30], [220, 220, 0], + [107, 142, 35], [152, 251, 152], [70, 130, 180], [220, 20, 60], + [255, 0, 0], [0, 0, 142], [0, 0, 70], [0, 60, 100], [0, 80, 100], + [0, 0, 230], [119, 11, 32]] + + +def ade_palette(): + """ADE20K palette for external use.""" + return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50], + [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255], + [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7], + [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82], + [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3], + [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255], + [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220], + [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224], + [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255], + [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7], + [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153], + [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255], + [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0], + [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255], + [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255], + [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255], + [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0], + [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0], + [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255], + [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255], + [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20], + [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255], + [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255], + [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255], + [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0], + [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0], + [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255], + [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112], + [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160], + [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163], + [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0], + [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0], + [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255], + [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204], + [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255], + [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255], + [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194], + [102, 255, 0], [92, 0, 255]] + + +def voc_palette(): + """Pascal VOC palette for external use.""" + return [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], + [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], + [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], + [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], + [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64, 128]] + + +def pcontext_palette(): + """Pascal Context palette for external use.""" + return [[180, 120, 120], [6, 230, 230], [80, 50, 50], [4, 200, 3], + [120, 120, 80], [140, 140, 140], [204, 5, 255], [230, 230, 230], + [4, 250, 7], [224, 5, 255], [235, 255, 7], [150, 5, 61], + [120, 120, 70], [8, 255, 51], [255, 6, 82], [143, 255, 140], + [204, 255, 4], [255, 51, 7], [204, 70, 3], [0, 102, 200], + [61, 230, 250], [255, 6, 51], [11, 102, 255], [255, 7, 71], + [255, 9, 224], [9, 7, 230], [220, 220, 220], [255, 9, 92], + [112, 9, 255], [8, 255, 214], [7, 255, 224], [255, 184, 6], + [10, 255, 71], [255, 41, 10], [7, 255, 255], [224, 255, 8], + [102, 8, 255], [255, 61, 6], [255, 194, 7], [255, 122, 8], + [0, 255, 20], [255, 8, 41], [255, 5, 153], [6, 51, 255], + [235, 12, 255], [160, 150, 20], [0, 163, 255], [140, 140, 140], + [250, 10, 15], [20, 255, 0], [31, 255, 0], [255, 31, 0], + [255, 224, 0], [153, 255, 0], [0, 0, 255], [255, 71, 0], + [0, 235, 255], [0, 173, 255], [31, 0, 255]] + + +def cocostuff_palette(): + """CocoStuff palette for external use.""" + return [[0, 192, 64], [0, 192, 64], [0, 64, 96], [128, 192, 192], + [0, 64, 64], [0, 192, 224], [0, 192, 192], [128, 192, 64], + [0, 192, 96], [128, 192, 64], [128, 32, 192], [0, 0, 224], + [0, 0, 64], [0, 160, 192], [128, 0, 96], [128, 0, 192], + [0, 32, 192], [128, 128, 224], [0, 0, 192], [128, 160, 192], + [128, 128, 0], [128, 0, 32], [128, 32, 0], [128, 0, 128], + [64, 128, 32], [0, 160, 0], [0, 0, 0], [192, 128, 160], [0, 32, 0], + [0, 128, 128], [64, 128, 160], [128, 160, 0], [0, 128, 0], + [192, 128, 32], [128, 96, 128], [0, 0, 128], [64, 0, 32], + [0, 224, 128], [128, 0, 0], [192, 0, 160], [0, 96, 128], + [128, 128, 128], [64, 0, 160], [128, 224, 128], [128, 128, 64], + [192, 0, 32], [128, 96, 0], [128, 0, 192], [0, 128, 32], + [64, 224, 0], [0, 0, 64], [128, 128, 160], [64, 96, 0], + [0, 128, 192], [0, 128, 160], [192, 224, 0], [0, 128, 64], + [128, 128, 32], [192, 32, 128], [0, 64, 192], [0, 0, 32], + [64, 160, 128], [128, 64, 64], [128, 0, 160], [64, 32, 128], + [128, 192, 192], [0, 0, 160], [192, 160, 128], [128, 192, 0], + [128, 0, 96], [192, 32, 0], [128, 64, 128], [64, 128, 96], + [64, 160, 0], [0, 64, 0], [192, 128, 224], [64, 32, 0], + [0, 192, 128], [64, 128, 224], [192, 160, 0], [0, 192, 0], + [192, 128, 96], [192, 96, 128], [0, 64, 128], [64, 0, 96], + [64, 224, 128], [128, 64, 0], [192, 0, 224], [64, 96, 128], + [128, 192, 128], [64, 0, 224], [192, 224, 128], [128, 192, 64], + [192, 0, 96], [192, 96, 0], [128, 64, 192], [0, 128, 96], + [0, 224, 0], [64, 64, 64], [128, 128, 224], [0, 96, 0], + [64, 192, 192], [0, 128, 224], [128, 224, 0], [64, 192, 64], + [128, 128, 96], [128, 32, 128], [64, 0, 192], [0, 64, 96], + [0, 160, 128], [192, 0, 64], [128, 64, 224], [0, 32, 128], + [192, 128, 192], [0, 64, 224], [128, 160, 128], [192, 128, 0], + [128, 64, 32], [128, 32, 64], [192, 0, 128], [64, 192, 32], + [0, 160, 64], [64, 0, 0], [192, 192, 160], [0, 32, 64], + [64, 128, 128], [64, 192, 160], [128, 160, 64], [64, 128, 0], + [192, 192, 32], [128, 96, 192], [64, 0, 128], [64, 64, 32], + [0, 224, 192], [192, 0, 0], [192, 64, 160], [0, 96, 192], + [192, 128, 128], [64, 64, 160], [128, 224, 192], [192, 128, 64], + [192, 64, 32], [128, 96, 64], [192, 0, 192], [0, 192, 32], + [64, 224, 64], [64, 0, 64], [128, 192, 160], [64, 96, 64], + [64, 128, 192], [0, 192, 160], [192, 224, 64], [64, 128, 64], + [128, 192, 32], [192, 32, 192], [64, 64, 192], [0, 64, 32], + [64, 160, 192], [192, 64, 64], [128, 64, 160], [64, 32, 192], + [192, 192, 192], [0, 64, 160], [192, 160, 192], [192, 192, 0], + [128, 64, 96], [192, 32, 64], [192, 64, 128], [64, 192, 96], + [64, 160, 64], [64, 64, 0]] + + +def loveda_palette(): + """LoveDA palette for external use.""" + return [[255, 255, 255], [255, 0, 0], [255, 255, 0], [0, 0, 255], + [159, 129, 183], [0, 255, 0], [255, 195, 128]] + + +def potsdam_palette(): + """Potsdam palette for external use.""" + return [[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0], + [255, 255, 0], [255, 0, 0]] + + +def vaihingen_palette(): + """Vaihingen palette for external use.""" + return [[255, 255, 255], [0, 0, 255], [0, 255, 255], [0, 255, 0], + [255, 255, 0], [255, 0, 0]] + + +def isaid_palette(): + """iSAID palette for external use.""" + return [[0, 0, 0], [0, 0, 63], [0, 63, 63], [0, 63, 0], [0, 63, 127], + [0, 63, 191], [0, 63, 255], [0, 127, 63], [0, 127, + 127], [0, 0, 127], + [0, 0, 191], [0, 0, 255], [0, 191, 127], [0, 127, 191], + [0, 127, 255], [0, 100, 155]] + + +def stare_palette(): + """STARE palette for external use.""" + return [[120, 120, 120], [6, 230, 230]] + + +def synapse_palette(): + """Synapse palette for external use.""" + return [[0, 0, 0], [0, 0, 255], [0, 255, 0], [255, 0, 0], [0, 255, 255], + [255, 0, 255], [255, 255, 0], [60, 255, 255], [240, 240, 240]] + + +def synapse_classes(): + """Synapse class names for external use.""" + return [ + 'background', 'aorta', 'gallbladder', 'left_kidney', 'right_kidney', + 'liver', 'pancreas', 'spleen', 'stomach' + ] + + +def lip_classes(): + """LIP class names for external use.""" + return [ + 'background', 'hat', 'hair', 'glove', 'sunglasses', 'upperclothes', + 'dress', 'coat', 'socks', 'pants', 'jumpsuits', 'scarf', 'skirt', + 'face', 'leftArm', 'rightArm', 'leftLeg', 'rightLeg', 'leftShoe', + 'rightShoe' + ] + + +def lip_palette(): + """LIP palette for external use.""" + return [ + 'Background', 'Hat', 'Hair', 'Glove', 'Sunglasses', 'UpperClothes', + 'Dress', 'Coat', 'Socks', 'Pants', 'Jumpsuits', 'Scarf', 'Skirt', + 'Face', 'Left-arm', 'Right-arm', 'Left-leg', 'Right-leg', 'Left-shoe', + 'Right-shoe' + ] + + +def bdd100k_classes(): + """BDD100K class names for external use(the class name is compatible with + Cityscapes ).""" + return [ + 'road', 'sidewalk', 'building', 'wall', 'fence', 'pole', + 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', + 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', + 'bicycle' + ] + + +def bdd100k_palette(): + """bdd100k palette for external use(same with cityscapes)""" + return [[128, 64, 128], [244, 35, 232], [70, 70, 70], [102, 102, 156], + [190, 153, 153], [153, 153, 153], [250, 170, 30], [220, 220, 0], + [107, 142, 35], [152, 251, 152], [70, 130, 180], [220, 20, 60], + [255, 0, 0], [0, 0, 142], [0, 0, 70], [0, 60, 100], [0, 80, 100], + [0, 0, 230], [119, 11, 32]] + + +def hsidrive_classes(): + """HSI Drive 2.0 class names for external use.""" + return [ + 'unlabelled', 'road', 'road marks', 'vegetation', 'painted metal', + 'sky', 'concrete', 'pedestrian', 'water', 'unpainted metal', 'glass' + ] + + +def hsidrive_palette(): + """HSI Drive 2.0 palette for external use.""" + return [[0, 0, 0], [77, 77, 77], [255, 255, 255], [0, 255, 0], [255, 0, 0], + [0, 0, 255], [102, 51, 0], [255, 255, 0], [0, 207, 250], + [255, 166, 0], [0, 204, 204]] + + +dataset_aliases = { + 'cityscapes': ['cityscapes'], + 'ade': ['ade', 'ade20k'], + 'voc': ['voc', 'pascal_voc', 'voc12', 'voc12aug'], + 'pcontext': ['pcontext', 'pascal_context', 'voc2010'], + 'loveda': ['loveda'], + 'potsdam': ['potsdam'], + 'vaihingen': ['vaihingen'], + 'cocostuff': [ + 'cocostuff', 'cocostuff10k', 'cocostuff164k', 'coco-stuff', + 'coco-stuff10k', 'coco-stuff164k', 'coco_stuff', 'coco_stuff10k', + 'coco_stuff164k' + ], + 'isaid': ['isaid', 'iSAID'], + 'stare': ['stare', 'STARE'], + 'lip': ['LIP', 'lip'], + 'mapillary_v1': ['mapillary_v1'], + 'mapillary_v2': ['mapillary_v2'], + 'bdd100k': ['bdd100k'], + 'hsidrive': [ + 'hsidrive', 'HSIDrive', 'HSI-Drive', 'hsidrive20', 'HSIDrive20', + 'HSI-Drive20' + ] +} + + +def get_classes(dataset): + """Get class names of a dataset.""" + alias2name = {} + for name, aliases in dataset_aliases.items(): + for alias in aliases: + alias2name[alias] = name + + if is_str(dataset): + if dataset in alias2name: + labels = eval(alias2name[dataset] + '_classes()') + else: + raise ValueError(f'Unrecognized dataset: {dataset}') + else: + raise TypeError(f'dataset must a str, but got {type(dataset)}') + return labels + + +def get_palette(dataset): + """Get class palette (RGB) of a dataset.""" + alias2name = {} + for name, aliases in dataset_aliases.items(): + for alias in aliases: + alias2name[alias] = name + + if is_str(dataset): + if dataset in alias2name: + labels = eval(alias2name[dataset] + '_palette()') + else: + raise ValueError(f'Unrecognized dataset: {dataset}') + else: + raise TypeError(f'dataset must a str, but got {type(dataset)}') + return labels diff --git a/reconstruction/modules/InterFormer/mmseg/utils/collect_env.py b/reconstruction/modules/InterFormer/mmseg/utils/collect_env.py new file mode 100644 index 0000000000000000000000000000000000000000..d5d6ea290283e3af2f29475f82d225072cf39d99 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/collect_env.py @@ -0,0 +1,18 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from mmengine.utils import get_git_hash +from mmengine.utils.dl_utils import collect_env as collect_base_env + +import mmseg + + +def collect_env(): + """Collect the information of the running environments.""" + env_info = collect_base_env() + env_info['MMSegmentation'] = f'{mmseg.__version__}+{get_git_hash()[:7]}' + + return env_info + + +if __name__ == '__main__': + for name, val in collect_env().items(): + print(f'{name}: {val}') diff --git a/reconstruction/modules/InterFormer/mmseg/utils/get_templates.py b/reconstruction/modules/InterFormer/mmseg/utils/get_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..7e9032ba96cbe750134676fe46fc26fb607779f5 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/get_templates.py @@ -0,0 +1,109 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List + +PREDEFINED_TEMPLATES = { + 'imagenet': [ + 'a bad photo of a {}.', + 'a photo of many {}.', + 'a sculpture of a {}.', + 'a photo of the hard to see {}.', + 'a low resolution photo of the {}.', + 'a rendering of a {}.', + 'graffiti of a {}.', + 'a bad photo of the {}.', + 'a cropped photo of the {}.', + 'a tattoo of a {}.', + 'the embroidered {}.', + 'a photo of a hard to see {}.', + 'a bright photo of a {}.', + 'a photo of a clean {}.', + 'a photo of a dirty {}.', + 'a dark photo of the {}.', + 'a drawing of a {}.', + 'a photo of my {}.', + 'the plastic {}.', + 'a photo of the cool {}.', + 'a close-up photo of a {}.', + 'a black and white photo of the {}.', + 'a painting of the {}.', + 'a painting of a {}.', + 'a pixelated photo of the {}.', + 'a sculpture of the {}.', + 'a bright photo of the {}.', + 'a cropped photo of a {}.', + 'a plastic {}.', + 'a photo of the dirty {}.', + 'a jpeg corrupted photo of a {}.', + 'a blurry photo of the {}.', + 'a photo of the {}.', + 'a good photo of the {}.', + 'a rendering of the {}.', + 'a {} in a video game.', + 'a photo of one {}.', + 'a doodle of a {}.', + 'a close-up photo of the {}.', + 'a photo of a {}.', + 'the origami {}.', + 'the {} in a video game.', + 'a sketch of a {}.', + 'a doodle of the {}.', + 'a origami {}.', + 'a low resolution photo of a {}.', + 'the toy {}.', + 'a rendition of the {}.', + 'a photo of the clean {}.', + 'a photo of a large {}.', + 'a rendition of a {}.', + 'a photo of a nice {}.', + 'a photo of a weird {}.', + 'a blurry photo of a {}.', + 'a cartoon {}.', + 'art of a {}.', + 'a sketch of the {}.', + 'a embroidered {}.', + 'a pixelated photo of a {}.', + 'itap of the {}.', + 'a jpeg corrupted photo of the {}.', + 'a good photo of a {}.', + 'a plushie {}.', + 'a photo of the nice {}.', + 'a photo of the small {}.', + 'a photo of the weird {}.', + 'the cartoon {}.', + 'art of the {}.', + 'a drawing of the {}.', + 'a photo of the large {}.', + 'a black and white photo of a {}.', + 'the plushie {}.', + 'a dark photo of a {}.', + 'itap of a {}.', + 'graffiti of the {}.', + 'a toy {}.', + 'itap of my {}.', + 'a photo of a cool {}.', + 'a photo of a small {}.', + 'a tattoo of the {}.', + ], + 'vild': [ + 'a photo of a {}.', + 'This is a photo of a {}', + 'There is a {} in the scene', + 'There is the {} in the scene', + 'a photo of a {} in the scene', + 'a photo of a small {}.', + 'a photo of a medium {}.', + 'a photo of a large {}.', + 'This is a photo of a small {}.', + 'This is a photo of a medium {}.', + 'This is a photo of a large {}.', + 'There is a small {} in the scene.', + 'There is a medium {} in the scene.', + 'There is a large {} in the scene.', + ], +} + + +def get_predefined_templates(template_set_name: str) -> List[str]: + if template_set_name not in PREDEFINED_TEMPLATES: + raise ValueError(f'Template set {template_set_name} not found') + return PREDEFINED_TEMPLATES[template_set_name] diff --git a/reconstruction/modules/InterFormer/mmseg/utils/io.py b/reconstruction/modules/InterFormer/mmseg/utils/io.py new file mode 100644 index 0000000000000000000000000000000000000000..7029c3cddda02c89cbb50cee9f8b7e7fa57378d9 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/io.py @@ -0,0 +1,42 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import gzip +import io +import pickle + +import cv2 +import numpy as np + + +def datafrombytes(content: bytes, backend: str = 'numpy') -> np.ndarray: + """Data decoding from bytes. + + Args: + content (bytes): The data bytes got from files or other streams. + backend (str): The data decoding backend type. Options are 'numpy', + 'nifti', 'cv2' and 'pickle'. Defaults to 'numpy'. + + Returns: + numpy.ndarray: Loaded data array. + """ + if backend == 'pickle': + data = pickle.loads(content) + else: + with io.BytesIO(content) as f: + if backend == 'nifti': + f = gzip.open(f) + try: + from nibabel import FileHolder, Nifti1Image + except ImportError: + print('nifti files io depends on nibabel, please run' + '`pip install nibabel` to install it') + fh = FileHolder(fileobj=f) + data = Nifti1Image.from_file_map({'header': fh, 'image': fh}) + data = Nifti1Image.from_bytes(data.to_bytes()).get_fdata() + elif backend == 'numpy': + data = np.load(f) + elif backend == 'cv2': + data = np.frombuffer(f.read(), dtype=np.uint8) + data = cv2.imdecode(data, cv2.IMREAD_UNCHANGED) + else: + raise ValueError + return data diff --git a/reconstruction/modules/InterFormer/mmseg/utils/mask_classification.py b/reconstruction/modules/InterFormer/mmseg/utils/mask_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..205d5259754abfe07e0d84ae0739cf08043815ff --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/mask_classification.py @@ -0,0 +1,205 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Tuple + +import torch +from mmcv.ops import point_sample +from mmengine.structures import InstanceData +from torch import Tensor + +from mmseg.registry import TASK_UTILS +from mmseg.utils import ConfigType, SampleList + + +def seg_data_to_instance_data(ignore_index: int, + batch_data_samples: SampleList): + """Convert the paradigm of ground truth from semantic segmentation to + instance segmentation. + + Args: + ignore_index (int): The label index to be ignored. + batch_data_samples (List[SegDataSample]): The Data + Samples. It usually includes information such as + `gt_sem_seg`. + + Returns: + tuple[Tensor]: A tuple contains two lists. + - batch_gt_instances (List[InstanceData]): Batch of + gt_instance. It usually includes ``labels``, each is + unique ground truth label id of images, with + shape (num_gt, ) and ``masks``, each is ground truth + masks of each instances of a image, shape (num_gt, h, w). + - batch_img_metas (List[Dict]): List of image meta information. + """ + batch_gt_instances = [] + + for data_sample in batch_data_samples: + gt_sem_seg = data_sample.gt_sem_seg.data + classes = torch.unique( + gt_sem_seg, + sorted=False, + return_inverse=False, + return_counts=False) + + # remove ignored region + gt_labels = classes[classes != ignore_index] + + masks = [] + for class_id in gt_labels: + masks.append(gt_sem_seg == class_id) + + if len(masks) == 0: + gt_masks = torch.zeros( + (0, gt_sem_seg.shape[-2], + gt_sem_seg.shape[-1])).to(gt_sem_seg).long() + else: + gt_masks = torch.stack(masks).squeeze(1).long() + + instance_data = InstanceData(labels=gt_labels, masks=gt_masks) + batch_gt_instances.append(instance_data) + return batch_gt_instances + + +class MatchMasks: + """Match the predictions to category labels. + + Args: + num_points (int): the number of sampled points to compute cost. + num_queries (int): the number of prediction masks. + num_classes (int): the number of classes. + assigner (BaseAssigner): the assigner to compute matching. + """ + + def __init__(self, + num_points: int, + num_queries: int, + num_classes: int, + assigner: ConfigType = None): + assert assigner is not None, "\'assigner\' in decode_head.train_cfg" \ + 'cannot be None' + assert num_points > 0, 'num_points should be a positive integer.' + self.num_points = num_points + self.num_queries = num_queries + self.num_classes = num_classes + self.assigner = TASK_UTILS.build(assigner) + + def get_targets(self, cls_scores: List[Tensor], mask_preds: List[Tensor], + batch_gt_instances: List[InstanceData]) -> Tuple: + """Compute best mask matches for all images for a decoder layer. + + Args: + cls_scores (List[Tensor]): Mask score logits from a single + decoder layer for all images. Each with shape (num_queries, + cls_out_channels). + mask_preds (List[Tensor]): Mask logits from a single decoder + layer for all images. Each with shape (num_queries, h, w). + batch_gt_instances (List[InstanceData]): each contains + ``labels`` and ``masks``. + + Returns: + tuple: a tuple containing the following targets. + + - labels (List[Tensor]): Labels of all images.\ + Each with shape (num_queries, ). + - mask_targets (List[Tensor]): Mask targets of\ + all images. Each with shape (num_queries, h, w). + - mask_weights (List[Tensor]): Mask weights of\ + all images. Each with shape (num_queries, ). + - avg_factor (int): Average factor that is used to + average the loss. `avg_factor` is usually equal + to the number of positive priors. + """ + batch_size = cls_scores.shape[0] + results = dict({ + 'labels': [], + 'mask_targets': [], + 'mask_weights': [], + }) + for i in range(batch_size): + labels, mask_targets, mask_weights\ + = self._get_targets_single(cls_scores[i], + mask_preds[i], + batch_gt_instances[i]) + results['labels'].append(labels) + results['mask_targets'].append(mask_targets) + results['mask_weights'].append(mask_weights) + + # shape (batch_size, num_queries) + labels = torch.stack(results['labels'], dim=0) + # shape (batch_size, num_gts, h, w) + mask_targets = torch.cat(results['mask_targets'], dim=0) + # shape (batch_size, num_queries) + mask_weights = torch.stack(results['mask_weights'], dim=0) + + avg_factor = sum( + [len(gt_instances.labels) for gt_instances in batch_gt_instances]) + + res = (labels, mask_targets, mask_weights, avg_factor) + + return res + + def _get_targets_single(self, cls_score: Tensor, mask_pred: Tensor, + gt_instances: InstanceData) \ + -> Tuple[Tensor, Tensor, Tensor]: + """Compute a set of best mask matches for one image. + + Args: + cls_score (Tensor): Mask score logits from a single decoder layer + for one image. Shape (num_queries, cls_out_channels). + mask_pred (Tensor): Mask logits for a single decoder layer for one + image. Shape (num_queries, h, w). + gt_instances (:obj:`InstanceData`): It contains ``labels`` and + ``masks``. + + Returns: + tuple[Tensor]: A tuple containing the following for one image. + + - labels (Tensor): Labels of each image. \ + shape (num_queries, ). + - mask_targets (Tensor): Mask targets of each image. \ + shape (num_queries, h, w). + - mask_weights (Tensor): Mask weights of each image. \ + shape (num_queries, ). + """ + gt_labels = gt_instances.labels + gt_masks = gt_instances.masks + # when "gt_labels" is empty, classify all queries to background + if len(gt_labels) == 0: + labels = gt_labels.new_full((self.num_queries, ), + self.num_classes, + dtype=torch.long) + mask_targets = gt_labels + mask_weights = gt_labels.new_zeros((self.num_queries, )) + return labels, mask_targets, mask_weights + # sample points + num_queries = cls_score.shape[0] + num_gts = gt_labels.shape[0] + + point_coords = torch.rand((1, self.num_points, 2), + device=cls_score.device) + # shape (num_queries, num_points) + mask_points_pred = point_sample( + mask_pred.unsqueeze(1), point_coords.repeat(num_queries, 1, + 1)).squeeze(1) + # shape (num_gts, num_points) + gt_points_masks = point_sample( + gt_masks.unsqueeze(1).float(), point_coords.repeat(num_gts, 1, + 1)).squeeze(1) + + sampled_gt_instances = InstanceData( + labels=gt_labels, masks=gt_points_masks) + sampled_pred_instances = InstanceData( + scores=cls_score, masks=mask_points_pred) + # assign and sample + matched_quiery_inds, matched_label_inds = self.assigner.assign( + pred_instances=sampled_pred_instances, + gt_instances=sampled_gt_instances) + labels = gt_labels.new_full((self.num_queries, ), + self.num_classes, + dtype=torch.long) + labels[matched_quiery_inds] = gt_labels[matched_label_inds] + + mask_weights = gt_labels.new_zeros((self.num_queries, )) + mask_weights[matched_quiery_inds] = 1 + mask_targets = gt_masks[matched_label_inds] + + return labels, mask_targets, mask_weights diff --git a/reconstruction/modules/InterFormer/mmseg/utils/misc.py b/reconstruction/modules/InterFormer/mmseg/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc469e8320d375135846cfb0474a0fc8d9b15d0 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/misc.py @@ -0,0 +1,128 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import List, Optional, Union + +import numpy as np +import torch +import torch.nn.functional as F + +from .typing_utils import SampleList + + +def add_prefix(inputs, prefix): + """Add prefix for dict. + + Args: + inputs (dict): The input dict with str keys. + prefix (str): The prefix to add. + + Returns: + + dict: The dict with keys updated with ``prefix``. + """ + + outputs = dict() + for name, value in inputs.items(): + outputs[f'{prefix}.{name}'] = value + + return outputs + + +def stack_batch(inputs: List[torch.Tensor], + data_samples: Optional[SampleList] = None, + size: Optional[tuple] = None, + size_divisor: Optional[int] = None, + pad_val: Union[int, float] = 0, + seg_pad_val: Union[int, float] = 255) -> torch.Tensor: + """Stack multiple inputs to form a batch and pad the images and gt_sem_segs + to the max shape use the right bottom padding mode. + + Args: + inputs (List[Tensor]): The input multiple tensors. each is a + CHW 3D-tensor. + data_samples (list[:obj:`SegDataSample`]): The list of data samples. + It usually includes information such as `gt_sem_seg`. + size (tuple, optional): Fixed padding size. + size_divisor (int, optional): The divisor of padded size. + pad_val (int, float): The padding value. Defaults to 0 + seg_pad_val (int, float): The padding value. Defaults to 255 + + Returns: + Tensor: The 4D-tensor. + List[:obj:`SegDataSample`]: After the padding of the gt_seg_map. + """ + assert isinstance(inputs, list), \ + f'Expected input type to be list, but got {type(inputs)}' + assert len({tensor.ndim for tensor in inputs}) == 1, \ + f'Expected the dimensions of all inputs must be the same, ' \ + f'but got {[tensor.ndim for tensor in inputs]}' + assert inputs[0].ndim == 3, f'Expected tensor dimension to be 3, ' \ + f'but got {inputs[0].ndim}' + assert len({tensor.shape[0] for tensor in inputs}) == 1, \ + f'Expected the channels of all inputs must be the same, ' \ + f'but got {[tensor.shape[0] for tensor in inputs]}' + + # only one of size and size_divisor should be valid + assert (size is not None) ^ (size_divisor is not None), \ + 'only one of size and size_divisor should be valid' + + padded_inputs = [] + padded_samples = [] + inputs_sizes = [(img.shape[-2], img.shape[-1]) for img in inputs] + max_size = np.stack(inputs_sizes).max(0) + if size_divisor is not None and size_divisor > 1: + # the last two dims are H,W, both subject to divisibility requirement + max_size = (max_size + + (size_divisor - 1)) // size_divisor * size_divisor + + for i in range(len(inputs)): + tensor = inputs[i] + if size is not None: + width = max(size[-1] - tensor.shape[-1], 0) + height = max(size[-2] - tensor.shape[-2], 0) + # (padding_left, padding_right, padding_top, padding_bottom) + padding_size = (0, width, 0, height) + elif size_divisor is not None: + width = max(max_size[-1] - tensor.shape[-1], 0) + height = max(max_size[-2] - tensor.shape[-2], 0) + padding_size = (0, width, 0, height) + else: + padding_size = [0, 0, 0, 0] + + # pad img + pad_img = F.pad(tensor, padding_size, value=pad_val) + padded_inputs.append(pad_img) + # pad gt_sem_seg + if data_samples is not None: + data_sample = data_samples[i] + pad_shape = None + if 'gt_sem_seg' in data_sample: + gt_sem_seg = data_sample.gt_sem_seg.data + del data_sample.gt_sem_seg.data + data_sample.gt_sem_seg.data = F.pad( + gt_sem_seg, padding_size, value=seg_pad_val) + pad_shape = data_sample.gt_sem_seg.shape + if 'gt_edge_map' in data_sample: + gt_edge_map = data_sample.gt_edge_map.data + del data_sample.gt_edge_map.data + data_sample.gt_edge_map.data = F.pad( + gt_edge_map, padding_size, value=seg_pad_val) + pad_shape = data_sample.gt_edge_map.shape + if 'gt_depth_map' in data_sample: + gt_depth_map = data_sample.gt_depth_map.data + del data_sample.gt_depth_map.data + data_sample.gt_depth_map.data = F.pad( + gt_depth_map, padding_size, value=seg_pad_val) + pad_shape = data_sample.gt_depth_map.shape + data_sample.set_metainfo({ + 'img_shape': tensor.shape[-2:], + 'pad_shape': pad_shape, + 'padding_size': padding_size + }) + padded_samples.append(data_sample) + else: + padded_samples.append( + dict( + img_padding_size=padding_size, + pad_shape=pad_img.shape[-2:])) + + return torch.stack(padded_inputs, dim=0), padded_samples diff --git a/reconstruction/modules/InterFormer/mmseg/utils/set_env.py b/reconstruction/modules/InterFormer/mmseg/utils/set_env.py new file mode 100644 index 0000000000000000000000000000000000000000..c948950d62a7463295c1055a27a9a0ce881d9fad --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/set_env.py @@ -0,0 +1,40 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import datetime +import warnings + +from mmengine import DefaultScope + + +def register_all_modules(init_default_scope: bool = True) -> None: + """Register all modules in mmseg into the registries. + + Args: + init_default_scope (bool): Whether initialize the mmseg default scope. + When `init_default_scope=True`, the global default scope will be + set to `mmseg`, and all registries will build modules from mmseg's + registry node. To understand more about the registry, please refer + to https://github.com/open-mmlab/mmengine/blob/main/docs/en/tutorials/registry.md + Defaults to True. + """ # noqa + import mmseg.datasets # noqa: F401,F403 + import mmseg.engine # noqa: F401,F403 + import mmseg.evaluation # noqa: F401,F403 + import mmseg.models # noqa: F401,F403 + import mmseg.structures # noqa: F401,F403 + + if init_default_scope: + never_created = DefaultScope.get_current_instance() is None \ + or not DefaultScope.check_instance_created('mmseg') + if never_created: + DefaultScope.get_instance('mmseg', scope_name='mmseg') + return + current_scope = DefaultScope.get_current_instance() + if current_scope.scope_name != 'mmseg': + warnings.warn('The current default scope ' + f'"{current_scope.scope_name}" is not "mmseg", ' + '`register_all_modules` will force the current' + 'default scope to be "mmseg". If this is not ' + 'expected, please set `init_default_scope=False`.') + # avoid name conflict + new_instance_name = f'mmseg-{datetime.datetime.now()}' + DefaultScope.get_instance(new_instance_name, scope_name='mmseg') diff --git a/reconstruction/modules/InterFormer/mmseg/utils/tokenizer.py b/reconstruction/modules/InterFormer/mmseg/utils/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..d56f5fae602506a27b9ae8835415e8dea7b611b7 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/tokenizer.py @@ -0,0 +1,240 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""CLIP tokenizer. + +Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright +(c) 2021 OpenAI. +""" +import gzip +import html +import os +from functools import lru_cache +from typing import List, Union + +import ftfy +import regex as re +import torch + +os.environ['TOKENIZERS_PARALLELISM'] = 'false' + + +@lru_cache() +def default_bpe(): + return os.path.join( + os.path.dirname(os.path.abspath(__file__)), + 'bpe_simple_vocab_16e6.txt.gz') + + +@lru_cache() +def bytes_to_unicode(): + """Returns list of utf-8 byte and a corresponding list of unicode strings. + + The reversible bpe codes work on unicode strings. This means you need a + large # of unicode characters in your vocab if you want to avoid UNKs. When + you're at something like a 10B token dataset you end up needing around 5K + for decent coverage. This is a significant percentage of your normal, say, + 32K bpe vocab. To avoid that, we want lookup tables between utf-8 bytes and + unicode strings. And avoids mapping to whitespace/control characters the + bpe code barfs on. + """ + bs = list(range(ord('!'), + ord('~') + 1)) + list(range( + ord('¡'), + ord('¬') + 1)) + list(range(ord('®'), + ord('ÿ') + 1)) + cs = bs[:] + n = 0 + for b in range(2**8): + if b not in bs: + bs.append(b) + cs.append(2**8 + n) + n += 1 + cs = [chr(n) for n in cs] + return dict(zip(bs, cs)) + + +def get_pairs(word): + """Return set of symbol pairs in a word. + + Word is represented as tuple of symbols (symbols being variable-length + strings). + """ + pairs = set() + prev_char = word[0] + for char in word[1:]: + pairs.add((prev_char, char)) + prev_char = char + return pairs + + +def basic_clean(text): + text = ftfy.fix_text(text) + text = html.unescape(html.unescape(text)) + return text.strip() + + +def whitespace_clean(text): + text = re.sub(r'\s+', ' ', text) + text = text.strip() + return text + + +class SimpleTokenizer: + + def __init__(self, bpe_path: str = default_bpe(), special_tokens=None): + self.byte_encoder = bytes_to_unicode() + self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} + merges = gzip.open(bpe_path).read().decode('utf-8').split('\n') + merges = merges[1:49152 - 256 - 2 + 1] + merges = [tuple(merge.split()) for merge in merges] + vocab = list(bytes_to_unicode().values()) + vocab = vocab + [v + '' for v in vocab] + for merge in merges: + vocab.append(''.join(merge)) + if not special_tokens: + special_tokens = ['', ''] + else: + special_tokens = ['', '' + ] + special_tokens + vocab.extend(special_tokens) + self.encoder = dict(zip(vocab, range(len(vocab)))) + self.decoder = {v: k for k, v in self.encoder.items()} + self.bpe_ranks = dict(zip(merges, range(len(merges)))) + self.cache = {t: t for t in special_tokens} + special = '|'.join(special_tokens) + self.pat = re.compile( + special + + r"""|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", + re.IGNORECASE) + + self.vocab_size = len(self.encoder) + self.all_special_ids = [self.encoder[t] for t in special_tokens] + + def bpe(self, token): + if token in self.cache: + return self.cache[token] + word = tuple(token[:-1]) + (token[-1] + '', ) + pairs = get_pairs(word) + + if not pairs: + return token + '' + + while True: + bigram = min( + pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf'))) + if bigram not in self.bpe_ranks: + break + first, second = bigram + new_word = [] + i = 0 + while i < len(word): + try: + j = word.index(first, i) + new_word.extend(word[i:j]) + i = j + except: # noqa: E722, E261 + new_word.extend(word[i:]) + break + + if word[i] == first and i < len(word) - 1 and word[ + i + 1] == second: + new_word.append(first + second) + i += 2 + else: + new_word.append(word[i]) + i += 1 + new_word = tuple(new_word) + word = new_word + if len(word) == 1: + break + else: + pairs = get_pairs(word) + word = ' '.join(word) + self.cache[token] = word + return word + + def encode(self, text): + bpe_tokens = [] + text = whitespace_clean(basic_clean(text)).lower() + for token in re.findall(self.pat, text): + token = ''.join(self.byte_encoder[b] + for b in token.encode('utf-8')) + bpe_tokens.extend(self.encoder[bpe_token] + for bpe_token in self.bpe(token).split(' ')) + return bpe_tokens + + def decode(self, tokens): + text = ''.join([self.decoder[token] for token in tokens]) + text = bytearray([self.byte_decoder[c] for c in text]).decode( + 'utf-8', errors='replace').replace('', ' ') + return text + + +_tokenizer = SimpleTokenizer() + + +def decode(output_ids: torch.Tensor): + output_ids = output_ids.cpu().numpy() + return _tokenizer.decode(output_ids) + + +def tokenize(texts: Union[str, List[str]], + context_length: int = 77) -> torch.LongTensor: + """Returns the tokenized representation of given input string(s) + + Parameters + ---------- + texts : Union[str, List[str]] + An input string or a list of input strings to tokenize + context_length : int + The context length to use; all CLIP models use 77 as the context length + + Returns + ------- + A two-dimensional tensor containing the resulting tokens, + shape = [number of input strings, context_length] + """ + if isinstance(texts, str): + texts = [texts] + + sot_token = _tokenizer.encoder[''] + eot_token = _tokenizer.encoder[''] + all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] + for text in texts] + result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + + for i, tokens in enumerate(all_tokens): + if len(tokens) > context_length: + tokens = tokens[:context_length] # Truncate + tokens[-1] = eot_token + result[i, :len(tokens)] = torch.tensor(tokens) + + return result + + +class HFTokenizer: + """HuggingFace tokenizer wrapper.""" + + def __init__(self, tokenizer_name: str): + from transformers import AutoTokenizer + self.tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) + + def save_pretrained(self, dest): + self.tokenizer.save_pretrained(dest) + + def __call__(self, + texts: Union[str, List[str]], + context_length: int = 77) -> torch.Tensor: + # same cleaning as for default tokenizer, except lowercasing + # adding lower (for case-sensitive tokenizers) will make it + # more robust but less sensitive to nuance + if isinstance(texts, str): + texts = [texts] + texts = [whitespace_clean(basic_clean(text)) for text in texts] + input_ids = self.tokenizer( + texts, + return_tensors='pt', + max_length=context_length, + padding='max_length', + truncation=True, + ).input_ids + return input_ids diff --git a/reconstruction/modules/InterFormer/mmseg/utils/typing_utils.py b/reconstruction/modules/InterFormer/mmseg/utils/typing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fba7d3b92bba8301171d2a0fffadfabfcd112976 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/utils/typing_utils.py @@ -0,0 +1,25 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Collecting some commonly used type hint in mmflow.""" +from typing import Dict, List, Optional, Sequence, Tuple, Union + +import torch +from mmengine.config import ConfigDict + +from mmseg.structures import SegDataSample + +# Type hint of config data +ConfigType = Union[ConfigDict, dict] +OptConfigType = Optional[ConfigType] +# Type hint of one or more config data +MultiConfig = Union[ConfigType, Sequence[ConfigType]] +OptMultiConfig = Optional[MultiConfig] + +SampleList = Sequence[SegDataSample] +OptSampleList = Optional[SampleList] + +# Type hint of Tensor +TensorDict = Dict[str, torch.Tensor] +TensorList = Sequence[torch.Tensor] + +ForwardResults = Union[Dict[str, torch.Tensor], List[SegDataSample], + Tuple[torch.Tensor], torch.Tensor] diff --git a/reconstruction/modules/InterFormer/mmseg/version.py b/reconstruction/modules/InterFormer/mmseg/version.py new file mode 100644 index 0000000000000000000000000000000000000000..b76bb4580ddfa0ba0ba13fa4896c49bac9cef65a --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/version.py @@ -0,0 +1,18 @@ +# Copyright (c) Open-MMLab. All rights reserved. + +__version__ = '1.2.2' + + +def parse_version_info(version_str): + version_info = [] + for x in version_str.split('.'): + if x.isdigit(): + version_info.append(int(x)) + elif x.find('rc') != -1: + patch_version = x.split('rc') + version_info.append(int(patch_version[0])) + version_info.append(f'rc{patch_version[1]}') + return tuple(version_info) + + +version_info = parse_version_info(__version__) diff --git a/reconstruction/modules/InterFormer/mmseg/visualization/__init__.py b/reconstruction/modules/InterFormer/mmseg/visualization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8cbb211e5243aafb4ab3d91f6a6f7ce0735b13a9 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/visualization/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from .local_visualizer import SegLocalVisualizer + +__all__ = ['SegLocalVisualizer'] diff --git a/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/__init__.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7bf05e6f75dbc429ffc4f2dfdb69f54e18f607cd Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/__init__.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/__init__.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4da7a1d3a990f5ae47676ad6ecfb972d3b7ad663 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/__init__.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/local_visualizer.cpython-310.pyc b/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/local_visualizer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68651ba2c8cdd93ce680794003b7362ce493c37f Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/local_visualizer.cpython-310.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/local_visualizer.cpython-38.pyc b/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/local_visualizer.cpython-38.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae56f96764a28334abe31887725344de6092fe13 Binary files /dev/null and b/reconstruction/modules/InterFormer/mmseg/visualization/__pycache__/local_visualizer.cpython-38.pyc differ diff --git a/reconstruction/modules/InterFormer/mmseg/visualization/local_visualizer.py b/reconstruction/modules/InterFormer/mmseg/visualization/local_visualizer.py new file mode 100644 index 0000000000000000000000000000000000000000..ee3d652c7bbe9d93ca481fb7a7ed4bb976eec80d --- /dev/null +++ b/reconstruction/modules/InterFormer/mmseg/visualization/local_visualizer.py @@ -0,0 +1,349 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from typing import Dict, List, Optional + +import cv2 +import mmcv +import numpy as np +import torch +from mmengine.dist import master_only +from mmengine.structures import PixelData +from mmengine.visualization import Visualizer + +from mmseg.registry import VISUALIZERS +from mmseg.structures import SegDataSample +from mmseg.utils import get_classes, get_palette + + +@VISUALIZERS.register_module() +class SegLocalVisualizer(Visualizer): + """Local Visualizer. + + Args: + name (str): Name of the instance. Defaults to 'visualizer'. + image (np.ndarray, optional): the origin image to draw. The format + should be RGB. Defaults to None. + vis_backends (list, optional): Visual backend config list. + Defaults to None. + save_dir (str, optional): Save file dir for all storage backends. + If it is None, the backend storage will not save any data. + classes (list, optional): Input classes for result rendering, as the + prediction of segmentation model is a segment map with label + indices, `classes` is a list which includes items responding to the + label indices. If classes is not defined, visualizer will take + `cityscapes` classes by default. Defaults to None. + palette (list, optional): Input palette for result rendering, which is + a list of color palette responding to the classes. Defaults to None. + dataset_name (str, optional): `Dataset name or alias `_ + visulizer will use the meta information of the dataset i.e. classes + and palette, but the `classes` and `palette` have higher priority. + Defaults to None. + alpha (int, float): The transparency of segmentation mask. + Defaults to 0.8. + + Examples: + >>> import numpy as np + >>> import torch + >>> from mmengine.structures import PixelData + >>> from mmseg.structures import SegDataSample + >>> from mmseg.visualization import SegLocalVisualizer + + >>> seg_local_visualizer = SegLocalVisualizer() + >>> image = np.random.randint(0, 256, + ... size=(10, 12, 3)).astype('uint8') + >>> gt_sem_seg_data = dict(data=torch.randint(0, 2, (1, 10, 12))) + >>> gt_sem_seg = PixelData(**gt_sem_seg_data) + >>> gt_seg_data_sample = SegDataSample() + >>> gt_seg_data_sample.gt_sem_seg = gt_sem_seg + >>> seg_local_visualizer.dataset_meta = dict( + >>> classes=('background', 'foreground'), + >>> palette=[[120, 120, 120], [6, 230, 230]]) + >>> seg_local_visualizer.add_datasample('visualizer_example', + ... image, gt_seg_data_sample) + >>> seg_local_visualizer.add_datasample( + ... 'visualizer_example', image, + ... gt_seg_data_sample, show=True) + """ # noqa + + def __init__(self, + name: str = 'visualizer', + image: Optional[np.ndarray] = None, + vis_backends: Optional[Dict] = None, + save_dir: Optional[str] = None, + classes: Optional[List] = None, + palette: Optional[List] = None, + dataset_name: Optional[str] = None, + alpha: float = 0.8, + **kwargs): + super().__init__(name, image, vis_backends, save_dir, **kwargs) + self.alpha: float = alpha + self.set_dataset_meta(palette, classes, dataset_name) + + def _get_center_loc(self, mask: np.ndarray) -> np.ndarray: + """Get semantic seg center coordinate. + + Args: + mask: np.ndarray: get from sem_seg + """ + loc = np.argwhere(mask == 1) + + loc_sort = np.array( + sorted(loc.tolist(), key=lambda row: (row[0], row[1]))) + y_list = loc_sort[:, 0] + unique, indices, counts = np.unique( + y_list, return_index=True, return_counts=True) + y_loc = unique[counts.argmax()] + y_most_freq_loc = loc[loc_sort[:, 0] == y_loc] + center_num = len(y_most_freq_loc) // 2 + x = y_most_freq_loc[center_num][1] + y = y_most_freq_loc[center_num][0] + return np.array([x, y]) + + def _draw_sem_seg(self, + image: np.ndarray, + sem_seg: PixelData, + classes: Optional[List], + palette: Optional[List], + with_labels: Optional[bool] = True) -> np.ndarray: + """Draw semantic seg of GT or prediction. + + Args: + image (np.ndarray): The image to draw. + sem_seg (:obj:`PixelData`): Data structure for pixel-level + annotations or predictions. + classes (list, optional): Input classes for result rendering, as + the prediction of segmentation model is a segment map with + label indices, `classes` is a list which includes items + responding to the label indices. If classes is not defined, + visualizer will take `cityscapes` classes by default. + Defaults to None. + palette (list, optional): Input palette for result rendering, which + is a list of color palette responding to the classes. + Defaults to None. + with_labels(bool, optional): Add semantic labels in visualization + result, Default to True. + + Returns: + np.ndarray: the drawn image which channel is RGB. + """ + num_classes = len(classes) + + sem_seg = sem_seg.cpu().data + ids = np.unique(sem_seg)[::-1] + legal_indices = ids < num_classes + ids = ids[legal_indices] + labels = np.array(ids, dtype=np.int64) + + colors = [palette[label] for label in labels] + + mask = np.zeros_like(image, dtype=np.uint8) + for label, color in zip(labels, colors): + mask[sem_seg[0] == label, :] = color + + if with_labels: + font = cv2.FONT_HERSHEY_SIMPLEX + # (0,1] to change the size of the text relative to the image + scale = 0.05 + fontScale = min(image.shape[0], image.shape[1]) / (25 / scale) + fontColor = (255, 255, 255) + if image.shape[0] < 300 or image.shape[1] < 300: + thickness = 1 + rectangleThickness = 1 + else: + thickness = 2 + rectangleThickness = 2 + lineType = 2 + + if isinstance(sem_seg[0], torch.Tensor): + masks = sem_seg[0].numpy() == labels[:, None, None] + else: + masks = sem_seg[0] == labels[:, None, None] + masks = masks.astype(np.uint8) + for mask_num in range(len(labels)): + classes_id = labels[mask_num] + classes_color = colors[mask_num] + loc = self._get_center_loc(masks[mask_num]) + text = classes[classes_id] + (label_width, label_height), baseline = cv2.getTextSize( + text, font, fontScale, thickness) + mask = cv2.rectangle(mask, loc, + (loc[0] + label_width + baseline, + loc[1] + label_height + baseline), + classes_color, -1) + mask = cv2.rectangle(mask, loc, + (loc[0] + label_width + baseline, + loc[1] + label_height + baseline), + (0, 0, 0), rectangleThickness) + mask = cv2.putText(mask, text, (loc[0], loc[1] + label_height), + font, fontScale, fontColor, thickness, + lineType) + color_seg = (image * (1 - self.alpha) + mask * self.alpha).astype( + np.uint8) + self.set_image(color_seg) + return color_seg + + def _draw_depth_map(self, image: np.ndarray, + depth_map: PixelData) -> np.ndarray: + """Draws a depth map on a given image. + + This function takes an image and a depth map as input, + renders the depth map, and concatenates it with the original image. + Finally, it updates the internal image state of the visualizer with + the concatenated result. + + Args: + image (np.ndarray): The original image where the depth map will + be drawn. The array should be in the format HxWx3 where H is + the height, W is the width. + + depth_map (PixelData): Depth map to be drawn. The depth map + should be in the form of a PixelData object. It will be + converted to a torch tensor if it is a numpy array. + + Returns: + np.ndarray: The concatenated image with the depth map drawn. + + Example: + >>> depth_map_data = PixelData(data=torch.rand(1, 10, 10)) + >>> image = np.random.randint(0, 256, + >>> size=(10, 10, 3)).astype('uint8') + >>> visualizer = SegLocalVisualizer() + >>> visualizer._draw_depth_map(image, depth_map_data) + """ + depth_map = depth_map.cpu().data + if isinstance(depth_map, np.ndarray): + depth_map = torch.from_numpy(depth_map) + if depth_map.ndim == 2: + depth_map = depth_map[None] + + depth_map = self.draw_featmap(depth_map, resize_shape=image.shape[:2]) + out_image = np.concatenate((image, depth_map), axis=0) + self.set_image(out_image) + return out_image + + def set_dataset_meta(self, + classes: Optional[List] = None, + palette: Optional[List] = None, + dataset_name: Optional[str] = None) -> None: + """Set meta information to visualizer. + + Args: + classes (list, optional): Input classes for result rendering, as + the prediction of segmentation model is a segment map with + label indices, `classes` is a list which includes items + responding to the label indices. If classes is not defined, + visualizer will take `cityscapes` classes by default. + Defaults to None. + palette (list, optional): Input palette for result rendering, which + is a list of color palette responding to the classes. + Defaults to None. + dataset_name (str, optional): `Dataset name or alias `_ + visulizer will use the meta information of the dataset i.e. + classes and palette, but the `classes` and `palette` have + higher priority. Defaults to None. + """ # noqa + # Set default value. When calling + # `SegLocalVisualizer().dataset_meta=xxx`, + # it will override the default value. + if dataset_name is None: + dataset_name = 'cityscapes' + classes = classes if classes else get_classes(dataset_name) + palette = palette if palette else get_palette(dataset_name) + assert len(classes) == len( + palette), 'The length of classes should be equal to palette' + self.dataset_meta: dict = {'classes': classes, 'palette': palette} + + @master_only + def add_datasample( + self, + name: str, + image: np.ndarray, + data_sample: Optional[SegDataSample] = None, + draw_gt: bool = True, + draw_pred: bool = True, + show: bool = False, + wait_time: float = 0, + # TODO: Supported in mmengine's Viusalizer. + out_file: Optional[str] = None, + step: int = 0, + with_labels: Optional[bool] = True) -> None: + """Draw datasample and save to all backends. + + - If GT and prediction are plotted at the same time, they are + displayed in a stitched image where the left image is the + ground truth and the right image is the prediction. + - If ``show`` is True, all storage backends are ignored, and + the images will be displayed in a local window. + - If ``out_file`` is specified, the drawn image will be + saved to ``out_file``. it is usually used when the display + is not available. + + Args: + name (str): The image identifier. + image (np.ndarray): The image to draw. + gt_sample (:obj:`SegDataSample`, optional): GT SegDataSample. + Defaults to None. + pred_sample (:obj:`SegDataSample`, optional): Prediction + SegDataSample. Defaults to None. + draw_gt (bool): Whether to draw GT SegDataSample. Default to True. + draw_pred (bool): Whether to draw Prediction SegDataSample. + Defaults to True. + show (bool): Whether to display the drawn image. Default to False. + wait_time (float): The interval of show (s). Defaults to 0. + out_file (str): Path to output file. Defaults to None. + step (int): Global step value to record. Defaults to 0. + with_labels(bool, optional): Add semantic labels in visualization + result, Defaults to True. + """ + classes = self.dataset_meta.get('classes', None) + palette = self.dataset_meta.get('palette', None) + + gt_img_data = None + pred_img_data = None + + if draw_gt and data_sample is not None: + if 'gt_sem_seg' in data_sample: + assert classes is not None, 'class information is ' \ + 'not provided when ' \ + 'visualizing semantic ' \ + 'segmentation results.' + gt_img_data = self._draw_sem_seg(image, data_sample.gt_sem_seg, + classes, palette, with_labels) + + if 'gt_depth_map' in data_sample: + gt_img_data = gt_img_data if gt_img_data is not None else image + gt_img_data = self._draw_depth_map(gt_img_data, + data_sample.gt_depth_map) + + if draw_pred and data_sample is not None: + + if 'pred_sem_seg' in data_sample: + + assert classes is not None, 'class information is ' \ + 'not provided when ' \ + 'visualizing semantic ' \ + 'segmentation results.' + pred_img_data = self._draw_sem_seg(image, + data_sample.pred_sem_seg, + classes, palette, + with_labels) + + if 'pred_depth_map' in data_sample: + pred_img_data = pred_img_data if pred_img_data is not None \ + else image + pred_img_data = self._draw_depth_map( + pred_img_data, data_sample.pred_depth_map) + + if gt_img_data is not None and pred_img_data is not None: + drawn_img = np.concatenate((gt_img_data, pred_img_data), axis=1) + elif gt_img_data is not None: + drawn_img = gt_img_data + else: + drawn_img = pred_img_data + + if show: + self.show(drawn_img, win_name=name, wait_time=wait_time) + + if out_file is not None: + mmcv.imwrite(mmcv.rgb2bgr(drawn_img), out_file) + else: + self.add_image(name, drawn_img, step) diff --git a/reconstruction/modules/InterFormer/mmsegmentation.egg-info/PKG-INFO b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..b1dc9ad431e2126e77bd42cc4478b46dc0fc122f --- /dev/null +++ b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/PKG-INFO @@ -0,0 +1,193 @@ +Metadata-Version: 2.4 +Name: mmsegmentation +Version: 1.2.2 +Summary: Open MMLab Semantic Segmentation Toolbox and Benchmark +Home-page: https://github.com/open-mmlab/mmsegmentation +Author: MMSegmentation Contributors +Author-email: openmmlab@gmail.com +License: Apache License 2.0 +Keywords: computer vision,semantic segmentation +Classifier: Development Status :: 4 - Beta +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: all +Provides-Extra: tests +Provides-Extra: optional +Provides-Extra: mim +Provides-Extra: multimodal +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: summary + +# InterFormer + +Official implementation of the paper: **"Interaction-aware Representation Modeling with Co-occurrence Consistency for Egocentric Hand-Object Parsing"**, *ICLR 2026* + +--- + +## 📋 Table of Contents + +- [Overview](#overview) +- [Environment Setup](#environment-setup) +- [Dataset Preparation](#dataset-preparation) +- [Pretrained Model](#pretrained-model) +- [Training](#training) + - [Single-GPU Training](#single-gpu-training) + - [Multi-GPU Training](#multi-gpu-training) +- [Testing](#testing) +- [Checkpoints](#checkpoints) +- [Results](#results) + +--- + +## Overview + +This repository contains the official code for **InterFormer**, a novel framework for egocentric hand-object parsing that leverages interaction-aware representation modeling with co-occurrence consistency. + +--- + +## Environment Setup + +Create and activate the conda environment using the provided configuration file: + +```bash +# Create environment from yaml file +conda env create -f mmseg.yaml + +# Activate the environment +conda activate mmseg +``` + +> **Note**: If you don't have `mmseg.yaml`, please ensure you have installed mmsegmentation and its dependencies. Alternatively, you can install manually: +> ```bash +> pip install torch torchvision +> pip install mmcv-full +> pip install mmsegmentation +> ``` + +--- + +## Dataset Preparation + +1. Download the dataset from [Google Drive](https://drive.google.com/file/d/1Pc6Ofd3q-yEwByxIqgaJfEJv4QtWtKjP/view?usp=drive_link) + +2. Extract the dataset: + ```bash + unzip dataset.zip -d /path/to/your/dataset/folder + ``` + +3. Update the dataset path in the configuration file: + ```bash + # Edit ./mmseg/configs/config_interformer.py + # Change the dataset path to your extracted folder + data_root = '/path/to/your/dataset/folder' + ``` + +--- + +## Pretrained Model + +Download the pretrained backbone model: + +```bash +# Download pretrained model +wget https://drive.google.com/file/d/13Wd08wkbscxAR1TAgaNWQ2_luYC9pahs/view?usp=drive_link -O pretrained_model/backbone.pth +``` + +Alternatively, download manually from [this link](https://drive.google.com/file/d/13Wd08wkbscxAR1TAgaNWQ2_luYC9pahs/view?usp=drive_link) and place it in the `pretrained_model/` directory. + +Then update the pretrained path in `./mmseg/configs/config_interformer.py `: +```python +pretrained = '/path/to/pretrained_model/backbone.pth' +``` + +--- + +## Training + +### Single-GPU Training + +Run the following command for single-GPU training: + +```bash +python tools/train.py ./mmseg/configs/config_interformer.py +``` + +### Multi-GPU Training + +For multi-GPU training, use the distributed training script: + +```bash +bash tools/dist_train.sh ./mmseg/configs/config_interformer.py +``` + +Example (4 GPUs): +```bash +bash tools/dist_train.sh ./mmseg/configs/config_interformer.py py 4 +``` + +### Training Log + +We provide our training log file (`Training_Log.log`) in this repository. The best results are achieved at **iteration 93,900**. + +--- + +## Testing + +### Single-GPU Testing + +To test a trained model on a single GPU: + +```bash +python tools/test.py +``` + +Example: +```bash +python tools/test.py config/config_interformer.py work_dirs/checkpoint.pth +``` + +--- + +## Checkpoints + +We provide our trained checkpoint for reproduction: + +- **Download link**: [Google Drive](https://drive.google.com/file/d/172Hi0jTTijEnbroYSUZgOfpsyue_HHxg/view?usp=drive_link) + +Download and use it for testing or inference. + +--- + +## Citation + +If you find this work useful for your research, please cite: + +```bibtex +@inproceedings{su2026interformer, + title={Interaction-aware Representation Modeling with Co-occurrence Consistency for Egocentric Hand-Object Parsing}, + author={Su, Yuejiao and Wang, Yi and Yao, Lei and Cui, Yawen and Chau, Lap-Pui}, + booktitle={International Conference on Learning Representations (ICLR)}, + year={2026} +} +``` + +--- + +## Contact + +For questions or issues, please open an issue on GitHub or contact the authors directly. diff --git a/reconstruction/modules/InterFormer/mmsegmentation.egg-info/SOURCES.txt b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..f0127ed0f1966f6fb07f411815dc80756920cffa --- /dev/null +++ b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/SOURCES.txt @@ -0,0 +1,200 @@ +LICENSE +README.md +setup.cfg +setup.py +mmseg/__init__.py +mmseg/version.py +mmseg/apis/__init__.py +mmseg/apis/inference.py +mmseg/apis/mmseg_inferencer.py +mmseg/apis/remote_sense_inferencer.py +mmseg/apis/utils.py +mmseg/datasets/__init__.py +mmseg/datasets/ade.py +mmseg/datasets/basesegdataset.py +mmseg/datasets/bdd100k.py +mmseg/datasets/chase_db1.py +mmseg/datasets/cityscapes.py +mmseg/datasets/coco_stuff.py +mmseg/datasets/dark_zurich.py +mmseg/datasets/dataset_wrappers.py +mmseg/datasets/decathlon.py +mmseg/datasets/drive.py +mmseg/datasets/dsdl.py +mmseg/datasets/hrf.py +mmseg/datasets/hsi_drive.py +mmseg/datasets/interformer_dataset.py +mmseg/datasets/isaid.py +mmseg/datasets/isprs.py +mmseg/datasets/levir.py +mmseg/datasets/lip.py +mmseg/datasets/loveda.py +mmseg/datasets/mapillary.py +mmseg/datasets/night_driving.py +mmseg/datasets/nyu.py +mmseg/datasets/pascal_context.py +mmseg/datasets/potsdam.py +mmseg/datasets/refuge.py +mmseg/datasets/stare.py +mmseg/datasets/synapse.py +mmseg/datasets/voc.py +mmseg/datasets/transforms/__init__.py +mmseg/datasets/transforms/formatting.py +mmseg/datasets/transforms/loading.py +mmseg/datasets/transforms/transforms.py +mmseg/engine/__init__.py +mmseg/engine/hooks/__init__.py +mmseg/engine/hooks/visualization_hook.py +mmseg/engine/optimizers/__init__.py +mmseg/engine/optimizers/force_default_constructor.py +mmseg/engine/optimizers/layer_decay_optimizer_constructor.py +mmseg/engine/schedulers/__init__.py +mmseg/engine/schedulers/poly_ratio_scheduler.py +mmseg/evaluation/__init__.py +mmseg/evaluation/metrics/__init__.py +mmseg/evaluation/metrics/citys_metric.py +mmseg/evaluation/metrics/depth_metric.py +mmseg/evaluation/metrics/iou_metric.py +mmseg/models/__init__.py +mmseg/models/builder.py +mmseg/models/data_preprocessor.py +mmseg/models/assigners/__init__.py +mmseg/models/assigners/base_assigner.py +mmseg/models/assigners/hungarian_assigner.py +mmseg/models/assigners/match_cost.py +mmseg/models/backbones/__init__.py +mmseg/models/backbones/beit.py +mmseg/models/backbones/bisenetv1.py +mmseg/models/backbones/bisenetv2.py +mmseg/models/backbones/cgnet.py +mmseg/models/backbones/ddrnet.py +mmseg/models/backbones/erfnet.py +mmseg/models/backbones/fast_scnn.py +mmseg/models/backbones/hrnet.py +mmseg/models/backbones/icnet.py +mmseg/models/backbones/mae.py +mmseg/models/backbones/mit.py +mmseg/models/backbones/mobilenet_v2.py +mmseg/models/backbones/mobilenet_v3.py +mmseg/models/backbones/mscan.py +mmseg/models/backbones/pidnet.py +mmseg/models/backbones/resnest.py +mmseg/models/backbones/resnet.py +mmseg/models/backbones/resnext.py +mmseg/models/backbones/stdc.py +mmseg/models/backbones/swin.py +mmseg/models/backbones/timm_backbone.py +mmseg/models/backbones/twins.py +mmseg/models/backbones/unet.py +mmseg/models/backbones/vit.py +mmseg/models/backbones/vpd.py +mmseg/models/decode_heads/__init__.py +mmseg/models/decode_heads/ann_head.py +mmseg/models/decode_heads/apc_head.py +mmseg/models/decode_heads/aspp_head.py +mmseg/models/decode_heads/cascade_decode_head.py +mmseg/models/decode_heads/cc_head.py +mmseg/models/decode_heads/da_head.py +mmseg/models/decode_heads/ddr_head.py +mmseg/models/decode_heads/decode_head.py +mmseg/models/decode_heads/dm_head.py +mmseg/models/decode_heads/dnl_head.py +mmseg/models/decode_heads/dpt_head.py +mmseg/models/decode_heads/ema_head.py +mmseg/models/decode_heads/enc_head.py +mmseg/models/decode_heads/fcn_head.py +mmseg/models/decode_heads/fpn_head.py +mmseg/models/decode_heads/gc_head.py +mmseg/models/decode_heads/ham_head.py +mmseg/models/decode_heads/interformer_decoder.py +mmseg/models/decode_heads/isa_head.py +mmseg/models/decode_heads/knet_head.py +mmseg/models/decode_heads/lraspp_head.py +mmseg/models/decode_heads/mask2former_head.py +mmseg/models/decode_heads/maskformer_head.py +mmseg/models/decode_heads/nl_head.py +mmseg/models/decode_heads/ocr_head.py +mmseg/models/decode_heads/pid_head.py +mmseg/models/decode_heads/point_head.py +mmseg/models/decode_heads/psa_head.py +mmseg/models/decode_heads/psp_head.py +mmseg/models/decode_heads/san_head.py +mmseg/models/decode_heads/segformer_head.py +mmseg/models/decode_heads/segmenter_mask_head.py +mmseg/models/decode_heads/sep_aspp_head.py +mmseg/models/decode_heads/sep_fcn_head.py +mmseg/models/decode_heads/setr_mla_head.py +mmseg/models/decode_heads/setr_up_head.py +mmseg/models/decode_heads/stdc_head.py +mmseg/models/decode_heads/uper_head.py +mmseg/models/decode_heads/vpd_depth_head.py +mmseg/models/losses/__init__.py +mmseg/models/losses/accuracy.py +mmseg/models/losses/boundary_loss.py +mmseg/models/losses/cross_entropy_loss.py +mmseg/models/losses/dice_loss.py +mmseg/models/losses/focal_loss.py +mmseg/models/losses/huasdorff_distance_loss.py +mmseg/models/losses/kldiv_loss.py +mmseg/models/losses/lovasz_loss.py +mmseg/models/losses/ohem_cross_entropy_loss.py +mmseg/models/losses/silog_loss.py +mmseg/models/losses/tversky_loss.py +mmseg/models/losses/utils.py +mmseg/models/necks/__init__.py +mmseg/models/necks/featurepyramid.py +mmseg/models/necks/fpn.py +mmseg/models/necks/ic_neck.py +mmseg/models/necks/jpu.py +mmseg/models/necks/mla_neck.py +mmseg/models/necks/multilevel_neck.py +mmseg/models/segmentors/__init__.py +mmseg/models/segmentors/base.py +mmseg/models/segmentors/cascade_encoder_decoder.py +mmseg/models/segmentors/depth_estimator.py +mmseg/models/segmentors/encoder_decoder.py +mmseg/models/segmentors/multimodal_encoder_decoder.py +mmseg/models/segmentors/seg_tta.py +mmseg/models/text_encoder/__init__.py +mmseg/models/text_encoder/clip_text_encoder.py +mmseg/models/utils/__init__.py +mmseg/models/utils/basic_block.py +mmseg/models/utils/embed.py +mmseg/models/utils/encoding.py +mmseg/models/utils/inverted_residual.py +mmseg/models/utils/make_divisible.py +mmseg/models/utils/point_sample.py +mmseg/models/utils/ppm.py +mmseg/models/utils/res_layer.py +mmseg/models/utils/san_layers.py +mmseg/models/utils/se_layer.py +mmseg/models/utils/self_attention_block.py +mmseg/models/utils/shape_convert.py +mmseg/models/utils/up_conv_block.py +mmseg/models/utils/wrappers.py +mmseg/registry/__init__.py +mmseg/registry/registry.py +mmseg/structures/__init__.py +mmseg/structures/seg_data_sample.py +mmseg/structures/sampler/__init__.py +mmseg/structures/sampler/base_pixel_sampler.py +mmseg/structures/sampler/builder.py +mmseg/structures/sampler/ohem_pixel_sampler.py +mmseg/utils/__init__.py +mmseg/utils/class_names.py +mmseg/utils/collect_env.py +mmseg/utils/get_templates.py +mmseg/utils/io.py +mmseg/utils/mask_classification.py +mmseg/utils/misc.py +mmseg/utils/set_env.py +mmseg/utils/tokenizer.py +mmseg/utils/typing_utils.py +mmseg/visualization/__init__.py +mmseg/visualization/local_visualizer.py +mmsegmentation.egg-info/PKG-INFO +mmsegmentation.egg-info/SOURCES.txt +mmsegmentation.egg-info/dependency_links.txt +mmsegmentation.egg-info/not-zip-safe +mmsegmentation.egg-info/requires.txt +mmsegmentation.egg-info/top_level.txt \ No newline at end of file diff --git a/reconstruction/modules/InterFormer/mmsegmentation.egg-info/dependency_links.txt b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/reconstruction/modules/InterFormer/mmsegmentation.egg-info/not-zip-safe b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/not-zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/not-zip-safe @@ -0,0 +1 @@ + diff --git a/reconstruction/modules/InterFormer/mmsegmentation.egg-info/requires.txt b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..5a02e8bc9387ff9c16d26b1202f195cfb3d2673a --- /dev/null +++ b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/requires.txt @@ -0,0 +1,10 @@ + +[all] + +[mim] + +[multimodal] + +[optional] + +[tests] diff --git a/reconstruction/modules/InterFormer/mmsegmentation.egg-info/top_level.txt b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..ea1c94957cbf838c497c3e42cc0599c750f431c8 --- /dev/null +++ b/reconstruction/modules/InterFormer/mmsegmentation.egg-info/top_level.txt @@ -0,0 +1 @@ +mmseg diff --git a/reconstruction/modules/InterFormer/setup.cfg b/reconstruction/modules/InterFormer/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..2ea07600c0b864d8ecbc4c293e1ad0d01594fcc0 --- /dev/null +++ b/reconstruction/modules/InterFormer/setup.cfg @@ -0,0 +1,19 @@ +[yapf] +based_on_style = pep8 +blank_line_before_nested_class_or_def = true +split_before_expression_after_opening_paren = true + +[isort] +line_length = 79 +multi_line_output = 0 +extra_standard_library = setuptools +known_first_party = mmseg +known_third_party = PIL,cityscapesscripts,cv2,detail,matplotlib,mmcv,numpy,onnxruntime,packaging,prettytable,pytest,pytorch_sphinx_theme,requests,scipy,seaborn,torch,ts +no_lines_before = STDLIB,LOCALFOLDER +default_section = THIRDPARTY + +[codespell] +skip = *.po,*.ts,*.ipynb +count = +quiet-level = 3 +ignore-words-list = formating,sur,hist,dota,warmup,damon diff --git a/reconstruction/modules/InterFormer/setup.py b/reconstruction/modules/InterFormer/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..45d923db60e9720547e2bcdac2f5bec8c18c37f8 --- /dev/null +++ b/reconstruction/modules/InterFormer/setup.py @@ -0,0 +1,200 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import os +import os.path as osp +import platform +import shutil +import sys +import warnings +from setuptools import find_packages, setup + + +def readme(): + with open('README.md', encoding='utf-8') as f: + content = f.read() + return content + + +version_file = 'mmseg/version.py' + + +def get_version(): + with open(version_file) as f: + exec(compile(f.read(), version_file, 'exec')) + return locals()['__version__'] + + +def parse_requirements(fname='requirements.txt', with_version=True): + """Parse the package dependencies listed in a requirements file but strips + specific versioning information. + + Args: + fname (str): path to requirements file + with_version (bool, default=False): if True include version specs + + Returns: + List[str]: list of requirements items + + CommandLine: + python -c "import setup; print(setup.parse_requirements())" + """ + import re + import sys + from os.path import exists + require_fpath = fname + + def parse_line(line): + """Parse information from a line in a requirements text file.""" + if line.startswith('-r '): + # Allow specifying requirements in other files + target = line.split(' ')[1] + for info in parse_require_file(target): + yield info + else: + info = {'line': line} + if line.startswith('-e '): + info['package'] = line.split('#egg=')[1] + else: + # Remove versioning from the package + pat = '(' + '|'.join(['>=', '==', '>']) + ')' + parts = re.split(pat, line, maxsplit=1) + parts = [p.strip() for p in parts] + + info['package'] = parts[0] + if len(parts) > 1: + op, rest = parts[1:] + if ';' in rest: + # Handle platform specific dependencies + # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies + version, platform_deps = map(str.strip, + rest.split(';')) + info['platform_deps'] = platform_deps + else: + version = rest # NOQA + info['version'] = (op, version) + yield info + + def parse_require_file(fpath): + with open(fpath) as f: + for line in f.readlines(): + line = line.strip() + if line and not line.startswith('#'): + yield from parse_line(line) + + def gen_packages_items(): + if exists(require_fpath): + for info in parse_require_file(require_fpath): + parts = [info['package']] + if with_version and 'version' in info: + parts.extend(info['version']) + if not sys.version.startswith('3.4'): + # apparently package_deps are broken in 3.4 + platform_deps = info.get('platform_deps') + if platform_deps is not None: + parts.append(';' + platform_deps) + item = ''.join(parts) + yield item + + packages = list(gen_packages_items()) + return packages + + +def add_mim_extension(): + """Add extra files that are required to support MIM into the package. + + These files will be added by creating a symlink to the originals if the + package is installed in `editable` mode (e.g. pip install -e .), or by + copying from the originals otherwise. + """ + + # parse installment mode + if 'develop' in sys.argv: + # installed by `pip install -e .` + if platform.system() == 'Windows': + # set `copy` mode here since symlink fails on Windows. + mode = 'copy' + else: + mode = 'symlink' + elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv or \ + platform.system() == 'Windows': + # installed by `pip install .` + # or create source distribution by `python setup.py sdist` + # set `copy` mode here since symlink fails with WinError on Windows. + mode = 'copy' + else: + return + + filenames = ['tools', 'configs', 'model-index.yml', 'dataset-index.yml'] + repo_path = osp.dirname(__file__) + mim_path = osp.join(repo_path, 'mmseg', '.mim') + os.makedirs(mim_path, exist_ok=True) + + for filename in filenames: + if osp.exists(filename): + src_path = osp.join(repo_path, filename) + tar_path = osp.join(mim_path, filename) + + if osp.isfile(tar_path) or osp.islink(tar_path): + os.remove(tar_path) + elif osp.isdir(tar_path): + shutil.rmtree(tar_path) + + if mode == 'symlink': + src_relpath = osp.relpath(src_path, osp.dirname(tar_path)) + try: + os.symlink(src_relpath, tar_path) + except OSError: + # Creating a symbolic link on windows may raise an + # `OSError: [WinError 1314]` due to privilege. If + # the error happens, the src file will be copied + mode = 'copy' + warnings.warn( + f'Failed to create a symbolic link for {src_relpath}, ' + f'and it will be copied to {tar_path}') + else: + continue + + if mode == 'copy': + if osp.isfile(src_path): + shutil.copyfile(src_path, tar_path) + elif osp.isdir(src_path): + shutil.copytree(src_path, tar_path) + else: + warnings.warn(f'Cannot copy file {src_path}.') + else: + raise ValueError(f'Invalid mode {mode}') + + +if __name__ == '__main__': + add_mim_extension() + setup( + name='mmsegmentation', + version=get_version(), + description='Open MMLab Semantic Segmentation Toolbox and Benchmark', + long_description=readme(), + long_description_content_type='text/markdown', + author='MMSegmentation Contributors', + author_email='openmmlab@gmail.com', + keywords='computer vision, semantic segmentation', + url='https://github.com/open-mmlab/mmsegmentation', + packages=find_packages(exclude=('configs', 'tools', 'demo')), + include_package_data=True, + classifiers=[ + 'Development Status :: 4 - Beta', + 'License :: OSI Approved :: Apache Software License', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + ], + license='Apache License 2.0', + install_requires=parse_requirements('requirements/runtime.txt'), + extras_require={ + 'all': parse_requirements('requirements.txt'), + 'tests': parse_requirements('requirements/tests.txt'), + 'optional': parse_requirements('requirements/optional.txt'), + 'mim': parse_requirements('requirements/mminstall.txt'), + 'multimodal': parse_requirements('requirements/multimodal.txt'), + }, + ext_modules=[], + zip_safe=False) diff --git a/reconstruction/modules/InterFormer/tools/analysis_tools/analyze_logs.py b/reconstruction/modules/InterFormer/tools/analysis_tools/analyze_logs.py new file mode 100644 index 0000000000000000000000000000000000000000..7464d231621b17249ce69f358479bbba42757362 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/analysis_tools/analyze_logs.py @@ -0,0 +1,130 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Modified from https://github.com/open- +mmlab/mmdetection/blob/master/tools/analysis_tools/analyze_logs.py.""" +import argparse +import json +from collections import defaultdict + +import matplotlib.pyplot as plt +import seaborn as sns + + +def plot_curve(log_dicts, args): + if args.backend is not None: + plt.switch_backend(args.backend) + sns.set_style(args.style) + # if legend is None, use {filename}_{key} as legend + legend = args.legend + if legend is None: + legend = [] + for json_log in args.json_logs: + for metric in args.keys: + legend.append(f'{json_log}_{metric}') + assert len(legend) == (len(args.json_logs) * len(args.keys)) + metrics = args.keys + + num_metrics = len(metrics) + for i, log_dict in enumerate(log_dicts): + epochs = list(log_dict.keys()) + for j, metric in enumerate(metrics): + print(f'plot curve of {args.json_logs[i]}, metric is {metric}') + plot_epochs = [] + plot_iters = [] + plot_values = [] + # In some log files exist lines of validation, + # `mode` list is used to only collect iter number + # of training line. + for epoch in epochs: + epoch_logs = log_dict[epoch] + if metric not in epoch_logs.keys(): + continue + if metric in ['mIoU', 'mAcc', 'aAcc']: + plot_epochs.append(epoch) + plot_values.append(epoch_logs[metric][0]) + else: + for idx in range(len(epoch_logs[metric])): + plot_iters.append(epoch_logs['step'][idx]) + plot_values.append(epoch_logs[metric][idx]) + ax = plt.gca() + label = legend[i * num_metrics + j] + if metric in ['mIoU', 'mAcc', 'aAcc']: + ax.set_xticks(plot_epochs) + plt.xlabel('step') + plt.plot(plot_epochs, plot_values, label=label, marker='o') + else: + plt.xlabel('iter') + plt.plot(plot_iters, plot_values, label=label, linewidth=0.5) + plt.legend() + if args.title is not None: + plt.title(args.title) + if args.out is None: + plt.show() + else: + print(f'save curve to: {args.out}') + plt.savefig(args.out) + plt.cla() + + +def parse_args(): + parser = argparse.ArgumentParser(description='Analyze Json Log') + parser.add_argument( + 'json_logs', + type=str, + nargs='+', + help='path of train log in json format') + parser.add_argument( + '--keys', + type=str, + nargs='+', + default=['mIoU'], + help='the metric that you want to plot') + parser.add_argument('--title', type=str, help='title of figure') + parser.add_argument( + '--legend', + type=str, + nargs='+', + default=None, + help='legend of each plot') + parser.add_argument( + '--backend', type=str, default=None, help='backend of plt') + parser.add_argument( + '--style', type=str, default='dark', help='style of plt') + parser.add_argument('--out', type=str, default=None) + args = parser.parse_args() + return args + + +def load_json_logs(json_logs): + # load and convert json_logs to log_dict, key is step, value is a sub dict + # keys of sub dict is different metrics + # value of sub dict is a list of corresponding values of all iterations + log_dicts = [dict() for _ in json_logs] + prev_step = 0 + for json_log, log_dict in zip(json_logs, log_dicts): + with open(json_log) as log_file: + for line in log_file: + log = json.loads(line.strip()) + # the final step in json file is 0. + if 'step' in log and log['step'] != 0: + step = log['step'] + prev_step = step + else: + step = prev_step + if step not in log_dict: + log_dict[step] = defaultdict(list) + for k, v in log.items(): + log_dict[step][k].append(v) + return log_dicts + + +def main(): + args = parse_args() + json_logs = args.json_logs + for json_log in json_logs: + assert json_log.endswith('.json') + log_dicts = load_json_logs(json_logs) + plot_curve(log_dicts, args) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/analysis_tools/benchmark.py b/reconstruction/modules/InterFormer/tools/analysis_tools/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..afaeabac85fa642b03c006b8a920c0d95d4cb400 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/analysis_tools/benchmark.py @@ -0,0 +1,121 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import time + +import numpy as np +import torch +from mmengine import Config +from mmengine.fileio import dump +from mmengine.model.utils import revert_sync_batchnorm +from mmengine.registry import init_default_scope +from mmengine.runner import Runner, load_checkpoint +from mmengine.utils import mkdir_or_exist + +from mmseg.registry import MODELS + + +def parse_args(): + parser = argparse.ArgumentParser(description='MMSeg benchmark a model') + parser.add_argument('config', help='test config file path') + parser.add_argument('checkpoint', help='checkpoint file') + parser.add_argument( + '--log-interval', type=int, default=50, help='interval of logging') + parser.add_argument( + '--work-dir', + help=('if specified, the results will be dumped ' + 'into the directory as json')) + parser.add_argument('--repeat-times', type=int, default=1) + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cfg = Config.fromfile(args.config) + + init_default_scope(cfg.get('default_scope', 'mmseg')) + + timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime()) + if args.work_dir is not None: + mkdir_or_exist(osp.abspath(args.work_dir)) + json_file = osp.join(args.work_dir, f'fps_{timestamp}.json') + else: + # use config filename as default work_dir if cfg.work_dir is None + work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + mkdir_or_exist(osp.abspath(work_dir)) + json_file = osp.join(work_dir, f'fps_{timestamp}.json') + + repeat_times = args.repeat_times + # set cudnn_benchmark + torch.backends.cudnn.benchmark = False + cfg.model.pretrained = None + + benchmark_dict = dict(config=args.config, unit='img / s') + overall_fps_list = [] + cfg.test_dataloader.batch_size = 1 + for time_index in range(repeat_times): + print(f'Run {time_index + 1}:') + # build the dataloader + data_loader = Runner.build_dataloader(cfg.test_dataloader) + + # build the model and load checkpoint + cfg.model.train_cfg = None + model = MODELS.build(cfg.model) + + if 'checkpoint' in args and osp.exists(args.checkpoint): + load_checkpoint(model, args.checkpoint, map_location='cpu') + + if torch.cuda.is_available(): + model = model.cuda() + + model = revert_sync_batchnorm(model) + + model.eval() + + # the first several iterations may be very slow so skip them + num_warmup = 5 + pure_inf_time = 0 + total_iters = 200 + + # benchmark with 200 batches and take the average + for i, data in enumerate(data_loader): + data = model.data_preprocessor(data, True) + inputs = data['inputs'] + data_samples = data['data_samples'] + if torch.cuda.is_available(): + torch.cuda.synchronize() + start_time = time.perf_counter() + + with torch.no_grad(): + model(inputs, data_samples, mode='predict') + + if torch.cuda.is_available(): + torch.cuda.synchronize() + elapsed = time.perf_counter() - start_time + + if i >= num_warmup: + pure_inf_time += elapsed + if (i + 1) % args.log_interval == 0: + fps = (i + 1 - num_warmup) / pure_inf_time + print(f'Done image [{i + 1:<3}/ {total_iters}], ' + f'fps: {fps:.2f} img / s') + + if (i + 1) == total_iters: + fps = (i + 1 - num_warmup) / pure_inf_time + print(f'Overall fps: {fps:.2f} img / s\n') + benchmark_dict[f'overall_fps_{time_index + 1}'] = round(fps, 2) + overall_fps_list.append(fps) + break + benchmark_dict['average_fps'] = round(np.mean(overall_fps_list), 2) + benchmark_dict['fps_variance'] = round(np.var(overall_fps_list), 4) + print(f'Average fps of {repeat_times} evaluations: ' + f'{benchmark_dict["average_fps"]}') + print(f'The variance of {repeat_times} evaluations: ' + f'{benchmark_dict["fps_variance"]}') + dump(benchmark_dict, json_file, indent=4) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/analysis_tools/browse_dataset.py b/reconstruction/modules/InterFormer/tools/analysis_tools/browse_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..925c14a8ab63b4e38950b6c6af58e37dba002a4c --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/analysis_tools/browse_dataset.py @@ -0,0 +1,77 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +from mmengine.config import Config, DictAction +from mmengine.utils import ProgressBar + +from mmseg.registry import DATASETS, VISUALIZERS +from mmseg.utils import register_all_modules + + +def parse_args(): + parser = argparse.ArgumentParser(description='Browse a dataset') + parser.add_argument('config', help='train config file path') + parser.add_argument( + '--output-dir', + default=None, + type=str, + help='If there is no display interface, you can save it') + parser.add_argument('--not-show', default=False, action='store_true') + parser.add_argument( + '--show-interval', + type=float, + default=2, + help='the interval of show (s)') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # register all modules in mmdet into the registries + register_all_modules() + + dataset = DATASETS.build(cfg.train_dataloader.dataset) + visualizer = VISUALIZERS.build(cfg.visualizer) + visualizer.dataset_meta = dataset.metainfo + + progress_bar = ProgressBar(len(dataset)) + for item in dataset: + img = item['inputs'].permute(1, 2, 0).numpy() + img = img[..., [2, 1, 0]] # bgr to rgb + data_sample = item['data_samples'].numpy() + img_path = osp.basename(item['data_samples'].img_path) + + out_file = osp.join( + args.output_dir, + osp.basename(img_path)) if args.output_dir is not None else None + + visualizer.add_datasample( + name=osp.basename(img_path), + image=img, + data_sample=data_sample, + draw_gt=True, + draw_pred=False, + wait_time=args.show_interval, + out_file=out_file, + show=not args.not_show) + progress_bar.update() + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/analysis_tools/confusion_matrix.py b/reconstruction/modules/InterFormer/tools/analysis_tools/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..39756cdfdd2341e7e02f9de24077da880b6021c3 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/analysis_tools/confusion_matrix.py @@ -0,0 +1,197 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os + +import matplotlib.pyplot as plt +import numpy as np +from matplotlib.ticker import MultipleLocator +from mmengine.config import Config, DictAction +from mmengine.registry import init_default_scope +from mmengine.utils import mkdir_or_exist, progressbar +from PIL import Image + +from mmseg.registry import DATASETS + +init_default_scope('mmseg') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Generate confusion matrix from segmentation results') + parser.add_argument('config', help='test config file path') + parser.add_argument( + 'prediction_path', help='prediction path where test folder result') + parser.add_argument( + 'save_dir', help='directory where confusion matrix will be saved') + parser.add_argument( + '--show', action='store_true', help='show confusion matrix') + parser.add_argument( + '--color-theme', + default='winter', + help='theme of the matrix color map') + parser.add_argument( + '--title', + default='Normalized Confusion Matrix', + help='title of the matrix color map') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def calculate_confusion_matrix(dataset, results): + """Calculate the confusion matrix. + + Args: + dataset (Dataset): Test or val dataset. + results (list[ndarray]): A list of segmentation results in each image. + """ + n = len(dataset.METAINFO['classes']) + confusion_matrix = np.zeros(shape=[n, n]) + assert len(dataset) == len(results) + ignore_index = dataset.ignore_index + reduce_zero_label = dataset.reduce_zero_label + prog_bar = progressbar.ProgressBar(len(results)) + for idx, per_img_res in enumerate(results): + res_segm = per_img_res + gt_segm = dataset[idx]['data_samples'] \ + .gt_sem_seg.data.squeeze().numpy().astype(np.uint8) + gt_segm, res_segm = gt_segm.flatten(), res_segm.flatten() + if reduce_zero_label: + gt_segm = gt_segm - 1 + to_ignore = gt_segm == ignore_index + + gt_segm, res_segm = gt_segm[~to_ignore], res_segm[~to_ignore] + inds = n * gt_segm + res_segm + mat = np.bincount(inds, minlength=n**2).reshape(n, n) + confusion_matrix += mat + prog_bar.update() + return confusion_matrix + + +def plot_confusion_matrix(confusion_matrix, + labels, + save_dir=None, + show=True, + title='Normalized Confusion Matrix', + color_theme='OrRd'): + """Draw confusion matrix with matplotlib. + + Args: + confusion_matrix (ndarray): The confusion matrix. + labels (list[str]): List of class names. + save_dir (str|optional): If set, save the confusion matrix plot to the + given path. Default: None. + show (bool): Whether to show the plot. Default: True. + title (str): Title of the plot. Default: `Normalized Confusion Matrix`. + color_theme (str): Theme of the matrix color map. Default: `winter`. + """ + # normalize the confusion matrix + per_label_sums = confusion_matrix.sum(axis=1)[:, np.newaxis] + confusion_matrix = \ + confusion_matrix.astype(np.float32) / per_label_sums * 100 + + num_classes = len(labels) + fig, ax = plt.subplots( + figsize=(2 * num_classes, 2 * num_classes * 0.8), dpi=300) + cmap = plt.get_cmap(color_theme) + im = ax.imshow(confusion_matrix, cmap=cmap) + colorbar = plt.colorbar(mappable=im, ax=ax) + colorbar.ax.tick_params(labelsize=20) # 设置 colorbar 标签的字体大小 + + title_font = {'weight': 'bold', 'size': 20} + ax.set_title(title, fontdict=title_font) + label_font = {'size': 40} + plt.ylabel('Ground Truth Label', fontdict=label_font) + plt.xlabel('Prediction Label', fontdict=label_font) + + # draw locator + xmajor_locator = MultipleLocator(1) + xminor_locator = MultipleLocator(0.5) + ax.xaxis.set_major_locator(xmajor_locator) + ax.xaxis.set_minor_locator(xminor_locator) + ymajor_locator = MultipleLocator(1) + yminor_locator = MultipleLocator(0.5) + ax.yaxis.set_major_locator(ymajor_locator) + ax.yaxis.set_minor_locator(yminor_locator) + + # draw grid + ax.grid(True, which='minor', linestyle='-') + + # draw label + ax.set_xticks(np.arange(num_classes)) + ax.set_yticks(np.arange(num_classes)) + ax.set_xticklabels(labels, fontsize=20) + ax.set_yticklabels(labels, fontsize=20) + + ax.tick_params( + axis='x', bottom=False, top=True, labelbottom=False, labeltop=True) + plt.setp( + ax.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor') + + # draw confusion matrix value + for i in range(num_classes): + for j in range(num_classes): + ax.text( + j, + i, + '{}%'.format( + round(confusion_matrix[i, j], 2 + ) if not np.isnan(confusion_matrix[i, j]) else -1), + ha='center', + va='center', + color='k', + size=20) + + ax.set_ylim(len(confusion_matrix) - 0.5, -0.5) # matplotlib>3.1.1 + + fig.tight_layout() + if save_dir is not None: + mkdir_or_exist(save_dir) + plt.savefig( + os.path.join(save_dir, 'confusion_matrix.png'), format='png') + if show: + plt.show() + + +def main(): + args = parse_args() + + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + results = [] + for img in sorted(os.listdir(args.prediction_path)): + img = os.path.join(args.prediction_path, img) + image = Image.open(img) + image = np.copy(image) + results.append(image) + + assert isinstance(results, list) + if isinstance(results[0], np.ndarray): + pass + else: + raise TypeError('invalid type of prediction results') + + dataset = DATASETS.build(cfg.test_dataloader.dataset) + confusion_matrix = calculate_confusion_matrix(dataset, results) + plot_confusion_matrix( + confusion_matrix, + dataset.METAINFO['classes'], + save_dir=args.save_dir, + show=args.show, + title=args.title, + color_theme=args.color_theme) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/analysis_tools/get_flops.py b/reconstruction/modules/InterFormer/tools/analysis_tools/get_flops.py new file mode 100644 index 0000000000000000000000000000000000000000..78a73988d4e037094bffb23f7e70b24439c97799 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/analysis_tools/get_flops.py @@ -0,0 +1,124 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import tempfile +from pathlib import Path + +import torch +from mmengine import Config, DictAction +from mmengine.logging import MMLogger +from mmengine.model import revert_sync_batchnorm +from mmengine.registry import init_default_scope + +from mmseg.models import BaseSegmentor +from mmseg.registry import MODELS +from mmseg.structures import SegDataSample + +try: + from mmengine.analysis import get_model_complexity_info + from mmengine.analysis.print_helper import _format_size +except ImportError: + raise ImportError('Please upgrade mmengine >= 0.6.0 to use this script.') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Get the FLOPs of a segmentor') + parser.add_argument('config', help='train config file path') + parser.add_argument( + '--shape', + type=int, + nargs='+', + default=[2048, 1024], + help='input image size') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def inference(args: argparse.Namespace, logger: MMLogger) -> dict: + config_name = Path(args.config) + + if not config_name.exists(): + logger.error(f'Config file {config_name} does not exist') + + cfg: Config = Config.fromfile(config_name) + cfg.work_dir = tempfile.TemporaryDirectory().name + cfg.log_level = 'WARN' + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + init_default_scope(cfg.get('scope', 'mmseg')) + + if len(args.shape) == 1: + input_shape = (3, args.shape[0], args.shape[0]) + elif len(args.shape) == 2: + input_shape = (3, ) + tuple(args.shape) + else: + raise ValueError('invalid input shape') + result = {} + + model: BaseSegmentor = MODELS.build(cfg.model) + if hasattr(model, 'auxiliary_head'): + model.auxiliary_head = None + if torch.cuda.is_available(): + model.cuda() + model = revert_sync_batchnorm(model) + result['ori_shape'] = input_shape[-2:] + result['pad_shape'] = input_shape[-2:] + data_batch = { + 'inputs': [torch.rand(input_shape)], + 'data_samples': [SegDataSample(metainfo=result)] + } + data = model.data_preprocessor(data_batch) + model.eval() + if cfg.model.decode_head.type in ['MaskFormerHead', 'Mask2FormerHead']: + # TODO: Support MaskFormer and Mask2Former + raise NotImplementedError('MaskFormer and Mask2Former are not ' + 'supported yet.') + outputs = get_model_complexity_info( + model, + input_shape=None, + inputs=data['inputs'], + show_table=False, + show_arch=False) + result['flops'] = _format_size(outputs['flops']) + result['params'] = _format_size(outputs['params']) + result['compute_type'] = 'direct: randomly generate a picture' + return result + + +def main(): + + args = parse_args() + logger = MMLogger.get_instance(name='MMLogger') + + result = inference(args, logger) + split_line = '=' * 30 + ori_shape = result['ori_shape'] + pad_shape = result['pad_shape'] + flops = result['flops'] + params = result['params'] + compute_type = result['compute_type'] + + if pad_shape != ori_shape: + print(f'{split_line}\nUse size divisor set input shape ' + f'from {ori_shape} to {pad_shape}') + print(f'{split_line}\nCompute type: {compute_type}\n' + f'Input shape: {pad_shape}\nFlops: {flops}\n' + f'Params: {params}\n{split_line}') + print('!!!Please be cautious if you use the results in papers. ' + 'You may need to check if all ops are supported and verify ' + 'that the flops computation is correct.') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/analysis_tools/visualization_cam.py b/reconstruction/modules/InterFormer/tools/analysis_tools/visualization_cam.py new file mode 100644 index 0000000000000000000000000000000000000000..00cdb3e04ab1f9000844ace781bc138f230d4630 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/analysis_tools/visualization_cam.py @@ -0,0 +1,127 @@ +# Copyright (c) OpenMMLab. All rights reserved. +"""Use the pytorch-grad-cam tool to visualize Class Activation Maps (CAM). + +requirement: pip install grad-cam +""" + +from argparse import ArgumentParser + +import numpy as np +import torch +import torch.nn.functional as F +from mmengine import Config +from mmengine.model import revert_sync_batchnorm +from PIL import Image +from pytorch_grad_cam import GradCAM +from pytorch_grad_cam.utils.image import preprocess_image, show_cam_on_image + +from mmseg.apis import inference_model, init_model, show_result_pyplot +from mmseg.utils import register_all_modules + + +class SemanticSegmentationTarget: + """wrap the model. + + requirement: pip install grad-cam + + Args: + category (int): Visualization class. + mask (ndarray): Mask of class. + size (tuple): Image size. + """ + + def __init__(self, category, mask, size): + self.category = category + self.mask = torch.from_numpy(mask) + self.size = size + if torch.cuda.is_available(): + self.mask = self.mask.cuda() + + def __call__(self, model_output): + model_output = torch.unsqueeze(model_output, dim=0) + model_output = F.interpolate( + model_output, size=self.size, mode='bilinear') + model_output = torch.squeeze(model_output, dim=0) + + return (model_output[self.category, :, :] * self.mask).sum() + + +def main(): + parser = ArgumentParser() + parser.add_argument('img', help='Image file') + parser.add_argument('config', help='Config file') + parser.add_argument('checkpoint', help='Checkpoint file') + parser.add_argument( + '--out-file', + default='prediction.png', + help='Path to output prediction file') + parser.add_argument( + '--cam-file', default='vis_cam.png', help='Path to output cam file') + parser.add_argument( + '--target-layers', + default='backbone.layer4[2]', + help='Target layers to visualize CAM') + parser.add_argument( + '--category-index', default='7', help='Category to visualize CAM') + parser.add_argument( + '--device', default='cuda:0', help='Device used for inference') + args = parser.parse_args() + + # build the model from a config file and a checkpoint file + register_all_modules() + model = init_model(args.config, args.checkpoint, device=args.device) + if args.device == 'cpu': + model = revert_sync_batchnorm(model) + + # test a single image + result = inference_model(model, args.img) + + # show the results + show_result_pyplot( + model, + args.img, + result, + draw_gt=False, + show=False if args.out_file is not None else True, + out_file=args.out_file) + + # result data conversion + prediction_data = result.pred_sem_seg.data + pre_np_data = prediction_data.cpu().numpy().squeeze(0) + + target_layers = args.target_layers + target_layers = [eval(f'model.{target_layers}')] + + category = int(args.category_index) + mask_float = np.float32(pre_np_data == category) + + # data processing + image = np.array(Image.open(args.img).convert('RGB')) + height, width = image.shape[0], image.shape[1] + rgb_img = np.float32(image) / 255 + config = Config.fromfile(args.config) + image_mean = config.data_preprocessor['mean'] + image_std = config.data_preprocessor['std'] + input_tensor = preprocess_image( + rgb_img, + mean=[x / 255 for x in image_mean], + std=[x / 255 for x in image_std]) + + # Grad CAM(Class Activation Maps) + # Can also be LayerCAM, XGradCAM, GradCAMPlusPlus, EigenCAM, EigenGradCAM + targets = [ + SemanticSegmentationTarget(category, mask_float, (height, width)) + ] + with GradCAM( + model=model, + target_layers=target_layers, + use_cuda=torch.cuda.is_available()) as cam: + grayscale_cam = cam(input_tensor=input_tensor, targets=targets)[0, :] + cam_image = show_cam_on_image(rgb_img, grayscale_cam, use_rgb=True) + + # save cam file + Image.fromarray(cam_image).save(args.cam_file) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/chase_db1.py b/reconstruction/modules/InterFormer/tools/dataset_converters/chase_db1.py new file mode 100644 index 0000000000000000000000000000000000000000..f4fefbd77435c5745d290269cd00f67fda604455 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/chase_db1.py @@ -0,0 +1,89 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +from mmengine.utils import mkdir_or_exist + +CHASE_DB1_LEN = 28 * 3 +TRAINING_LEN = 60 + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert CHASE_DB1 dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='path of CHASEDB1.zip') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'CHASE_DB1') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + print('Extracting CHASEDB1.zip...') + zip_file = zipfile.ZipFile(dataset_path) + zip_file.extractall(tmp_dir) + + print('Generating training dataset...') + + assert len(os.listdir(tmp_dir)) == CHASE_DB1_LEN, \ + f'len(os.listdir(tmp_dir)) != {CHASE_DB1_LEN}' + + for img_name in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(tmp_dir, img_name)) + if osp.splitext(img_name)[1] == '.jpg': + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'training', + osp.splitext(img_name)[0] + '.png')) + else: + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a + # threshold to convert the nonstandard annotation imgs. The + # value divided by 128 is equivalent to '1 if value >= 128 + # else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(img_name)[0] + '.png')) + + for img_name in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(tmp_dir, img_name)) + if osp.splitext(img_name)[1] == '.jpg': + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'validation', + osp.splitext(img_name)[0] + '.png')) + else: + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(img_name)[0] + '.png')) + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/cityscapes.py b/reconstruction/modules/InterFormer/tools/dataset_converters/cityscapes.py new file mode 100644 index 0000000000000000000000000000000000000000..0d6a80135d906db7330a736ccbcc908e0a6309c6 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/cityscapes.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +from cityscapesscripts.preparation.json2labelImg import json2labelImg +from mmengine.utils import (mkdir_or_exist, scandir, track_parallel_progress, + track_progress) + + +def convert_json_to_label(json_file): + label_file = json_file.replace('_polygons.json', '_labelTrainIds.png') + json2labelImg(json_file, label_file, 'trainIds') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert Cityscapes annotations to TrainIds') + parser.add_argument('cityscapes_path', help='cityscapes data path') + parser.add_argument('--gt-dir', default='gtFine', type=str) + parser.add_argument('-o', '--out-dir', help='output path') + parser.add_argument( + '--nproc', default=1, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cityscapes_path = args.cityscapes_path + out_dir = args.out_dir if args.out_dir else cityscapes_path + mkdir_or_exist(out_dir) + + gt_dir = osp.join(cityscapes_path, args.gt_dir) + + poly_files = [] + for poly in scandir(gt_dir, '_polygons.json', recursive=True): + poly_file = osp.join(gt_dir, poly) + poly_files.append(poly_file) + if args.nproc > 1: + track_parallel_progress(convert_json_to_label, poly_files, args.nproc) + else: + track_progress(convert_json_to_label, poly_files) + + split_names = ['train', 'val', 'test'] + + for split in split_names: + filenames = [] + for poly in scandir( + osp.join(gt_dir, split), '_polygons.json', recursive=True): + filenames.append(poly.replace('_gtFine_polygons.json', '')) + with open(osp.join(out_dir, f'{split}.txt'), 'w') as f: + f.writelines(f + '\n' for f in filenames) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/coco_stuff10k.py b/reconstruction/modules/InterFormer/tools/dataset_converters/coco_stuff10k.py new file mode 100644 index 0000000000000000000000000000000000000000..920127ee10fc09b76f8e2344ecdf3b7800d51802 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/coco_stuff10k.py @@ -0,0 +1,308 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import shutil +from functools import partial + +import numpy as np +from mmengine.utils import (mkdir_or_exist, track_parallel_progress, + track_progress) +from PIL import Image +from scipy.io import loadmat + +COCO_LEN = 10000 + +clsID_to_trID = { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 5: 5, + 6: 6, + 7: 7, + 8: 8, + 9: 9, + 10: 10, + 11: 11, + 13: 12, + 14: 13, + 15: 14, + 16: 15, + 17: 16, + 18: 17, + 19: 18, + 20: 19, + 21: 20, + 22: 21, + 23: 22, + 24: 23, + 25: 24, + 27: 25, + 28: 26, + 31: 27, + 32: 28, + 33: 29, + 34: 30, + 35: 31, + 36: 32, + 37: 33, + 38: 34, + 39: 35, + 40: 36, + 41: 37, + 42: 38, + 43: 39, + 44: 40, + 46: 41, + 47: 42, + 48: 43, + 49: 44, + 50: 45, + 51: 46, + 52: 47, + 53: 48, + 54: 49, + 55: 50, + 56: 51, + 57: 52, + 58: 53, + 59: 54, + 60: 55, + 61: 56, + 62: 57, + 63: 58, + 64: 59, + 65: 60, + 67: 61, + 70: 62, + 72: 63, + 73: 64, + 74: 65, + 75: 66, + 76: 67, + 77: 68, + 78: 69, + 79: 70, + 80: 71, + 81: 72, + 82: 73, + 84: 74, + 85: 75, + 86: 76, + 87: 77, + 88: 78, + 89: 79, + 90: 80, + 92: 81, + 93: 82, + 94: 83, + 95: 84, + 96: 85, + 97: 86, + 98: 87, + 99: 88, + 100: 89, + 101: 90, + 102: 91, + 103: 92, + 104: 93, + 105: 94, + 106: 95, + 107: 96, + 108: 97, + 109: 98, + 110: 99, + 111: 100, + 112: 101, + 113: 102, + 114: 103, + 115: 104, + 116: 105, + 117: 106, + 118: 107, + 119: 108, + 120: 109, + 121: 110, + 122: 111, + 123: 112, + 124: 113, + 125: 114, + 126: 115, + 127: 116, + 128: 117, + 129: 118, + 130: 119, + 131: 120, + 132: 121, + 133: 122, + 134: 123, + 135: 124, + 136: 125, + 137: 126, + 138: 127, + 139: 128, + 140: 129, + 141: 130, + 142: 131, + 143: 132, + 144: 133, + 145: 134, + 146: 135, + 147: 136, + 148: 137, + 149: 138, + 150: 139, + 151: 140, + 152: 141, + 153: 142, + 154: 143, + 155: 144, + 156: 145, + 157: 146, + 158: 147, + 159: 148, + 160: 149, + 161: 150, + 162: 151, + 163: 152, + 164: 153, + 165: 154, + 166: 155, + 167: 156, + 168: 157, + 169: 158, + 170: 159, + 171: 160, + 172: 161, + 173: 162, + 174: 163, + 175: 164, + 176: 165, + 177: 166, + 178: 167, + 179: 168, + 180: 169, + 181: 170, + 182: 171 +} + + +def convert_to_trainID(tuple_path, in_img_dir, in_ann_dir, out_img_dir, + out_mask_dir, is_train): + imgpath, maskpath = tuple_path + shutil.copyfile( + osp.join(in_img_dir, imgpath), + osp.join(out_img_dir, 'train2014', imgpath) if is_train else osp.join( + out_img_dir, 'test2014', imgpath)) + annotate = loadmat(osp.join(in_ann_dir, maskpath)) + mask = annotate['S'].astype(np.uint8) + mask_copy = mask.copy() + for clsID, trID in clsID_to_trID.items(): + mask_copy[mask == clsID] = trID + seg_filename = osp.join(out_mask_dir, 'train2014', + maskpath.split('.')[0] + + '_labelTrainIds.png') if is_train else osp.join( + out_mask_dir, 'test2014', + maskpath.split('.')[0] + '_labelTrainIds.png') + Image.fromarray(mask_copy).save(seg_filename, 'PNG') + + +def generate_coco_list(folder): + train_list = osp.join(folder, 'imageLists', 'train.txt') + test_list = osp.join(folder, 'imageLists', 'test.txt') + train_paths = [] + test_paths = [] + + with open(train_list) as f: + for filename in f: + basename = filename.strip() + imgpath = basename + '.jpg' + maskpath = basename + '.mat' + train_paths.append((imgpath, maskpath)) + + with open(test_list) as f: + for filename in f: + basename = filename.strip() + imgpath = basename + '.jpg' + maskpath = basename + '.mat' + test_paths.append((imgpath, maskpath)) + + return train_paths, test_paths + + +def parse_args(): + parser = argparse.ArgumentParser( + description=\ + 'Convert COCO Stuff 10k annotations to mmsegmentation format') # noqa + parser.add_argument('coco_path', help='coco stuff path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--nproc', default=16, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + coco_path = args.coco_path + nproc = args.nproc + + out_dir = args.out_dir or coco_path + out_img_dir = osp.join(out_dir, 'images') + out_mask_dir = osp.join(out_dir, 'annotations') + + mkdir_or_exist(osp.join(out_img_dir, 'train2014')) + mkdir_or_exist(osp.join(out_img_dir, 'test2014')) + mkdir_or_exist(osp.join(out_mask_dir, 'train2014')) + mkdir_or_exist(osp.join(out_mask_dir, 'test2014')) + + train_list, test_list = generate_coco_list(coco_path) + assert (len(train_list) + + len(test_list)) == COCO_LEN, 'Wrong length of list {} & {}'.format( + len(train_list), len(test_list)) + + if args.nproc > 1: + track_parallel_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=True), + train_list, + nproc=nproc) + track_parallel_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=False), + test_list, + nproc=nproc) + else: + track_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=True), train_list) + track_progress( + partial( + convert_to_trainID, + in_img_dir=osp.join(coco_path, 'images'), + in_ann_dir=osp.join(coco_path, 'annotations'), + out_img_dir=out_img_dir, + out_mask_dir=out_mask_dir, + is_train=False), test_list) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/coco_stuff164k.py b/reconstruction/modules/InterFormer/tools/dataset_converters/coco_stuff164k.py new file mode 100644 index 0000000000000000000000000000000000000000..a13114ab1e0c37675369b2e9ba065cbfb2dca1e7 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/coco_stuff164k.py @@ -0,0 +1,265 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import shutil +from functools import partial +from glob import glob + +import numpy as np +from mmengine.utils import (mkdir_or_exist, track_parallel_progress, + track_progress) +from PIL import Image + +COCO_LEN = 123287 + +clsID_to_trID = { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 5: 5, + 6: 6, + 7: 7, + 8: 8, + 9: 9, + 10: 10, + 12: 11, + 13: 12, + 14: 13, + 15: 14, + 16: 15, + 17: 16, + 18: 17, + 19: 18, + 20: 19, + 21: 20, + 22: 21, + 23: 22, + 24: 23, + 26: 24, + 27: 25, + 30: 26, + 31: 27, + 32: 28, + 33: 29, + 34: 30, + 35: 31, + 36: 32, + 37: 33, + 38: 34, + 39: 35, + 40: 36, + 41: 37, + 42: 38, + 43: 39, + 45: 40, + 46: 41, + 47: 42, + 48: 43, + 49: 44, + 50: 45, + 51: 46, + 52: 47, + 53: 48, + 54: 49, + 55: 50, + 56: 51, + 57: 52, + 58: 53, + 59: 54, + 60: 55, + 61: 56, + 62: 57, + 63: 58, + 64: 59, + 66: 60, + 69: 61, + 71: 62, + 72: 63, + 73: 64, + 74: 65, + 75: 66, + 76: 67, + 77: 68, + 78: 69, + 79: 70, + 80: 71, + 81: 72, + 83: 73, + 84: 74, + 85: 75, + 86: 76, + 87: 77, + 88: 78, + 89: 79, + 91: 80, + 92: 81, + 93: 82, + 94: 83, + 95: 84, + 96: 85, + 97: 86, + 98: 87, + 99: 88, + 100: 89, + 101: 90, + 102: 91, + 103: 92, + 104: 93, + 105: 94, + 106: 95, + 107: 96, + 108: 97, + 109: 98, + 110: 99, + 111: 100, + 112: 101, + 113: 102, + 114: 103, + 115: 104, + 116: 105, + 117: 106, + 118: 107, + 119: 108, + 120: 109, + 121: 110, + 122: 111, + 123: 112, + 124: 113, + 125: 114, + 126: 115, + 127: 116, + 128: 117, + 129: 118, + 130: 119, + 131: 120, + 132: 121, + 133: 122, + 134: 123, + 135: 124, + 136: 125, + 137: 126, + 138: 127, + 139: 128, + 140: 129, + 141: 130, + 142: 131, + 143: 132, + 144: 133, + 145: 134, + 146: 135, + 147: 136, + 148: 137, + 149: 138, + 150: 139, + 151: 140, + 152: 141, + 153: 142, + 154: 143, + 155: 144, + 156: 145, + 157: 146, + 158: 147, + 159: 148, + 160: 149, + 161: 150, + 162: 151, + 163: 152, + 164: 153, + 165: 154, + 166: 155, + 167: 156, + 168: 157, + 169: 158, + 170: 159, + 171: 160, + 172: 161, + 173: 162, + 174: 163, + 175: 164, + 176: 165, + 177: 166, + 178: 167, + 179: 168, + 180: 169, + 181: 170, + 255: 255 +} + + +def convert_to_trainID(maskpath, out_mask_dir, is_train): + mask = np.array(Image.open(maskpath)) + mask_copy = mask.copy() + for clsID, trID in clsID_to_trID.items(): + mask_copy[mask == clsID] = trID + seg_filename = osp.join( + out_mask_dir, 'train2017', + osp.basename(maskpath).split('.')[0] + + '_labelTrainIds.png') if is_train else osp.join( + out_mask_dir, 'val2017', + osp.basename(maskpath).split('.')[0] + '_labelTrainIds.png') + Image.fromarray(mask_copy).save(seg_filename, 'PNG') + + +def parse_args(): + parser = argparse.ArgumentParser( + description=\ + 'Convert COCO Stuff 164k annotations to mmsegmentation format') # noqa + parser.add_argument('coco_path', help='coco stuff path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--nproc', default=16, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + coco_path = args.coco_path + nproc = args.nproc + + out_dir = args.out_dir or coco_path + out_img_dir = osp.join(out_dir, 'images') + out_mask_dir = osp.join(out_dir, 'annotations') + + mkdir_or_exist(osp.join(out_mask_dir, 'train2017')) + mkdir_or_exist(osp.join(out_mask_dir, 'val2017')) + + if out_dir != coco_path: + shutil.copytree(osp.join(coco_path, 'images'), out_img_dir) + + train_list = glob(osp.join(coco_path, 'annotations', 'train2017', '*.png')) + train_list = [file for file in train_list if '_labelTrainIds' not in file] + test_list = glob(osp.join(coco_path, 'annotations', 'val2017', '*.png')) + test_list = [file for file in test_list if '_labelTrainIds' not in file] + assert (len(train_list) + + len(test_list)) == COCO_LEN, 'Wrong length of list {} & {}'.format( + len(train_list), len(test_list)) + + if args.nproc > 1: + track_parallel_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=True), + train_list, + nproc=nproc) + track_parallel_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=False), + test_list, + nproc=nproc) + else: + track_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=True), + train_list) + track_progress( + partial( + convert_to_trainID, out_mask_dir=out_mask_dir, is_train=False), + test_list) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/drive.py b/reconstruction/modules/InterFormer/tools/dataset_converters/drive.py new file mode 100644 index 0000000000000000000000000000000000000000..076fd05a2029216e0f1a1494610181fdaa7fbef9 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/drive.py @@ -0,0 +1,114 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import cv2 +import mmcv +from mmengine.utils import mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert DRIVE dataset to mmsegmentation format') + parser.add_argument( + 'training_path', help='the training part of DRIVE dataset') + parser.add_argument( + 'testing_path', help='the testing part of DRIVE dataset') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + training_path = args.training_path + testing_path = args.testing_path + if args.out_dir is None: + out_dir = osp.join('data', 'DRIVE') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + print('Extracting training.zip...') + zip_file = zipfile.ZipFile(training_path) + zip_file.extractall(tmp_dir) + + print('Generating training dataset...') + now_dir = osp.join(tmp_dir, 'training', 'images') + for img_name in os.listdir(now_dir): + img = mmcv.imread(osp.join(now_dir, img_name)) + mmcv.imwrite( + img, + osp.join( + out_dir, 'images', 'training', + osp.splitext(img_name)[0].replace('_training', '') + + '.png')) + + now_dir = osp.join(tmp_dir, 'training', '1st_manual') + for img_name in os.listdir(now_dir): + cap = cv2.VideoCapture(osp.join(now_dir, img_name)) + ret, img = cap.read() + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(img_name)[0] + '.png')) + + print('Extracting test.zip...') + zip_file = zipfile.ZipFile(testing_path) + zip_file.extractall(tmp_dir) + + print('Generating validation dataset...') + now_dir = osp.join(tmp_dir, 'test', 'images') + for img_name in os.listdir(now_dir): + img = mmcv.imread(osp.join(now_dir, img_name)) + mmcv.imwrite( + img, + osp.join( + out_dir, 'images', 'validation', + osp.splitext(img_name)[0].replace('_test', '') + '.png')) + + now_dir = osp.join(tmp_dir, 'test', '1st_manual') + if osp.exists(now_dir): + for img_name in os.listdir(now_dir): + cap = cv2.VideoCapture(osp.join(now_dir, img_name)) + ret, img = cap.read() + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a + # threshold to convert the nonstandard annotation imgs. The + # value divided by 128 is equivalent to '1 if value >= 128 + # else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(img_name)[0] + '.png')) + + now_dir = osp.join(tmp_dir, 'test', '2nd_manual') + if osp.exists(now_dir): + for img_name in os.listdir(now_dir): + cap = cv2.VideoCapture(osp.join(now_dir, img_name)) + ret, img = cap.read() + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(img_name)[0] + '.png')) + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/hrf.py b/reconstruction/modules/InterFormer/tools/dataset_converters/hrf.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfd80c9ee42e3b5cba4a12a6c8b32ddbb2f1f11 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/hrf.py @@ -0,0 +1,112 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +from mmengine.utils import mkdir_or_exist + +HRF_LEN = 15 +TRAINING_LEN = 5 + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert HRF dataset to mmsegmentation format') + parser.add_argument('healthy_path', help='the path of healthy.zip') + parser.add_argument( + 'healthy_manualsegm_path', help='the path of healthy_manualsegm.zip') + parser.add_argument('glaucoma_path', help='the path of glaucoma.zip') + parser.add_argument( + 'glaucoma_manualsegm_path', help='the path of glaucoma_manualsegm.zip') + parser.add_argument( + 'diabetic_retinopathy_path', + help='the path of diabetic_retinopathy.zip') + parser.add_argument( + 'diabetic_retinopathy_manualsegm_path', + help='the path of diabetic_retinopathy_manualsegm.zip') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + images_path = [ + args.healthy_path, args.glaucoma_path, args.diabetic_retinopathy_path + ] + annotations_path = [ + args.healthy_manualsegm_path, args.glaucoma_manualsegm_path, + args.diabetic_retinopathy_manualsegm_path + ] + if args.out_dir is None: + out_dir = osp.join('data', 'HRF') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + print('Generating images...') + for now_path in images_path: + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + zip_file = zipfile.ZipFile(now_path) + zip_file.extractall(tmp_dir) + + assert len(os.listdir(tmp_dir)) == HRF_LEN, \ + f'len(os.listdir(tmp_dir)) != {HRF_LEN}' + + for filename in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'training', + osp.splitext(filename)[0] + '.png')) + for filename in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Generating annotations...') + for now_path in annotations_path: + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + zip_file = zipfile.ZipFile(now_path) + zip_file.extractall(tmp_dir) + + assert len(os.listdir(tmp_dir)) == HRF_LEN, \ + f'len(os.listdir(tmp_dir)) != {HRF_LEN}' + + for filename in sorted(os.listdir(tmp_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a + # threshold to convert the nonstandard annotation imgs. The + # value divided by 128 is equivalent to '1 if value >= 128 + # else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(filename)[0] + '.png')) + for filename in sorted(os.listdir(tmp_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(tmp_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/isaid.py b/reconstruction/modules/InterFormer/tools/dataset_converters/isaid.py new file mode 100644 index 0000000000000000000000000000000000000000..1d5ccd9c776e9621c261e6d168bf6aa4f7b451f6 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/isaid.py @@ -0,0 +1,246 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import os +import os.path as osp +import shutil +import tempfile +import zipfile + +import mmcv +import numpy as np +from mmengine.utils import ProgressBar, mkdir_or_exist +from PIL import Image + +iSAID_palette = \ + { + 0: (0, 0, 0), + 1: (0, 0, 63), + 2: (0, 63, 63), + 3: (0, 63, 0), + 4: (0, 63, 127), + 5: (0, 63, 191), + 6: (0, 63, 255), + 7: (0, 127, 63), + 8: (0, 127, 127), + 9: (0, 0, 127), + 10: (0, 0, 191), + 11: (0, 0, 255), + 12: (0, 191, 127), + 13: (0, 127, 191), + 14: (0, 127, 255), + 15: (0, 100, 155) + } + +iSAID_invert_palette = {v: k for k, v in iSAID_palette.items()} + + +def iSAID_convert_from_color(arr_3d, palette=iSAID_invert_palette): + """RGB-color encoding to grayscale labels.""" + arr_2d = np.zeros((arr_3d.shape[0], arr_3d.shape[1]), dtype=np.uint8) + + for c, i in palette.items(): + m = np.all(arr_3d == np.array(c).reshape(1, 1, 3), axis=2) + arr_2d[m] = i + + return arr_2d + + +def slide_crop_image(src_path, out_dir, mode, patch_H, patch_W, overlap): + img = np.asarray(Image.open(src_path).convert('RGB')) + + img_H, img_W, _ = img.shape + + if img_H < patch_H and img_W > patch_W: + + img = mmcv.impad(img, shape=(patch_H, img_W), pad_val=0) + + img_H, img_W, _ = img.shape + + elif img_H > patch_H and img_W < patch_W: + + img = mmcv.impad(img, shape=(img_H, patch_W), pad_val=0) + + img_H, img_W, _ = img.shape + + elif img_H < patch_H and img_W < patch_W: + + img = mmcv.impad(img, shape=(patch_H, patch_W), pad_val=0) + + img_H, img_W, _ = img.shape + + for x in range(0, img_W, patch_W - overlap): + for y in range(0, img_H, patch_H - overlap): + x_str = x + x_end = x + patch_W + if x_end > img_W: + diff_x = x_end - img_W + x_str -= diff_x + x_end = img_W + y_str = y + y_end = y + patch_H + if y_end > img_H: + diff_y = y_end - img_H + y_str -= diff_y + y_end = img_H + + img_patch = img[y_str:y_end, x_str:x_end, :] + img_patch = Image.fromarray(img_patch.astype(np.uint8)) + image = osp.basename(src_path).split('.')[0] + '_' + str( + y_str) + '_' + str(y_end) + '_' + str(x_str) + '_' + str( + x_end) + '.png' + # print(image) + save_path_image = osp.join(out_dir, 'img_dir', mode, str(image)) + img_patch.save(save_path_image, format='BMP') + + +def slide_crop_label(src_path, out_dir, mode, patch_H, patch_W, overlap): + label = mmcv.imread(src_path, channel_order='rgb') + label = iSAID_convert_from_color(label) + img_H, img_W = label.shape + + if img_H < patch_H and img_W > patch_W: + + label = mmcv.impad(label, shape=(patch_H, img_W), pad_val=255) + + img_H = patch_H + + elif img_H > patch_H and img_W < patch_W: + + label = mmcv.impad(label, shape=(img_H, patch_W), pad_val=255) + + img_W = patch_W + + elif img_H < patch_H and img_W < patch_W: + + label = mmcv.impad(label, shape=(patch_H, patch_W), pad_val=255) + + img_H = patch_H + img_W = patch_W + + for x in range(0, img_W, patch_W - overlap): + for y in range(0, img_H, patch_H - overlap): + x_str = x + x_end = x + patch_W + if x_end > img_W: + diff_x = x_end - img_W + x_str -= diff_x + x_end = img_W + y_str = y + y_end = y + patch_H + if y_end > img_H: + diff_y = y_end - img_H + y_str -= diff_y + y_end = img_H + + lab_patch = label[y_str:y_end, x_str:x_end] + lab_patch = Image.fromarray(lab_patch.astype(np.uint8), mode='P') + + image = osp.basename(src_path).split('.')[0].split( + '_')[0] + '_' + str(y_str) + '_' + str(y_end) + '_' + str( + x_str) + '_' + str(x_end) + '_instance_color_RGB' + '.png' + lab_patch.save(osp.join(out_dir, 'ann_dir', mode, str(image))) + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert iSAID dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='iSAID folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + + parser.add_argument( + '--patch_width', + default=896, + type=int, + help='Width of the cropped image patch') + parser.add_argument( + '--patch_height', + default=896, + type=int, + help='Height of the cropped image patch') + parser.add_argument( + '--overlap_area', default=384, type=int, help='Overlap area') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + dataset_path = args.dataset_path + # image patch width and height + patch_H, patch_W = args.patch_width, args.patch_height + + overlap = args.overlap_area # overlap area + + if args.out_dir is None: + out_dir = osp.join('data', 'iSAID') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'test')) + + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'test')) + + assert os.path.exists(os.path.join(dataset_path, 'train')), \ + f'train is not in {dataset_path}' + assert os.path.exists(os.path.join(dataset_path, 'val')), \ + f'val is not in {dataset_path}' + assert os.path.exists(os.path.join(dataset_path, 'test')), \ + f'test is not in {dataset_path}' + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for dataset_mode in ['train', 'val', 'test']: + + # for dataset_mode in [ 'test']: + print(f'Extracting {dataset_mode}ing.zip...') + img_zipp_list = glob.glob( + os.path.join(dataset_path, dataset_mode, 'images', '*.zip')) + print('Find the data', img_zipp_list) + for img_zipp in img_zipp_list: + zip_file = zipfile.ZipFile(img_zipp) + zip_file.extractall(os.path.join(tmp_dir, dataset_mode, 'img')) + src_path_list = glob.glob( + os.path.join(tmp_dir, dataset_mode, 'img', 'images', '*.png')) + + src_prog_bar = ProgressBar(len(src_path_list)) + for i, img_path in enumerate(src_path_list): + if dataset_mode != 'test': + slide_crop_image(img_path, out_dir, dataset_mode, patch_H, + patch_W, overlap) + + else: + shutil.move(img_path, + os.path.join(out_dir, 'img_dir', dataset_mode)) + src_prog_bar.update() + + if dataset_mode != 'test': + label_zipp_list = glob.glob( + os.path.join(dataset_path, dataset_mode, 'Semantic_masks', + '*.zip')) + for label_zipp in label_zipp_list: + zip_file = zipfile.ZipFile(label_zipp) + zip_file.extractall( + os.path.join(tmp_dir, dataset_mode, 'lab')) + + lab_path_list = glob.glob( + os.path.join(tmp_dir, dataset_mode, 'lab', 'images', + '*.png')) + lab_prog_bar = ProgressBar(len(lab_path_list)) + for i, lab_path in enumerate(lab_path_list): + slide_crop_label(lab_path, out_dir, dataset_mode, patch_H, + patch_W, overlap) + lab_prog_bar.update() + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/levircd.py b/reconstruction/modules/InterFormer/tools/dataset_converters/levircd.py new file mode 100644 index 0000000000000000000000000000000000000000..8717f3e856ba3f171b511f34d0217e1fda87ccb6 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/levircd.py @@ -0,0 +1,99 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import math +import os +import os.path as osp + +import mmcv +import numpy as np +from mmengine.utils import ProgressBar + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert levir-cd dataset to mmsegmentation format') + parser.add_argument('--dataset_path', help='potsdam folder path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--clip_size', + type=int, + help='clipped size of image after preparation', + default=256) + parser.add_argument( + '--stride_size', + type=int, + help='stride of clipping original images', + default=256) + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + input_folder = args.dataset_path + png_files = glob.glob( + os.path.join(input_folder, '**/*.png'), recursive=True) + output_folder = args.out_dir + prog_bar = ProgressBar(len(png_files)) + for png_file in png_files: + new_path = os.path.join( + output_folder, + os.path.relpath(os.path.dirname(png_file), input_folder)) + os.makedirs(os.path.dirname(new_path), exist_ok=True) + label = False + if 'label' in png_file: + label = True + clip_big_image(png_file, new_path, args, label) + prog_bar.update() + + +def clip_big_image(image_path, clip_save_dir, args, to_label=False): + image = mmcv.imread(image_path) + + h, w, c = image.shape + clip_size = args.clip_size + stride_size = args.stride_size + + num_rows = math.ceil((h - clip_size) / stride_size) if math.ceil( + (h - clip_size) / + stride_size) * stride_size + clip_size >= h else math.ceil( + (h - clip_size) / stride_size) + 1 + num_cols = math.ceil((w - clip_size) / stride_size) if math.ceil( + (w - clip_size) / + stride_size) * stride_size + clip_size >= w else math.ceil( + (w - clip_size) / stride_size) + 1 + + x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1)) + xmin = x * clip_size + ymin = y * clip_size + + xmin = xmin.ravel() + ymin = ymin.ravel() + xmin_offset = np.where(xmin + clip_size > w, w - xmin - clip_size, + np.zeros_like(xmin)) + ymin_offset = np.where(ymin + clip_size > h, h - ymin - clip_size, + np.zeros_like(ymin)) + boxes = np.stack([ + xmin + xmin_offset, ymin + ymin_offset, + np.minimum(xmin + clip_size, w), + np.minimum(ymin + clip_size, h) + ], + axis=1) + + if to_label: + image[image == 255] = 1 + image = image[:, :, 0] + for box in boxes: + start_x, start_y, end_x, end_y = box + clipped_image = image[start_y:end_y, start_x:end_x] \ + if to_label else image[start_y:end_y, start_x:end_x, :] + idx = osp.basename(image_path).split('.')[0] + mmcv.imwrite( + clipped_image.astype(np.uint8), + osp.join(clip_save_dir, + f'{idx}_{start_x}_{start_y}_{end_x}_{end_y}.png')) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/loveda.py b/reconstruction/modules/InterFormer/tools/dataset_converters/loveda.py new file mode 100644 index 0000000000000000000000000000000000000000..5b0ef4bb8bbd07f60dfc0397e9659f0200b96f5d --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/loveda.py @@ -0,0 +1,73 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import shutil +import tempfile +import zipfile + +from mmengine.utils import mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert LoveDA dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='LoveDA folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'loveDA') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'img_dir')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'test')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + + assert 'Train.zip' in os.listdir(dataset_path), \ + f'Train.zip is not in {dataset_path}' + assert 'Val.zip' in os.listdir(dataset_path), \ + f'Val.zip is not in {dataset_path}' + assert 'Test.zip' in os.listdir(dataset_path), \ + f'Test.zip is not in {dataset_path}' + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for dataset in ['Train', 'Val', 'Test']: + zip_file = zipfile.ZipFile( + os.path.join(dataset_path, dataset + '.zip')) + zip_file.extractall(tmp_dir) + data_type = dataset.lower() + for location in ['Rural', 'Urban']: + for image_type in ['images_png', 'masks_png']: + if image_type == 'images_png': + dst = osp.join(out_dir, 'img_dir', data_type) + else: + dst = osp.join(out_dir, 'ann_dir', data_type) + if dataset == 'Test' and image_type == 'masks_png': + continue + else: + src_dir = osp.join(tmp_dir, dataset, location, + image_type) + src_lst = os.listdir(src_dir) + for file in src_lst: + shutil.move(osp.join(src_dir, file), dst) + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/nyu.py b/reconstruction/modules/InterFormer/tools/dataset_converters/nyu.py new file mode 100644 index 0000000000000000000000000000000000000000..49e09e7af6844b709e681f6d9f4df14ed547a00c --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/nyu.py @@ -0,0 +1,89 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +import shutil +import tempfile +import zipfile + +from mmengine.utils import mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert NYU Depth dataset to mmsegmentation format') + parser.add_argument('raw_data', help='the path of raw data') + parser.add_argument( + '-o', '--out_dir', help='output path', default='./data/nyu') + args = parser.parse_args() + return args + + +def reorganize(raw_data_dir: str, out_dir: str): + """Reorganize NYU Depth dataset files into the required directory + structure. + + Args: + raw_data_dir (str): Path to the raw data directory. + out_dir (str): Output directory for the organized dataset. + """ + + def move_data(data_list, dst_prefix, fname_func): + """Move data files from source to destination directory. + + Args: + data_list (list): List of data file paths. + dst_prefix (str): Prefix to be added to destination paths. + fname_func (callable): Function to process file names + """ + for data_item in data_list: + data_item = data_item.strip().strip('/') + new_item = fname_func(data_item) + shutil.move( + osp.join(raw_data_dir, data_item), + osp.join(out_dir, dst_prefix, new_item)) + + def process_phase(phase): + """Process a dataset phase (e.g., 'train' or 'test').""" + with open(osp.join(raw_data_dir, f'nyu_{phase}.txt')) as f: + data = filter(lambda x: len(x.strip()) > 0, f.readlines()) + data = map(lambda x: x.split()[:2], data) + images, annos = zip(*data) + + move_data(images, f'images/{phase}', + lambda x: x.replace('/rgb', '')) + move_data(annos, f'annotations/{phase}', + lambda x: x.replace('/sync_depth', '')) + + process_phase('train') + process_phase('test') + + +def main(): + args = parse_args() + + print('Making directories...') + mkdir_or_exist(args.out_dir) + for subdir in [ + 'images/train', 'images/test', 'annotations/train', + 'annotations/test' + ]: + mkdir_or_exist(osp.join(args.out_dir, subdir)) + + print('Generating images and annotations...') + + if args.raw_data.endswith('.zip'): + with tempfile.TemporaryDirectory() as tmp_dir: + zip_file = zipfile.ZipFile(args.raw_data) + zip_file.extractall(tmp_dir) + reorganize(osp.join(tmp_dir, 'nyu'), args.out_dir) + else: + assert osp.isdir( + args.raw_data + ), 'the argument --raw-data should be either a zip file or directory.' + reorganize(args.raw_data, args.out_dir) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/pascal_context.py b/reconstruction/modules/InterFormer/tools/dataset_converters/pascal_context.py new file mode 100644 index 0000000000000000000000000000000000000000..a92d1dc6411137b92fe67fbde0fc554060194085 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/pascal_context.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from functools import partial + +import numpy as np +from detail import Detail +from mmengine.utils import mkdir_or_exist, track_progress +from PIL import Image + +_mapping = np.sort( + np.array([ + 0, 2, 259, 260, 415, 324, 9, 258, 144, 18, 19, 22, 23, 397, 25, 284, + 158, 159, 416, 33, 162, 420, 454, 295, 296, 427, 44, 45, 46, 308, 59, + 440, 445, 31, 232, 65, 354, 424, 68, 326, 72, 458, 34, 207, 80, 355, + 85, 347, 220, 349, 360, 98, 187, 104, 105, 366, 189, 368, 113, 115 + ])) +_key = np.array(range(len(_mapping))).astype('uint8') + + +def generate_labels(img_id, detail, out_dir): + + def _class_to_index(mask, _mapping, _key): + # assert the values + values = np.unique(mask) + for i in range(len(values)): + assert (values[i] in _mapping) + index = np.digitize(mask.ravel(), _mapping, right=True) + return _key[index].reshape(mask.shape) + + mask = Image.fromarray( + _class_to_index(detail.getMask(img_id), _mapping=_mapping, _key=_key)) + filename = img_id['file_name'] + mask.save(osp.join(out_dir, filename.replace('jpg', 'png'))) + return osp.splitext(osp.basename(filename))[0] + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert PASCAL VOC annotations to mmsegmentation format') + parser.add_argument('devkit_path', help='pascal voc devkit path') + parser.add_argument('json_path', help='annoation json filepath') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + devkit_path = args.devkit_path + if args.out_dir is None: + out_dir = osp.join(devkit_path, 'VOC2010', 'SegmentationClassContext') + else: + out_dir = args.out_dir + json_path = args.json_path + mkdir_or_exist(out_dir) + img_dir = osp.join(devkit_path, 'VOC2010', 'JPEGImages') + + train_detail = Detail(json_path, img_dir, 'train') + train_ids = train_detail.getImgs() + + val_detail = Detail(json_path, img_dir, 'val') + val_ids = val_detail.getImgs() + + mkdir_or_exist( + osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext')) + + train_list = track_progress( + partial(generate_labels, detail=train_detail, out_dir=out_dir), + train_ids) + with open( + osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext', + 'train.txt'), 'w') as f: + f.writelines(line + '\n' for line in sorted(train_list)) + + val_list = track_progress( + partial(generate_labels, detail=val_detail, out_dir=out_dir), val_ids) + with open( + osp.join(devkit_path, 'VOC2010/ImageSets/SegmentationContext', + 'val.txt'), 'w') as f: + f.writelines(line + '\n' for line in sorted(val_list)) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/potsdam.py b/reconstruction/modules/InterFormer/tools/dataset_converters/potsdam.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c713ee2a08d2f6eaf68fb225899504b8f4e829 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/potsdam.py @@ -0,0 +1,158 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import math +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +import numpy as np +from mmengine.utils import ProgressBar, mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert potsdam dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='potsdam folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--clip_size', + type=int, + help='clipped size of image after preparation', + default=512) + parser.add_argument( + '--stride_size', + type=int, + help='stride of clipping original images', + default=256) + args = parser.parse_args() + return args + + +def clip_big_image(image_path, clip_save_dir, args, to_label=False): + # Original image of Potsdam dataset is very large, thus pre-processing + # of them is adopted. Given fixed clip size and stride size to generate + # clipped image, the intersection of width and height is determined. + # For example, given one 5120 x 5120 original image, the clip size is + # 512 and stride size is 256, thus it would generate 20x20 = 400 images + # whose size are all 512x512. + image = mmcv.imread(image_path) + + h, w, c = image.shape + clip_size = args.clip_size + stride_size = args.stride_size + + num_rows = math.ceil((h - clip_size) / stride_size) if math.ceil( + (h - clip_size) / + stride_size) * stride_size + clip_size >= h else math.ceil( + (h - clip_size) / stride_size) + 1 + num_cols = math.ceil((w - clip_size) / stride_size) if math.ceil( + (w - clip_size) / + stride_size) * stride_size + clip_size >= w else math.ceil( + (w - clip_size) / stride_size) + 1 + + x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1)) + xmin = x * clip_size + ymin = y * clip_size + + xmin = xmin.ravel() + ymin = ymin.ravel() + xmin_offset = np.where(xmin + clip_size > w, w - xmin - clip_size, + np.zeros_like(xmin)) + ymin_offset = np.where(ymin + clip_size > h, h - ymin - clip_size, + np.zeros_like(ymin)) + boxes = np.stack([ + xmin + xmin_offset, ymin + ymin_offset, + np.minimum(xmin + clip_size, w), + np.minimum(ymin + clip_size, h) + ], + axis=1) + + if to_label: + color_map = np.array([[0, 0, 0], [255, 255, 255], [255, 0, 0], + [255, 255, 0], [0, 255, 0], [0, 255, 255], + [0, 0, 255]]) + flatten_v = np.matmul( + image.reshape(-1, c), + np.array([2, 3, 4]).reshape(3, 1)) + out = np.zeros_like(flatten_v) + for idx, class_color in enumerate(color_map): + value_idx = np.matmul(class_color, + np.array([2, 3, 4]).reshape(3, 1)) + out[flatten_v == value_idx] = idx + image = out.reshape(h, w) + + for box in boxes: + start_x, start_y, end_x, end_y = box + clipped_image = image[start_y:end_y, + start_x:end_x] if to_label else image[ + start_y:end_y, start_x:end_x, :] + idx_i, idx_j = osp.basename(image_path).split('_')[2:4] + mmcv.imwrite( + clipped_image.astype(np.uint8), + osp.join( + clip_save_dir, + f'{idx_i}_{idx_j}_{start_x}_{start_y}_{end_x}_{end_y}.png')) + + +def main(): + args = parse_args() + splits = { + 'train': [ + '2_10', '2_11', '2_12', '3_10', '3_11', '3_12', '4_10', '4_11', + '4_12', '5_10', '5_11', '5_12', '6_10', '6_11', '6_12', '6_7', + '6_8', '6_9', '7_10', '7_11', '7_12', '7_7', '7_8', '7_9' + ], + 'val': [ + '5_15', '6_15', '6_13', '3_13', '4_14', '6_14', '5_14', '2_13', + '4_15', '2_14', '5_13', '4_13', '3_14', '7_13' + ] + } + + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'potsdam') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + + zipp_list = glob.glob(os.path.join(dataset_path, '*.zip')) + print('Find the data', zipp_list) + + for zipp in zipp_list: + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + zip_file = zipfile.ZipFile(zipp) + zip_file.extractall(tmp_dir) + src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif')) + if not len(src_path_list): + sub_tmp_dir = os.path.join(tmp_dir, os.listdir(tmp_dir)[0]) + src_path_list = glob.glob(os.path.join(sub_tmp_dir, '*.tif')) + + prog_bar = ProgressBar(len(src_path_list)) + for i, src_path in enumerate(src_path_list): + idx_i, idx_j = osp.basename(src_path).split('_')[2:4] + data_type = 'train' if f'{idx_i}_{idx_j}' in splits[ + 'train'] else 'val' + if 'label' in src_path: + dst_dir = osp.join(out_dir, 'ann_dir', data_type) + clip_big_image(src_path, dst_dir, args, to_label=True) + else: + dst_dir = osp.join(out_dir, 'img_dir', data_type) + clip_big_image(src_path, dst_dir, args, to_label=False) + prog_bar.update() + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/refuge.py b/reconstruction/modules/InterFormer/tools/dataset_converters/refuge.py new file mode 100644 index 0000000000000000000000000000000000000000..1186866ab3fd58c4d72e5f573938053a8d7c80b2 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/refuge.py @@ -0,0 +1,110 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +import numpy as np +from mmengine.utils import mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert REFUGE dataset to mmsegmentation format') + parser.add_argument('--raw_data_root', help='the root path of raw data') + + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def extract_img(root: str, + cur_dir: str, + out_dir: str, + mode: str = 'train', + file_type: str = 'img') -> None: + """_summary_ + + Args: + Args: + root (str): root where the extracted data is saved + cur_dir (cur_dir): dir where the zip_file exists + out_dir (str): root dir where the data is saved + + mode (str, optional): Defaults to 'train'. + file_type (str, optional): Defaults to 'img',else to 'mask'. + """ + zip_file = zipfile.ZipFile(cur_dir) + zip_file.extractall(root) + for cur_dir, dirs, files in os.walk(root): + # filter child dirs and directories with "Illustration" and "MACOSX" + if len(dirs) == 0 and \ + cur_dir.split('\\')[-1].find('Illustration') == -1 and \ + cur_dir.find('MACOSX') == -1: + + file_names = [ + file for file in files + if file.endswith('.jpg') or file.endswith('.bmp') + ] + for filename in sorted(file_names): + img = mmcv.imread(osp.join(cur_dir, filename)) + + if file_type == 'annotations': + img = img[:, :, 0] + img[np.where(img == 0)] = 1 + img[np.where(img == 128)] = 2 + img[np.where(img == 255)] = 0 + mmcv.imwrite( + img, + osp.join(out_dir, file_type, mode, + osp.splitext(filename)[0] + '.png')) + + +def main(): + args = parse_args() + + raw_data_root = args.raw_data_root + if args.out_dir is None: + out_dir = osp.join('./data', 'REFUGE') + + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'images', 'test')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'test')) + + print('Generating images and annotations...') + # process data from the child dir on the first rank + cur_dir, dirs, files = list(os.walk(raw_data_root))[0] + print('====================') + + files = list(filter(lambda x: x.endswith('.zip'), files)) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for file in files: + # search data folders for training,validation,test + mode = list( + filter(lambda x: file.lower().find(x) != -1, + ['training', 'test', 'validation']))[0] + file_root = osp.join(tmp_dir, file[:-4]) + file_type = 'images' if file.find('Anno') == -1 and file.find( + 'GT') == -1 else 'annotations' + extract_img(file_root, osp.join(cur_dir, file), out_dir, mode, + file_type) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/stare.py b/reconstruction/modules/InterFormer/tools/dataset_converters/stare.py new file mode 100644 index 0000000000000000000000000000000000000000..4a23ba4dd8a4744bca9d1a506c79131c0e42c73d --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/stare.py @@ -0,0 +1,167 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import gzip +import os +import os.path as osp +import tarfile +import tempfile + +import mmcv +from mmengine.utils import mkdir_or_exist + +STARE_LEN = 20 +TRAINING_LEN = 10 + + +def un_gz(src, dst): + g_file = gzip.GzipFile(src) + with open(dst, 'wb+') as f: + f.write(g_file.read()) + g_file.close() + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert STARE dataset to mmsegmentation format') + parser.add_argument('image_path', help='the path of stare-images.tar') + parser.add_argument('labels_ah', help='the path of labels-ah.tar') + parser.add_argument('labels_vk', help='the path of labels-vk.tar') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + image_path = args.image_path + labels_ah = args.labels_ah + labels_vk = args.labels_vk + if args.out_dir is None: + out_dir = osp.join('data', 'STARE') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(out_dir) + mkdir_or_exist(osp.join(out_dir, 'images')) + mkdir_or_exist(osp.join(out_dir, 'images', 'training')) + mkdir_or_exist(osp.join(out_dir, 'images', 'validation')) + mkdir_or_exist(osp.join(out_dir, 'annotations')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'training')) + mkdir_or_exist(osp.join(out_dir, 'annotations', 'validation')) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + mkdir_or_exist(osp.join(tmp_dir, 'gz')) + mkdir_or_exist(osp.join(tmp_dir, 'files')) + + print('Extracting stare-images.tar...') + with tarfile.open(image_path) as f: + f.extractall(osp.join(tmp_dir, 'gz')) + + for filename in os.listdir(osp.join(tmp_dir, 'gz')): + un_gz( + osp.join(tmp_dir, 'gz', filename), + osp.join(tmp_dir, 'files', + osp.splitext(filename)[0])) + + now_dir = osp.join(tmp_dir, 'files') + + assert len(os.listdir(now_dir)) == STARE_LEN, \ + f'len(os.listdir(now_dir)) != {STARE_LEN}' + + for filename in sorted(os.listdir(now_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'training', + osp.splitext(filename)[0] + '.png')) + + for filename in sorted(os.listdir(now_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img, + osp.join(out_dir, 'images', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Removing the temporary files...') + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + mkdir_or_exist(osp.join(tmp_dir, 'gz')) + mkdir_or_exist(osp.join(tmp_dir, 'files')) + + print('Extracting labels-ah.tar...') + with tarfile.open(labels_ah) as f: + f.extractall(osp.join(tmp_dir, 'gz')) + + for filename in os.listdir(osp.join(tmp_dir, 'gz')): + un_gz( + osp.join(tmp_dir, 'gz', filename), + osp.join(tmp_dir, 'files', + osp.splitext(filename)[0])) + + now_dir = osp.join(tmp_dir, 'files') + + assert len(os.listdir(now_dir)) == STARE_LEN, \ + f'len(os.listdir(now_dir)) != {STARE_LEN}' + + for filename in sorted(os.listdir(now_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(now_dir, filename)) + # The annotation img should be divided by 128, because some of + # the annotation imgs are not standard. We should set a threshold + # to convert the nonstandard annotation imgs. The value divided by + # 128 equivalent to '1 if value >= 128 else 0' + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(filename)[0] + '.png')) + + for filename in sorted(os.listdir(now_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Removing the temporary files...') + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + mkdir_or_exist(osp.join(tmp_dir, 'gz')) + mkdir_or_exist(osp.join(tmp_dir, 'files')) + + print('Extracting labels-vk.tar...') + with tarfile.open(labels_vk) as f: + f.extractall(osp.join(tmp_dir, 'gz')) + + for filename in os.listdir(osp.join(tmp_dir, 'gz')): + un_gz( + osp.join(tmp_dir, 'gz', filename), + osp.join(tmp_dir, 'files', + osp.splitext(filename)[0])) + + now_dir = osp.join(tmp_dir, 'files') + + assert len(os.listdir(now_dir)) == STARE_LEN, \ + f'len(os.listdir(now_dir)) != {STARE_LEN}' + + for filename in sorted(os.listdir(now_dir))[:TRAINING_LEN]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'training', + osp.splitext(filename)[0] + '.png')) + + for filename in sorted(os.listdir(now_dir))[TRAINING_LEN:]: + img = mmcv.imread(osp.join(now_dir, filename)) + mmcv.imwrite( + img[:, :, 0] // 128, + osp.join(out_dir, 'annotations', 'validation', + osp.splitext(filename)[0] + '.png')) + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/synapse.py b/reconstruction/modules/InterFormer/tools/dataset_converters/synapse.py new file mode 100644 index 0000000000000000000000000000000000000000..42dac6b7eff94107b8b3a59984622cb1fd2e7599 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/synapse.py @@ -0,0 +1,155 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +import nibabel as nib +import numpy as np +from mmengine.utils import mkdir_or_exist +from PIL import Image + + +def read_files_from_txt(txt_path): + with open(txt_path) as f: + files = f.readlines() + files = [file.strip() for file in files] + return files + + +def read_nii_file(nii_path): + img = nib.load(nii_path).get_fdata() + return img + + +def split_3d_image(img): + c, _, _ = img.shape + res = [] + for i in range(c): + res.append(img[i, :, :]) + return res + + +def label_mapping(label): + """Label mapping from TransUNet paper setting. It only has 9 classes, which + are 'background', 'aorta', 'gallbladder', 'left_kidney', 'right_kidney', + 'liver', 'pancreas', 'spleen', 'stomach', respectively. Other foreground + classes in original dataset are all set to background. + + More details could be found here: https://arxiv.org/abs/2102.04306 + """ + maped_label = np.zeros_like(label) + maped_label[label == 8] = 1 + maped_label[label == 4] = 2 + maped_label[label == 3] = 3 + maped_label[label == 2] = 4 + maped_label[label == 6] = 5 + maped_label[label == 11] = 6 + maped_label[label == 1] = 7 + maped_label[label == 7] = 8 + return maped_label + + +def pares_args(): + parser = argparse.ArgumentParser( + description='Convert synapse dataset to mmsegmentation format') + parser.add_argument( + '--dataset-path', type=str, help='synapse dataset path.') + parser.add_argument( + '--save-path', + default='data/synapse', + type=str, + help='save path of the dataset.') + args = parser.parse_args() + return args + + +def main(): + args = pares_args() + dataset_path = args.dataset_path + save_path = args.save_path + + if not osp.exists(dataset_path): + raise ValueError('The dataset path does not exist. ' + 'Please enter a correct dataset path.') + if not osp.exists(osp.join(dataset_path, 'img')) \ + or not osp.exists(osp.join(dataset_path, 'label')): + raise FileNotFoundError('The dataset structure is incorrect. ' + 'Please check your dataset.') + + train_id = read_files_from_txt(osp.join(dataset_path, 'train.txt')) + train_id = [idx[3:7] for idx in train_id] + + test_id = read_files_from_txt(osp.join(dataset_path, 'val.txt')) + test_id = [idx[3:7] for idx in test_id] + + mkdir_or_exist(osp.join(save_path, 'img_dir/train')) + mkdir_or_exist(osp.join(save_path, 'img_dir/val')) + mkdir_or_exist(osp.join(save_path, 'ann_dir/train')) + mkdir_or_exist(osp.join(save_path, 'ann_dir/val')) + + # It follows data preparation pipeline from here: + # https://github.com/Beckschen/TransUNet/tree/main/datasets + for i, idx in enumerate(train_id): + img_3d = read_nii_file( + osp.join(dataset_path, 'img', 'img' + idx + '.nii.gz')) + label_3d = read_nii_file( + osp.join(dataset_path, 'label', 'label' + idx + '.nii.gz')) + + img_3d = np.clip(img_3d, -125, 275) + img_3d = (img_3d + 125) / 400 + img_3d *= 255 + img_3d = np.transpose(img_3d, [2, 0, 1]) + img_3d = np.flip(img_3d, 2) + + label_3d = np.transpose(label_3d, [2, 0, 1]) + label_3d = np.flip(label_3d, 2) + label_3d = label_mapping(label_3d) + + for c in range(img_3d.shape[0]): + img = img_3d[c] + label = label_3d[c] + + img = Image.fromarray(img).convert('RGB') + label = Image.fromarray(label).convert('L') + img.save( + osp.join( + save_path, 'img_dir/train', 'case' + idx.zfill(4) + + '_slice' + str(c).zfill(3) + '.jpg')) + label.save( + osp.join( + save_path, 'ann_dir/train', 'case' + idx.zfill(4) + + '_slice' + str(c).zfill(3) + '.png')) + + for i, idx in enumerate(test_id): + img_3d = read_nii_file( + osp.join(dataset_path, 'img', 'img' + idx + '.nii.gz')) + label_3d = read_nii_file( + osp.join(dataset_path, 'label', 'label' + idx + '.nii.gz')) + + img_3d = np.clip(img_3d, -125, 275) + img_3d = (img_3d + 125) / 400 + img_3d *= 255 + img_3d = np.transpose(img_3d, [2, 0, 1]) + img_3d = np.flip(img_3d, 2) + + label_3d = np.transpose(label_3d, [2, 0, 1]) + label_3d = np.flip(label_3d, 2) + label_3d = label_mapping(label_3d) + + for c in range(img_3d.shape[0]): + img = img_3d[c] + label = label_3d[c] + + img = Image.fromarray(img).convert('RGB') + label = Image.fromarray(label).convert('L') + img.save( + osp.join( + save_path, 'img_dir/val', 'case' + idx.zfill(4) + + '_slice' + str(c).zfill(3) + '.jpg')) + label.save( + osp.join( + save_path, 'ann_dir/val', 'case' + idx.zfill(4) + + '_slice' + str(c).zfill(3) + '.png')) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/vaihingen.py b/reconstruction/modules/InterFormer/tools/dataset_converters/vaihingen.py new file mode 100644 index 0000000000000000000000000000000000000000..db980144eb491846a844b0a374bb7a01d5509265 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/vaihingen.py @@ -0,0 +1,156 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import glob +import math +import os +import os.path as osp +import tempfile +import zipfile + +import mmcv +import numpy as np +from mmengine.utils import ProgressBar, mkdir_or_exist + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert vaihingen dataset to mmsegmentation format') + parser.add_argument('dataset_path', help='vaihingen folder path') + parser.add_argument('--tmp_dir', help='path of the temporary directory') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--clip_size', + type=int, + help='clipped size of image after preparation', + default=512) + parser.add_argument( + '--stride_size', + type=int, + help='stride of clipping original images', + default=256) + args = parser.parse_args() + return args + + +def clip_big_image(image_path, clip_save_dir, to_label=False): + # Original image of Vaihingen dataset is very large, thus pre-processing + # of them is adopted. Given fixed clip size and stride size to generate + # clipped image, the intersection of width and height is determined. + # For example, given one 5120 x 5120 original image, the clip size is + # 512 and stride size is 256, thus it would generate 20x20 = 400 images + # whose size are all 512x512. + image = mmcv.imread(image_path) + + h, w, c = image.shape + cs = args.clip_size + ss = args.stride_size + + num_rows = math.ceil((h - cs) / ss) if math.ceil( + (h - cs) / ss) * ss + cs >= h else math.ceil((h - cs) / ss) + 1 + num_cols = math.ceil((w - cs) / ss) if math.ceil( + (w - cs) / ss) * ss + cs >= w else math.ceil((w - cs) / ss) + 1 + + x, y = np.meshgrid(np.arange(num_cols + 1), np.arange(num_rows + 1)) + xmin = x * cs + ymin = y * cs + + xmin = xmin.ravel() + ymin = ymin.ravel() + xmin_offset = np.where(xmin + cs > w, w - xmin - cs, np.zeros_like(xmin)) + ymin_offset = np.where(ymin + cs > h, h - ymin - cs, np.zeros_like(ymin)) + boxes = np.stack([ + xmin + xmin_offset, ymin + ymin_offset, + np.minimum(xmin + cs, w), + np.minimum(ymin + cs, h) + ], + axis=1) + + if to_label: + color_map = np.array([[0, 0, 0], [255, 255, 255], [255, 0, 0], + [255, 255, 0], [0, 255, 0], [0, 255, 255], + [0, 0, 255]]) + flatten_v = np.matmul( + image.reshape(-1, c), + np.array([2, 3, 4]).reshape(3, 1)) + out = np.zeros_like(flatten_v) + for idx, class_color in enumerate(color_map): + value_idx = np.matmul(class_color, + np.array([2, 3, 4]).reshape(3, 1)) + out[flatten_v == value_idx] = idx + image = out.reshape(h, w) + + for box in boxes: + start_x, start_y, end_x, end_y = box + clipped_image = image[start_y:end_y, + start_x:end_x] if to_label else image[ + start_y:end_y, start_x:end_x, :] + area_idx = osp.basename(image_path).split('_')[3].strip('.tif') + mmcv.imwrite( + clipped_image.astype(np.uint8), + osp.join(clip_save_dir, + f'{area_idx}_{start_x}_{start_y}_{end_x}_{end_y}.png')) + + +def main(): + splits = { + 'train': [ + 'area1', 'area11', 'area13', 'area15', 'area17', 'area21', + 'area23', 'area26', 'area28', 'area3', 'area30', 'area32', + 'area34', 'area37', 'area5', 'area7' + ], + 'val': [ + 'area6', 'area24', 'area35', 'area16', 'area14', 'area22', + 'area10', 'area4', 'area2', 'area20', 'area8', 'area31', 'area33', + 'area27', 'area38', 'area12', 'area29' + ], + } + + dataset_path = args.dataset_path + if args.out_dir is None: + out_dir = osp.join('data', 'vaihingen') + else: + out_dir = args.out_dir + + print('Making directories...') + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'img_dir', 'val')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'train')) + mkdir_or_exist(osp.join(out_dir, 'ann_dir', 'val')) + + zipp_list = glob.glob(os.path.join(dataset_path, '*.zip')) + print('Find the data', zipp_list) + + with tempfile.TemporaryDirectory(dir=args.tmp_dir) as tmp_dir: + for zipp in zipp_list: + zip_file = zipfile.ZipFile(zipp) + zip_file.extractall(tmp_dir) + src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif')) + if 'ISPRS_semantic_labeling_Vaihingen' in zipp: + src_path_list = glob.glob( + os.path.join(os.path.join(tmp_dir, 'top'), '*.tif')) + if 'ISPRS_semantic_labeling_Vaihingen_ground_truth_eroded_COMPLETE' in zipp: # noqa + src_path_list = glob.glob(os.path.join(tmp_dir, '*.tif')) + # delete unused area9 ground truth + for area_ann in src_path_list: + if 'area9' in area_ann: + src_path_list.remove(area_ann) + prog_bar = ProgressBar(len(src_path_list)) + for i, src_path in enumerate(src_path_list): + area_idx = osp.basename(src_path).split('_')[3].strip('.tif') + data_type = 'train' if area_idx in splits['train'] else 'val' + if 'noBoundary' in src_path: + dst_dir = osp.join(out_dir, 'ann_dir', data_type) + clip_big_image(src_path, dst_dir, to_label=True) + else: + dst_dir = osp.join(out_dir, 'img_dir', data_type) + clip_big_image(src_path, dst_dir, to_label=False) + prog_bar.update() + + print('Removing the temporary files...') + + print('Done!') + + +if __name__ == '__main__': + args = parse_args() + main() diff --git a/reconstruction/modules/InterFormer/tools/dataset_converters/voc_aug.py b/reconstruction/modules/InterFormer/tools/dataset_converters/voc_aug.py new file mode 100644 index 0000000000000000000000000000000000000000..a536f4290d06e4a6c3c9fa8dbadfda847fec583b --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dataset_converters/voc_aug.py @@ -0,0 +1,92 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from functools import partial + +import numpy as np +from mmengine.utils import mkdir_or_exist, scandir, track_parallel_progress +from PIL import Image +from scipy.io import loadmat + +AUG_LEN = 10582 + + +def convert_mat(mat_file, in_dir, out_dir): + data = loadmat(osp.join(in_dir, mat_file)) + mask = data['GTcls'][0]['Segmentation'][0].astype(np.uint8) + seg_filename = osp.join(out_dir, mat_file.replace('.mat', '.png')) + Image.fromarray(mask).save(seg_filename, 'PNG') + + +def generate_aug_list(merged_list, excluded_list): + return list(set(merged_list) - set(excluded_list)) + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert PASCAL VOC annotations to mmsegmentation format') + parser.add_argument('devkit_path', help='pascal voc devkit path') + parser.add_argument('aug_path', help='pascal voc aug path') + parser.add_argument('-o', '--out_dir', help='output path') + parser.add_argument( + '--nproc', default=1, type=int, help='number of process') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + devkit_path = args.devkit_path + aug_path = args.aug_path + nproc = args.nproc + if args.out_dir is None: + out_dir = osp.join(devkit_path, 'VOC2012', 'SegmentationClassAug') + else: + out_dir = args.out_dir + mkdir_or_exist(out_dir) + in_dir = osp.join(aug_path, 'dataset', 'cls') + + track_parallel_progress( + partial(convert_mat, in_dir=in_dir, out_dir=out_dir), + list(scandir(in_dir, suffix='.mat')), + nproc=nproc) + + full_aug_list = [] + with open(osp.join(aug_path, 'dataset', 'train.txt')) as f: + full_aug_list += [line.strip() for line in f] + with open(osp.join(aug_path, 'dataset', 'val.txt')) as f: + full_aug_list += [line.strip() for line in f] + + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', + 'train.txt')) as f: + ori_train_list = [line.strip() for line in f] + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', + 'val.txt')) as f: + val_list = [line.strip() for line in f] + + aug_train_list = generate_aug_list(ori_train_list + full_aug_list, + val_list) + assert len(aug_train_list) == AUG_LEN, 'len(aug_train_list) != {}'.format( + AUG_LEN) + + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', + 'trainaug.txt'), 'w') as f: + f.writelines(line + '\n' for line in aug_train_list) + + aug_list = generate_aug_list(full_aug_list, ori_train_list + val_list) + assert len(aug_list) == AUG_LEN - len( + ori_train_list), 'len(aug_list) != {}'.format(AUG_LEN - + len(ori_train_list)) + with open( + osp.join(devkit_path, 'VOC2012/ImageSets/Segmentation', 'aug.txt'), + 'w') as f: + f.writelines(line + '\n' for line in aug_list) + + print('Done!') + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/deployment/pytorch2torchscript.py b/reconstruction/modules/InterFormer/tools/deployment/pytorch2torchscript.py new file mode 100644 index 0000000000000000000000000000000000000000..e69e705bb13ff3cca233534c34fcdaaeda02825b --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/deployment/pytorch2torchscript.py @@ -0,0 +1,185 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse + +import numpy as np +import torch +import torch._C +import torch.serialization +from mmengine import Config +from mmengine.runner import load_checkpoint +from torch import nn + +from mmseg.models import build_segmentor + +torch.manual_seed(3) + + +def digit_version(version_str): + digit_version = [] + for x in version_str.split('.'): + if x.isdigit(): + digit_version.append(int(x)) + elif x.find('rc') != -1: + patch_version = x.split('rc') + digit_version.append(int(patch_version[0]) - 1) + digit_version.append(int(patch_version[1])) + return digit_version + + +def check_torch_version(): + torch_minimum_version = '1.8.0' + torch_version = digit_version(torch.__version__) + + assert (torch_version >= digit_version(torch_minimum_version)), \ + f'Torch=={torch.__version__} is not support for converting to ' \ + f'torchscript. Please install pytorch>={torch_minimum_version}.' + + +def _convert_batchnorm(module): + module_output = module + if isinstance(module, torch.nn.SyncBatchNorm): + module_output = torch.nn.BatchNorm2d(module.num_features, module.eps, + module.momentum, module.affine, + module.track_running_stats) + if module.affine: + module_output.weight.data = module.weight.data.clone().detach() + module_output.bias.data = module.bias.data.clone().detach() + # keep requires_grad unchanged + module_output.weight.requires_grad = module.weight.requires_grad + module_output.bias.requires_grad = module.bias.requires_grad + module_output.running_mean = module.running_mean + module_output.running_var = module.running_var + module_output.num_batches_tracked = module.num_batches_tracked + for name, child in module.named_children(): + module_output.add_module(name, _convert_batchnorm(child)) + del module + return module_output + + +def _demo_mm_inputs(input_shape, num_classes): + """Create a superset of inputs needed to run test or train batches. + + Args: + input_shape (tuple): + input batch dimensions + num_classes (int): + number of semantic classes + """ + (N, C, H, W) = input_shape + rng = np.random.RandomState(0) + imgs = rng.rand(*input_shape) + segs = rng.randint( + low=0, high=num_classes - 1, size=(N, 1, H, W)).astype(np.uint8) + img_metas = [{ + 'img_shape': (H, W, C), + 'ori_shape': (H, W, C), + 'pad_shape': (H, W, C), + 'filename': '.png', + 'scale_factor': 1.0, + 'flip': False, + } for _ in range(N)] + mm_inputs = { + 'imgs': torch.FloatTensor(imgs).requires_grad_(True), + 'img_metas': img_metas, + 'gt_semantic_seg': torch.LongTensor(segs) + } + return mm_inputs + + +def pytorch2libtorch(model, + input_shape, + show=False, + output_file='tmp.pt', + verify=False): + """Export Pytorch model to TorchScript model and verify the outputs are + same between Pytorch and TorchScript. + + Args: + model (nn.Module): Pytorch model we want to export. + input_shape (tuple): Use this input shape to construct + the corresponding dummy input and execute the model. + show (bool): Whether print the computation graph. Default: False. + output_file (string): The path to where we store the + output TorchScript model. Default: `tmp.pt`. + verify (bool): Whether compare the outputs between + Pytorch and TorchScript. Default: False. + """ + if isinstance(model.decode_head, nn.ModuleList): + num_classes = model.decode_head[-1].num_classes + else: + num_classes = model.decode_head.num_classes + + mm_inputs = _demo_mm_inputs(input_shape, num_classes) + + imgs = mm_inputs.pop('imgs') + + # replace the original forword with forward_dummy + model.forward = model.forward_dummy + model.eval() + traced_model = torch.jit.trace( + model, + example_inputs=imgs, + check_trace=verify, + ) + + if show: + print(traced_model.graph) + + traced_model.save(output_file) + print(f'Successfully exported TorchScript model: {output_file}') + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Convert MMSeg to TorchScript') + parser.add_argument('config', help='test config file path') + parser.add_argument('--checkpoint', help='checkpoint file', default=None) + parser.add_argument( + '--show', action='store_true', help='show TorchScript graph') + parser.add_argument( + '--verify', action='store_true', help='verify the TorchScript model') + parser.add_argument('--output-file', type=str, default='tmp.pt') + parser.add_argument( + '--shape', + type=int, + nargs='+', + default=[512, 512], + help='input image size (height, width)') + args = parser.parse_args() + return args + + +if __name__ == '__main__': + args = parse_args() + check_torch_version() + + if len(args.shape) == 1: + input_shape = (1, 3, args.shape[0], args.shape[0]) + elif len(args.shape) == 2: + input_shape = ( + 1, + 3, + ) + tuple(args.shape) + else: + raise ValueError('invalid input shape') + + cfg = Config.fromfile(args.config) + cfg.model.pretrained = None + + # build the model and load checkpoint + cfg.model.train_cfg = None + segmentor = build_segmentor( + cfg.model, train_cfg=None, test_cfg=cfg.get('test_cfg')) + # convert SyncBN to BN + segmentor = _convert_batchnorm(segmentor) + + if args.checkpoint: + load_checkpoint(segmentor, args.checkpoint, map_location='cpu') + + # convert the PyTorch model to LibTorch model + pytorch2libtorch( + segmentor, + input_shape, + show=args.show, + output_file=args.output_file, + verify=args.verify) diff --git a/reconstruction/modules/InterFormer/tools/dist_test.sh b/reconstruction/modules/InterFormer/tools/dist_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..89711fd5c02cfc1f0386e5354506d4b74ecac251 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dist_test.sh @@ -0,0 +1,20 @@ +CONFIG=$1 +CHECKPOINT=$2 +GPUS=$3 +NNODES=${NNODES:-1} +NODE_RANK=${NODE_RANK:-0} +PORT=${PORT:-29500} +MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +python -m torch.distributed.launch \ + --nnodes=$NNODES \ + --node_rank=$NODE_RANK \ + --master_addr=$MASTER_ADDR \ + --nproc_per_node=$GPUS \ + --master_port=$PORT \ + $(dirname "$0")/test.py \ + $CONFIG \ + $CHECKPOINT \ + --launcher pytorch \ + ${@:4} diff --git a/reconstruction/modules/InterFormer/tools/dist_train.sh b/reconstruction/modules/InterFormer/tools/dist_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..a857df78788edb8841b6f67d74dd0e6cfb77d8ab --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/dist_train.sh @@ -0,0 +1,17 @@ +CONFIG=$1 +GPUS=$2 +NNODES=${NNODES:-1} +NODE_RANK=${NODE_RANK:-0} +PORT=${PORT:-29500} +MASTER_ADDR=${MASTER_ADDR:-"127.0.0.1"} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +python -m torch.distributed.launch \ + --nnodes=$NNODES \ + --node_rank=$NODE_RANK \ + --master_addr=$MASTER_ADDR \ + --nproc_per_node=$GPUS \ + --master_port=$PORT \ + $(dirname "$0")/train.py \ + $CONFIG \ + --launcher pytorch ${@:3} diff --git a/reconstruction/modules/InterFormer/tools/misc/browse_dataset.py b/reconstruction/modules/InterFormer/tools/misc/browse_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..7863eb74f2cab53d025afad347f7886a5ce29919 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/misc/browse_dataset.py @@ -0,0 +1,73 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +from mmengine import Config, DictAction +from mmengine.registry import init_default_scope +from mmengine.utils import ProgressBar + +from mmseg.registry import DATASETS, VISUALIZERS + + +def parse_args(): + parser = argparse.ArgumentParser(description='Browse a dataset') + parser.add_argument('config', help='train config file path') + parser.add_argument( + '--output-dir', + default=None, + type=str, + help='If there is no display interface, you can save it') + parser.add_argument('--not-show', default=False, action='store_true') + parser.add_argument( + '--show-interval', + type=float, + default=2, + help='the interval of show (s)') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + return args + + +def main(): + args = parse_args() + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # register all modules in mmseg into the registries + init_default_scope('mmseg') + + dataset = DATASETS.build(cfg.train_dataloader.dataset) + cfg.visualizer['save_dir'] = args.output_dir + visualizer = VISUALIZERS.build(cfg.visualizer) + visualizer.dataset_meta = dataset.METAINFO + + progress_bar = ProgressBar(len(dataset)) + for item in dataset: + img = item['inputs'].permute(1, 2, 0).numpy() + data_sample = item['data_samples'].numpy() + img_path = osp.basename(item['data_samples'].img_path) + + img = img[..., [2, 1, 0]] # bgr to rgb + + visualizer.add_datasample( + osp.basename(img_path), + img, + data_sample, + show=not args.not_show, + wait_time=args.show_interval) + + progress_bar.update() + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/misc/print_config.py b/reconstruction/modules/InterFormer/tools/misc/print_config.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1c024a6a44157a0b0d4d6213d18d67f57a33c5 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/misc/print_config.py @@ -0,0 +1,69 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import warnings + +from mmengine import Config, DictAction + +from mmseg.apis import init_model + + +def parse_args(): + parser = argparse.ArgumentParser(description='Print the whole config') + parser.add_argument('config', help='config file path') + parser.add_argument( + '--graph', action='store_true', help='print the models graph') + parser.add_argument( + '--options', + nargs='+', + action=DictAction, + help="--options is deprecated in favor of --cfg_options' and it will " + 'not be supported in version v0.22.0. Override some settings in the ' + 'used config, the key-value pair in xxx=yyy format will be merged ' + 'into config file. If the value to be overwritten is a list, it ' + 'should be like key="[a,b]" or key=a,b It also allows nested ' + 'list/tuple values, e.g. key="[(a,b),(c,d)]" Note that the quotation ' + 'marks are necessary and that no white space is allowed.') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + args = parser.parse_args() + + if args.options and args.cfg_options: + raise ValueError( + '--options and --cfg-options cannot be both ' + 'specified, --options is deprecated in favor of --cfg-options. ' + '--options will not be supported in version v0.22.0.') + if args.options: + warnings.warn('--options is deprecated in favor of --cfg-options, ' + '--options will not be supported in version v0.22.0.') + args.cfg_options = args.options + + return args + + +def main(): + args = parse_args() + + cfg = Config.fromfile(args.config) + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + print(f'Config:\n{cfg.pretty_text}') + # dump config + cfg.dump('example.py') + # dump models graph + if args.graph: + model = init_model(args.config, device='cpu') + print(f'Model graph:\n{str(model)}') + with open('example-graph.txt', 'w') as f: + f.writelines(str(model)) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/misc/publish_model.py b/reconstruction/modules/InterFormer/tools/misc/publish_model.py new file mode 100644 index 0000000000000000000000000000000000000000..e035ad90e85e0e03d8304c1d5b524c5ac322c644 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/misc/publish_model.py @@ -0,0 +1,50 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import subprocess +from hashlib import sha256 + +import torch + +BLOCK_SIZE = 128 * 1024 + + +def parse_args(): + parser = argparse.ArgumentParser( + description='Process a checkpoint to be published') + parser.add_argument('in_file', help='input checkpoint filename') + parser.add_argument('out_file', help='output checkpoint filename') + args = parser.parse_args() + return args + + +def sha256sum(filename: str) -> str: + """Compute SHA256 message digest from a file.""" + hash_func = sha256() + byte_array = bytearray(BLOCK_SIZE) + memory_view = memoryview(byte_array) + with open(filename, 'rb', buffering=0) as file: + for block in iter(lambda: file.readinto(memory_view), 0): + hash_func.update(memory_view[:block]) + return hash_func.hexdigest() + + +def process_checkpoint(in_file, out_file): + checkpoint = torch.load(in_file, map_location='cpu') + # remove optimizer for smaller file size + if 'optimizer' in checkpoint: + del checkpoint['optimizer'] + # if it is necessary to remove some sensitive data in checkpoint['meta'], + # add the code here. + torch.save(checkpoint, out_file) + sha = sha256sum(in_file) + final_file = out_file.rstrip('.pth') + f'-{sha[:8]}.pth' + subprocess.Popen(['mv', out_file, final_file]) + + +def main(): + args = parse_args() + process_checkpoint(args.in_file, args.out_file) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/model_converters/beit2mmseg.py b/reconstruction/modules/InterFormer/tools/model_converters/beit2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..20f8f0f4509f93291782ca152bf04ab019b0e0ff --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/model_converters/beit2mmseg.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_beit(ckpt): + new_ckpt = OrderedDict() + + for k, v in ckpt.items(): + if k.startswith('patch_embed'): + new_key = k.replace('patch_embed.proj', 'patch_embed.projection') + new_ckpt[new_key] = v + if k.startswith('blocks'): + new_key = k.replace('blocks', 'layers') + if 'norm' in new_key: + new_key = new_key.replace('norm', 'ln') + elif 'mlp.fc1' in new_key: + new_key = new_key.replace('mlp.fc1', 'ffn.layers.0.0') + elif 'mlp.fc2' in new_key: + new_key = new_key.replace('mlp.fc2', 'ffn.layers.1') + new_ckpt[new_key] = v + else: + new_key = k + new_ckpt[new_key] = v + + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained beit models to' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_beit(state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/model_converters/clip2mmseg.py b/reconstruction/modules/InterFormer/tools/model_converters/clip2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..9a97e4b04ab45740ee37149d30a85b67245868f5 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/model_converters/clip2mmseg.py @@ -0,0 +1,163 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_vitlayer(paras): + new_para_name = '' + if paras[0] == 'ln_1': + new_para_name = '.'.join(['ln1'] + paras[1:]) + elif paras[0] == 'attn': + new_para_name = '.'.join(['attn.attn'] + paras[1:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['ln2'] + paras[1:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffn.layers.0.0'] + paras[-1:]) + else: + new_para_name = '.'.join(['ffn.layers.1'] + paras[-1:]) + else: + print(f'Wrong for {paras}') + return new_para_name + + +def convert_translayer(paras): + new_para_name = '' + if paras[0] == 'attn': + new_para_name = '.'.join(['attentions.0.attn'] + paras[1:]) + elif paras[0] == 'ln_1': + new_para_name = '.'.join(['norms.0'] + paras[1:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['norms.1'] + paras[1:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffns.0.layers.0.0'] + paras[2:]) + elif paras[1] == 'c_proj': + new_para_name = '.'.join(['ffns.0.layers.1'] + paras[2:]) + else: + print(f'Wrong for {paras}') + else: + print(f'Wrong for {paras}') + return new_para_name + + +def convert_key_name(ckpt, visual_split): + new_ckpt = OrderedDict() + for k, v in ckpt.items(): + key_list = k.split('.') + if key_list[0] == 'visual': + new_transform_name = 'image_encoder' + if key_list[1] == 'class_embedding': + new_name = '.'.join([new_transform_name, 'cls_token']) + elif key_list[1] == 'positional_embedding': + new_name = '.'.join([new_transform_name, 'pos_embed']) + elif key_list[1] == 'conv1': + new_name = '.'.join([ + new_transform_name, 'patch_embed.projection', key_list[2] + ]) + elif key_list[1] == 'ln_pre': + new_name = '.'.join( + [new_transform_name, key_list[1], key_list[2]]) + elif key_list[1] == 'transformer': + new_layer_name = 'layers' + layer_index = key_list[3] + paras = key_list[4:] + if int(layer_index) < visual_split: + new_para_name = convert_vitlayer(paras) + new_name = '.'.join([ + new_transform_name, new_layer_name, layer_index, + new_para_name + ]) + else: + new_para_name = convert_translayer(paras) + new_transform_name = 'decode_head.rec_with_attnbias' + new_layer_name = 'layers' + layer_index = str(int(layer_index) - visual_split) + new_name = '.'.join([ + new_transform_name, new_layer_name, layer_index, + new_para_name + ]) + elif key_list[1] == 'proj': + new_name = 'decode_head.rec_with_attnbias.proj.weight' + elif key_list[1] == 'ln_post': + new_name = k.replace('visual', 'decode_head.rec_with_attnbias') + else: + print(f'pop parameter: {k}') + continue + else: + text_encoder_name = 'text_encoder' + if key_list[0] == 'transformer': + layer_name = 'transformer' + layer_index = key_list[2] + paras = key_list[3:] + new_para_name = convert_translayer(paras) + new_name = '.'.join([ + text_encoder_name, layer_name, layer_index, new_para_name + ]) + elif key_list[0] in [ + 'positional_embedding', 'text_projection', 'bg_embed', + 'attn_mask', 'logit_scale', 'token_embedding', 'ln_final' + ]: + new_name = 'text_encoder.' + k + else: + print(f'pop parameter: {k}') + continue + new_ckpt[new_name] = v + + return new_ckpt + + +def convert_tensor(ckpt): + cls_token = ckpt['image_encoder.cls_token'] + new_cls_token = cls_token.unsqueeze(0).unsqueeze(0) + ckpt['image_encoder.cls_token'] = new_cls_token + pos_embed = ckpt['image_encoder.pos_embed'] + new_pos_embed = pos_embed.unsqueeze(0) + ckpt['image_encoder.pos_embed'] = new_pos_embed + proj_weight = ckpt['decode_head.rec_with_attnbias.proj.weight'] + new_proj_weight = proj_weight.transpose(1, 0) + ckpt['decode_head.rec_with_attnbias.proj.weight'] = new_proj_weight + return ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + if any([s in args.src for s in ['B-16', 'b16', 'base_patch16']]): + visual_split = 9 + elif any([s in args.src for s in ['L-14', 'l14', 'large_patch14']]): + visual_split = 18 + else: + print('Make sure the clip model is ViT-B/16 or ViT-L/14!') + visual_split = -1 + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if isinstance(checkpoint, torch.jit.RecursiveScriptModule): + state_dict = checkpoint.state_dict() + else: + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + # deit checkpoint + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_key_name(state_dict, visual_split) + weight = convert_tensor(weight) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/model_converters/mit2mmseg.py b/reconstruction/modules/InterFormer/tools/model_converters/mit2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..f10cbbf9d40d3656be0d447460c12fc83771c14c --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/model_converters/mit2mmseg.py @@ -0,0 +1,82 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_mit(ckpt): + new_ckpt = OrderedDict() + # Process the concat between q linear weights and kv linear weights + for k, v in ckpt.items(): + if k.startswith('head'): + continue + # patch embedding conversion + elif k.startswith('patch_embed'): + stage_i = int(k.split('.')[0].replace('patch_embed', '')) + new_k = k.replace(f'patch_embed{stage_i}', f'layers.{stage_i-1}.0') + new_v = v + if 'proj.' in new_k: + new_k = new_k.replace('proj.', 'projection.') + # transformer encoder layer conversion + elif k.startswith('block'): + stage_i = int(k.split('.')[0].replace('block', '')) + new_k = k.replace(f'block{stage_i}', f'layers.{stage_i-1}.1') + new_v = v + if 'attn.q.' in new_k: + sub_item_k = k.replace('q.', 'kv.') + new_k = new_k.replace('q.', 'attn.in_proj_') + new_v = torch.cat([v, ckpt[sub_item_k]], dim=0) + elif 'attn.kv.' in new_k: + continue + elif 'attn.proj.' in new_k: + new_k = new_k.replace('proj.', 'attn.out_proj.') + elif 'attn.sr.' in new_k: + new_k = new_k.replace('sr.', 'sr.') + elif 'mlp.' in new_k: + string = f'{new_k}-' + new_k = new_k.replace('mlp.', 'ffn.layers.') + if 'fc1.weight' in new_k or 'fc2.weight' in new_k: + new_v = v.reshape((*v.shape, 1, 1)) + new_k = new_k.replace('fc1.', '0.') + new_k = new_k.replace('dwconv.dwconv.', '1.') + new_k = new_k.replace('fc2.', '4.') + string += f'{new_k} {v.shape}-{new_v.shape}' + # norm layer conversion + elif k.startswith('norm'): + stage_i = int(k.split('.')[0].replace('norm', '')) + new_k = k.replace(f'norm{stage_i}', f'layers.{stage_i-1}.2') + new_v = v + else: + new_k = k + new_v = v + new_ckpt[new_k] = new_v + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained segformer to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_mit(state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/model_converters/san2mmseg.py b/reconstruction/modules/InterFormer/tools/model_converters/san2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..301a46608e0f14df17138922ae3a747aee105372 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/model_converters/san2mmseg.py @@ -0,0 +1,220 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_key_name(ckpt): + new_ckpt = OrderedDict() + + for k, v in ckpt.items(): + key_list = k.split('.') + if key_list[0] == 'clip_visual_extractor': + new_transform_name = 'image_encoder' + if key_list[1] == 'class_embedding': + new_name = '.'.join([new_transform_name, 'cls_token']) + elif key_list[1] == 'positional_embedding': + new_name = '.'.join([new_transform_name, 'pos_embed']) + elif key_list[1] == 'conv1': + new_name = '.'.join([ + new_transform_name, 'patch_embed.projection', key_list[2] + ]) + elif key_list[1] == 'ln_pre': + new_name = '.'.join( + [new_transform_name, key_list[1], key_list[2]]) + elif key_list[1] == 'resblocks': + new_layer_name = 'layers' + layer_index = key_list[2] + paras = key_list[3:] + if paras[0] == 'ln_1': + new_para_name = '.'.join(['ln1'] + key_list[4:]) + elif paras[0] == 'attn': + new_para_name = '.'.join(['attn.attn'] + key_list[4:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['ln2'] + key_list[4:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffn.layers.0.0'] + + key_list[-1:]) + else: + new_para_name = '.'.join(['ffn.layers.1'] + + key_list[-1:]) + new_name = '.'.join([ + new_transform_name, new_layer_name, layer_index, + new_para_name + ]) + elif key_list[0] == 'side_adapter_network': + decode_head_name = 'decode_head' + module_name = 'side_adapter_network' + if key_list[1] == 'vit_model': + if key_list[2] == 'blocks': + layer_name = 'encode_layers' + layer_index = key_list[3] + paras = key_list[4:] + if paras[0] == 'norm1': + new_para_name = '.'.join(['ln1'] + key_list[5:]) + elif paras[0] == 'attn': + new_para_name = '.'.join(key_list[4:]) + new_para_name = new_para_name.replace( + 'attn.qkv.', 'attn.attn.in_proj_') + new_para_name = new_para_name.replace( + 'attn.proj', 'attn.attn.out_proj') + elif paras[0] == 'norm2': + new_para_name = '.'.join(['ln2'] + key_list[5:]) + elif paras[0] == 'mlp': + new_para_name = '.'.join(['ffn'] + key_list[5:]) + new_para_name = new_para_name.replace( + 'fc1', 'layers.0.0') + new_para_name = new_para_name.replace( + 'fc2', 'layers.1') + else: + print(f'Wrong for {k}') + new_name = '.'.join([ + decode_head_name, module_name, layer_name, layer_index, + new_para_name + ]) + elif key_list[2] == 'pos_embed': + new_name = '.'.join( + [decode_head_name, module_name, 'pos_embed']) + elif key_list[2] == 'patch_embed': + new_name = '.'.join([ + decode_head_name, module_name, 'patch_embed', + 'projection', key_list[4] + ]) + else: + print(f'Wrong for {k}') + elif key_list[1] == 'query_embed' or key_list[ + 1] == 'query_pos_embed': + new_name = '.'.join( + [decode_head_name, module_name, key_list[1]]) + elif key_list[1] == 'fusion_layers': + layer_name = 'conv_clips' + layer_index = key_list[2][-1] + paras = '.'.join(key_list[3:]) + new_para_name = paras.replace('input_proj.0', '0') + new_para_name = new_para_name.replace('input_proj.1', '1.conv') + new_name = '.'.join([ + decode_head_name, module_name, layer_name, layer_index, + new_para_name + ]) + elif key_list[1] == 'mask_decoder': + new_name = 'decode_head.' + k + else: + print(f'Wrong for {k}') + elif key_list[0] == 'clip_rec_head': + module_name = 'rec_with_attnbias' + if key_list[1] == 'proj': + new_name = '.'.join( + [decode_head_name, module_name, 'proj.weight']) + elif key_list[1] == 'ln_post': + new_name = '.'.join( + [decode_head_name, module_name, 'ln_post', key_list[2]]) + elif key_list[1] == 'resblocks': + new_layer_name = 'layers' + layer_index = key_list[2] + paras = key_list[3:] + if paras[0] == 'ln_1': + new_para_name = '.'.join(['norms.0'] + paras[1:]) + elif paras[0] == 'attn': + new_para_name = '.'.join(['attentions.0.attn'] + paras[1:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['norms.1'] + paras[1:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffns.0.layers.0.0'] + + paras[2:]) + elif paras[1] == 'c_proj': + new_para_name = '.'.join(['ffns.0.layers.1'] + + paras[2:]) + else: + print(f'Wrong for {k}') + new_name = '.'.join([ + decode_head_name, module_name, new_layer_name, layer_index, + new_para_name + ]) + else: + print(f'Wrong for {k}') + elif key_list[0] == 'ov_classifier': + text_encoder_name = 'text_encoder' + if key_list[1] == 'transformer': + layer_name = 'transformer' + layer_index = key_list[3] + paras = key_list[4:] + if paras[0] == 'attn': + new_para_name = '.'.join(['attentions.0.attn'] + paras[1:]) + elif paras[0] == 'ln_1': + new_para_name = '.'.join(['norms.0'] + paras[1:]) + elif paras[0] == 'ln_2': + new_para_name = '.'.join(['norms.1'] + paras[1:]) + elif paras[0] == 'mlp': + if paras[1] == 'c_fc': + new_para_name = '.'.join(['ffns.0.layers.0.0'] + + paras[2:]) + elif paras[1] == 'c_proj': + new_para_name = '.'.join(['ffns.0.layers.1'] + + paras[2:]) + else: + print(f'Wrong for {k}') + else: + print(f'Wrong for {k}') + new_name = '.'.join([ + text_encoder_name, layer_name, layer_index, new_para_name + ]) + elif key_list[1] in [ + 'positional_embedding', 'text_projection', 'bg_embed', + 'attn_mask', 'logit_scale', 'token_embedding', 'ln_final' + ]: + new_name = k.replace('ov_classifier', 'text_encoder') + else: + print(f'Wrong for {k}') + elif key_list[0] == 'criterion': + new_name = k + else: + print(f'Wrong for {k}') + new_ckpt[new_name] = v + return new_ckpt + + +def convert_tensor(ckpt): + cls_token = ckpt['image_encoder.cls_token'] + new_cls_token = cls_token.unsqueeze(0).unsqueeze(0) + ckpt['image_encoder.cls_token'] = new_cls_token + pos_embed = ckpt['image_encoder.pos_embed'] + new_pos_embed = pos_embed.unsqueeze(0) + ckpt['image_encoder.pos_embed'] = new_pos_embed + proj_weight = ckpt['decode_head.rec_with_attnbias.proj.weight'] + new_proj_weight = proj_weight.transpose(1, 0) + ckpt['decode_head.rec_with_attnbias.proj.weight'] = new_proj_weight + return ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + # deit checkpoint + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_key_name(state_dict) + weight = convert_tensor(weight) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/model_converters/stdc2mmseg.py b/reconstruction/modules/InterFormer/tools/model_converters/stdc2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea3b8342f546692f50a8e3c0b740f881058229c --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/model_converters/stdc2mmseg.py @@ -0,0 +1,71 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_stdc(ckpt, stdc_type): + new_state_dict = {} + if stdc_type == 'STDC1': + stage_lst = ['0', '1', '2.0', '2.1', '3.0', '3.1', '4.0', '4.1'] + else: + stage_lst = [ + '0', '1', '2.0', '2.1', '2.2', '2.3', '3.0', '3.1', '3.2', '3.3', + '3.4', '4.0', '4.1', '4.2' + ] + for k, v in ckpt.items(): + ori_k = k + flag = False + if 'cp.' in k: + k = k.replace('cp.', '') + if 'features.' in k: + num_layer = int(k.split('.')[1]) + feature_key_lst = 'features.' + str(num_layer) + '.' + stages_key_lst = 'stages.' + stage_lst[num_layer] + '.' + k = k.replace(feature_key_lst, stages_key_lst) + flag = True + if 'conv_list' in k: + k = k.replace('conv_list', 'layers') + flag = True + if 'avd_layer.' in k: + if 'avd_layer.0' in k: + k = k.replace('avd_layer.0', 'downsample.conv') + elif 'avd_layer.1' in k: + k = k.replace('avd_layer.1', 'downsample.bn') + flag = True + if flag: + new_state_dict[k] = ckpt[ori_k] + + return new_state_dict + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained STDC1/2 to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + parser.add_argument('type', help='model type: STDC1 or STDC2') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + + assert args.type in ['STDC1', + 'STDC2'], 'STD type should be STDC1 or STDC2!' + weight = convert_stdc(state_dict, args.type) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/model_converters/swin2mmseg.py b/reconstruction/modules/InterFormer/tools/model_converters/swin2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..d434f9465bbdad6bebc7d5962e8bfaf63c7c9e72 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/model_converters/swin2mmseg.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_swin(ckpt): + new_ckpt = OrderedDict() + + def correct_unfold_reduction_order(x): + out_channel, in_channel = x.shape + x = x.reshape(out_channel, 4, in_channel // 4) + x = x[:, [0, 2, 1, 3], :].transpose(1, + 2).reshape(out_channel, in_channel) + return x + + def correct_unfold_norm_order(x): + in_channel = x.shape[0] + x = x.reshape(4, in_channel // 4) + x = x[[0, 2, 1, 3], :].transpose(0, 1).reshape(in_channel) + return x + + for k, v in ckpt.items(): + if k.startswith('head'): + continue + elif k.startswith('layers'): + new_v = v + if 'attn.' in k: + new_k = k.replace('attn.', 'attn.w_msa.') + elif 'mlp.' in k: + if 'mlp.fc1.' in k: + new_k = k.replace('mlp.fc1.', 'ffn.layers.0.0.') + elif 'mlp.fc2.' in k: + new_k = k.replace('mlp.fc2.', 'ffn.layers.1.') + else: + new_k = k.replace('mlp.', 'ffn.') + elif 'downsample' in k: + new_k = k + if 'reduction.' in k: + new_v = correct_unfold_reduction_order(v) + elif 'norm.' in k: + new_v = correct_unfold_norm_order(v) + else: + new_k = k + new_k = new_k.replace('layers', 'stages', 1) + elif k.startswith('patch_embed'): + new_v = v + if 'proj' in k: + new_k = k.replace('proj', 'projection') + else: + new_k = k + else: + new_v = v + new_k = k + + new_ckpt[new_k] = new_v + + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in official pretrained swin models to' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_swin(state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/model_converters/twins2mmseg.py b/reconstruction/modules/InterFormer/tools/model_converters/twins2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..647d41784aa07468be4b3f2e183064ad55266ad1 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/model_converters/twins2mmseg.py @@ -0,0 +1,87 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_twins(args, ckpt): + + new_ckpt = OrderedDict() + + for k, v in list(ckpt.items()): + new_v = v + if k.startswith('head'): + continue + elif k.startswith('patch_embeds'): + if 'proj.' in k: + new_k = k.replace('proj.', 'projection.') + else: + new_k = k + elif k.startswith('blocks'): + # Union + if 'attn.q.' in k: + new_k = k.replace('q.', 'attn.in_proj_') + new_v = torch.cat([v, ckpt[k.replace('attn.q.', 'attn.kv.')]], + dim=0) + elif 'mlp.fc1' in k: + new_k = k.replace('mlp.fc1', 'ffn.layers.0.0') + elif 'mlp.fc2' in k: + new_k = k.replace('mlp.fc2', 'ffn.layers.1') + # Only pcpvt + elif args.model == 'pcpvt': + if 'attn.proj.' in k: + new_k = k.replace('proj.', 'attn.out_proj.') + else: + new_k = k + + # Only svt + else: + if 'attn.proj.' in k: + k_lst = k.split('.') + if int(k_lst[2]) % 2 == 1: + new_k = k.replace('proj.', 'attn.out_proj.') + else: + new_k = k + else: + new_k = k + new_k = new_k.replace('blocks.', 'layers.') + elif k.startswith('pos_block'): + new_k = k.replace('pos_block', 'position_encodings') + if 'proj.0.' in new_k: + new_k = new_k.replace('proj.0.', 'proj.') + else: + new_k = k + if 'attn.kv.' not in k: + new_ckpt[new_k] = new_v + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + parser.add_argument('model', help='model: pcpvt or svt') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + else: + state_dict = checkpoint + + weight = convert_twins(args, state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/model_converters/vit2mmseg.py b/reconstruction/modules/InterFormer/tools/model_converters/vit2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..1d1f8a427e232290c6dcf490e33f777275dd238a --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/model_converters/vit2mmseg.py @@ -0,0 +1,70 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp +from collections import OrderedDict + +import mmengine +import torch +from mmengine.runner import CheckpointLoader + + +def convert_vit(ckpt): + + new_ckpt = OrderedDict() + + for k, v in ckpt.items(): + if k.startswith('head'): + continue + if k.startswith('norm'): + new_k = k.replace('norm.', 'ln1.') + elif k.startswith('patch_embed'): + if 'proj' in k: + new_k = k.replace('proj', 'projection') + else: + new_k = k + elif k.startswith('blocks'): + if 'norm' in k: + new_k = k.replace('norm', 'ln') + elif 'mlp.fc1' in k: + new_k = k.replace('mlp.fc1', 'ffn.layers.0.0') + elif 'mlp.fc2' in k: + new_k = k.replace('mlp.fc2', 'ffn.layers.1') + elif 'attn.qkv' in k: + new_k = k.replace('attn.qkv.', 'attn.attn.in_proj_') + elif 'attn.proj' in k: + new_k = k.replace('attn.proj', 'attn.attn.out_proj') + else: + new_k = k + new_k = new_k.replace('blocks.', 'layers.') + else: + new_k = k + new_ckpt[new_k] = v + + return new_ckpt + + +def main(): + parser = argparse.ArgumentParser( + description='Convert keys in timm pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + checkpoint = CheckpointLoader.load_checkpoint(args.src, map_location='cpu') + if 'state_dict' in checkpoint: + # timm checkpoint + state_dict = checkpoint['state_dict'] + elif 'model' in checkpoint: + # deit checkpoint + state_dict = checkpoint['model'] + else: + state_dict = checkpoint + weight = convert_vit(state_dict) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(weight, args.dst) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/model_converters/vitjax2mmseg.py b/reconstruction/modules/InterFormer/tools/model_converters/vitjax2mmseg.py new file mode 100644 index 0000000000000000000000000000000000000000..81bc2ea020e32d086fc4ce2153cc2bf51edd4d48 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/model_converters/vitjax2mmseg.py @@ -0,0 +1,123 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os.path as osp + +import mmengine +import numpy as np +import torch + + +def vit_jax_to_torch(jax_weights, num_layer=12): + torch_weights = dict() + + # patch embedding + conv_filters = jax_weights['embedding/kernel'] + conv_filters = conv_filters.permute(3, 2, 0, 1) + torch_weights['patch_embed.projection.weight'] = conv_filters + torch_weights['patch_embed.projection.bias'] = jax_weights[ + 'embedding/bias'] + + # pos embedding + torch_weights['pos_embed'] = jax_weights[ + 'Transformer/posembed_input/pos_embedding'] + + # cls token + torch_weights['cls_token'] = jax_weights['cls'] + + # head + torch_weights['ln1.weight'] = jax_weights['Transformer/encoder_norm/scale'] + torch_weights['ln1.bias'] = jax_weights['Transformer/encoder_norm/bias'] + + # transformer blocks + for i in range(num_layer): + jax_block = f'Transformer/encoderblock_{i}' + torch_block = f'layers.{i}' + + # attention norm + torch_weights[f'{torch_block}.ln1.weight'] = jax_weights[ + f'{jax_block}/LayerNorm_0/scale'] + torch_weights[f'{torch_block}.ln1.bias'] = jax_weights[ + f'{jax_block}/LayerNorm_0/bias'] + + # attention + query_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/query/kernel'] + query_bias = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/query/bias'] + key_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/key/kernel'] + key_bias = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/key/bias'] + value_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/value/kernel'] + value_bias = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/value/bias'] + + qkv_weight = torch.from_numpy( + np.stack((query_weight, key_weight, value_weight), 1)) + qkv_weight = torch.flatten(qkv_weight, start_dim=1) + qkv_bias = torch.from_numpy( + np.stack((query_bias, key_bias, value_bias), 0)) + qkv_bias = torch.flatten(qkv_bias, start_dim=0) + + torch_weights[f'{torch_block}.attn.attn.in_proj_weight'] = qkv_weight + torch_weights[f'{torch_block}.attn.attn.in_proj_bias'] = qkv_bias + to_out_weight = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/out/kernel'] + to_out_weight = torch.flatten(to_out_weight, start_dim=0, end_dim=1) + torch_weights[ + f'{torch_block}.attn.attn.out_proj.weight'] = to_out_weight + torch_weights[f'{torch_block}.attn.attn.out_proj.bias'] = jax_weights[ + f'{jax_block}/MultiHeadDotProductAttention_1/out/bias'] + + # mlp norm + torch_weights[f'{torch_block}.ln2.weight'] = jax_weights[ + f'{jax_block}/LayerNorm_2/scale'] + torch_weights[f'{torch_block}.ln2.bias'] = jax_weights[ + f'{jax_block}/LayerNorm_2/bias'] + + # mlp + torch_weights[f'{torch_block}.ffn.layers.0.0.weight'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_0/kernel'] + torch_weights[f'{torch_block}.ffn.layers.0.0.bias'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_0/bias'] + torch_weights[f'{torch_block}.ffn.layers.1.weight'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_1/kernel'] + torch_weights[f'{torch_block}.ffn.layers.1.bias'] = jax_weights[ + f'{jax_block}/MlpBlock_3/Dense_1/bias'] + + # transpose weights + for k, v in torch_weights.items(): + if 'weight' in k and 'patch_embed' not in k and 'ln' not in k: + v = v.permute(1, 0) + torch_weights[k] = v + + return torch_weights + + +def main(): + # stole refactoring code from Robin Strudel, thanks + parser = argparse.ArgumentParser( + description='Convert keys from jax official pretrained vit models to ' + 'MMSegmentation style.') + parser.add_argument('src', help='src model path or url') + # The dst path must be a full path of the new checkpoint. + parser.add_argument('dst', help='save path') + args = parser.parse_args() + + jax_weights = np.load(args.src) + jax_weights_tensor = {} + for key in jax_weights.files: + value = torch.from_numpy(jax_weights[key]) + jax_weights_tensor[key] = value + if 'L_16-i21k' in args.src: + num_layer = 24 + else: + num_layer = 12 + torch_weights = vit_jax_to_torch(jax_weights_tensor, num_layer) + mmengine.mkdir_or_exist(osp.dirname(args.dst)) + torch.save(torch_weights, args.dst) + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/slurm_test.sh b/reconstruction/modules/InterFormer/tools/slurm_test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4e6f7bf4e33267f269cf0f455924cb70166ccd4b --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/slurm_test.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -x + +PARTITION=$1 +JOB_NAME=$2 +CONFIG=$3 +CHECKPOINT=$4 +GPUS=${GPUS:-4} +GPUS_PER_NODE=${GPUS_PER_NODE:-4} +CPUS_PER_TASK=${CPUS_PER_TASK:-5} +PY_ARGS=${@:5} +SRUN_ARGS=${SRUN_ARGS:-""} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +srun -p ${PARTITION} \ + --job-name=${JOB_NAME} \ + --gres=gpu:${GPUS_PER_NODE} \ + --ntasks=${GPUS} \ + --ntasks-per-node=${GPUS_PER_NODE} \ + --cpus-per-task=${CPUS_PER_TASK} \ + --kill-on-bad-exit=1 \ + ${SRUN_ARGS} \ + python -u tools/test.py ${CONFIG} ${CHECKPOINT} --launcher="slurm" ${PY_ARGS} diff --git a/reconstruction/modules/InterFormer/tools/slurm_train.sh b/reconstruction/modules/InterFormer/tools/slurm_train.sh new file mode 100644 index 0000000000000000000000000000000000000000..ab232105f0309c720ed81a522eca14b6fbd64afd --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/slurm_train.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -x + +PARTITION=$1 +JOB_NAME=$2 +CONFIG=$3 +GPUS=${GPUS:-4} +GPUS_PER_NODE=${GPUS_PER_NODE:-4} +CPUS_PER_TASK=${CPUS_PER_TASK:-5} +SRUN_ARGS=${SRUN_ARGS:-""} +PY_ARGS=${@:4} + +PYTHONPATH="$(dirname $0)/..":$PYTHONPATH \ +srun -p ${PARTITION} \ + --job-name=${JOB_NAME} \ + --gres=gpu:${GPUS_PER_NODE} \ + --ntasks=${GPUS} \ + --ntasks-per-node=${GPUS_PER_NODE} \ + --cpus-per-task=${CPUS_PER_TASK} \ + --kill-on-bad-exit=1 \ + ${SRUN_ARGS} \ + python -u tools/train.py ${CONFIG} --launcher="slurm" ${PY_ARGS} diff --git a/reconstruction/modules/InterFormer/tools/test.py b/reconstruction/modules/InterFormer/tools/test.py new file mode 100644 index 0000000000000000000000000000000000000000..0d7f39b3a8b5f94d33ce8529755013451184d5ed --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/test.py @@ -0,0 +1,123 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import os +import os.path as osp + +from mmengine.config import Config, DictAction +from mmengine.runner import Runner + + +# TODO: support fuse_conv_bn, visualization, and format_only +def parse_args(): + parser = argparse.ArgumentParser( + description='MMSeg test (and eval) a model') + parser.add_argument('config', help='train config file path') + parser.add_argument('checkpoint', help='checkpoint file') + parser.add_argument( + '--work-dir', + help=('if specified, the evaluation metric results will be dumped' + 'into the directory as json')) + parser.add_argument( + '--out', + type=str, + help='The directory to save output prediction for offline evaluation') + parser.add_argument( + '--show', action='store_true', help='show prediction results') + parser.add_argument( + '--show-dir', + help='directory where painted images will be saved. ' + 'If specified, it will be automatically saved ' + 'to the work_dir/timestamp/show_dir') + parser.add_argument( + '--wait-time', type=float, default=2, help='the interval of show (s)') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--launcher', + choices=['none', 'pytorch', 'slurm', 'mpi'], + default='none', + help='job launcher') + parser.add_argument( + '--tta', action='store_true', help='Test time augmentation') + # When using PyTorch version >= 2.0.0, the `torch.distributed.launch` + # will pass the `--local-rank` parameter to `tools/train.py` instead + # of `--local_rank`. + parser.add_argument('--local_rank', '--local-rank', type=int, default=0) + args = parser.parse_args() + if 'LOCAL_RANK' not in os.environ: + os.environ['LOCAL_RANK'] = str(args.local_rank) + + return args + + +def trigger_visualization_hook(cfg, args): + default_hooks = cfg.default_hooks + if 'visualization' in default_hooks: + visualization_hook = default_hooks['visualization'] + # Turn on visualization + visualization_hook['draw'] = True + if args.show: + visualization_hook['show'] = True + visualization_hook['wait_time'] = args.wait_time + if args.show_dir: + visualizer = cfg.visualizer + visualizer['save_dir'] = args.show_dir + else: + raise RuntimeError( + 'VisualizationHook must be included in default_hooks.' + 'refer to usage ' + '"visualization=dict(type=\'VisualizationHook\')"') + + return cfg + + +def main(): + args = parse_args() + + # load config + cfg = Config.fromfile(args.config) + cfg.launcher = args.launcher + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # work_dir is determined in this priority: CLI > segment in file > filename + if args.work_dir is not None: + # update configs according to CLI args if args.work_dir is not None + cfg.work_dir = args.work_dir + elif cfg.get('work_dir', None) is None: + # use config filename as default work_dir if cfg.work_dir is None + cfg.work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + + cfg.load_from = args.checkpoint + + if args.show or args.show_dir: + cfg = trigger_visualization_hook(cfg, args) + + if args.tta: + cfg.test_dataloader.dataset.pipeline = cfg.tta_pipeline + cfg.tta_model.module = cfg.model + cfg.model = cfg.tta_model + + # add output_dir in metric + if args.out is not None: + cfg.test_evaluator['output_dir'] = args.out + cfg.test_evaluator['keep_results'] = True + + # build the runner from config + runner = Runner.from_cfg(cfg) + + # start testing + runner.test() + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/InterFormer/tools/torchserve/mmseg2torchserve.py b/reconstruction/modules/InterFormer/tools/torchserve/mmseg2torchserve.py new file mode 100644 index 0000000000000000000000000000000000000000..23f99638e799fd0b37a6737cc833dd7d24f611f8 --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/torchserve/mmseg2torchserve.py @@ -0,0 +1,112 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from argparse import ArgumentParser, Namespace +from pathlib import Path +from tempfile import TemporaryDirectory + +from mmengine import Config +from mmengine.utils import mkdir_or_exist + +try: + from model_archiver.model_packaging import package_model + from model_archiver.model_packaging_utils import ModelExportUtils +except ImportError: + package_model = None + + +def mmseg2torchserve( + config_file: str, + checkpoint_file: str, + output_folder: str, + model_name: str, + model_version: str = '1.0', + force: bool = False, +): + """Converts mmsegmentation model (config + checkpoint) to TorchServe + `.mar`. + + Args: + config_file: + In MMSegmentation config format. + The contents vary for each task repository. + checkpoint_file: + In MMSegmentation checkpoint format. + The contents vary for each task repository. + output_folder: + Folder where `{model_name}.mar` will be created. + The file created will be in TorchServe archive format. + model_name: + If not None, used for naming the `{model_name}.mar` file + that will be created under `output_folder`. + If None, `{Path(checkpoint_file).stem}` will be used. + model_version: + Model's version. + force: + If True, if there is an existing `{model_name}.mar` + file under `output_folder` it will be overwritten. + """ + mkdir_or_exist(output_folder) + + config = Config.fromfile(config_file) + + with TemporaryDirectory() as tmpdir: + config.dump(f'{tmpdir}/config.py') + + args = Namespace( + **{ + 'model_file': f'{tmpdir}/config.py', + 'serialized_file': checkpoint_file, + 'handler': f'{Path(__file__).parent}/mmseg_handler.py', + 'model_name': model_name or Path(checkpoint_file).stem, + 'version': model_version, + 'export_path': output_folder, + 'force': force, + 'requirements_file': None, + 'extra_files': None, + 'runtime': 'python', + 'archive_format': 'default' + }) + manifest = ModelExportUtils.generate_manifest_json(args) + package_model(args, manifest) + + +def parse_args(): + parser = ArgumentParser( + description='Convert mmseg models to TorchServe `.mar` format.') + parser.add_argument('config', type=str, help='config file path') + parser.add_argument('checkpoint', type=str, help='checkpoint file path') + parser.add_argument( + '--output-folder', + type=str, + required=True, + help='Folder where `{model_name}.mar` will be created.') + parser.add_argument( + '--model-name', + type=str, + default=None, + help='If not None, used for naming the `{model_name}.mar`' + 'file that will be created under `output_folder`.' + 'If None, `{Path(checkpoint_file).stem}` will be used.') + parser.add_argument( + '--model-version', + type=str, + default='1.0', + help='Number used for versioning.') + parser.add_argument( + '-f', + '--force', + action='store_true', + help='overwrite the existing `{model_name}.mar`') + args = parser.parse_args() + + return args + + +if __name__ == '__main__': + args = parse_args() + + if package_model is None: + raise ImportError('`torch-model-archiver` is required.' + 'Try: pip install torch-model-archiver') + + mmseg2torchserve(args.config, args.checkpoint, args.output_folder, + args.model_name, args.model_version, args.force) diff --git a/reconstruction/modules/InterFormer/tools/torchserve/mmseg_handler.py b/reconstruction/modules/InterFormer/tools/torchserve/mmseg_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..dbe5ded8482c1113a6adb45a22b650af71f6294e --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/torchserve/mmseg_handler.py @@ -0,0 +1,56 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import base64 +import os + +import cv2 +import mmcv +import torch +from mmengine.model.utils import revert_sync_batchnorm +from ts.torch_handler.base_handler import BaseHandler + +from mmseg.apis import inference_model, init_model + + +class MMsegHandler(BaseHandler): + + def initialize(self, context): + properties = context.system_properties + self.map_location = 'cuda' if torch.cuda.is_available() else 'cpu' + self.device = torch.device(self.map_location + ':' + + str(properties.get('gpu_id')) if torch.cuda. + is_available() else self.map_location) + self.manifest = context.manifest + + model_dir = properties.get('model_dir') + serialized_file = self.manifest['model']['serializedFile'] + checkpoint = os.path.join(model_dir, serialized_file) + self.config_file = os.path.join(model_dir, 'config.py') + + self.model = init_model(self.config_file, checkpoint, self.device) + self.model = revert_sync_batchnorm(self.model) + self.initialized = True + + def preprocess(self, data): + images = [] + + for row in data: + image = row.get('data') or row.get('body') + if isinstance(image, str): + image = base64.b64decode(image) + image = mmcv.imfrombytes(image) + images.append(image) + + return images + + def inference(self, data, *args, **kwargs): + results = [inference_model(self.model, img) for img in data] + return results + + def postprocess(self, data): + output = [] + + for image_result in data: + _, buffer = cv2.imencode('.png', image_result[0].astype('uint8')) + content = buffer.tobytes() + output.append(content) + return output diff --git a/reconstruction/modules/InterFormer/tools/torchserve/test_torchserve.py b/reconstruction/modules/InterFormer/tools/torchserve/test_torchserve.py new file mode 100644 index 0000000000000000000000000000000000000000..b015b6658556e5045af2daf5d998de0de61e1f6b --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/torchserve/test_torchserve.py @@ -0,0 +1,58 @@ +# Copyright (c) OpenMMLab. All rights reserved. +from argparse import ArgumentParser +from io import BytesIO + +import matplotlib.pyplot as plt +import mmcv +import requests + +from mmseg.apis import inference_model, init_model + + +def parse_args(): + parser = ArgumentParser( + description='Compare result of torchserve and pytorch,' + 'and visualize them.') + parser.add_argument('img', help='Image file') + parser.add_argument('config', help='Config file') + parser.add_argument('checkpoint', help='Checkpoint file') + parser.add_argument('model_name', help='The model name in the server') + parser.add_argument( + '--inference-addr', + default='127.0.0.1:8080', + help='Address and port of the inference server') + parser.add_argument( + '--result-image', + type=str, + default=None, + help='save server output in result-image') + parser.add_argument( + '--device', default='cuda:0', help='Device used for inference') + + args = parser.parse_args() + return args + + +def main(args): + url = 'http://' + args.inference_addr + '/predictions/' + args.model_name + with open(args.img, 'rb') as image: + tmp_res = requests.post(url, image) + content = tmp_res.content + if args.result_image: + with open(args.result_image, 'wb') as out_image: + out_image.write(content) + plt.imshow(mmcv.imread(args.result_image, 'grayscale')) + plt.show() + else: + plt.imshow(plt.imread(BytesIO(content))) + plt.show() + model = init_model(args.config, args.checkpoint, args.device) + image = mmcv.imread(args.img) + result = inference_model(model, image) + plt.imshow(result[0]) + plt.show() + + +if __name__ == '__main__': + args = parse_args() + main(args) diff --git a/reconstruction/modules/InterFormer/tools/train.py b/reconstruction/modules/InterFormer/tools/train.py new file mode 100644 index 0000000000000000000000000000000000000000..10fdaa1874be0348f3945296a29526236c103d9f --- /dev/null +++ b/reconstruction/modules/InterFormer/tools/train.py @@ -0,0 +1,104 @@ +# Copyright (c) OpenMMLab. All rights reserved. +import argparse +import logging +import os +import os.path as osp + +from mmengine.config import Config, DictAction +from mmengine.logging import print_log +from mmengine.runner import Runner + +from mmseg.registry import RUNNERS + + +def parse_args(): + parser = argparse.ArgumentParser(description='Train a segmentor') + parser.add_argument('config', help='train config file path') + parser.add_argument('--work-dir', help='the dir to save logs and models') + parser.add_argument( + '--resume', + action='store_true', + default=False, + help='resume from the latest checkpoint in the work_dir automatically') + parser.add_argument( + '--amp', + action='store_true', + default=False, + help='enable automatic-mixed-precision training') + parser.add_argument( + '--cfg-options', + nargs='+', + action=DictAction, + help='override some settings in the used config, the key-value pair ' + 'in xxx=yyy format will be merged into config file. If the value to ' + 'be overwritten is a list, it should be like key="[a,b]" or key=a,b ' + 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" ' + 'Note that the quotation marks are necessary and that no white space ' + 'is allowed.') + parser.add_argument( + '--launcher', + choices=['none', 'pytorch', 'slurm', 'mpi'], + default='none', + help='job launcher') + # When using PyTorch version >= 2.0.0, the `torch.distributed.launch` + # will pass the `--local-rank` parameter to `tools/train.py` instead + # of `--local_rank`. + parser.add_argument('--local_rank', '--local-rank', type=int, default=0) + args = parser.parse_args() + if 'LOCAL_RANK' not in os.environ: + os.environ['LOCAL_RANK'] = str(args.local_rank) + + return args + + +def main(): + args = parse_args() + + # load config + cfg = Config.fromfile(args.config) + cfg.launcher = args.launcher + if args.cfg_options is not None: + cfg.merge_from_dict(args.cfg_options) + + # work_dir is determined in this priority: CLI > segment in file > filename + if args.work_dir is not None: + # update configs according to CLI args if args.work_dir is not None + cfg.work_dir = args.work_dir + elif cfg.get('work_dir', None) is None: + # use config filename as default work_dir if cfg.work_dir is None + cfg.work_dir = osp.join('./work_dirs', + osp.splitext(osp.basename(args.config))[0]) + + # enable automatic-mixed-precision training + if args.amp is True: + optim_wrapper = cfg.optim_wrapper.type + if optim_wrapper == 'AmpOptimWrapper': + print_log( + 'AMP training is already enabled in your config.', + logger='current', + level=logging.WARNING) + else: + assert optim_wrapper == 'OptimWrapper', ( + '`--amp` is only supported when the optimizer wrapper type is ' + f'`OptimWrapper` but got {optim_wrapper}.') + cfg.optim_wrapper.type = 'AmpOptimWrapper' + cfg.optim_wrapper.loss_scale = 'dynamic' + + # resume training + cfg.resume = args.resume + + # build the runner from config + if 'runner_type' not in cfg: + # build the default runner + runner = Runner.from_cfg(cfg) + else: + # build customized runner from the registry + # if 'runner_type' is set in the cfg + runner = RUNNERS.build(cfg) + + # start training + runner.train() + + +if __name__ == '__main__': + main() diff --git a/reconstruction/modules/sam-3d-objects/.gitignore b/reconstruction/modules/sam-3d-objects/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ed8ebf583f771da9150c35db3955987b7d757904 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/.gitignore @@ -0,0 +1 @@ +__pycache__ \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/CODE_OF_CONDUCT.md b/reconstruction/modules/sam-3d-objects/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..cf9dc244896688c330dba81d06f2cfc5568d7aea --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/CODE_OF_CONDUCT.md @@ -0,0 +1,80 @@ +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to make participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or +advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic +address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a +professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies within all project spaces, and it also applies when +an individual is representing the project or its community in public spaces. +Examples of representing a project or community include using an official +project e-mail address, posting via an official social media account, or acting +as an appointed representative at an online or offline event. Representation of +a project may be further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when there is a +reasonable belief that an individual's behavior may have a negative impact on +the project or its community. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at . All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/CONTRIBUTING.md b/reconstruction/modules/sam-3d-objects/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..f853448d128c8e64ab1446451f92c014e5a4ba3d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/CONTRIBUTING.md @@ -0,0 +1,39 @@ +# Contributing to sam-3d-objects +We want to make contributing to this project as easy and transparent as +possible. + +## Our Development Process +... (in particular how this is synced with internal changes to the project) + +## Pull Requests +We actively welcome your pull requests. + +1. Fork the repo and create your branch from `main`. +2. If you've added code that should be tested, add tests. +3. If you've changed APIs, update the documentation. +4. Ensure the test suite passes. +5. Make sure your code lints. +6. If you haven't already, complete the Contributor License Agreement ("CLA"). + +## Contributor License Agreement ("CLA") +In order to accept your pull request, we need you to submit a CLA. You only need +to do this once to work on any of Meta's open source projects. + +Complete your CLA here: + +## Issues +We use GitHub issues to track public bugs. Please ensure your description is +clear and has sufficient instructions to be able to reproduce the issue. + +Meta has a [bounty program](https://bugbounty.meta.com/) for the safe +disclosure of security bugs. In those cases, please go through the process +outlined on that page and do not file a public issue. + +## Coding Style +* 2 spaces for indentation rather than tabs +* 80 character line length +* ... + +## License +By contributing to sam-3d-objects, you agree that your contributions will be licensed +under the LICENSE file in the root directory of this source tree. \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/LICENSE b/reconstruction/modules/sam-3d-objects/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e58d758cc3d92e6d1a57b52f7e4d203d02a67e98 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/LICENSE @@ -0,0 +1,52 @@ +SAM License +Last Updated: November 19, 2025 + +“Agreement” means the terms and conditions for use, reproduction, distribution and modification of the SAM Materials set forth herein. + +“SAM Materials” means, collectively, Documentation and the models, software and algorithms, including machine-learning model code, trained model weights, inference-enabling code, training-enabling code, fine-tuning enabling code, and other elements of the foregoing distributed by Meta and made available under this Agreement. + +“Documentation” means the specifications, manuals and documentation accompanying +SAM Materials distributed by Meta. + +“Licensee” or “you” means you, or your employer or any other person or entity (if you are entering into this Agreement on such person or entity’s behalf), of the age required under applicable laws, rules or regulations to provide legal consent and that has legal authority to bind your employer or such other person or entity if you are entering in this Agreement on their behalf. + +“Meta” or “we” means Meta Platforms Ireland Limited (if you are located in or, if you are an entity, your principal place of business is in the EEA or Switzerland) or Meta Platforms, Inc. (if you are located outside of the EEA or Switzerland). + +“Sanctions” means any economic or trade sanctions or restrictions administered or enforced by the United States (including the Office of Foreign Assets Control of the U.S. Department of the Treasury (“OFAC”), the U.S. Department of State and the U.S. Department of Commerce), the United Nations, the European Union, or the United Kingdom. + +“Trade Controls” means any of the following: Sanctions and applicable export and import controls. + +By using or distributing any portion or element of the SAM Materials, you agree to be bound by this Agreement. + +1. License Rights and Redistribution. + +a. Grant of Rights. You are granted a non-exclusive, worldwide, non-transferable and royalty-free limited license under Meta’s intellectual property or other rights owned by Meta embodied in the SAM Materials to use, reproduce, distribute, copy, create derivative works of, and make modifications to the SAM Materials. + +i. Grant of Patent License. Subject to the terms and conditions of this License, you are granted a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by Meta that are necessarily infringed alone or by combination of their contribution(s) with the SAM 3 Materials. If you institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM 3 Materials incorporated within the work constitutes direct or contributory patent infringement, then any patent licenses granted to you under this License for that work shall terminate as of the date such litigation is filed. + +b. Redistribution and Use. + +i. Distribution of SAM Materials, and any derivative works thereof, are subject to the terms of this Agreement. If you distribute or make the SAM Materials, or any derivative works thereof, available to a third party, you may only do so under the terms of this Agreement and you shall provide a copy of this Agreement with any such SAM Materials. + +ii. If you submit for publication the results of research you perform on, using, or otherwise in connection with SAM Materials, you must acknowledge the use of SAM Materials in your publication. + +iii. Your use of the SAM Materials must comply with applicable laws and regulations, including Trade Control Laws and applicable privacy and data protection laws. +iv. Your use of the SAM Materials will not involve or encourage others to reverse engineer, decompile or discover the underlying components of the SAM Materials. +v. You are not the target of Trade Controls and your use of SAM Materials must comply with Trade Controls. You agree not to use, or permit others to use, SAM Materials for any activities subject to the International Traffic in Arms Regulations (ITAR) or end uses prohibited by Trade Controls, including those related to military or warfare purposes, nuclear industries or applications, espionage, or the development or use of guns or illegal weapons. +2. User Support. Your use of the SAM Materials is done at your own discretion; Meta does not process any information nor provide any service in relation to such use. Meta is under no obligation to provide any support services for the SAM Materials. Any support provided is “as is”, “with all faults”, and without warranty of any kind. + +3. Disclaimer of Warranty. UNLESS REQUIRED BY APPLICABLE LAW, THE SAM MATERIALS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OF ANY KIND, AND META DISCLAIMS ALL WARRANTIES OF ANY KIND, BOTH EXPRESS AND IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING OR REDISTRIBUTING THE SAM MATERIALS AND ASSUME ANY RISKS ASSOCIATED WITH YOUR USE OF THE SAM MATERIALS AND ANY OUTPUT AND RESULTS. + +4. Limitation of Liability. IN NO EVENT WILL META OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, ARISING OUT OF THIS AGREEMENT, FOR ANY LOST PROFITS OR ANY DIRECT OR INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL, EXEMPLARY OR PUNITIVE DAMAGES, EVEN IF META OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING. + +5. Intellectual Property. + +a. Subject to Meta’s ownership of SAM Materials and derivatives made by or for Meta, with respect to any derivative works and modifications of the SAM Materials that are made by you, as between you and Meta, you are and will be the owner of such derivative works and modifications. + +b. If you institute litigation or other proceedings against Meta or any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the SAM Materials, outputs or results, or any portion of any of the foregoing, constitutes infringement of intellectual property or other rights owned or licensable by you, then any licenses granted to you under this Agreement shall terminate as of the date such litigation or claim is filed or instituted. You will indemnify and hold harmless Meta from and against any claim by any third party arising out of or related to your use or distribution of the SAM Materials. + +6. Term and Termination. The term of this Agreement will commence upon your acceptance of this Agreement or access to the SAM Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein. Meta may terminate this Agreement if you are in breach of any term or condition of this Agreement. Upon termination of this Agreement, you shall delete and cease use of the SAM Materials. Sections 3, 4 and 7 shall survive the termination of this Agreement. + +7. Governing Law and Jurisdiction. This Agreement will be governed and construed under the laws of the State of California without regard to choice of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement. The courts of California shall have exclusive jurisdiction of any dispute arising out of this Agreement. + +8. Modifications and Amendments. Meta may modify this Agreement from time to time; provided that they are similar in spirit to the current version of the Agreement, but may differ in detail to address new problems or concerns. All such changes will be effective immediately. Your continued use of the SAM Materials after any modification to this Agreement constitutes your agreement to such modification. Except as provided in this Agreement, no modification or addition to any provision of this Agreement will be binding unless it is in writing and signed by an authorized representative of both you and Meta. diff --git a/reconstruction/modules/sam-3d-objects/README.md b/reconstruction/modules/sam-3d-objects/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3bcc4e6d8255efc7601406ce1471ef9a531ab411 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/README.md @@ -0,0 +1,152 @@ +# SAM 3D + +SAM 3D Objects is one part of SAM 3D, a pair of models for object and human mesh reconstruction. If you’re looking for SAM 3D Body, [click here](https://github.com/facebookresearch/sam-3d-body). + +# SAM 3D Objects + +**SAM 3D Team**, [Xingyu Chen](https://scholar.google.com/citations?user=gjSHr6YAAAAJ&hl=en&oi=sra)\*, [Fu-Jen Chu](https://fujenchu.github.io/)\*, [Pierre Gleize](https://scholar.google.com/citations?user=4imOcw4AAAAJ&hl=en&oi=ao)\*, [Kevin J Liang](https://kevinjliang.github.io/)\*, [Alexander Sax](https://alexsax.github.io/)\*, [Hao Tang](https://scholar.google.com/citations?user=XY6Nh9YAAAAJ&hl=en&oi=sra)\*, [Weiyao Wang](https://sites.google.com/view/weiyaowang/home)\*, [Michelle Guo](https://scholar.google.com/citations?user=lyjjpNMAAAAJ&hl=en&oi=ao), [Thibaut Hardin](https://github.com/Thibaut-H), [Xiang Li](https://ryanxli.github.io/)⚬, [Aohan Lin](https://github.com/linaohan), [Jia-Wei Liu](https://jia-wei-liu.github.io/), [Ziqi Ma](https://ziqi-ma.github.io/)⚬, [Anushka Sagar](https://www.linkedin.com/in/anushkasagar/), [Bowen Song](https://scholar.google.com/citations?user=QQKVkfcAAAAJ&hl=en&oi=sra)⚬, [Xiaodong Wang](https://scholar.google.com/citations?authuser=2&user=rMpcFYgAAAAJ), [Jianing Yang](https://jedyang.com/)⚬, [Bowen Zhang](http://home.ustc.edu.cn/~zhangbowen/)⚬, [Piotr Dollár](https://pdollar.github.io/)†, [Georgia Gkioxari](https://georgiagkioxari.com/)†, [Matt Feiszli](https://scholar.google.com/citations?user=A-wA73gAAAAJ&hl=en&oi=ao)†§, [Jitendra Malik](https://people.eecs.berkeley.edu/~malik/)†§ + +***Meta Superintelligence Labs*** + +*Core contributor (Alphabetical, Equal Contribution), ⚬Intern, †Project leads, §Equal Contribution + +[[`Paper`](https://ai.meta.com/research/publications/sam-3d-3dfy-anything-in-images/)] [[`Code`](https://github.com/facebookresearch/sam-3d-objects)] [[`Website`](https://ai.meta.com/sam3d/)] [[`Demo`](https://www.aidemos.meta.com/segment-anything/editor/convert-image-to-3d)] [[`Blog`](https://ai.meta.com/blog/sam-3d/)] [[`BibTeX`](#citing-sam-3d-objects)] [[`Roboflow`](https://blog.roboflow.com/sam-3d/)] + +**SAM 3D Objects** is a foundation model that reconstructs full 3D shape geometry, texture, and layout from a single image, excelling in real-world scenarios with occlusion and clutter by using progressive training and a data engine with human feedback. It outperforms prior 3D generation models in human preference tests on real-world objects and scenes. We released code, weights, online demo, and a new challenging benchmark. + + +

+ +----- + +

+ +## Latest updates + +**11/19/2025** - Checkpoints Launched, Web Demo and Paper are out. + +## Installation + +Follow the [setup](doc/setup.md) steps before running the following. + +## Single or Multi-Object 3D Generation + +SAM 3D Objects can convert masked objects in an image, into 3D models with pose, shape, texture, and layout. SAM 3D is designed to be robust in challenging natural images, handling small objects and occlusions, unusual poses, and difficult situations encountered in uncurated natural scenes like this kidsroom: + +

+ + +

+ +For a quick start, run `python demo.py` or use the the following lines of code: + +```python +import sys + +# import inference code +sys.path.append("notebook") +from inference import Inference, load_image, load_single_mask + +# load model +tag = "hf" +config_path = f"checkpoints/{tag}/pipeline.yaml" +inference = Inference(config_path, compile=False) + +# load image and mask +image = load_image("notebook/images/shutterstock_stylish_kidsroom_1640806567/image.png") +mask = load_single_mask("notebook/images/shutterstock_stylish_kidsroom_1640806567", index=14) + +# run model +output = inference(image, mask, seed=42) + +# export gaussian splat +output["gs"].save_ply(f"splat.ply") +``` + +For more details and multi-object reconstruction, please take a look at out two jupyter notebooks: +* [single object](notebook/demo_single_object.ipynb) +* [multi object](notebook/demo_multi_object.ipynb) + + +## SAM 3D Body + +[SAM 3D Body (3DB)](https://github.com/facebookresearch/sam-3d-body) is a robust promptable foundation model for single-image 3D human mesh recovery (HMR). + +As a way to combine the strengths of both **SAM 3D Objects** and **SAM 3D Body**, we provide an example notebook that demonstrates how to combine the results of both models such that they are aligned in the same frame of reference. Check it out [here](notebook/demo_3db_mesh_alignment.ipynb). + +## License + +The SAM 3D Objects model checkpoints and code are licensed under [SAM License](./LICENSE). + +## Contributing + +See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md). + +## Contributors + +The SAM 3D Objects project was made possible with the help of many contributors. + +Robbie Adkins, +Paris Baptiste, +Karen Bergan, +Kai Brown, +Michelle Chan, +Ida Cheng, +Khadijat Durojaiye, +Patrick Edwards, +Daniella Factor, +Facundo Figueroa, +Rene de la Fuente, +Eva Galper, +Cem Gokmen, +Alex He, +Enmanuel Hernandez, +Dex Honsa, +Leonna Jones, +Arpit Kalla, +Kris Kitani, +Helen Klein, +Kei Koyama, +Robert Kuo, +Vivian Lee, +Alex Lende, +Jonny Li, +Kehan Lyu, +Faye Ma, +Mallika Malhotra, +Sasha Mitts, +William Ngan, +George Orlin, +Peter Park, +Don Pinkus, +Roman Radle, +Nikhila Ravi, +Azita Shokrpour, +Jasmine Shone, +Zayida Suber, +Phillip Thomas, +Tatum Turner, +Joseph Walker, +Meng Wang, +Claudette Ward, +Andrew Westbury, +Lea Wilken, +Nan Yang, +Yael Yungster + + +## Citing SAM 3D Objects + +If you use SAM 3D Objects in your research, please use the following BibTeX entry. + +``` +@article{sam3dteam2025sam3d3dfyimages, + title={SAM 3D: 3Dfy Anything in Images}, + author={SAM 3D Team and Xingyu Chen and Fu-Jen Chu and Pierre Gleize and Kevin J Liang and Alexander Sax and Hao Tang and Weiyao Wang and Michelle Guo and Thibaut Hardin and Xiang Li and Aohan Lin and Jiawei Liu and Ziqi Ma and Anushka Sagar and Bowen Song and Xiaodong Wang and Jianing Yang and Bowen Zhang and Piotr Dollár and Georgia Gkioxari and Matt Feiszli and Jitendra Malik}, + year={2025}, + eprint={2511.16624}, + archivePrefix={arXiv}, + primaryClass={cs.CV}, + url={https://arxiv.org/abs/2511.16624}, +} +``` diff --git a/reconstruction/modules/sam-3d-objects/checkpoints/.gitignore b/reconstruction/modules/sam-3d-objects/checkpoints/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c96a04f008ee21e260b28f7701595ed59e2839e3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/checkpoints/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/demo.py b/reconstruction/modules/sam-3d-objects/demo.py new file mode 100644 index 0000000000000000000000000000000000000000..ac520372e1d50242bfbf1068516d475e3c3393aa --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/demo.py @@ -0,0 +1,22 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +import sys + +# import inference code +sys.path.append("notebook") +from inference import Inference, load_image, load_single_mask + +# load model +tag = "hf" +config_path = f"checkpoints/{tag}/pipeline.yaml" +inference = Inference(config_path, compile=False) + +# load image (RGBA only, mask is embedded in the alpha channel) +image = load_image("notebook/images/shutterstock_stylish_kidsroom_1640806567/image.png") +mask = load_single_mask("notebook/images/shutterstock_stylish_kidsroom_1640806567", index=14) + +# run model +output = inference(image, mask, seed=42) + +# export gaussian splat +output["gs"].save_ply(f"splat.ply") +print("Your reconstruction has been saved to splat.ply") diff --git a/reconstruction/modules/sam-3d-objects/doc/arch.png b/reconstruction/modules/sam-3d-objects/doc/arch.png new file mode 100644 index 0000000000000000000000000000000000000000..33fe32eab3fbc3c2888e84b3c1e83cc3a005a6fa --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/doc/arch.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59468933f3e24dfe37d286db290d8af1c5d027cd3f105f9f05049ec83a42152f +size 276423 diff --git a/reconstruction/modules/sam-3d-objects/doc/intro.png b/reconstruction/modules/sam-3d-objects/doc/intro.png new file mode 100644 index 0000000000000000000000000000000000000000..2ec8da8d17cf5b656266031c0ed4619da02ee3c2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/doc/intro.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0dc7f15c24357a15a988623ed22b366393af7205b1ca6b5d3e15a84f7bfbfa3 +size 782621 diff --git a/reconstruction/modules/sam-3d-objects/doc/kidsroom_transparent.gif b/reconstruction/modules/sam-3d-objects/doc/kidsroom_transparent.gif new file mode 100644 index 0000000000000000000000000000000000000000..31dcce66e5400929a450aadcf6d7ea4d665f8f65 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/doc/kidsroom_transparent.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b40aa1bf732c91c87dc68ebbe29be67117822dba29f74896bacfbf5e453a678 +size 7769835 diff --git a/reconstruction/modules/sam-3d-objects/doc/setup.md b/reconstruction/modules/sam-3d-objects/doc/setup.md new file mode 100644 index 0000000000000000000000000000000000000000..1da6cd77a185dee7cde52ee3f8bed679028a963c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/doc/setup.md @@ -0,0 +1,58 @@ +# Setup + +## Prerequisites + +* A linux 64-bits architecture (i.e. `linux-64` platform in `mamba info`). +* A NVIDIA GPU with at least 32 Gb of VRAM. + +## 1. Setup Python Environment + +The following will install the default environment. If you use `conda` instead of `mamba`, replace its name in the first two lines. Note that you may have to build the environment on a compute node with GPU (e.g., you may get a `RuntimeError: Not compiled with GPU support` error when running certain parts of the code that use Pytorch3D). + +```bash +# create sam3d-objects environment +mamba env create -f environments/default.yml +mamba activate sam3d-objects + +# for pytorch/cuda dependencies +export PIP_EXTRA_INDEX_URL="https://pypi.ngc.nvidia.com https://download.pytorch.org/whl/cu121" + +# install sam3d-objects and core dependencies +pip install -e '.[dev]' +pip install -e '.[p3d]' # pytorch3d dependency on pytorch is broken, this 2-step approach solves it + +# for inference +export PIP_FIND_LINKS="https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.5.1_cu121.html" +pip install -e '.[inference]' + +# patch things that aren't yet in official pip packages +./patching/hydra # https://github.com/facebookresearch/hydra/pull/2863 +``` + +## 2. Getting Checkpoints + +### From HuggingFace + +⚠️ Before using SAM 3D Objects, please request access to the checkpoints on the SAM 3D Objects +Hugging Face [repo](https://huggingface.co/facebook/sam-3d-objects). Once accepted, you +need to be authenticated to download the checkpoints. You can do this by running +the following [steps](https://huggingface.co/docs/huggingface_hub/en/quick-start#authentication) +(e.g. `hf auth login` after generating an access token). + +⚠️ SAM 3D Objects is available via HuggingFace globally, **except** in comprehensively sanctioned jurisdictions. +Sanctioned jurisdiction will result in requests being **rejected**. + +```bash +pip install 'huggingface-hub[cli]<1.0' + +TAG=hf +hf download \ + --repo-type model \ + --local-dir checkpoints/${TAG}-download \ + --max-workers 1 \ + facebook/sam-3d-objects +mv checkpoints/${TAG}-download/checkpoints checkpoints/${TAG} +rm -rf checkpoints/${TAG}-download +``` + + diff --git a/reconstruction/modules/sam-3d-objects/environments/default.yml b/reconstruction/modules/sam-3d-objects/environments/default.yml new file mode 100644 index 0000000000000000000000000000000000000000..091170ea69a1a81555c0b1b7add5666711030aff --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/environments/default.yml @@ -0,0 +1,216 @@ +name: sam3d-objects +channels: + - conda-forge +dependencies: + - _libgcc_mutex=0.1=conda_forge + - _openmp_mutex=4.5=2_gnu + - alsa-lib=1.2.13=hb9d3cd8_0 + - attr=2.5.1=h166bdaf_1 + - binutils=2.43=h4852527_4 + - binutils_impl_linux-64=2.43=h4bf12b8_4 + - binutils_linux-64=2.43=h4852527_4 + - bzip2=1.0.8=h4bc722e_7 + - c-compiler=1.7.0=hd590300_1 + - ca-certificates=2025.1.31=hbcca054_0 + - cairo=1.18.0=h3faef2a_0 + - cuda-cccl=12.1.109=ha770c72_0 + - cuda-cccl-impl=2.0.1=ha770c72_1 + - cuda-cccl_linux-64=12.1.109=ha770c72_0 + - cuda-command-line-tools=12.1.1=ha770c72_0 + - cuda-compiler=12.1.1=hbad6d8a_0 + - cuda-cudart=12.1.105=hd3aeb46_0 + - cuda-cudart-dev=12.1.105=hd3aeb46_0 + - cuda-cudart-dev_linux-64=12.1.105=h59595ed_0 + - cuda-cudart-static=12.1.105=hd3aeb46_0 + - cuda-cudart-static_linux-64=12.1.105=h59595ed_0 + - cuda-cudart_linux-64=12.1.105=h59595ed_0 + - cuda-cuobjdump=12.1.111=h59595ed_0 + - cuda-cupti=12.1.105=h59595ed_0 + - cuda-cupti-dev=12.1.105=h59595ed_0 + - cuda-cuxxfilt=12.1.105=h59595ed_0 + - cuda-driver-dev=12.1.105=hd3aeb46_0 + - cuda-driver-dev_linux-64=12.1.105=h59595ed_0 + - cuda-gdb=12.1.105=hd47b8d6_0 + - cuda-libraries=12.1.1=ha770c72_0 + - cuda-libraries-dev=12.1.1=ha770c72_0 + - cuda-nsight=12.1.105=ha770c72_0 + - cuda-nvcc=12.1.105=hcdd1206_1 + - cuda-nvcc-dev_linux-64=12.1.105=ha770c72_0 + - cuda-nvcc-impl=12.1.105=hd3aeb46_0 + - cuda-nvcc-tools=12.1.105=hd3aeb46_0 + - cuda-nvcc_linux-64=12.1.105=h8a487aa_1 + - cuda-nvdisasm=12.1.105=h59595ed_0 + - cuda-nvml-dev=12.1.105=h59595ed_0 + - cuda-nvprof=12.1.105=h59595ed_0 + - cuda-nvprune=12.1.105=h59595ed_0 + - cuda-nvrtc=12.1.105=hd3aeb46_0 + - cuda-nvrtc-dev=12.1.105=hd3aeb46_0 + - cuda-nvtx=12.1.105=h59595ed_0 + - cuda-nvvp=12.1.105=h59595ed_0 + - cuda-opencl=12.1.105=h59595ed_0 + - cuda-opencl-dev=12.1.105=h59595ed_0 + - cuda-profiler-api=12.1.105=ha770c72_0 + - cuda-sanitizer-api=12.1.105=h59595ed_0 + - cuda-toolkit=12.1.1=ha804496_0 + - cuda-tools=12.1.1=ha770c72_0 + - cuda-version=12.1=h1d6eff3_3 + - cuda-visual-tools=12.1.1=ha770c72_0 + - cxx-compiler=1.7.0=h00ab1b0_1 + - dbus=1.13.6=h5008d03_3 + - expat=2.6.4=h5888daf_0 + - font-ttf-dejavu-sans-mono=2.37=hab24e00_0 + - font-ttf-inconsolata=3.000=h77eed37_0 + - font-ttf-source-code-pro=2.038=h77eed37_0 + - font-ttf-ubuntu=0.83=h77eed37_3 + - fontconfig=2.15.0=h7e30c49_1 + - fonts-conda-ecosystem=1=0 + - fonts-conda-forge=1=0 + - freetype=2.13.3=h48d6fc4_0 + - gcc=12.4.0=h236703b_2 + - gcc_impl_linux-64=12.4.0=h26ba24d_2 + - gcc_linux-64=12.4.0=h6b7512a_8 + - gds-tools=1.6.1.9=hd3aeb46_0 + - gettext=0.23.1=h5888daf_0 + - gettext-tools=0.23.1=h5888daf_0 + - glib=2.82.2=h07242d1_1 + - glib-tools=2.82.2=h4833e2c_1 + - gmp=6.3.0=hac33072_2 + - graphite2=1.3.13=h59595ed_1003 + - gst-plugins-base=1.24.4=h9ad1361_0 + - gstreamer=1.24.4=haf2f30d_0 + - gxx=12.4.0=h236703b_2 + - gxx_impl_linux-64=12.4.0=h3ff227c_2 + - gxx_linux-64=12.4.0=h8489865_8 + - harfbuzz=8.5.0=hfac3d4d_0 + - icu=73.2=h59595ed_0 + - kernel-headers_linux-64=3.10.0=he073ed8_18 + - keyutils=1.6.1=h166bdaf_0 + - krb5=1.21.3=h659f571_0 + - lame=3.100=h166bdaf_1003 + - ld_impl_linux-64=2.43=h712a8e2_4 + - libasprintf=0.23.1=h8e693c7_0 + - libasprintf-devel=0.23.1=h8e693c7_0 + - libcap=2.75=h39aace5_0 + - libclang-cpp15=15.0.7=default_h127d8a8_5 + - libclang13=19.1.2=default_h9c6a7e4_1 + - libcublas=12.1.3.1=hd3aeb46_0 + - libcublas-dev=12.1.3.1=hd3aeb46_0 + - libcufft=11.0.2.54=hd3aeb46_0 + - libcufft-dev=11.0.2.54=hd3aeb46_0 + - libcufile=1.6.1.9=hd3aeb46_0 + - libcufile-dev=1.6.1.9=hd3aeb46_0 + - libcups=2.3.3=h4637d8d_4 + - libcurand=10.3.2.106=hd3aeb46_0 + - libcurand-dev=10.3.2.106=hd3aeb46_0 + - libcusolver=11.4.5.107=hd3aeb46_0 + - libcusolver-dev=11.4.5.107=hd3aeb46_0 + - libcusparse=12.1.0.106=hd3aeb46_0 + - libcusparse-dev=12.1.0.106=hd3aeb46_0 + - libedit=3.1.20250104=pl5321h7949ede_0 + - libevent=2.1.12=hf998b51_1 + - libexpat=2.6.4=h5888daf_0 + - libffi=3.4.6=h2dba641_0 + - libflac=1.4.3=h59595ed_0 + - libgcc=14.2.0=h767d61c_2 + - libgcc-devel_linux-64=12.4.0=h1762d19_102 + - libgcc-ng=14.2.0=h69a702a_2 + - libgcrypt-lib=1.11.0=hb9d3cd8_2 + - libgettextpo=0.23.1=h5888daf_0 + - libgettextpo-devel=0.23.1=h5888daf_0 + - libglib=2.82.2=h2ff4ddf_1 + - libgomp=14.2.0=h767d61c_2 + - libgpg-error=1.51=hbd13f7d_1 + - libiconv=1.18=h4ce23a2_1 + - libjpeg-turbo=3.0.0=hd590300_1 + - libllvm15=15.0.7=hb3ce162_4 + - libllvm19=19.1.2=ha7bfdaf_0 + - liblzma=5.6.4=hb9d3cd8_0 + - liblzma-devel=5.6.4=hb9d3cd8_0 + - libnpp=12.1.0.40=hd3aeb46_0 + - libnpp-dev=12.1.0.40=hd3aeb46_0 + - libnsl=2.0.1=hd590300_0 + - libnuma=2.0.18=h4ab18f5_2 + - libnvjitlink=12.1.105=hd3aeb46_0 + - libnvjitlink-dev=12.1.105=hd3aeb46_0 + - libnvjpeg=12.2.0.2=h59595ed_0 + - libnvjpeg-dev=12.2.0.2=ha770c72_0 + - libogg=1.3.5=h4ab18f5_0 + - libopus=1.3.1=h7f98852_1 + - libpng=1.6.47=h943b412_0 + - libpq=16.8=h87c4ccc_0 + - libsanitizer=12.4.0=ha732cd4_2 + - libsndfile=1.2.2=hc60ed4a_1 + - libsqlite=3.49.1=hee588c1_2 + - libstdcxx=14.2.0=h8f9b012_2 + - libstdcxx-devel_linux-64=12.4.0=h1762d19_102 + - libstdcxx-ng=14.2.0=h4852527_2 + - libsystemd0=257.4=h4e0b6ca_1 + - libuuid=2.38.1=h0b41bf4_0 + - libvorbis=1.3.7=h9c3ff4c_0 + - libxcb=1.15=h0b41bf4_0 + - libxkbcommon=1.7.0=h662e7e4_0 + - libxkbfile=1.1.0=h166bdaf_1 + - libxml2=2.12.7=h4c95cb1_3 + - libzlib=1.3.1=hb9d3cd8_2 + - lz4-c=1.10.0=h5888daf_1 + - mpg123=1.32.9=hc50e24c_0 + - mysql-common=8.3.0=h70512c7_5 + - mysql-libs=8.3.0=ha479ceb_5 + - ncurses=6.5=h2d0b736_3 + - nsight-compute=2023.1.1.4=h3718151_0 + - nspr=4.36=h5888daf_0 + - nss=3.108=h159eef7_0 + - ocl-icd=2.3.2=hb9d3cd8_2 + - opencl-headers=2024.10.24=h5888daf_0 + - openssl=3.4.1=h7b32b05_0 + - packaging=24.2=pyhd8ed1ab_2 + - pcre2=10.44=hba22ea6_2 + - pip=25.0.1=pyh8b19718_0 + - pixman=0.44.2=h29eaf8c_0 + - pthread-stubs=0.4=hb9d3cd8_1002 + - pulseaudio-client=17.0=hb77b528_0 + - python=3.11.0=he550d4f_1_cpython + - qt-main=5.15.8=hc9dc06e_21 + - readline=8.2=h8c095d6_2 + - setuptools=75.8.2=pyhff2d567_0 + - sysroot_linux-64=2.17=h0157908_18 + - tk=8.6.13=noxft_h4845f30_101 + - tzdata=2025b=h78e105d_0 + - wayland=1.23.1=h3e06ad9_0 + - wheel=0.45.1=pyhd8ed1ab_1 + - xcb-util=0.4.0=hd590300_1 + - xcb-util-image=0.4.0=h8ee46fc_1 + - xcb-util-keysyms=0.4.0=h8ee46fc_1 + - xcb-util-renderutil=0.3.9=hd590300_1 + - xcb-util-wm=0.4.1=h8ee46fc_1 + - xkeyboard-config=2.42=h4ab18f5_0 + - xorg-compositeproto=0.4.2=hb9d3cd8_1002 + - xorg-damageproto=1.2.1=hb9d3cd8_1003 + - xorg-fixesproto=5.0=hb9d3cd8_1003 + - xorg-inputproto=2.3.2=hb9d3cd8_1003 + - xorg-kbproto=1.0.7=hb9d3cd8_1003 + - xorg-libice=1.1.2=hb9d3cd8_0 + - xorg-libsm=1.2.6=he73a12e_0 + - xorg-libx11=1.8.9=h8ee46fc_0 + - xorg-libxau=1.0.12=hb9d3cd8_0 + - xorg-libxcomposite=0.4.6=h0b41bf4_1 + - xorg-libxdamage=1.1.5=h7f98852_1 + - xorg-libxdmcp=1.1.5=hb9d3cd8_0 + - xorg-libxext=1.3.4=h0b41bf4_2 + - xorg-libxfixes=5.0.3=h7f98852_1004 + - xorg-libxi=1.7.10=h4bc722e_1 + - xorg-libxrandr=1.5.2=h7f98852_1 + - xorg-libxrender=0.9.11=hd590300_0 + - xorg-libxtst=1.2.5=h4bc722e_0 + - xorg-randrproto=1.5.0=hb9d3cd8_1002 + - xorg-recordproto=1.14.2=hb9d3cd8_1003 + - xorg-renderproto=0.11.1=hb9d3cd8_1003 + - xorg-util-macros=1.20.2=hb9d3cd8_0 + - xorg-xextproto=7.3.0=hb9d3cd8_1004 + - xorg-xf86vidmodeproto=2.3.1=hb9d3cd8_1005 + - xorg-xproto=7.0.31=hb9d3cd8_1008 + - xz=5.6.4=hbcc6ac9_0 + - xz-gpl-tools=5.6.4=hbcc6ac9_0 + - xz-tools=5.6.4=hb9d3cd8_0 + - zlib=1.3.1=hb9d3cd8_2 + - zstd=1.5.7=hb8e6e7a_2 diff --git a/reconstruction/modules/sam-3d-objects/generate_mesh_sam3d.py b/reconstruction/modules/sam-3d-objects/generate_mesh_sam3d.py new file mode 100644 index 0000000000000000000000000000000000000000..743dca7cad432c3f3699d7df1bcf7e9193c6d7fe --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/generate_mesh_sam3d.py @@ -0,0 +1,963 @@ +""" +trajectory_folder/ +├── frame_0.jpeg +└── masks/ + ├── plane_0.png + ├── object_0.png + ├── object_1.png + ├── object_2.png + └── ... + +python generate_mesh_sam3d.py --image_path /path/to/video_dir/all_frames/000000.png --masks_dir /path/to/video_dir/video_segmentation/masks/frame_000000_masks/ + +python generate_mesh_sam3d.py --image_path /path/to/video_dir/all_frames/000000.png --masks_dir /path/to/video_dir/video_segmentation/masks/frame_000000_masks/ --with_hand_mesh --mask_files brown_cup_inside_hand_0.png phone_0.png --hand_mask_path /path/to/video_dir/video_segmentation/masks/frame_000000_masks/hand_0.png --hand_mesh_path /path/to/hawor_mesh_0_canonical.obj + +python generate_mesh_sam3d.py --image_path /path/to/image.jpg --masks_dir /path/to/masks/ + +OR, for batch mode: + +all_frames_folder/ +├── task_frame_0.jpeg +├── task2_frame_0.jpeg +├── masks_task_frame_0/ +│ ├── plane_0.png +│ ├── object_0.png +│ ├── object_1.png +│ ├── object_2.png +│ └── ... +└── masks_task2_frame_0/ + ├── plane_0.png + ├── object_0.png + ├── object_1.png + ├── object_2.png + └── ... + + +python generate_mesh_sam3d.py --images_dir /path/to/dataset --masks_root /path/to/dataset + +OR, for batch mode with a JSON file of image paths: + +python generate_mesh_sam3d.py --json_path /path/to/manifest.json --with_mesh_postprocess True --with_texture_baking True --use_vertex_color False +""" + + +import argparse +import os +import json +from typing import Iterable, List, Optional, Sequence + +import torch +import trimesh +from pytorch3d.transforms import quaternion_to_matrix +import numpy as np +from scipy.spatial.transform import Rotation as R +from PIL import Image +from loguru import logger + +from notebook.inference import ( # type: ignore[import-not-found] + Inference, + load_image, + load_mask, +) +from sam3d_objects.data.dataset.tdfy.transforms_3d import ( + compose_transform, +) + +import torch.nn.functional as F +import torchvision +from pytorch3d.transforms import Transform3d + +from sam3d_objects.pipeline.inference_pipeline_pointmap import camera_to_pytorch3d_camera +from sam3d_objects.pipeline.utils.pointmap import infer_intrinsics_from_pointmap + +from omegaconf import OmegaConf +from hydra.utils import instantiate +from pathlib import Path +import open3d as o3d + +from tqdm import tqdm + + +def str2bool(v): + """Parse boolean values from command line arguments.""" + if isinstance(v, bool): + return v + if v.lower() in ('yes', 'true', 't', 'y', '1'): + return True + elif v.lower() in ('no', 'false', 'f', 'n', '0'): + return False + else: + raise argparse.ArgumentTypeError(f'Boolean value expected, got: {v}') + + +def _iter_images(images_dir: Path, extensions: Sequence[str]) -> Iterable[Path]: + exts = {e.lower().lstrip(".") for e in extensions if e.strip()} + for p in sorted(images_dir.iterdir()): + if not p.is_file(): + continue + if p.suffix.lower().lstrip(".") in exts: + yield p + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser( + description=( + "Run SAM 3D Objects on an RGB image and a set of binary masks " + "to produce a single 3D scene (Gaussian splats) with all objects " + "laid out together, like demo_multi_object.ipynb." + ), + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + + parser.add_argument( + "--image_path", + type=str, + required=False, + help="Path to the input RGB image.", + ) + parser.add_argument( + "--masks_dir", + type=str, + default=None, + help=( + "Directory containing the binary masks." + ), + ) + parser.add_argument( + "--images_dir", + type=str, + default=None, + help=( + "If set, run in batch mode over all jpg/jpeg images in this folder. " + "Each image will use a masks directory of the form: /masks_." + ), + ) + parser.add_argument( + "--masks_root", + type=str, + default=None, + help="Root folder for per-image masks directories in batch mode. Defaults to --images_dir.", + ) + parser.add_argument( + "--json_path", + type=str, + default=None, + help="Path to the JSON file containing the image paths and masks directory paths.", + ) + parser.add_argument( + "--masks_prefix", + type=str, + default="masks_", + help="Prefix for per-image masks directory in batch mode (masks_).", + ) + parser.add_argument( + "--extensions", + type=str, + default="jpg,jpeg", + help="Comma-separated list of image extensions to include in batch mode (case-insensitive).", + ) + parser.add_argument( + "--skip_missing_masks", + action="store_true", + help="(Batch mode) Skip images whose computed masks directory does not exist.", + ) + parser.add_argument( + "--skip_existing", + action="store_true", + help="(Batch mode) Skip images whose masks directory already contains layout.json.", + ) + parser.add_argument( + "--dry_run", + action="store_true", + help="(Batch mode) Print what would run but do not execute.", + ) + parser.add_argument( + "--config", + type=str, + default="checkpoints/hf/pipeline.yaml", + help="Path to the SAM 3D Objects inference pipeline YAML config.", + ) + parser.add_argument( + "--seed", + type=int, + default=42, + help="Base random seed for SAM 3D Objects.", + ) + parser.add_argument( + "--with_mesh_postprocess", + type=str2bool, + default=True, + help="Whether to use mesh postprocessing.", + ) + parser.add_argument( + "--with_texture_baking", + type=str2bool, + default=True, + help="Whether to use texture baking.", + ) + parser.add_argument( + "--use_vertex_color", + type=str2bool, + default=False, + help="Whether to use vertex color.", + ) + parser.add_argument( + "--with_hand_mesh", + action="store_true", + help="Enable mode to process with a provided hand mesh.", + ) + parser.add_argument( + "--mask_files", + type=str, + nargs="+", + default=None, + help="Only these mask filenames (under --masks_dir). Default: all *.png except hands.", + ) + parser.add_argument( + "--hand_mask_path", + type=str, + default=None, + help="Path to the hand mask PNG file (used with --with_hand_mesh).", + ) + parser.add_argument( + "--hand_mesh_path", + type=str, + default=None, + help="Path to the hand mesh OBJ file (used with --with_hand_mesh).", + ) + parser.add_argument( + "--force_layout_post_optimization", + action="store_true", + help="Enable forced layout post-optimization (uses ICP for rotation alignment and keeps alignment even if IOU is below threshold).", + ) + parser.add_argument( + "--disable_shape_icp", + action="store_true", + help="Disable shape ICP in post-optimization.", + ) + + return parser.parse_args() + + +def _as_list(x: torch.Tensor) -> List[float]: + return [float(v) for v in x.detach().cpu().flatten().tolist()] + + +def _save_layout_json(outputs: List[dict], plane_quat, plane_translation, objects_dir: str, filename: str = "layout.json") -> str: + """Save per-object layout transforms (local->scene) to a JSON file.""" + layout_path = os.path.join(objects_dir, filename) + objects = [] + for i, out in enumerate(outputs): + rotation = out.get("rotation", None) + translation = out.get("translation", None) + scale = out.get("scale", None) + glb = out.get("glb", None) + object_name = out.get("object_name", None) + new_quat = out.get("new_quat", None) + + if rotation is None or translation is None or scale is None or glb is None: + continue + + # rotation is a quaternion in PyTorch3D convention: (w, x, y, z) + q_wxyz = rotation.detach().cpu().flatten() + q_xyzw = torch.stack([q_wxyz[1], q_wxyz[2], q_wxyz[3], q_wxyz[0]]) + + R = quaternion_to_matrix(rotation.detach()) + tfm = compose_transform(scale=scale.detach(), rotation=R, translation=translation.detach()) + M = tfm.get_matrix().detach().cpu().squeeze(0) # (4,4) + + objects.append( + { + "index": i, + "mesh_obj": f"{object_name}.obj", + "local_to_scene": { + "translation": _as_list(translation), + "scale": _as_list(scale), + "quat_wxyz": _as_list(q_wxyz), + "new_quat": _as_list(new_quat), + "quat_xyzw": _as_list(q_xyzw), + "matrix_4x4_row_major": [float(v) for v in M.reshape(-1).tolist()], + }, + } + ) + if plane_quat is not None and plane_translation is not None: + objects.append( + { + "index": len(outputs), + "mesh_obj": f"plane.obj", + "local_to_scene": { + "translation": plane_translation.ravel().tolist(), + "new_quat": plane_quat.ravel().tolist(), + "scale": [1.0, 1.0, 1.0], + }, + } + ) + + payload = { + "frame": "sam3d_scene", + "note": ( + "Transforms are local->scene as used by SAM3D make_scene/_export_scene_glb. " + "Scale is typically uniform (same xyz). Absolute metric scale may be arbitrary." + ), + "objects": objects, + } + + with open(layout_path, "w", encoding="utf-8") as f: + json.dump(payload, f, indent=2) + + return layout_path + + +P3D_TO_ISAAC = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]], dtype=np.float32) +_R_ZUP_TO_YUP = np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]], dtype=np.float32) +_R_YUP_TO_ZUP = _R_ZUP_TO_YUP.T + + +def _is_hand_mask_name(filename: str) -> bool: + stem = os.path.splitext(os.path.basename(filename))[0].lower() + return "hand" in stem + + +def _mask_has_area(mask, min_side: int = 2) -> bool: + m = np.asarray(mask) + if m.ndim == 3: + m = m.max(axis=-1) + ys, xs = np.nonzero(m > 0) + if ys.size == 0: + return False + return (int(ys.max()) - int(ys.min()) + 1) >= min_side and ( + int(xs.max()) - int(xs.min()) + 1 + ) >= min_side + + +def _clip_pointmap(pointmap: torch.Tensor, mask: torch.Tensor, clip_pointmap_beyond_scale: float) -> tuple[torch.Tensor, torch.Tensor]: + if clip_pointmap_beyond_scale is None: + return pointmap + pointmap_size = (pointmap.shape[1], pointmap.shape[2]) + if mask.dim() == 2: + mask = mask.unsqueeze(0) + mask_resized = torchvision.transforms.functional.resize( + mask, pointmap_size, + interpolation=torchvision.transforms.InterpolationMode.NEAREST + ).squeeze(0) + + pointmap_flat = pointmap.reshape(3, -1) + # Get valid points from the mask + mask_bool = mask_resized.reshape(-1) > 0.5 + mask_points = pointmap_flat[:, mask_bool] + mask_distance = mask_points.nanmedian(dim=-1).values[-1] + logger.info(f"mask_distance: {mask_distance}") + + pointmap_clipped_flat = torch.where( + pointmap_flat[2, ...].abs() > clip_pointmap_beyond_scale * mask_distance, + torch.full_like(pointmap_flat, float('nan')), + pointmap_flat + ) + pointmap_clipped = pointmap_clipped_flat.reshape(pointmap.shape) + return pointmap_clipped + +def compute_pointmap(image, depth_model, dtype=torch.bfloat16, pointmap=None, clip_pointmap_beyond_scale=None): + loaded_image = (np.array(image) / 255.0).astype(np.float32) + loaded_image = torch.from_numpy(loaded_image) + loaded_mask = loaded_image[..., -1] + loaded_image = loaded_image.permute(2, 0, 1).contiguous()[:3] + + device = torch.device("cuda") + if pointmap is None: + with torch.no_grad(): + with torch.autocast(device_type="cuda", dtype=dtype): + output = depth_model(loaded_image) + pointmaps = output["pointmaps"] + camera_convention_transform = ( + Transform3d() + .rotate(camera_to_pytorch3d_camera(device=device).rotation) + .to(device) + ) + points_tensor = camera_convention_transform.transform_points(pointmaps) + intrinsics = output.get("intrinsics", None) + else: + output = {} + points_tensor = pointmap.to(device) + if loaded_image.shape != points_tensor.shape: + # Interpolate points_tensor to match loaded_image size + # loaded_image has shape [3, H, W], we need H and W + points_tensor = torch.nn.functional.interpolate( + points_tensor.permute(2, 0, 1).unsqueeze(0), + size=(loaded_image.shape[1], loaded_image.shape[2]), + mode="nearest", + ).squeeze(0).permute(1, 2, 0) + intrinsics = None + + points_tensor = points_tensor.permute(2, 0, 1) + points_tensor = _clip_pointmap(points_tensor, loaded_mask, clip_pointmap_beyond_scale=clip_pointmap_beyond_scale) + + # Prepare the point map tensor + point_map_tensor = { + "pointmap": points_tensor, + "pts_color": loaded_image, + } + + # If depth model doesn't provide intrinsics, infer them + if intrinsics is None: + intrinsics_result = infer_intrinsics_from_pointmap( + points_tensor.permute(1, 2, 0), device=device + ) + point_map_tensor["intrinsics"] = intrinsics_result["intrinsics"] + + return point_map_tensor + + +def _down_sample_img(img_3chw: torch.Tensor): + # img_3chw: (3, H, W) + x = img_3chw.unsqueeze(0) + if x.dtype == torch.uint8: + x = x.float() / 255.0 + max_side = max(x.shape[2], x.shape[3]) + scale_factor = 1.0 + + # heuristics + if max_side > 3800: + scale_factor = 0.125 + if max_side > 1900: + scale_factor = 0.25 + elif max_side > 1200: + scale_factor = 0.5 + + x = torch.nn.functional.interpolate( + x, + scale_factor=(scale_factor, scale_factor), + mode="bilinear", + align_corners=False, + antialias=True, + ) # -> (1, 3, H/4, W/4) + return x.squeeze(0) + +def _normalize(v): + return v / np.linalg.norm(v) + +def process_image_with_provided_object( + image_path, + masks_path, + mask_path_for_object, + inference: Inference, + mesh_path, + output_dir: str, + provided_object_name: str = "provided_object", + force_layout_post_optimization: bool = False, + disable_shape_icp: bool = False, +): + """ + Process an image with multiple masks and one provided object. + Saves meshes and layout in the same format as _process_one. + + Args: + image_path: Path to the input image + masks_path: List of paths to mask files for objects to generate + mask_path_for_object: Path to mask for the provided object + inference: Inference pipeline + mesh_path: Path to directory containing right_vertices.npy and right_faces.npy + output_dir: Directory to save outputs (meshes and layout.json) + provided_object_name: Name for the provided object (default: "provided_object") + """ + os.makedirs(output_dir, exist_ok=True) + + image = load_image(image_path) + mask_list = [] + mask_names = [] + for mask_path in masks_path: + mask = load_mask(mask_path) + mask_list.append(mask) + object_name = os.path.splitext(os.path.basename(mask_path))[0] + mask_names.append(object_name) + + mesh = trimesh.load(mesh_path) + provided_object = { + "mesh": mesh, + "mask": load_mask(mask_path_for_object), + "use_network_pose": False, + "initial_pose": { + "rotation": [1, 0, 0, 0], + "translation": [0, 0, 0], + "scale": [1, 1, 1], + }, + } + + print(f"[SAM3D] Processing {len(mask_list)} masks + 1 provided object...") + result = inference.run_with_provided_object(image, mask_list, provided_object, force_layout_post_optimization=force_layout_post_optimization, disable_shape_icp=disable_shape_icp) + + outputs = [] + + # Process and save generated objects + for idx, gen_obj in enumerate(result["generated_objects"]): + object_name = mask_names[idx] + print(f"Saving generated object {idx + 1}/{len(result['generated_objects'])}: {object_name}") + + object_folder = os.path.join(output_dir, object_name) + os.makedirs(object_folder, exist_ok=True) + + glb = gen_obj.get("glb", None) + if glb is not None: + output_path = os.path.join(object_folder, f"{object_name}.obj") + glb.export(output_path) + print(f"Saved mesh to: {output_path}") + + mesh_old = glb.copy() + mesh_old_vertices = np.zeros_like(mesh_old.vertices) + for j in range(mesh_old.vertices.shape[0]): + mesh_old_vertices[j] = mesh_old.vertices[j] + + vertices_arr = glb.vertices.astype(np.float32) @ _R_YUP_TO_ZUP + vertices_tensor = torch.from_numpy(vertices_arr).float().to(gen_obj["rotation"].device) + R_l2c = quaternion_to_matrix(gen_obj["rotation"]) + l2c_transform = compose_transform( + scale=gen_obj["scale"], + rotation=R_l2c, + translation=gen_obj["translation"], + ) + transformed_vertices = l2c_transform.transform_points(vertices_tensor.unsqueeze(0)) + new_mesh_vertices = transformed_vertices.squeeze(0).cpu().numpy() @ P3D_TO_ISAAC + glb.vertices = new_mesh_vertices + + matrix, transformed, cost = trimesh.registration.procrustes( + mesh_old_vertices, + new_mesh_vertices, + reflection=False, + return_cost=True + ) + gen_obj["new_quat"] = torch.tensor(R.from_matrix(matrix[:3, :3]).as_quat(scalar_first=True)) + + gen_obj["object_name"] = object_name + gen_obj["glb"] = glb + outputs.append(gen_obj) + + provided_result = result.get("provided_object_result", None) + if provided_result is not None: + print(f" - Saving provided object: {provided_object_name}") + + object_folder = os.path.join(output_dir, provided_object_name) + os.makedirs(object_folder, exist_ok=True) + + provided_mesh = provided_result.get("mesh", None) + if provided_mesh is not None: + output_path = os.path.join(object_folder, f"{provided_object_name}.obj") + provided_mesh.export(output_path) + print(f" Saved mesh to: {output_path}") + + rotation = provided_result.get("rotation", None) + translation = provided_result.get("translation", None) + scale = provided_result.get("scale", None) + + if rotation is not None and translation is not None and scale is not None: + print("rotation: ", rotation) + print("translation: ", translation) + print("scale: ", scale) + mesh_old = provided_mesh.copy() + mesh_old_vertices = np.zeros_like(mesh_old.vertices) + for j in range(mesh_old.vertices.shape[0]): + mesh_old_vertices[j] = mesh_old.vertices[j] + + vertices_arr = provided_mesh.vertices.astype(np.float32) @ _R_YUP_TO_ZUP + vertices_tensor = torch.from_numpy(vertices_arr).float().to(rotation.device) + R_l2c = quaternion_to_matrix(rotation) + l2c_transform = compose_transform( + scale=scale, + rotation=R_l2c, + translation=translation, + ) + transformed_vertices = l2c_transform.transform_points(vertices_tensor.unsqueeze(0)) + new_mesh_vertices = transformed_vertices.squeeze(0).cpu().numpy() @ P3D_TO_ISAAC + provided_mesh.vertices = new_mesh_vertices + + matrix, transformed, cost = trimesh.registration.procrustes( + mesh_old_vertices, + new_mesh_vertices, + reflection=False, + return_cost=True + ) + provided_result["new_quat"] = torch.tensor(R.from_matrix(matrix[:3, :3]).as_quat(scalar_first=True)) + + provided_result["object_name"] = provided_object_name + provided_result["glb"] = provided_mesh + outputs.append(provided_result) + + _save_layout_json(outputs, None, None, output_dir) + print(f"[SAM3D] Saved layout.json to: {output_dir}") + + print("[SAM3D] Done.") + return result + +def _process_one( + image_path: str, + masks_dir: str, + *, + inference: Inference, + depth_model, + cfg, + seed: int, + with_mesh_postprocess: bool = True, + with_texture_baking: bool = True, + use_vertex_color: bool = False, + force_layout_post_optimization: bool = False, + disable_shape_icp: bool = False, + mask_files: Optional[Sequence[str]] = None, +) -> None: + if mask_files: + mask_paths = [ + os.path.join(masks_dir, f) if not os.path.isabs(f) else f for f in mask_files + ] + else: + mask_paths = [ + os.path.join(masks_dir, f) + for f in os.listdir(masks_dir) + if f.lower().endswith(".png") + ] + plane_exists = any(os.path.basename(p) == "plane_0.png" for p in mask_paths) + # if not plane_exists: + # print(f"[SAM3D] No plane mask found in: {masks_dir}. Skipping...") + # return + print(f"[SAM3D] Using {len(mask_paths)} masks from: {masks_dir}") + + print(f"[SAM3D] Loading image from: {image_path}") + image = load_image(image_path) + + print("[SAM3D] Running 3D reconstruction for each object mask (this may take a while)...") + outputs = [] + + for i, mask_path in enumerate(mask_paths): + # if "plane_0.png" in mask_path: + # continue + name = os.path.basename(mask_path) + if _is_hand_mask_name(name): + print(f" - Skipping {name} (hand masks are HaWoR, not SAM-3D objects)") + continue + mask = load_mask(mask_path) + if not _mask_has_area(mask): + print(f" - Skipping {name} (empty or tiny mask; would crash crop/resize)") + continue + print(f" - Reconstructing object {i + 1}/{len(mask_paths)} ({name})") + try: + output = inference(image, mask, seed=seed + i, with_mesh_postprocess=with_mesh_postprocess, with_texture_baking=with_texture_baking, use_vertex_color=use_vertex_color, force_layout_post_optimization=force_layout_post_optimization, disable_shape_icp=disable_shape_icp) + except Exception as exc: + print(f" - Failed {name}: {exc}") + continue + # Include the object name in the output dictionary + object_name = os.path.splitext(os.path.basename(mask_path))[0] + output["object_name"] = object_name + + object_folder = os.path.join(masks_dir, object_name) + os.makedirs(object_folder, exist_ok=True) + output_path = os.path.join(object_folder, f"{object_name}.obj") + + mesh = output["glb"] + mesh.export(output_path) + print(f"Saved mesh to: {output_path}") + + mesh_old = mesh.copy() + mesh_old_vertices = np.zeros_like(mesh_old.vertices) + for j in range(mesh_old.vertices.shape[0]): + mesh_old_vertices[j] = mesh_old.vertices[j] + + vertices = mesh.vertices.astype(np.float32) @ _R_YUP_TO_ZUP + vertices_tensor = torch.from_numpy(vertices).float().to(output["rotation"].device) + R_l2c = quaternion_to_matrix(output["rotation"]) + l2c_transform = compose_transform( + scale=output["scale"], + rotation=R_l2c, + translation=output["translation"], + ) + vertices = l2c_transform.transform_points(vertices_tensor.unsqueeze(0)) + new_mesh_vertices = vertices.squeeze(0).cpu().numpy() @ P3D_TO_ISAAC + mesh.vertices = new_mesh_vertices + matrix, transformed, cost = trimesh.registration.procrustes( + mesh_old_vertices, + new_mesh_vertices, + reflection=False, + return_cost=True + ) + output["new_quat"] = torch.tensor(R.from_matrix(matrix[:3, :3]).as_quat(scalar_first=True)) + outputs.append(output) + + # Getting plane mesh + + # rgb_pil = Image.open(image_path).convert("RGB") + # mask_pil = Image.open(masks_dir + "/plane_0.png") + + # image = np.array(rgb_pil) + # mask = np.array(mask_pil) + + # if mask.ndim == 2: + # mask = mask[..., None] + + # # Replace alpha channel with provided mask + # image = np.concatenate([image[..., :3], mask], axis=-1) + + # # Match pipeline.yaml defaults + # device = "cuda" if torch.cuda.is_available() else "cpu" + + # dtype_str = str(cfg.get("dtype", "float16")) + # dtype_map = { + # "float16": torch.float16, + # "fp16": torch.float16, + # "bfloat16": torch.bfloat16, + # "bf16": torch.bfloat16, + # "float32": torch.float32, + # "fp32": torch.float32, + # } + # dtype = dtype_map.get(dtype_str.lower(), torch.float16) + + # pointmap_dict = compute_pointmap( + # image, + # depth_model=depth_model, + # dtype=dtype, + # ) + # # pointmap = pointmap_dict["pointmap"] + # # intrinsics = pointmap_dict["intrinsics"] + + # floor_mask = _down_sample_img(torch.from_numpy(image[..., -1]).float().unsqueeze(0))[0] > 0.5 + # pts = _down_sample_img(pointmap_dict["pointmap"]) + # pts_hwc = pts.cpu().permute((1, 2, 0)) + # valid_mask_points = floor_mask.cpu().numpy() + # if valid_mask_points.any(): + # # Get points within mask + # masked_points = pts_hwc[valid_mask_points] + # # Filter out invalid points (zero points from depth estimation failures) + # valid_points_mask = torch.norm(masked_points, dim=-1) > 1e-6 + # valid_points = masked_points[valid_points_mask] + # points = valid_points.numpy() + # else: + # points = np.array([]).reshape(0, 3) + # pcd = o3d.geometry.PointCloud() + # pcd.points = o3d.utility.Vector3dVector(points.astype(np.float64, copy=False)) + # plane_model, inliers = pcd.segment_plane(0.02, 3, 1000) + # a, b, c, d = plane_model + # print(f"Plane equation: {a:.2f}x + {b:.2f}y + {c:.2f}z + {d:.2f} = 0") + + # inlier_points = np.asarray(pcd.points)[inliers] + + # z_range = np.max(inlier_points[:, 2]) - np.min(inlier_points[:, 2]) + # if z_range > 6.0: # Large range - likely flying points + # thresh = 0.90 # Remove 10% + # elif z_range > 2.0: # Moderate range + # thresh = 0.93 # Remove 7% + # else: # Small range - clean + # thresh = 0.95 # Remove 5% + # depth_quantile = float(np.quantile(inlier_points[:, 2], thresh)) + # clean_points = inlier_points[inlier_points[:, 2] <= depth_quantile] + # if clean_points.shape[0] < 3: + # raise ValueError("Too few points after flying-point removal.") + + # normal = _normalize(np.array([a, b, c], dtype=np.float64)) + + # if abs(float(normal[2])) < 0.9: + # tangent = np.array([0.0, 0.0, 1.0], dtype=np.float64) + # else: + # tangent = np.array([1.0, 0.0, 0.0], dtype=np.float64) + + # v1 = _normalize(np.cross(normal, tangent)) + # v2 = _normalize(np.cross(normal, v1)) + # if float(np.dot(np.cross(v1, v2), normal)) < 0.0: + # v2 = -v2 + # min_vals = np.min(clean_points, axis=0) + # max_vals = np.max(clean_points, axis=0) + # centroid = (min_vals + max_vals) / 2.0 + # camera_pos = np.array([0.0, 0.0, 0.0], dtype=np.float64) + # camera_to_centroid = centroid - camera_pos + # cam_dist = float(np.linalg.norm(camera_to_centroid)) + # if cam_dist < 1e-9: + # print("Degenerate: centroid at camera; fallback") + # away_axis = v1 + # perp_axis = v2 + # else: + # away_direction = camera_to_centroid / cam_dist + # away_in_plane = away_direction - np.dot(away_direction, normal) * normal + # away_in_plane_norm = float(np.linalg.norm(away_in_plane)) + # if away_in_plane_norm > 1e-6: + # away_axis = away_in_plane / away_in_plane_norm + # perp_axis = _normalize(np.cross(normal, away_axis)) + # else: + # away_axis = v1 + # perp_axis = v2 + # perp_axis = perp_axis - np.dot(perp_axis, away_axis) * away_axis + # perp_axis = _normalize(perp_axis) + # if float(np.dot(np.cross(away_axis, perp_axis), normal)) < 0.0: + # perp_axis = -perp_axis + + # # --- Compute extents in camera-aligned (away/perp) coordinates --- + # relative_points = clean_points - centroid + # away_coords = np.dot(relative_points, away_axis) + # perp_coords = np.dot(relative_points, perp_axis) + + # away_min, away_max = np.percentile(away_coords, [0, 100]) + # perp_min, perp_max = np.percentile(perp_coords, [0, 100]) + + # away_extent = max(float(away_max - away_min), 0.1) + # perp_extent = max(float(perp_max - perp_min), 0.1) + + # away_extension_near = away_extent * 0.1 + # away_extension_far = away_extent * 0.5 + # perp_extension = perp_extent * 0.2 + + # x_near = away_extent / 2.0 + away_extension_near # towards camera + # x_far = away_extent / 2.0 + away_extension_far # away from camera + # y_half = perp_extent / 2.0 + perp_extension + # vertices_local = np.array( + # [ + # [-x_near, -y_half, 0.0], # 0: near, left + # [x_far, -y_half, 0.0], # 1: far, left + # [-x_near, y_half, 0.0], # 2: near, right + # [x_far, y_half, 0.0], # 3: far, right + # ], + # dtype=np.float64, + # ) + # faces = np.array([[0, 1, 3, 2]], dtype=np.int64) + # canonical_mesh = trimesh.Trimesh( + # vertices=vertices_local.astype(np.float32), + # faces=faces, + # process=False, + # ) + # canonical_mesh.visual.face_colors = np.array([128, 128, 128, 255], dtype=np.uint8) + # object_folder = os.path.join(masks_dir, "plane") + # os.makedirs(object_folder, exist_ok=True) + # output_path = os.path.join(object_folder, f"plane.obj") + # canonical_mesh.export(output_path) + # R_world = np.stack([away_axis, perp_axis, normal], axis=1) # (3,3) + # A_world = R_world.T # (3,3) (row-vector form) + # b_world = centroid # (3,) + + # # vertices_world = vertices_local @ A_world + b_world + # # vertices_final = vertices_world @ P3D_TO_ISAAC [To be used for confirming that the mesh with baked in transformations is correct] + # A_final = A_world @ P3D_TO_ISAAC + # R_final = A_final.T + # q_wxyz = R.from_matrix(R_final).as_quat(scalar_first=True) + # translation = b_world @ P3D_TO_ISAAC + + _save_layout_json(outputs, None, None, masks_dir) + + print("[SAM3D] Done.") + + +def main() -> None: + args = parse_args() + # Shared config/model init (reused in batch mode) + print(f"[SAM3D] Loading SAM 3D Objects pipeline from: {args.config}") + inference = Inference(args.config, compile=False) + + cfg = OmegaConf.load(str(Path(args.config))) + device = "cuda" if torch.cuda.is_available() else "cpu" + depth_model = instantiate(cfg.depth_model, device=device) + + # Batch mode + if args.images_dir or args.json_path: + masks_prefix = str(args.masks_prefix) + exts = [e.strip() for e in str(args.extensions).split(",") if e.strip()] + + if args.images_dir is not None: + images_dir = Path(args.images_dir) + if not images_dir.exists(): + raise FileNotFoundError(f"--images_dir does not exist: {images_dir}") + if not images_dir.is_dir(): + raise NotADirectoryError(f"--images_dir is not a directory: {images_dir}") + + images = list(_iter_images(images_dir, exts)) + else: + json_path = Path(args.json_path) + if not json_path.exists(): + raise FileNotFoundError(f"--json_path does not exist: {json_path}") + if not json_path.is_file(): + raise NotADirectoryError(f"--json_path is not a file: {json_path}") + + with open(json_path, "r") as f: + data = json.load(f) + images = [Path(item) for item in data] + + # import random + # num_select = max(1, int(0.1 * len(images))) + # images = random.sample(images, num_select) + + print(f"[SAM3D] Batch mode: found {len(images)} image(s)") + print(f"[SAM3D] Batch mode: masks_prefix={masks_prefix}") + + for idx, image_path in enumerate(tqdm(images, desc="SAM3D batch", unit="image"), start=1): + img_stem = image_path.stem + if args.masks_root is not None: + masks_root = Path(args.masks_root) + else: + masks_root = Path(image_path.parent) + masks_dir = masks_root / f"{masks_prefix}{img_stem}" + + if not masks_dir.exists(): + msg = f"[SAM3D] ({idx}/{len(images)}) masks dir missing, image={image_path.name} masks_dir={masks_dir}" + if args.skip_missing_masks: + print(msg + " -> SKIP") + continue + raise FileNotFoundError(msg) + + if args.skip_existing and (masks_dir / "layout.json").exists(): + print(f"[SAM3D] ({idx}/{len(images)}) layout.json exists, image={image_path.name} -> SKIP") + continue + + print(f"[SAM3D] ({idx}/{len(images)}) Processing image={image_path.name} masks_dir={masks_dir}") + if args.dry_run: + continue + _process_one( + str(image_path), + str(masks_dir), + inference=inference, + depth_model=depth_model, + cfg=cfg, + seed=args.seed, + with_mesh_postprocess=args.with_mesh_postprocess, + with_texture_baking=args.with_texture_baking, + use_vertex_color=args.use_vertex_color, + force_layout_post_optimization=args.force_layout_post_optimization, + disable_shape_icp=args.disable_shape_icp, + ) + + return + + if args.with_hand_mesh: + print("Processing image with provided object...") + + # Build full paths from --mask_files names and --masks_dir + mask_files = [ + os.path.join(args.masks_dir, f) + for f in args.mask_files + ] + print(f"Found {len(mask_files)} mask files in {args.masks_dir}") + + results = process_image_with_provided_object( + args.image_path, + mask_files, + args.hand_mask_path, + inference, + args.hand_mesh_path, + output_dir=args.masks_dir, + provided_object_name="hand_hawor", + force_layout_post_optimization=args.force_layout_post_optimization, + disable_shape_icp=args.disable_shape_icp, + ) + return + + if not args.image_path or not args.masks_dir: + raise ValueError( + "Single-image mode requires --image_path and --masks_dir. " + "Alternatively, use batch mode with --images_dir." + ) + + _process_one( + args.image_path, + args.masks_dir, + inference=inference, + depth_model=depth_model, + cfg=cfg, + seed=args.seed, + with_mesh_postprocess=args.with_mesh_postprocess, + with_texture_baking=args.with_texture_baking, + use_vertex_color=args.use_vertex_color, + force_layout_post_optimization=args.force_layout_post_optimization, + disable_shape_icp=args.disable_shape_icp, + mask_files=args.mask_files, + ) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/notebook/__pycache__/inference.cpython-310.pyc b/reconstruction/modules/sam-3d-objects/notebook/__pycache__/inference.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b044d29080942ff76de9aa6413f48d8ccbbf26f8 Binary files /dev/null and b/reconstruction/modules/sam-3d-objects/notebook/__pycache__/inference.cpython-310.pyc differ diff --git a/reconstruction/modules/sam-3d-objects/notebook/demo_3db_mesh_alignment.ipynb b/reconstruction/modules/sam-3d-objects/notebook/demo_3db_mesh_alignment.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..899f868bbdf49bdb12bd17ed06bd5ffe88bf3de4 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/demo_3db_mesh_alignment.ipynb @@ -0,0 +1,180 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# SAM 3D Body (3DB) Mesh Alignment to SAM 3D Object Scale\n", + "\n", + "This notebook processes a single 3DB mesh and aligns it to the SAM 3D Objects scale.\n", + "\n", + "**Input Data:**\n", + "- `images/human_object/image.jpg` - Input image for MoGe\n", + "- `meshes/human_object/3DB_results/mask_human.png` - Human mask\n", + "- `meshes/human_object/3DB_results/human.ply` - Single 3DB mesh in OpenGL coordinates\n", + "- `meshes/human_object/3DB_results/focal_length.json` - 3DB focal length\n", + "\n", + "**Output:**\n", + "- `meshes/human_object/aligned_meshes/human_aligned.ply` - Aligned 3DB mesh in OpenGL coordinates" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import torch\n", + "import matplotlib.pyplot as plt\n", + "from PIL import Image\n", + "from mesh_alignment import process_and_save_alignment\n", + "\n", + "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n", + "print(f\"Using device: {device}\")\n", + "PATH = os.getcwd()\n", + "print(f\"Current working directory: {PATH}\")\n", + "\n", + "# Please inference the SAM 3D Body (3DB) Repo (https://github.com/facebookresearch/sam-3d-body) to get the 3DB Results\n", + "image_path = f\"{PATH}/images/human_object/image.png\"\n", + "mask_path = f\"{PATH}/meshes/human_object/3DB_results/mask_human.png\"\n", + "mesh_path = f\"{PATH}/meshes/human_object/3DB_results/human.ply\"\n", + "focal_length_json_path = f\"{PATH}/meshes/human_object/3DB_results/focal_length.json\"\n", + "output_dir = f\"{PATH}/meshes/human_object/aligned_meshes\"\n", + "os.makedirs(output_dir, exist_ok=True)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 0. Inference and Save SAM 3D Objects" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Please inference SAM 3D Objects Repo with https://github.com/facebookresearch/sam-3d-objects/blob/main/notebook/demo_multi_object.ipynb\n", + "# The above notebook will apply the generated layout to the generated objects, and same them as ply. \n", + "# Then, this cell will load the posed SAM 3D Objects and transform them into the OpenGL coordinate system, which is the same system as SAM 3D Body. \n", + "import numpy as np\n", + "import open3d as o3d\n", + "\n", + "# Load PLY file\n", + "input_path = 'gaussians/human_object_posed.ply'\n", + "output_path = 'meshes/human_object/3Dfy_results/0.ply'\n", + "mesh = o3d.io.read_point_cloud(input_path)\n", + "points = np.asarray(mesh.points)\n", + "\n", + "# Transform to OpenGL coordinate system. \n", + "points[:, [0, 2]] *= -1 # flip x and z\n", + "mesh.points = o3d.utility.Vector3dVector(points)\n", + "o3d.io.write_point_cloud(output_path, mesh)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Load and Display Input Data" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "input_image = Image.open(image_path)\n", + "mask = Image.open(mask_path).convert('L')\n", + "fig, axes = plt.subplots(1, 2, figsize=(10, 5))\n", + "axes[0].imshow(input_image)\n", + "axes[0].set_title('Input Image')\n", + "axes[0].axis('off')\n", + "axes[1].imshow(mask, cmap='gray')\n", + "axes[1].set_title('Mask')\n", + "axes[1].axis('off')\n", + "plt.tight_layout()\n", + "plt.show()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Process and Save Aligned Mesh" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "success, output_mesh_path, result = process_and_save_alignment(\n", + " mesh_path=mesh_path,\n", + " mask_path=mask_path,\n", + " image_path=image_path,\n", + " output_dir=output_dir,\n", + " device=device,\n", + " focal_length_json_path=focal_length_json_path\n", + ")\n", + "\n", + "if success:\n", + " print(f\"Alignment completed successfully! Output: {output_mesh_path}\")\n", + "else:\n", + " print(\"Alignment failed!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Interactive 3D Visualization\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from mesh_alignment import visualize_meshes_interactive\n", + "\n", + "aligned_mesh_path = f\"{PATH}/meshes/human_object/aligned_meshes/human_aligned.ply\"\n", + "dfy_mesh_path = f\"{PATH}/meshes/human_object/3Dfy_results/0.ply\"\n", + "\n", + "demo, combined_glb_path = visualize_meshes_interactive(\n", + " aligned_mesh_path=aligned_mesh_path,\n", + " dfy_mesh_path=dfy_mesh_path,\n", + " share=True\n", + ")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.0" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/reconstruction/modules/sam-3d-objects/notebook/demo_multi_object.ipynb b/reconstruction/modules/sam-3d-objects/notebook/demo_multi_object.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..a6d8a22cebc472ec5a843d0a779234021d53c24d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/demo_multi_object.ipynb @@ -0,0 +1,164 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Copyright (c) Meta Platforms, Inc. and affiliates." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Imports and Model Loading" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import uuid\n", + "import imageio\n", + "import numpy as np\n", + "from IPython.display import Image as ImageDisplay\n", + "\n", + "from inference import Inference, ready_gaussian_for_video_rendering, load_image, load_masks, display_image, make_scene, render_video, interactive_visualizer" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "PATH = os.getcwd()\n", + "TAG = \"hf\"\n", + "config_path = f\"{PATH}/../checkpoints/{TAG}/pipeline.yaml\"\n", + "inference = Inference(config_path, compile=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Load input image to lift to 3D (multiple objects)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "IMAGE_PATH = f\"{PATH}/images/shutterstock_stylish_kidsroom_1640806567/image.png\"\n", + "IMAGE_NAME = os.path.basename(os.path.dirname(IMAGE_PATH))\n", + "\n", + "image = load_image(IMAGE_PATH)\n", + "masks = load_masks(os.path.dirname(IMAGE_PATH), extension=\".png\")\n", + "display_image(image, masks)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Generate Gaussian Splats" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "outputs = [inference(image, mask, seed=42) for mask in masks]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Visualize Gaussian Splat of the Scene\n", + "### a. Animated Gif" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "scene_gs = make_scene(*outputs)\n", + "# export posed gaussian splatting (as point cloud)\n", + "scene_gs.save_ply(f\"{PATH}/gaussians/{IMAGE_NAME}_posed.ply\")\n", + "\n", + "scene_gs = ready_gaussian_for_video_rendering(scene_gs)\n", + "# export gaussian splatting (as point cloud)\n", + "scene_gs.save_ply(f\"{PATH}/gaussians/multi/{IMAGE_NAME}.ply\")\n", + "\n", + "video = render_video(\n", + " scene_gs,\n", + " r=1,\n", + " fov=60,\n", + " resolution=512,\n", + ")[\"color\"]\n", + "\n", + "# save video as gif\n", + "imageio.mimsave(\n", + " os.path.join(f\"{PATH}/gaussians/multi/{IMAGE_NAME}.gif\"),\n", + " video,\n", + " format=\"GIF\",\n", + " duration=1000 / 30, # default assuming 30fps from the input MP4\n", + " loop=0, # 0 means loop indefinitely\n", + ")\n", + "\n", + "# notebook display\n", + "ImageDisplay(url=f\"gaussians/multi/{IMAGE_NAME}.gif?cache_invalidator={uuid.uuid4()}\",)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### b. Interactive Visualizer" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# might take a while to load (black screen)\n", + "interactive_visualizer(f\"{PATH}/gaussians/multi/{IMAGE_NAME}.ply\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.0" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/reconstruction/modules/sam-3d-objects/notebook/demo_single_object.ipynb b/reconstruction/modules/sam-3d-objects/notebook/demo_single_object.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4ce07ca05646cd8ce6f1367a575b205c27679d61 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/demo_single_object.ipynb @@ -0,0 +1,164 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Copyright (c) Meta Platforms, Inc. and affiliates." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 1. Imports and Model Loading" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import imageio\n", + "import uuid\n", + "from IPython.display import Image as ImageDisplay\n", + "from inference import Inference, ready_gaussian_for_video_rendering, render_video, load_image, load_single_mask, display_image, make_scene, interactive_visualizer" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "PATH = os.getcwd()\n", + "TAG = \"hf\"\n", + "config_path = f\"{PATH}/../checkpoints/{TAG}/pipeline.yaml\"\n", + "inference = Inference(config_path, compile=False)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Load input image to lift to 3D (single object)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "IMAGE_PATH = f\"{PATH}/images/shutterstock_stylish_kidsroom_1640806567/image.png\"\n", + "IMAGE_NAME = os.path.basename(os.path.dirname(IMAGE_PATH))\n", + "\n", + "image = load_image(IMAGE_PATH)\n", + "mask = load_single_mask(os.path.dirname(IMAGE_PATH), index=14)\n", + "display_image(image, masks=[mask])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Generate Gaussian Splat" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# run model\n", + "output = inference(image, mask, seed=42)\n", + "\n", + "# export gaussian splat (as point cloud)\n", + "output[\"gs\"].save_ply(f\"{PATH}/gaussians/single/{IMAGE_NAME}.ply\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Visualize Gaussian Splat\n", + "### a. Animated Gif" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# render gaussian splat\n", + "scene_gs = make_scene(output)\n", + "scene_gs = ready_gaussian_for_video_rendering(scene_gs)\n", + "\n", + "video = render_video(\n", + " scene_gs,\n", + " r=1,\n", + " fov=60,\n", + " pitch_deg=15,\n", + " yaw_start_deg=-45,\n", + " resolution=512,\n", + ")[\"color\"]\n", + "\n", + "# save video as gif\n", + "imageio.mimsave(\n", + " os.path.join(f\"{PATH}/gaussians/single/{IMAGE_NAME}.gif\"),\n", + " video,\n", + " format=\"GIF\",\n", + " duration=1000 / 30, # default assuming 30fps from the input MP4\n", + " loop=0, # 0 means loop indefinitely\n", + ")\n", + "\n", + "# notebook display\n", + "ImageDisplay(url=f\"gaussians/single/{IMAGE_NAME}.gif?cache_invalidator={uuid.uuid4()}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### b. Interactive Visualizer" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# might take a while to load (black screen)\n", + "interactive_visualizer(f\"{PATH}/gaussians/single/{IMAGE_NAME}.ply\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "sam3d_objects-3dfy", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.0" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/reconstruction/modules/sam-3d-objects/notebook/gaussians/multi/.gitignore b/reconstruction/modules/sam-3d-objects/notebook/gaussians/multi/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c96a04f008ee21e260b28f7701595ed59e2839e3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/gaussians/multi/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/notebook/gaussians/single/.gitignore b/reconstruction/modules/sam-3d-objects/notebook/gaussians/single/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c96a04f008ee21e260b28f7701595ed59e2839e3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/gaussians/single/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/0.png new file mode 100644 index 0000000000000000000000000000000000000000..56d4c5ebbae41300c125f8cf5c01d4e23462434a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0809c5419d9ff57480a732b2831cec4a48718b03b576280f9aadb86f0b4f859f +size 384582 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/1.png new file mode 100644 index 0000000000000000000000000000000000000000..45de5af270a524f4155fd95e691f915a3ee8a834 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a0c0db3618489c01a4b2fe7859fb9737c91d462e008af3625aacd641cfd1e386 +size 185049 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/10.png new file mode 100644 index 0000000000000000000000000000000000000000..bdb5b108b126f0996357cae0d19c129b17fa234c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f464c61845ce02decd71733c90adc357849f9f39e56f88676a1fb036f4cccf4 +size 177646 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/11.png new file mode 100644 index 0000000000000000000000000000000000000000..44ec8b69484ea8967a37ce35a844f7ba9cde18d7 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:16b99b74faa96b723bc5ccbdb58598d7e05222717c3501bd0d750e44a3ac25a9 +size 145586 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/12.png new file mode 100644 index 0000000000000000000000000000000000000000..0f0c5c4a3c806b297668d75df47029dbb68158a1 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc1f5f429e8ffd64268d6dc7900d57f368713935559cfa7e1866f0e011c0b13f +size 137566 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/13.png new file mode 100644 index 0000000000000000000000000000000000000000..9dd9e8fccc64603bed04dcab786acf001a841d67 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6fdeaf771ee75a5ea5f245709c4e9b8ccce995398b6d8a9ae6c9313ae08d5040 +size 332878 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/14.png new file mode 100644 index 0000000000000000000000000000000000000000..a5fabcee40a064a4be6b7aa174975a2aaec79c0a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:971e9af72f9fdcea4a1538e9181cbf8821bede0a04e58ceb0b85a430e0641a4f +size 176280 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/15.png new file mode 100644 index 0000000000000000000000000000000000000000..6cc362598c25acb9a5abb95d21057eac7ab2beb2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5dd08a28bbb65e33eb2a76a690ede171fd4651b61e0a1a180dd33aa88aff4d28 +size 155733 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/2.png new file mode 100644 index 0000000000000000000000000000000000000000..dd5f799a9f1070d4f42333b974fac5d1f0da58cd --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:686103c83102fa9bd887919aa719856ba87b703ed7472342c860d248b094ce13 +size 183399 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/3.png new file mode 100644 index 0000000000000000000000000000000000000000..521c102bbf3e720e593e76458b1f27bbcf61f079 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fab63cd88806b58212a17f68ac2b0ccb1b5a266dc830ddc62fc16b238042b4b +size 757723 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/4.png new file mode 100644 index 0000000000000000000000000000000000000000..0a82f8c8731a4b9124d9a0df422d2f087c0a3141 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:205d67263f78b970e4ffc34a82e315f0fcf3eb28316fdd2b818bddef916ae358 +size 407366 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/5.png new file mode 100644 index 0000000000000000000000000000000000000000..bfd79ef95c343579dd687710f455eca4b75d46f0 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:913c6d7fa003da7532007dfa18ceb21f2b05dddd4714230a80595082a2b33b48 +size 147054 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/6.png new file mode 100644 index 0000000000000000000000000000000000000000..89fbdd0bc9220b34d650d759128c5fac57b233fe --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f77b4ad4639a96c858453ceb03d22a77698c5e275ab1f37d208ce3900aa3fe8c +size 418775 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/7.png new file mode 100644 index 0000000000000000000000000000000000000000..84e91343a583a901eebc1a3f01dab7e569846a27 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:963205066849b9f8676281e4344be26f35cbb8e75d5ad67015ed2ee13160549e +size 383501 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/8.png new file mode 100644 index 0000000000000000000000000000000000000000..1181ecaf78961fe446f9bfc0bc89f263aad47d01 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8ba70a2c567ff85bf321e1d87409ba6bc370e46a727759ac749f5a2c4779198 +size 149810 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/9.png new file mode 100644 index 0000000000000000000000000000000000000000..542df43d5ca02e7e26c9e86ec6e953c3866aa4ce --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88364b1e917d467b519381b59b333a0af9b8fb2b2a533d314fbd1537bdbb8055 +size 259194 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/image.png new file mode 100644 index 0000000000000000000000000000000000000000..c84e19ee1ef1df8d8ee45ab84923d31cf4974527 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/137444513_Livingroom-graphic81/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8357b2d32d3ab1c03b04d9fa5afc55235197e207581398ff062fc68cfe631e1c +size 2345661 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/0.png new file mode 100644 index 0000000000000000000000000000000000000000..69f331b177eadcd7f0bfaa17d10c0cd8ac285d67 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0bad7aa8b519b5609a944854097a28b00cedd52d0aa4a6e8226e8387791f9bcf +size 47773 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/1.png new file mode 100644 index 0000000000000000000000000000000000000000..55e533b4caec6671e60681b09959a3ef3884e570 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:012a02985383f5ece7cec14147825530ddf84c37fcfb2d23df71cb9ed241d184 +size 29624 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/10.png new file mode 100644 index 0000000000000000000000000000000000000000..4452d51d435e48645cdc369d5780742b07060e68 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:583fe95e126bfaa847c90da953f614807bde6fcdcca44c7b8e37880632241cd0 +size 90628 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/11.png new file mode 100644 index 0000000000000000000000000000000000000000..cf56fb1534e6d00b01cd9bfb78df95a27d3d1ea4 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe96b6b8e3d3396e863a0518c10090d48c1193a083b8b6113e120509c79de7ce +size 421913 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/12.png new file mode 100644 index 0000000000000000000000000000000000000000..7669fe9f82a990004be0045b196f21549ee70dcc --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2b18f0791a8f50aabf97363ee4af157605cdbbb21e31dce19c54ad07772dad49 +size 36563 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/13.png new file mode 100644 index 0000000000000000000000000000000000000000..e56c0180d5dc90ad5037d21259ad5c364538567e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:53721539dff5273f9b102825721dbda014bfd20df069d26454246bc11786b97d +size 234365 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/14.png new file mode 100644 index 0000000000000000000000000000000000000000..87e9f0040d5adadc2489aa4c6868f483cc8ee1a4 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ada68d1447f44661a9ed783a4f7fa7e25db09ac7f0a196bde424223ba01b06d2 +size 373792 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/15.png new file mode 100644 index 0000000000000000000000000000000000000000..4254aec984647d08c4478f54c897b9130abb8686 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:81f47bf47227ce7aaf46632614e29d9bf44fa61d56f3ae2ccffc9bd41329c6d0 +size 136498 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/16.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/16.png new file mode 100644 index 0000000000000000000000000000000000000000..94c1885ee1ff492ff4b495ce0c9c22f11846e8f4 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45b17ec7cf1b658257e6fc16e5fe072b4f39a42e896ea72eca56c03cbb460d72 +size 63526 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/17.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/17.png new file mode 100644 index 0000000000000000000000000000000000000000..81c1564d250b9c2d6c0b6b62e7dce5b9e2b726d6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/17.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea8da55701280c181e25d10a9ca0da7c2985752b4cba2b5479da80d4b4575f88 +size 53340 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/18.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/18.png new file mode 100644 index 0000000000000000000000000000000000000000..ed4713a6773b726d5b2f1307d2ace4b99b6da565 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/18.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93c16571444d8459252ef292cfaca84add80bc7f2e9c04dac28b8bad700ca43a +size 66941 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/19.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/19.png new file mode 100644 index 0000000000000000000000000000000000000000..0607a1870b168e87933ba57943b6df5fa0639d6c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/19.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92c8c3b48e3cac16bbbaa36c2da60044953f99747191328be985dab05f0e3535 +size 31858 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/2.png new file mode 100644 index 0000000000000000000000000000000000000000..6b416eaeefb5d2f743a39d194d278c847360d742 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0405118bf3d39d16dd275764dde2e3d12f18002157e0d4c47674fe5d7d90c9b +size 47331 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/20.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/20.png new file mode 100644 index 0000000000000000000000000000000000000000..ecf20fe1c70c4a89c473c7ef8a0c53a170aee4e5 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/20.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8699c39cfd5e95ca4a771ce6c294bc29e1825bc0fe9dd357b975c92293d209ad +size 31511 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/21.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/21.png new file mode 100644 index 0000000000000000000000000000000000000000..e0147cd5253372db319216e0d00087f0bd4a8fac --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/21.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92e667e666d5d04a41e9bfa55a7a4e9a7ac82d94a2b54c13012bec4aa9d553d5 +size 48809 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/22.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/22.png new file mode 100644 index 0000000000000000000000000000000000000000..5f0a16aa7923424e52a5579ecb2eb9860bc16597 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/22.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c8cc57c3ef44f7ade7023acef4f04e22ae826baea4ae8b6d4177f5eda8a4e12 +size 29979 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/3.png new file mode 100644 index 0000000000000000000000000000000000000000..3156677ff9a59a165c6a630476bda9b34f9db76b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f1ce3affaf23e88a5716a31430461afc5600d38ea24ffbd6f39a71c36edc13d1 +size 458805 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/4.png new file mode 100644 index 0000000000000000000000000000000000000000..7a1ac8af0ba4c51f8c1a87945e78fc1627ab2ebc --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b008997a4673bc1e0b9a03cb6021dc0ceec635fc240dff8e022895aeb466602 +size 321365 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/5.png new file mode 100644 index 0000000000000000000000000000000000000000..48dd5219600aa1a7ca7c8fb19e38f2a8750d2c49 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e51cf27cc93d48dcd057700a05ef3eba8a054d622d2c7a21305566d1f994854f +size 65099 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/6.png new file mode 100644 index 0000000000000000000000000000000000000000..3977fd275c887e2f74a7012b2b430004437d5038 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6aa929d3526d1f701ce136fe148e3d11b30d1717a400ca8427f487e5459d405e +size 151480 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/7.png new file mode 100644 index 0000000000000000000000000000000000000000..c294ae98d31f808bdad1011c4530090df9d925df --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6032c06d2ed358d43617607c573b6139dfbef796c9b476369100ccc93cbe0116 +size 417988 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/8.png new file mode 100644 index 0000000000000000000000000000000000000000..963e9b2646eb89436f99197afec1f15e575f44a6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a42df2010c7581c2b2b086abe0dc79b7d0d2a3183f0c6db8cf9e7fd238bab15a +size 47516 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/9.png new file mode 100644 index 0000000000000000000000000000000000000000..6a77def9c4a025365a16c72610f3d4275f4a7c78 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e70f191e901b2ffd1e71ee182f8e06c768311bdd5093e8dfe27e16d35f6acda +size 164507 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/image.png new file mode 100644 index 0000000000000000000000000000000000000000..e2f002bc3ec6eb5787ef45fe95788f8fb709181e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/2560px-David_-_The_Death_of_Socrates/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f03bfc79730a585e3bc8bf90929f371e7f0fd42a34fa7f23a9aea0da83cd33b0 +size 693606 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/0.png new file mode 100644 index 0000000000000000000000000000000000000000..bbb6bc8091bbf91cee28fa4f6caf5496dec8f162 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:63d662d21747fb1bca89f1aa5c8fb54ccb574e686d47376900da9290c7e5b16c +size 10381 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/1.png new file mode 100644 index 0000000000000000000000000000000000000000..acbb9994b2a76dd447d552056c955314b5f39d6a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8c3028ec52f4c41f6d24beac8ae2ee865d57467dc7cc8e0f6408d0ed15496518 +size 59153 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/10.png new file mode 100644 index 0000000000000000000000000000000000000000..e37f9e2dc105efa28d4ccc4402ac20229edc3260 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b3b3cb9f2187fe99ae612eea8a0c912f0b4efe5c2013f2391cb0fdea0465c30e +size 20799 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/11.png new file mode 100644 index 0000000000000000000000000000000000000000..fbfcb9add672e83fc853817306648e185620105c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d8d9792ceac9c6e8e4ce2f159d497bd62c046769f73d448d9b9b82f57a94170 +size 62699 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/12.png new file mode 100644 index 0000000000000000000000000000000000000000..7c879f6e50200b23437b5934212e6c5d73c0add7 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:10ee9beb3a67339db3fe076a0150ccd5fb84bcee52710cb7a7690a1e339f7d8d +size 19397 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/13.png new file mode 100644 index 0000000000000000000000000000000000000000..f410d63dc1d05a18c9856fc8c41ddcdc6e13d7e2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:86d741ddc0266c6449a7c2ccc4d5ae912cff379eabb0e36e51c26f45f0f1f99f +size 14569 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/14.png new file mode 100644 index 0000000000000000000000000000000000000000..7ec8f04dda10c11b5814736e42e8147653a846c7 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:984426df9ee3a661efc342865a688675c0a815230131550a6fdfee8f0265a1ec +size 59269 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/15.png new file mode 100644 index 0000000000000000000000000000000000000000..69f0ed87417feafbaae8a64bbce154f5965b378b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84b60b2f79ce1f26121271a80b1504d640ce101c14d2b47c407b3829549c1750 +size 16817 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/16.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/16.png new file mode 100644 index 0000000000000000000000000000000000000000..33155ca609c73be1070e6984dedfdd9e463599f3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58042b4d678afff0274612aa8984b521f4be1edc928664dfb4a03dd04512363e +size 34664 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/17.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/17.png new file mode 100644 index 0000000000000000000000000000000000000000..8a736ebcc3e6684002465acb1465a99bd787edf1 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/17.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9df3facae439a964f93ce9ce812618922d65d84242addc197618cc351b861916 +size 51192 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/18.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/18.png new file mode 100644 index 0000000000000000000000000000000000000000..1f5bbbe3170d1b2359b5d3cde1f3834139dd6b15 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/18.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c4d801516527771555f726f333e59c0b788e0fcbef759c3f442c06d7e0107ed +size 54482 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/19.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/19.png new file mode 100644 index 0000000000000000000000000000000000000000..9f8fba7c710ce6aa82618ea13a6542ab6d18f11c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/19.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db1bc6c14c94f500b888d5a00cca2bb3ca22fdeba5534d19d9af961201974311 +size 19323 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/2.png new file mode 100644 index 0000000000000000000000000000000000000000..05169220828749b347eb8b2125a15aba576a8274 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7cf626fe211ee91176281618e03410e823975413e598e268dc9747447068b4df +size 18189 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/20.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/20.png new file mode 100644 index 0000000000000000000000000000000000000000..c2af21a6196f131c12ca8f479c75389760f7ae62 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/20.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d84038e94e8f711bbf6557456d178d4e735039f75ae58e5451f7b34ba3249af6 +size 11145 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/21.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/21.png new file mode 100644 index 0000000000000000000000000000000000000000..1c46d3a8b1e32b6162f3f6ea7e1333802115693d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/21.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22da32b12d0d6cbcdd34a845f7d1c8d473c5f3f6ea64b0c8a94e2989c99bbf5a +size 81580 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/22.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/22.png new file mode 100644 index 0000000000000000000000000000000000000000..629d99601f622015d409a4e0e7a96245ccc339c2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/22.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fd3bf8b744ceaeff950347a2bdf139275575c0994066c01ef0b97b6195ca3bd +size 16637 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/23.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/23.png new file mode 100644 index 0000000000000000000000000000000000000000..e4436d41088cf721d64e972c444fc6f6f60835c4 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/23.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:219a34dca7ca7fc659452bde7748984479e53d76b2a37b81752dddd299656458 +size 11354 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/24.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/24.png new file mode 100644 index 0000000000000000000000000000000000000000..166dce1b42e055b343c3888dd06e848bb149b2c5 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/24.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5e78d254100ac46615f30e37debfb26e17ddf1a4af4326e3eadf2b048b857847 +size 32075 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/25.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/25.png new file mode 100644 index 0000000000000000000000000000000000000000..644a1d84dfaa48eee290328c22d35fd679085057 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/25.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72dfab928b6166cf9deab756f4d4ac872443a8b0471d752e1c92b921461f2b53 +size 10008 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/3.png new file mode 100644 index 0000000000000000000000000000000000000000..08e88257fc58620502a88540900568ab3a94a961 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:377be5749f62691bdcbf466f01e0361042eccf113f4e4c383ef03352ecb40e59 +size 72168 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/4.png new file mode 100644 index 0000000000000000000000000000000000000000..c520d3f178ecfe2b956ab0d6d63aef7ad5020302 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f66f7916afeb1c78a4b7d7e4c704ca234b9b789229a440c2705a0e835b017521 +size 33306 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/5.png new file mode 100644 index 0000000000000000000000000000000000000000..731491a9bece742574989b2da283eca3afc42b5c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:037068451f685886d1f4d6afed8361dcc8bd35de8dbd042c41261cfb1a674a26 +size 13387 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/6.png new file mode 100644 index 0000000000000000000000000000000000000000..35d452c17353e4474d5711650f668932c9b6b87a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61991f245a79d3aace4024e9a8e5faa90f88c612c847158e83c144a0c0045a15 +size 57032 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/7.png new file mode 100644 index 0000000000000000000000000000000000000000..06d6c0acdee7edfb5817416abd51c0a90a161680 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7fc2ad73184943e3ec29e7442c5abf0ba9c64b582c3b7a2b3af013e415b8be6 +size 14159 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/8.png new file mode 100644 index 0000000000000000000000000000000000000000..ef8c3b46d9ca2108fd83e08c394bc7542a0e7931 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8494b9399c2b02a00c0f7ff9980d7c196e84ec556034c5850c16171ba0103e58 +size 30426 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/9.png new file mode 100644 index 0000000000000000000000000000000000000000..99120efb3ea77007182d7cdf24a0d3ddb265cd2b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4c8aeac1283e2ebed492be3c222a1f6e9d98c2f78708ed42989399363b9c16b +size 43496 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/image.png new file mode 100644 index 0000000000000000000000000000000000000000..a52a5c03bd9b6080c965f23e5a474f68ca54d614 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id14_032207032-scenes-traffic-rome-12-12_processed/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8b3141e043dc57e27f3e8d45ced171cf3b70bad2e550d5a23ef6d532769e9ca0 +size 1364177 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/0.png new file mode 100644 index 0000000000000000000000000000000000000000..c652b3d247b7797a2af869a85ddb0cfc5d21233c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:446abd5e491869fbe629022187e89aea16a8eeb284569822ea8bae1588665933 +size 20330 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/1.png new file mode 100644 index 0000000000000000000000000000000000000000..c95b564c3a6433eefc922fcf29f7caec66101a80 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0ab6dccfec4db3077b9badd34378e22708f775f9594a2f1253c6094fa039927 +size 13460 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/2.png new file mode 100644 index 0000000000000000000000000000000000000000..a18c99f9beec6e5e00595a5dc260ad8c8c68978b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4767a2da7cc036e3272ae7d632d029cf0eba9fa08718d40b0ee3190077e5894 +size 12921 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/3.png new file mode 100644 index 0000000000000000000000000000000000000000..0e444291424383540a5f74cb9b8c0497a396d1c9 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cc83eb87da8a9fd45a0294078e3393a03b0273de5931c9faefd7b9e2c3241766 +size 44389 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/4.png new file mode 100644 index 0000000000000000000000000000000000000000..95c65be0cf2e404de8b0b78bac2ea45ea1740cfb --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ddedde31c5d2d434ae7e8f269a23396a5135197b1b77438ea35c76dc1cd328f6 +size 157000 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/5.png new file mode 100644 index 0000000000000000000000000000000000000000..2d046ac9b4650181d8eef523bc9a7a12f93cee8f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:83aa99e157e6d0ea7b06eded549470003974b4a1fb0b7343c5bf613f4b03e76c +size 17678 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/6.png new file mode 100644 index 0000000000000000000000000000000000000000..0badf32074e4a99b6779b37ef773fd8bc6107a4e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ec3160909f3ad62784a2f6cd84ac55c9f23f5ea31341d549f52c369f83a35c1 +size 23300 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/7.png new file mode 100644 index 0000000000000000000000000000000000000000..73c60aea0e730d8cd636e1cc5393a76103c48ef1 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:309960e820d4c7979d9d6abedc2cb6517a356691502148140226524e09efcae1 +size 246024 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/8.png new file mode 100644 index 0000000000000000000000000000000000000000..e8e9dac9769d5895d53f236c507d946759d9f6b6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4558b6b76d859c04b65374f5aef91ecd3086d80e4621330f6c7bb271908fcbe +size 10436 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/9.png new file mode 100644 index 0000000000000000000000000000000000000000..d2f4a950cd37edac2446f85289f58274f6acff8d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:be4d4fb4745f3d4b40c846699f1d7158db960f2badeff51f572323818998b5da +size 149044 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/image.png new file mode 100644 index 0000000000000000000000000000000000000000..df0ee8b0672ec41c86b025787f33c590f4a81906 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id15_shutterstock_1105318669_processed/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44acf4b25f94017d4723007b4032cc40286dc15139bf5aec2e6a146826a9ecd3 +size 1118557 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/0.png new file mode 100644 index 0000000000000000000000000000000000000000..3af3a48434faa0f0d068c89c370f0fe1fb83e63c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ba22d8860f81d90c33c7f676c4d0b865162e101d2bf5a913ee412628a3460c3 +size 9853 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/1.png new file mode 100644 index 0000000000000000000000000000000000000000..9589b4e9ee3c49b34d74488a7ebfcfec53c8f1f8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11b2dd6e1f63321037224725177dbad1481f523694697ca78026cafa1970afa1 +size 10889 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/10.png new file mode 100644 index 0000000000000000000000000000000000000000..91d650c83afe79ed3123bb5af65cc415a16a3431 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f32b18a030332f2d9734e28893b7ff8bb6865d0a35f952b38f14ce6c43b53bad +size 91262 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/11.png new file mode 100644 index 0000000000000000000000000000000000000000..8b88000202fa3788e7081cf260558be14af32590 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:78ba39dc09292c4199e0cc4b09fc62b8e57ccccf439158bd80d6508f3fedd6a4 +size 14500 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/12.png new file mode 100644 index 0000000000000000000000000000000000000000..0c89857a50419a4da8ee057a5bc33ed72aa422c7 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4cf9b8ace355f4dc475f4f46c1373c8366809fc4b9ccdc8f516b3a02588561e +size 7426 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/13.png new file mode 100644 index 0000000000000000000000000000000000000000..a0dad584e0d32f9d4ac1152951bf1661fa6f8920 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:886c32d4512c34a63e7485bac5a44e181b7518bfa27761d55f4754fe2785da8a +size 94050 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/14.png new file mode 100644 index 0000000000000000000000000000000000000000..24e348c2abd7254c26d12819c13e28ca92d2e0d8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1da2b567780736adb671f0d7b8b0864079aca56473651c7d9eef65bf64332898 +size 13965 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/15.png new file mode 100644 index 0000000000000000000000000000000000000000..46c43a959cb2d65af3d80a10a5b3dcd0343857a6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50619ff0ba8f1ed1e7e79d970077fee5eede6157f854604f7c3182199f66d8a7 +size 31892 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/16.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/16.png new file mode 100644 index 0000000000000000000000000000000000000000..e5b16a6489e56191e2dc152213539d4ec5335fab --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:770767aaa030facd8b13626efaa43660a318fbc2a0e4e84510d7d24a78c0251c +size 35515 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/17.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/17.png new file mode 100644 index 0000000000000000000000000000000000000000..a01d4c3e908d9051c0b8e0e712fe3097d89d5bdb --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/17.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b08209297eb6ddbd8e163c262ac47cc9a0ac3df160a3dbdec47f02b6f543c15 +size 8223 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/18.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/18.png new file mode 100644 index 0000000000000000000000000000000000000000..8c1828bcf0496ed38c158cd60e4281f46bd84745 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/18.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ec919add328491b5b48ee7dd1bc263fa23b0670a290f64cf790093989b13d96 +size 53870 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/19.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/19.png new file mode 100644 index 0000000000000000000000000000000000000000..180a46f50bc809112f166dd1a3cd279536380af6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/19.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35769b774692f13d7f307f0f8ed60f58287d667b949359e2e58b53c7d34fd012 +size 29643 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/2.png new file mode 100644 index 0000000000000000000000000000000000000000..7b3b1a6e4315d61062a8f5ddc48046e613ca60b8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:18e3c35b9ca894c609a937e16061f6a5d3aa478b1ecfd759603e69ba72308e82 +size 9668 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/20.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/20.png new file mode 100644 index 0000000000000000000000000000000000000000..af0bc3f014f07ece4c007d4019746e10c25c4b33 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/20.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1ddb051be2d3220c4d6aac796800300078216fe6ec232667acffdb3bee70c7b4 +size 69925 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/21.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/21.png new file mode 100644 index 0000000000000000000000000000000000000000..7c3b10f4522a7557ae1581995cf56236f08f07a8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/21.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a6282fcb1bbf6bd860aeaf83d679b82c850043648bf30ebf98cc5783e23e7f9 +size 78795 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/22.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/22.png new file mode 100644 index 0000000000000000000000000000000000000000..f6be71195331379262322b55c2597ed48de1e861 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/22.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9096e53df1ea928ab9fec331ff2bd59474eb546e81dd1d4e4823ca1bab01e91 +size 148565 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/3.png new file mode 100644 index 0000000000000000000000000000000000000000..39059f6d11bc7cd1afe98fdc3e9e9eb5196b99fc --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce8493565cbb31dacb7933eeb2b62f0e4181299d6b23b4ec2601e4971e9df228 +size 14511 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/4.png new file mode 100644 index 0000000000000000000000000000000000000000..a3081bb0f03c35b64de4b6d57501f723d9c340c2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29048317a32c244e2dff1c2b0c87660b00fe2089d1a4bdd56e702c75df42d06b +size 83988 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/5.png new file mode 100644 index 0000000000000000000000000000000000000000..e12ab89536574ab0ed10229c7d4ced6ac291984e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:defde70405f385a8a60ab7ced6934d714230a564a52d3b7a81e9511f9f6a365c +size 11635 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/6.png new file mode 100644 index 0000000000000000000000000000000000000000..fba8569db93549896959a9fdbeceead1e8153e5a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02d51c33bb92ceccde4f4a35bd53b61c3a73a6d75c72d772c3ef732e9b7f8041 +size 58063 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/7.png new file mode 100644 index 0000000000000000000000000000000000000000..d69aa983f25b413e19b3bdb01f9dcba5400b9e34 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:152452c76cb870a45ce190adbde336d6cdafa7e76cca89abe3bb2bde2bdfa74d +size 29426 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/8.png new file mode 100644 index 0000000000000000000000000000000000000000..f5c7ee1d31c6746c2faaa7d701bca7cac7f603da --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5feb7a6d257e4c19bf2ade7dda90e28baa1e81b4b318fd523e3021183f450549 +size 12418 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/9.png new file mode 100644 index 0000000000000000000000000000000000000000..3f99c52ba5cbed19b84d3cd23fcf370d25663cfc --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a763967c5739198f7f715d1b2b362bef371a89b7aaa4c1dcbbbb2aa82b9398b +size 7757 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/image.png new file mode 100644 index 0000000000000000000000000000000000000000..f7ee26c17276860ac87f9101b8c44e5d27386b1e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id32_307354001_H264HD1080_processed/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9410d176e5e7bb20cf74d758eac0fe5412d4590b387c8be08c0f71919442c986 +size 856799 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/0.png new file mode 100644 index 0000000000000000000000000000000000000000..3a8344727d75725b287d545f15b7d10492e61d94 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ce371bb48f50aea4072727f0be60d7215ac975db2e7b27d8168d5a3e5a23350 +size 16660 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/1.png new file mode 100644 index 0000000000000000000000000000000000000000..4e5b3ac84ecb8b5452662d08031132ff4f272f10 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d7e42e17028e528af53c62da580df975acc561dff22ef1d5e5fc075362c3889 +size 80290 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/10.png new file mode 100644 index 0000000000000000000000000000000000000000..0c0d56783f0f2f3cef88d93015f8bb36fc3e0b48 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab50c563a74f0000661823a9f3231866b5cd042403e76d07e9fc2f8d183ed9be +size 32494 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/11.png new file mode 100644 index 0000000000000000000000000000000000000000..5e941b5a3de0bf4c480bf9381e94875fbd094ae2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2369b6607e94f08984c9ffb4271eb5c6314056db80467615d3f7b7d38c12ca31 +size 35735 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/12.png new file mode 100644 index 0000000000000000000000000000000000000000..69ab67b004b96c8f9767788363050119d1d4ffc4 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbdb48c3aab7a71cac7a9863b291a000c52722e4032e71035c130343faa7097d +size 7331 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/13.png new file mode 100644 index 0000000000000000000000000000000000000000..e319d009581383a4a460b373b17aa1099430e8d2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c288e4566a5fa2edbf3fe1accf9d6999c1dfea40aff4c340e0fa8b803b2d22e3 +size 8877 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/14.png new file mode 100644 index 0000000000000000000000000000000000000000..923bbb9c072570c447a995d68d1acf0c7d16fb5f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0c57d15f0b71c8ec039de0eddfce36627454d60ad24eb7ad41ad6bfb7151f338 +size 7427 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/15.png new file mode 100644 index 0000000000000000000000000000000000000000..17282a53a4184f166170f2505dcdc3632c210cce --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aaabaee29bf7aa87816e7490a0641b63d1e0ed820be6aebaec251562fd7a5b35 +size 9226 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/16.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/16.png new file mode 100644 index 0000000000000000000000000000000000000000..8e728626130c1aa9ccce32dd9c300267bab3c88a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:67202d9361f928fac45f6c0da19eb2ff81f3480aa20d68f07db5367c1a962f6e +size 59463 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/17.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/17.png new file mode 100644 index 0000000000000000000000000000000000000000..4de123b9a60c4503a89d570fe79142c30fcc1ee3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/17.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aeb8eaf41d72e0c4ff26581be112c44119af39998625ccd222970aa4e6bbd0cf +size 18504 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/2.png new file mode 100644 index 0000000000000000000000000000000000000000..901783ca1556e5e2f4c526ab99b24f24f35c1710 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bffdfe112444f00282c37b5af64ddbfe6562c68d0acc55fe3ea520f48e64ad52 +size 31972 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/3.png new file mode 100644 index 0000000000000000000000000000000000000000..888d6c8f3b63385dd2825a52ad7717e4a16dd039 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c0ff005d87bff3c6da20a2fa4a03e0365d7e0c61b6534a40776e02977bef1900 +size 42952 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/4.png new file mode 100644 index 0000000000000000000000000000000000000000..304786667b3998bc74be7f549414f741e506116f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfaa5d7c7c6aa7ad97b5d8c8cd7a209ce428844135d26e404c989fc612a93084 +size 9269 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/5.png new file mode 100644 index 0000000000000000000000000000000000000000..4b86d956ff4bfa4046b6e304ccf524f6393245f2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c908fbb87444fe89a870e67d5965692f6ba7843c12147f9493006845b141ddf8 +size 81266 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/6.png new file mode 100644 index 0000000000000000000000000000000000000000..6542d027d3d32b1c64aa7246d9ad821f9e769579 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40bd4383d96c5bebdb6527288d578ec8b90d63979c3bd72c32a21a74af22ea56 +size 11576 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/7.png new file mode 100644 index 0000000000000000000000000000000000000000..aad0d5e32e57f9bc88ef7f1bb5eddfb085a31103 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92d20fd79019bfd34fced88a439379acc71c534824bb0895d3978e5d9f6d3500 +size 21483 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/8.png new file mode 100644 index 0000000000000000000000000000000000000000..1345537ab4f94c63eff019158bd52e7fc7a65e59 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8c377eae72603974e1a49b0df814db9cbc52d35bd8c6c4e8cb22fe9587ba694 +size 75265 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/9.png new file mode 100644 index 0000000000000000000000000000000000000000..af7eac776b82d2744afdaacb63aa98ae8e1384a6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6befa0dd51cd519276a2ed48ae0612dd85b9c7f8dddbbd96450c709d0e15d711 +size 10746 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/image.png new file mode 100644 index 0000000000000000000000000000000000000000..71b737675566bb71b730d6695c27699a1bfa852a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/edited_id37_203733676_Programmers_Computer_Monitors_H264HD1080_processed/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:71bf717cbffc0b70705afae95f09cd33ec13b77d30f8c52d8c44708e08d4d7a4 +size 939820 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/human_object/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/human_object/0.png new file mode 100644 index 0000000000000000000000000000000000000000..082a871232d19a72d5cdf74b9419585cf3dbb901 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/human_object/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d0e581bd291548596aa4d0bbbc29529c6a57ad3566ad52e541783e1394375f0 +size 2696 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/human_object/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/human_object/image.png new file mode 100644 index 0000000000000000000000000000000000000000..aed382c49f7d909e90d41b32d4b5b0bec5e63bd8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/human_object/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:41ff3e857bde2d2ccaf2cfb0d08392591294957aa3b79dcbb6bc36385f30d838 +size 1287082 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/0.png new file mode 100644 index 0000000000000000000000000000000000000000..5e2e87a1864419069a383d3e773496c2b87f8663 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6270e1f38498fda901a3ffdc874c2bcd593cfbbc8dc741f7cab45db9e058c92 +size 411774 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/1.png new file mode 100644 index 0000000000000000000000000000000000000000..f8e963333d8316d9cf7d2d1c448c5b2851d40f99 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6e036674964da81a681fcc62349440761f9171598a8cb49e4b76393181609058 +size 411052 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/10.png new file mode 100644 index 0000000000000000000000000000000000000000..c2eff17df97c49479e6e708b00709b245a77bbc4 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:543585b24f5c4aafae82bc5f81a46dfd128803ad5b752f88ebfae4cc5f837631 +size 1324889 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/11.png new file mode 100644 index 0000000000000000000000000000000000000000..fc28bffc3da969eb626c79f23332c1c4e11773df --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3060ccef3567b9bf54ace57646e20b54ec90a12fd2393559669dc8aab3bfba05 +size 594492 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/12.png new file mode 100644 index 0000000000000000000000000000000000000000..14c313478e983fd19d9c91bb060cb0ae95440fe8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a37077990987967d56a7b69cf18c255af469bee50f7f5709e8977adcf315124a +size 354930 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/13.png new file mode 100644 index 0000000000000000000000000000000000000000..9c9873724b4aa7e076768126b306b02ac04fc597 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c786935dcd0b0d9d4d7f951ff13268d449cfe17b85c72791e9e0d299d1887491 +size 519252 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/14.png new file mode 100644 index 0000000000000000000000000000000000000000..2714b7a1bf9610fc27b2563ac31d4a677310bda3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:adf0fa4a24fb1ac09e04b23fa9aebde6b7946dacc500d1de58ee36ff5eb20b5c +size 1845668 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/15.png new file mode 100644 index 0000000000000000000000000000000000000000..00451fc788cfdc56e056ce48ac3fefc6826e6a51 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:339577357764bfb13de0902d211ec8651a9e6e2295a3d3453bee1f209546e0a7 +size 242365 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/16.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/16.png new file mode 100644 index 0000000000000000000000000000000000000000..35d9c4f4ccaff4606203d50a315291563bb623b1 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:daf3ce8f6d542eee7a0bcfdf296abe3c8c20931e9ab71d387fcb9ff1dbf7b694 +size 385587 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/17.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/17.png new file mode 100644 index 0000000000000000000000000000000000000000..b2494a00b0a09745e07ab70b523e8ea2a2b1f5fe --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/17.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:751c28105e372734a8ad5755e7ed0dc2ca5bdcf53db78933c1ac9bde19b3b04b +size 296785 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/18.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/18.png new file mode 100644 index 0000000000000000000000000000000000000000..11b2bb840819ab84fc0e36130b564768865bc6c2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/18.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8ed09c58c957a2775156512c95aaec34705033c429e07d0d6dd0d46effbe85e +size 417586 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/19.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/19.png new file mode 100644 index 0000000000000000000000000000000000000000..4ad953bcd5bce395034e73bd55e1b27bbbeeb7b9 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/19.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34c82643623202ce16e28f8ed3ecf71703a8d02bed686643caae11f8c0a1eb00 +size 2093512 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/2.png new file mode 100644 index 0000000000000000000000000000000000000000..c9589f62130a5ace74e402715df41e14f95bc356 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12f95ade4871f79fc8e55867dda84385d5143d89e8d9fe8931c53b4743cc0555 +size 135529 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/3.png new file mode 100644 index 0000000000000000000000000000000000000000..7505e9dae1504beb346e069f16fe0d46b6e6c676 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d7c4c2da1457de6aaba530e80cb406a6d9e5f039c10f4d5e7bfe9410c48e75a +size 921592 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/4.png new file mode 100644 index 0000000000000000000000000000000000000000..7e5d6a21ca9c5df5e5d4b3fb7257d9208851afa9 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a80b3bf65bd7e913e2ef2f23b7f338a0d2816d9023643b35940468df9e92ec0 +size 1095311 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/5.png new file mode 100644 index 0000000000000000000000000000000000000000..55b735ce82e66ef793282f2cd048b4656f520d73 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9d4771d790bf9cb4dbdebbe291cc159e232fdab6f6909b20e7761e37f746725a +size 443978 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/6.png new file mode 100644 index 0000000000000000000000000000000000000000..39351e1fccadaf97d1c91704d2c5a837709d4a68 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:62ec27a9b56a1c497c4c1179a65363e29fd933f1b9eb97b01cab794eb50bff0d +size 494613 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/7.png new file mode 100644 index 0000000000000000000000000000000000000000..f543e7c8f5e7e976fe6f662fa9a33ca2d95ad73a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4dd9ba6acf93045facd5c999a6e30168d6b7e1564f6f73c026276b087a60bafb +size 680091 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/8.png new file mode 100644 index 0000000000000000000000000000000000000000..c91cdf4b85b82c515225e25228bc7794d622272d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96c35031c2328aa49c67fdab2e83bbb4cbb8a5ded87e4e74d897ed2c465c85f9 +size 136756 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/9.png new file mode 100644 index 0000000000000000000000000000000000000000..c38dcce393d6154e9fe7d96f344dc0bbb5225ded --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5405c3a656780e64dfd134ae074aa78d88fb63594428a04c177c23ce147fe499 +size 380006 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/image.png new file mode 100644 index 0000000000000000000000000000000000000000..b432853e309a05412b47921811319bdd26220abc --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/id3_shutterstock_WildAnimal_Waterhole_2010559391/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af1bd538a0dc94c21d51771a27f7324d4bd282b59a33d2720749bf43438aea55 +size 16450105 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/0.png new file mode 100644 index 0000000000000000000000000000000000000000..101882a9f7b3e2582f5af45d39d6601ddfb0103f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:811eada8e42b6870a403bf63cbf0ba2ec06bf585c993833cc6b4a13585ec77b8 +size 190228 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/1.png new file mode 100644 index 0000000000000000000000000000000000000000..33d843a2db40f7756a95bb7b64f0461d64270867 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2909ff96663850eeef06e1138b035963ed373ab52e41997ffcd3e353eddf322f +size 103840 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/10.png new file mode 100644 index 0000000000000000000000000000000000000000..0c2273bc19e5a594ad4d5577a0f1f53fd4fddda8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4753e5d83da72709045207b2e3529b200f61d4950e51a772ac1379102b017114 +size 1133281 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/11.png new file mode 100644 index 0000000000000000000000000000000000000000..d8a0ac6730b2e679489d7f9f3f977d9316b7d714 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b6192fd14a4ad225f6244c438507a43b15e3d098a19553f6006e93cff957053 +size 143140 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/12.png new file mode 100644 index 0000000000000000000000000000000000000000..68cfffdebd306986402541a47a2b6cb5c65d9fdd --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6a2abc6064dad4aaac15a17622f56b7b706f0fdafba5769555033fd05b6eeae0 +size 224978 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/13.png new file mode 100644 index 0000000000000000000000000000000000000000..6d3a2672d69ac600d075fa82f7c7506c7519e560 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c7e81bca3a52eea70ec4262dbf52de7441cae99836f391bed08cec7eb1e27e97 +size 189308 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/14.png new file mode 100644 index 0000000000000000000000000000000000000000..21b38fe072e5287ad8e78a6cf9fa997e9c4b0a5f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:556e50d5459c5c49cd6b5cbff863f4f1329ac7251b300c2544f0ff54ea0330cf +size 179830 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/15.png new file mode 100644 index 0000000000000000000000000000000000000000..aebbf3082f8744548c95045bfc5aa593137e3e1f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c772f18dbd35bce73ec2f86840ab410abc0c9e8232f16b8c723c65a684ed8228 +size 281173 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/16.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/16.png new file mode 100644 index 0000000000000000000000000000000000000000..26f17d6bbccde1fccf2e2a97f964fa67cb22f445 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cde300c7942eab5d9969154f6523cae3227d61aa0eff9a2ed071e8a0a78eca14 +size 146997 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/17.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/17.png new file mode 100644 index 0000000000000000000000000000000000000000..f4ca67f9750653cb89fe4a30197b686b460ff81e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/17.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49f47d1bab6c53ab0c139f3c7432aac6d2589afbcb57b4bec43c0886d7314bea +size 2056504 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/2.png new file mode 100644 index 0000000000000000000000000000000000000000..67c742b05ac0c60285b2789f623492468fad31e6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9a88f90aa90369defdfcefd532071c8e1d2abfa71466bd5c7960d94d759f8e7c +size 245684 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/3.png new file mode 100644 index 0000000000000000000000000000000000000000..b23f05a41cb92b2adad9db3191c1c5d0e7f6de60 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9e56259833b9bd99bca9aeae4aca61c70afa8b372e90f4a29262d139210784a +size 104485 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/4.png new file mode 100644 index 0000000000000000000000000000000000000000..c61790b4c26ad87ff737d09937b565b1df430f8d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f0bfb111908fcabba880f3c98ec74008ea7354f011a26bef5fb887d6cfec7d5 +size 327041 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/5.png new file mode 100644 index 0000000000000000000000000000000000000000..d4d810151c3d46e96531b9c06cfb29094e7f6091 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d02b2851f2bea7e59158f4f29fea8dfa8af24dbb366de0dcb4d0027912e044c +size 70240 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/6.png new file mode 100644 index 0000000000000000000000000000000000000000..0002c9480080a7ef5d423218c26d9e0e2a750366 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14d149c28bbe532d3d7036e8b68951ba848bed5e7eb0500e3734620651d97b5d +size 284078 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/7.png new file mode 100644 index 0000000000000000000000000000000000000000..fd5b979f200fa3a5edb2caecd78898f1a1ca8a36 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8347ae57b043a0545efc099a0cee212048990a87ea5441a4610e9bd5fb6cc74 +size 620277 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/8.png new file mode 100644 index 0000000000000000000000000000000000000000..0ea0d1904d43a7ba43e03d60c2e640e3d672008b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c22ad1a6d3845ffafe2e518d297390d6ffa079c6de8c0eab68e7661477f1605 +size 257930 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/9.png new file mode 100644 index 0000000000000000000000000000000000000000..f454b7a87ac58017e4cb5f595e72c30dda7bba7a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8aee7326d4906e75f3040c13138a58c0f6f46a5a8af9b22c000ab79406231bdf +size 256328 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/image.png new file mode 100644 index 0000000000000000000000000000000000000000..c62be8deea0f26148d30c3241ccdccf41f085f1f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/kid_box/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d4d55dcebda52e7be9fd60e6fe68ce3fe52fdee5f7fe086bffda7520466e9ed +size 4596856 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/0.png new file mode 100644 index 0000000000000000000000000000000000000000..2ce8f1c0da656e07d3b6f693df3e6de325e1a282 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06e338962a1fe8bdb9eb5be8842c3d07004f7c042c4b14107730f933075ce7af +size 219306 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/1.png new file mode 100644 index 0000000000000000000000000000000000000000..9ee3f94e6661e5de937bb89edad9605f4080f032 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cfb208caa6bb31f20f7403e3f34e35f9646229bb9a826e0f39afbfb09f440f0 +size 215323 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/2.png new file mode 100644 index 0000000000000000000000000000000000000000..906669ea361f313f6433d5191ff8c4207c1840e8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:983d914ead99af42b40db50462fdbbd5881f410c390c65951dc63d64f857e495 +size 1256108 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/3.png new file mode 100644 index 0000000000000000000000000000000000000000..ebe83540ca7a8ca0e348a6bfb4ab85f2e8bfb4fa --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b2fd4ea1be642965f80f90dfbef0a0621103f6500eb04ee4bde688d3420ff2d +size 144368 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/4.png new file mode 100644 index 0000000000000000000000000000000000000000..ae25bed8777c4ea7802aa9e144e6183dbc0ac6c3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5b33fee56e1a442aa32f973abc3bf2f6684106e116ca2aa7f1ee798cd101020 +size 138490 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/5.png new file mode 100644 index 0000000000000000000000000000000000000000..c4913f61f13053a952d24a2fc92d8d61350d3942 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2a5b01a03150383207bccafe82a330cf694eb013fdf3cd4bd56941a48b881b8 +size 1249016 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/image.png new file mode 100644 index 0000000000000000000000000000000000000000..d5f8339b1213f3379b93996d738ff0197387d572 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/pond5_080554841-two-professional-fencers-show-/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:748ade7a2b1a16edd4888cc79796766557520bcc9e78b9e4ac5d1aa95e0f844c +size 1277045 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/0.png new file mode 100644 index 0000000000000000000000000000000000000000..2aca39a974be904e6bee5c3c490859204b215146 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6e6b799d3db79cbc537fcdfb89f26ae1d22a223a8b17e9a493d27b648abf5865 +size 1952388 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/1.png new file mode 100644 index 0000000000000000000000000000000000000000..27b2b27da8cf056423db960c9b48458c00870076 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:644c0f0568f7ac3de70398349c93c85a165b8dba44e8df844b6f330ef8858d63 +size 213902 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/2.png new file mode 100644 index 0000000000000000000000000000000000000000..ae4771c0783c34f11ee45d4687b37bc7946c5433 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8fea0472191f97f99f4e6d240839c527ad65adc96945a32c3848e1df88393f4 +size 1377749 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/3.png new file mode 100644 index 0000000000000000000000000000000000000000..d5cf3cfd96c53b188b2109eca5422eb39f9b70b3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:24b364c75dc48aad3f0ad4ef797a2bec249490d3a4d054ecf5e3dbdcec4f0e4c +size 2999434 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/4.png new file mode 100644 index 0000000000000000000000000000000000000000..a86997e57fa0e85e5720b564c71cc2e7cb9ceef4 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:188ac6f946850d193c97b0a245d1cab4965a4fc0f3e257b9123d66d5ecef2684 +size 1141279 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/image.png new file mode 100644 index 0000000000000000000000000000000000000000..9435897a4262cbf2af54c2cea1d57ed0f12d8b5c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1243680295/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4bf45cd59253fcd480676ff9f7b39a2fae8eee9dc36538ffd2ad260328f0d0e6 +size 18554028 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/0.png new file mode 100644 index 0000000000000000000000000000000000000000..d9d5ec4e48020cf4ae88fc90443a3040aefa7d33 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c55c0c4da98e2c33716aa297139100c506b8ddeb748b6d8a07e1cb00cc4f07a9 +size 305224 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/1.png new file mode 100644 index 0000000000000000000000000000000000000000..5362c89102c232561a7767cadf76baf54e66cc23 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77486b7d0df7e4f6d412fb3869a83aefa29c3716df1ba07e4895d23ab05ddd9e +size 104126 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/10.png new file mode 100644 index 0000000000000000000000000000000000000000..03abb1ec59efb6a20182b85d71d991fd83a210a5 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4fb901ff38451d598b5a05c20f85399eb51bd06fa1ac23ed9fe18359af957f98 +size 128431 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/11.png new file mode 100644 index 0000000000000000000000000000000000000000..5caf08f4069a5628ab57e13968bd7f3ea5d28175 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4dbe2e06213427a10d94e6960fc558922fb5c59cad23c5da75cea478d666273f +size 132128 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/12.png new file mode 100644 index 0000000000000000000000000000000000000000..93b834acfc00c36865393b782369bad27f1f1f12 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:674792640b16d2523ef0d7fb9a18a9dfe5acb8f754bc1b4f065a02e095bfaaf5 +size 105957 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/13.png new file mode 100644 index 0000000000000000000000000000000000000000..0d19eb143926e070ca5c471382f6a5afe4d1a0cd --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:004062349c5ede0e9c00903f5d256a5cdc9849c5586ba1eb5db3475b7fd2b55d +size 415138 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/14.png new file mode 100644 index 0000000000000000000000000000000000000000..7ea79600cc26885b5b189bfbb92ab623e40c0e1e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2f0a37526445bc377f845830c3b2364a7ad8335f2df914dc36ad85b3a6e43f89 +size 140478 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/15.png new file mode 100644 index 0000000000000000000000000000000000000000..053db76b6834e331852710be1472244cc3f659ca --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4495a133af8e05dadeef7345c63816fcdab60bfb502b56110ffe1a2231f4b8b3 +size 1060156 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/16.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/16.png new file mode 100644 index 0000000000000000000000000000000000000000..6d35e02a75cd55d7fcf70381bf7d3cba679181e9 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f5cc651d524be58cadfb2110c36a8a8771661e88b7921360ae01478c8b8f531 +size 118483 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/17.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/17.png new file mode 100644 index 0000000000000000000000000000000000000000..97ce1edee9021ae4dc25c8c6448d19f723729b43 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/17.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edd50dbcb8716f8285c4aefa6aeb85815c08deb6810840be4a9a9ce3acbad431 +size 359657 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/18.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/18.png new file mode 100644 index 0000000000000000000000000000000000000000..7c5b57de5a8a0a673c59c4c2946d276e57c696ba --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/18.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bab837412703acc6db395157d9fc142eb1a6b5ef6d4a6c581bd17672b86b4ad +size 131082 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/19.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/19.png new file mode 100644 index 0000000000000000000000000000000000000000..896ea00a6ac29833555fc50572994b97f4f16269 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/19.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:46cf976cd0eada854f8315e6abf51e0e26691012644e72503d1ed16686622151 +size 419565 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/2.png new file mode 100644 index 0000000000000000000000000000000000000000..a9347929ad01d6674f89b3138d10d1f91517479e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0135f2ad0c87ec24d972dadd59635b0f74c901bdd0bb4456468dbb79c53990a +size 3492711 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/20.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/20.png new file mode 100644 index 0000000000000000000000000000000000000000..bbef39484c9863e59e567dd9bfabd6b6b9968845 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/20.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd5df1386d5df0b2a76c9f1e450eff2896a344148095555d220a072da2650de0 +size 315703 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/21.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/21.png new file mode 100644 index 0000000000000000000000000000000000000000..0a4bdc379c3d055daecc52418f7304763eb55717 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/21.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34647327b347cc88411ea724e13044b2228b52777e26bb01b040c96e6a32379f +size 127619 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/22.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/22.png new file mode 100644 index 0000000000000000000000000000000000000000..2108b8e633483cfd0534063b8fe3f0e1186a996c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/22.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aeb679654c5f0aee433209eca431262a3de19383b51d090bdfafe275a5c6c677 +size 121418 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/23.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/23.png new file mode 100644 index 0000000000000000000000000000000000000000..073cc4b77e387fd875bd5a9310e76fc668fd08c7 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/23.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:893c70c3ba60bff49d5d36c424d1bfd4080f75e2c21c12a678f91ce0c36cc55a +size 373122 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/24.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/24.png new file mode 100644 index 0000000000000000000000000000000000000000..f1c4e856fce65cb97283aaceb1ab152cd79a34df --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/24.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6235fe518070b17c8f0c160a7a1a938d79d1a0458bef7d665050662ed569b5a6 +size 535035 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/25.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/25.png new file mode 100644 index 0000000000000000000000000000000000000000..af57f1f20bee11dd9e5d2a5822fb7244777c4e0e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/25.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f164125c6a8ea1f88f0b7bd9446f65d3c6c740296f801490dbe5344b10d51de8 +size 427861 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/3.png new file mode 100644 index 0000000000000000000000000000000000000000..3165e3842dd4e27d4460dc43f878724dd61092ba --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4dd935286c8a2ee4f9074a6c05d075c53f137cf3be95137500930151456165fb +size 750774 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/4.png new file mode 100644 index 0000000000000000000000000000000000000000..32dd410707df02ba8fc4c96be0dc33c80d66ff7e --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f25a368ebf8d3569741dabf10a10d2d86869a069829f5fa1f752115e70d74ec +size 344462 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/5.png new file mode 100644 index 0000000000000000000000000000000000000000..d6fa88057931d1903bf34b1fca0e242b490368d8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fdb45bab111b7bf0d6867d0f226e620b8b03f000742ca884090c9b756ddc3e2 +size 1088246 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/6.png new file mode 100644 index 0000000000000000000000000000000000000000..ad79563b9740a79ffcbea15e4d6a682e1b2eaa57 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:11f3460e29b0dad538a352094fbf1b2c2479d5eabf68395ce6aeb31fceb1c631 +size 154506 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/7.png new file mode 100644 index 0000000000000000000000000000000000000000..55d4baafe94ddeb1be694a33e1e5e55e6942a025 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db7551f7fb56baee1777e8cd02ca516dc498872fa925594fe35b0b8cf32d4e90 +size 105521 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/8.png new file mode 100644 index 0000000000000000000000000000000000000000..614f11a4e039e22ba14de47ebd8a6e470424d460 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e3d4824f8740542f032889acd9ba15625035a581ecdc1b3aef341eca74d07fd1 +size 1728119 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/9.png new file mode 100644 index 0000000000000000000000000000000000000000..948d6bf0c507043c69228a1680651a2beaf87d48 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d4490a78058fcd5da52556bc0c93b7bd502eb3df043c5ce056877b771a0bcba0 +size 4337154 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/image.png new file mode 100644 index 0000000000000000000000000000000000000000..7cb9498be86a75c5e594f00e29530bb6a1617395 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_1980085646/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31f634606194e21d1b0640ad8a6fc8aed3f7453034d6260ae8d009b4cfc16e60 +size 13269588 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/0.png new file mode 100644 index 0000000000000000000000000000000000000000..175d23a7d85e06acd5e6c87c742fac256bf5c371 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a074a865657163bb5c0d07c5be76753941674dfd50ba235923807cb07696a088 +size 164000 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/1.png new file mode 100644 index 0000000000000000000000000000000000000000..682e49cb55c4a614e6c7c6178fd3c688278ae858 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4e9e5ef96289b0fc383dbfc182dbbb6c35f7bfab4f61576f1f77731de6608de +size 203377 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/10.png new file mode 100644 index 0000000000000000000000000000000000000000..fb3f24b86d8a290af1f035c296ea4687bcfa7238 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb061d525f3c400be44b224adcd5eaaaf7d3b4c3152817a119eb47162875a2f8 +size 355321 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/11.png new file mode 100644 index 0000000000000000000000000000000000000000..a0124a8a6c12c710c4715115942a3b64f41ccd10 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76f2f86a71aa8c63db0179428fbf4dd84cb24bf11fabf3269353a31e37a0a63e +size 160343 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/12.png new file mode 100644 index 0000000000000000000000000000000000000000..5cf68e916789dac5075250bf6472a23f5365c03d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52ff0c18f2670d8ece3e05d562586023c4f71c53767f3460abdcb93769732780 +size 943743 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/13.png new file mode 100644 index 0000000000000000000000000000000000000000..fda14c8d5cf94ea1c5358683525d5a1250bfdd08 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82d8034a5903851245f15d6e93043e89f406ff5d82c930d91dd210f41dae3c65 +size 324561 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/14.png new file mode 100644 index 0000000000000000000000000000000000000000..9214f07fae709e27c471258a2bedea07c330878a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e88c875df40390f8e8336ffcfc705088a2f58286b942ebe70ce160bc809d33fc +size 165207 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/15.png new file mode 100644 index 0000000000000000000000000000000000000000..f93eab8f60d10583a73bc3128a56a9dd16ba6b96 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72e1ca05f198fa139a22d99aa6d84974a6652bfef85781f197f3facb16d5b4d6 +size 209578 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/16.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/16.png new file mode 100644 index 0000000000000000000000000000000000000000..35f602ff03b853090590406e7370401c3c23444a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2cb1b68fbda5295636fc5b99adecb7f72984bc5d7770abfbaf2f5028193c839f +size 155110 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/17.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/17.png new file mode 100644 index 0000000000000000000000000000000000000000..566df53283413d9d75b6cee5220825da4e3b5965 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/17.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4b0364436fa44fe7177d0d810080af358b5d6954f7f1ae4f607b76ec3d8e7544 +size 823901 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/18.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/18.png new file mode 100644 index 0000000000000000000000000000000000000000..b98a04b7e5f3debe85addf43fc3229e05a04f496 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/18.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec0b23e455433e2c925e8c3c7a6c8cd8fd49d81582dea1d2d5f422a4881dca67 +size 1736564 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/19.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/19.png new file mode 100644 index 0000000000000000000000000000000000000000..69a88eb41082da73c18067004fcc6cd94128b067 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/19.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0e8513aee09cc2da4e74aeaadfd37c0842e95ee61b35d9543855462c281b290d +size 209262 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/2.png new file mode 100644 index 0000000000000000000000000000000000000000..7b81f5afd3c8eb2f113d5b2e0f802a12979b23cf --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c6b46722eb35784238b95a689340c1bc833a9d8a4b5867e6311157d56de54c9 +size 603077 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/20.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/20.png new file mode 100644 index 0000000000000000000000000000000000000000..4b1d4cc35e721dc6b493ea279b1fe4cb95e0a285 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/20.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cae5365e1afde3bc1361ab506690cbbafe563eafd69485e97ffc704690754732 +size 147833 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/21.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/21.png new file mode 100644 index 0000000000000000000000000000000000000000..98dc29406bfee9d30839160c7ccd56adde2e9268 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/21.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4348c168fa65271055aeb615d3fd6c4959ef9f9c5e2235b121f5e48b1015a804 +size 3712482 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/22.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/22.png new file mode 100644 index 0000000000000000000000000000000000000000..e000e2c70b80599ffa70e8f072c1fd51fbec36e6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/22.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9bf53cd8a15a6a23390da2d096aefd1a54abe2ec478c38a56ce698e3d72e4777 +size 152752 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/23.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/23.png new file mode 100644 index 0000000000000000000000000000000000000000..1582bc0fc395f9130673420768773f1232177419 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/23.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a361678e4433b2d90b9bcd7d7455a061b0e34c0adb0960a0bcba7e5369758668 +size 150775 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/24.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/24.png new file mode 100644 index 0000000000000000000000000000000000000000..b2305937be39149a722d9491bfa3ed138504bc92 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/24.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7e2b64de2f3f77cd967beaa4cdc55b63233d4abff1f58d89b57932128c6167d8 +size 205019 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/25.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/25.png new file mode 100644 index 0000000000000000000000000000000000000000..bad0522c2b337d05c6ca87752525aa0da17cf322 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/25.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffade161210a528e08f77925e3fb469a309988c20dfec067714955e85eaa551a +size 462935 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/26.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/26.png new file mode 100644 index 0000000000000000000000000000000000000000..0a29818778cf9ea9c9a55005400fa3a610806e3b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/26.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4396ee2d58f36cdd5ca1c661b430b0222a2aa58596c50324becdf809c26b73f0 +size 2808666 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/27.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/27.png new file mode 100644 index 0000000000000000000000000000000000000000..8348a0a993f87007ead9727c81fcd643ebb4cdd9 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/27.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bde48de3fb94792dbe0641cc092cb4ed3e797f9ddef9a053aa7ddeab57f5fede +size 156473 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/28.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/28.png new file mode 100644 index 0000000000000000000000000000000000000000..76bb023352f0e07b35e444fd482a63b596cd43f0 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/28.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42fb2891c1ea819af18df3c1dfe3bc7bfe6e6871bb62a8425cdab7647719bb26 +size 186569 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/29.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/29.png new file mode 100644 index 0000000000000000000000000000000000000000..a091518a2d4b1aade2302b282fb0bd75e036f9ff --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/29.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca3080d6ed26be1e3ae2d027de69f51b89d38d8504d14891ec96df1a12fedb6e +size 142518 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/3.png new file mode 100644 index 0000000000000000000000000000000000000000..85c9330a4ab78ad1168612d7f0cf58824c3a3f87 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e89eb8363449e8fe00bccd1511b5501fb10cf96e1751cfe96fd40b3b6e873886 +size 237092 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/30.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/30.png new file mode 100644 index 0000000000000000000000000000000000000000..6867f1c5d6e9733f2195ada20f0cf1916ca8f54d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/30.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eb104b181e458c48a99912aac2610bfbc29dd1cfb013b66189a37f976fbd134b +size 483929 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/31.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/31.png new file mode 100644 index 0000000000000000000000000000000000000000..814b6af4ade688723305e35198496096f559119d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/31.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09186053a1c55067ccbbe3d819e4ae5970f31bd168a02a03445e20f01d78ce3f +size 207326 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/32.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/32.png new file mode 100644 index 0000000000000000000000000000000000000000..f8ef774003fa912d301cc90f2887fd15260d6fb6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/32.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89070a707cd92ff782aad02fb565c229cffead87bc317665c6abb46bc33bd616 +size 1841977 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/33.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/33.png new file mode 100644 index 0000000000000000000000000000000000000000..4dddf681a8ac31d74f866e5d0aeeab648a774bc3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/33.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8eb97204c85fa505eb1ea91792c041039bfff60555f9834b286a972cadd6deb +size 2185213 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/34.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/34.png new file mode 100644 index 0000000000000000000000000000000000000000..466a74afa9fbd30e49cd885ef84dae80186a25f2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/34.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccaf5ee410a90a6e25909fb6cb61b0272612d854a29e26747916708b41112f1e +size 185901 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/35.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/35.png new file mode 100644 index 0000000000000000000000000000000000000000..9f53c31ebfa9f28bb37452694a6ab845e8600e74 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/35.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0b03609a9368504bbcbf5e324bebfb91b4fe2dc25813f5ddb38e94e75a9b3a11 +size 718834 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/36.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/36.png new file mode 100644 index 0000000000000000000000000000000000000000..f47db27544aff3a9ebf3c2a6915ee346d1550487 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/36.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bab9e81ecbaa2c0ddead41f7c3e2982d446218b129f84224ed968fd50098216b +size 194120 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/37.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/37.png new file mode 100644 index 0000000000000000000000000000000000000000..f4782529bf8482c2fd3c5cc1ff4001a6fa63297b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/37.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d901a27ed58ced76da697a45e0989e18bdab5818ba01e1d808420d2eda77e53 +size 279328 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/38.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/38.png new file mode 100644 index 0000000000000000000000000000000000000000..0f155806cb244283ad812a86835d61e29b190d9d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/38.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33e21193e737af18391bbdac07789098a15d2cb81c7777ad6b5d6dc37e1ba2c0 +size 1234159 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/39.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/39.png new file mode 100644 index 0000000000000000000000000000000000000000..0237d5d5b4da89b7c3f80c3a764164331f2ad322 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/39.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d38b4a0183711616f8049b8088c37898eac27d780f173c7bfa808dbc767e3e2e +size 164156 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/4.png new file mode 100644 index 0000000000000000000000000000000000000000..1ca59912e793412be775744d88825a6dc8b264c7 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afd954b5af78f1350e2af40b8a130c41be91269748fa3846e8ddaf0173ad928e +size 164728 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/40.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/40.png new file mode 100644 index 0000000000000000000000000000000000000000..35aa33b98eefab57acd94aebf615273eb4cd2f42 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/40.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01c71218ab6d849c070779ee51494a741935772531dd9cc9fa898de233ba2322 +size 3986394 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/41.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/41.png new file mode 100644 index 0000000000000000000000000000000000000000..05d38e6f4b374f71621c750db67152c38213979f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/41.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:171bd70d130b0f4b48089907832071e8ec9e4a0c56d40e7b17990aecf315fc8e +size 241541 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/42.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/42.png new file mode 100644 index 0000000000000000000000000000000000000000..924f61cc75b6661f8f3f82bcacaab726a0848e22 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/42.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb40db6ff539ce73c2d404e2ea2593cf76b63bd89f5fa6e6a653182219f275c2 +size 223836 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/43.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/43.png new file mode 100644 index 0000000000000000000000000000000000000000..81492bb43086af9af0b603647a100e2b45c77124 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/43.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6feb2a48052299bc2830a14933927e30253433f4f6dd3e70cb8e1d077d7846c1 +size 233412 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/44.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/44.png new file mode 100644 index 0000000000000000000000000000000000000000..d2057160b1c8e7135d13d0bae80445603943de92 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/44.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50d88df29c04cb07c28c718197900942642d298bdba8e99a03c1d78306fad399 +size 163098 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/45.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/45.png new file mode 100644 index 0000000000000000000000000000000000000000..0a62af7b6f8ebba966d4590da1210ca20a6ee674 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/45.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb23f5cbd7e3083856cfe1b1050b6168ce0d2b3c32b741ef5ba7066457e95322 +size 453591 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/5.png new file mode 100644 index 0000000000000000000000000000000000000000..40af8f64c0458513dabf04944985e1e0025066b4 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:959b02eb6bc9d5679e2d5711f2acb6c5c5697196238e6d351bac26c0e2604f49 +size 155074 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/6.png new file mode 100644 index 0000000000000000000000000000000000000000..8092a56abb3eb4d7382ed93141ff7443d5edae99 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb69cf0bcaab181178163eec5f8526b6fe93010da20df470b3af00a143a04d1b +size 206101 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/7.png new file mode 100644 index 0000000000000000000000000000000000000000..866f1a87076bd4b66676da533343a8d0fc74ed33 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0fd51c8e2587b83c963831cb66be4774a095406ad0bcb3ba48402d80920af45e +size 249785 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/8.png new file mode 100644 index 0000000000000000000000000000000000000000..aa9ec6a9805dc41f0ba446c36222038bf8489171 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02de73400cb43f1072519ea7918a5842770cd9530bdcc1c622028a5cc5da69bd +size 544545 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/9.png new file mode 100644 index 0000000000000000000000000000000000000000..47bc52a5eae00fa1a72f79bdb1f3b32061454d50 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d14b067339f80973b057005d2320682d39a10e67c65a2cfe70b3e210867a6018 +size 1146376 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/image.png new file mode 100644 index 0000000000000000000000000000000000000000..8a71a8531660d38bcf2846936604fe98c5a861b7 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_modern_colorful_Interior_2620125197/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9831d03fb1c64b9a073c284a565d9432bed9fa86f4349108cab3b02783ae1a9f +size 18082633 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/0.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/0.png new file mode 100644 index 0000000000000000000000000000000000000000..18086de453fac2fb9e65997bb2a27038cc255f60 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/0.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b03f9325f1827d0fd89e3f2429331be4a2b5004e033bc02cc8ffd1b69f5d188 +size 613896 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/1.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/1.png new file mode 100644 index 0000000000000000000000000000000000000000..7dc3292f5e506faa22036d7ffdbc8e24c62307d5 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbf51087fc9eadaf59fc49a3c6473723a6ffe18b7f1b0937dc6d95d6f86c90c8 +size 147847 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/10.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/10.png new file mode 100644 index 0000000000000000000000000000000000000000..8ef15a62815c6ace110b0d00b1d1a77e26766c30 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/10.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a735ffce608ec3a5d774420d046e2ac5013b3f0db321a8b9c0fe86d6f7681c7e +size 1387997 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/11.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/11.png new file mode 100644 index 0000000000000000000000000000000000000000..4a356fc3491a1d6e435b0a24b69ae11408747281 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/11.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85b3829c3469f4629a09bfae9df26dc78b85082c6b903c5d0c900faddc48c952 +size 256040 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/12.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/12.png new file mode 100644 index 0000000000000000000000000000000000000000..e263264344949173e1bba500838f7cf275ed558d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/12.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01dc87ddd34dc75195771e225241877c0d5c8b6bf8fc0dff54ba21cd4f56c0ad +size 555818 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/13.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/13.png new file mode 100644 index 0000000000000000000000000000000000000000..be0c4797396d98a636999f92798db012a501747f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/13.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9662a4377e2ae4da9b883967ffd8f9891ef8c7b2debe420bb3e9ae928a2ad56 +size 5645275 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/14.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/14.png new file mode 100644 index 0000000000000000000000000000000000000000..0f4584b61a5eaeed8826080b7d4e97f9ec5b6706 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/14.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7a79c2f537a20bfd70c001df42dd8d916d4c5f7fce4ea7ee99738aa178b29c13 +size 1012416 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/15.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/15.png new file mode 100644 index 0000000000000000000000000000000000000000..6eeda60ecd57049234fac368ff875cbfabc0ba93 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/15.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26181526f2dcbdd461ad32fb7a83be452f99ae320f13f9422bbce71cb3956b5b +size 211291 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/16.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/16.png new file mode 100644 index 0000000000000000000000000000000000000000..9f098bf19cc3daf3b17e8ad3ec9d292ce9759fbe --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c86d6758407282f247d15dd6ac32fa92805f07d7391768061bffe756c7129ecf +size 1720892 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/17.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/17.png new file mode 100644 index 0000000000000000000000000000000000000000..a1c8b98865334d88c0074a6d8e6f66690d37c6d2 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/17.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0ad6d8822be6fe9097de11f6e5dffb4338a20c1f8c329956085b919d397413c +size 1147243 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/18.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/18.png new file mode 100644 index 0000000000000000000000000000000000000000..fe303c530c3a631678fce6cc6c7985df4bf0f1bb --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/18.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d51d96984cefd162b6db550a1932cd4c882410a1e0f18d2f076ad6471cd371d5 +size 267421 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/19.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/19.png new file mode 100644 index 0000000000000000000000000000000000000000..bdcaf3851308befdd4f0d0660513c3b38723e6a3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/19.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:402999fdf22459177c170c59a8ec903dc96efd291051ed62abab7831f5f960b2 +size 311802 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/2.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/2.png new file mode 100644 index 0000000000000000000000000000000000000000..e0d06d031b4dbef43a1e7b04b50f062e7a98bc4b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4a270c6906c90609f3c62ebfd92f452372f7ca1d6fc9fcf89fc1c5473b3c7fe +size 162888 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/20.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/20.png new file mode 100644 index 0000000000000000000000000000000000000000..1a347c35e375dee6200cff7e1cd68343aca07f6c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/20.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbd1f8b2f0f0be471cfa323d87effbb5a7862e5bb9c4cb6c78eb7df46ffcd992 +size 769661 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/21.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/21.png new file mode 100644 index 0000000000000000000000000000000000000000..9d5a96ffa49736f459a039872ab1202124e5704f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/21.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:380ecde0738a1d17421bf2fc1138bae87bada45319811f47e7835575c2f7dc2f +size 2119968 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/22.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/22.png new file mode 100644 index 0000000000000000000000000000000000000000..80b2d606ca35a8dde69131156b2f301c7789bd86 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/22.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:151ae2e88a469fadb0f97579d959573148a15fbe9b9d28f398b1681a7477449c +size 207067 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/23.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/23.png new file mode 100644 index 0000000000000000000000000000000000000000..522d04074d227eefab32bbc0a09407f5463f5e78 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/23.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:196e9651bddc01dfa6b259a7a3aa375f084cc4df8f3882a046fe71632ec0ace4 +size 660926 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/24.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/24.png new file mode 100644 index 0000000000000000000000000000000000000000..ebb0ac8420d9fc4bc3cda02869a2aaa08d856677 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/24.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:56729721732517ab80eae13a49ed8f340786066db641d9ea3b238d186950c613 +size 168292 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/25.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/25.png new file mode 100644 index 0000000000000000000000000000000000000000..3ce031caf1abba92453963bb08e5ac8af94ab7f6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/25.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae1a72df8820bd7cf390664bbf98ed717081e771eeff22ea352845675d05656c +size 1345688 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/26.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/26.png new file mode 100644 index 0000000000000000000000000000000000000000..b4e9225f912e74b3a48a9118f9ce94a1c452b1fd --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/26.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:121f06ef2cb59d0f5643edbc36c5c6201ae62683ce45ced7548f2f430e3aff00 +size 204528 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/3.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/3.png new file mode 100644 index 0000000000000000000000000000000000000000..c47f29c8bedd569a232c1f842dcd082c283fc46b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d73162f36725f6e39906d27e35956a0b66e37eb45caad2446af0115fc3f816c +size 162530 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/4.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/4.png new file mode 100644 index 0000000000000000000000000000000000000000..e28a9714eb8293b047c717581951808c9c24d5e6 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/4.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d554be46fae4806fe2240689bd2391d1482ebb66ed768ee16cc3ee99df41ce5 +size 140221 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/5.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/5.png new file mode 100644 index 0000000000000000000000000000000000000000..9f538a6a2c1c3bee1365b456b0c51a00f018621a --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/5.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a7690e45cdc09fb3a5b6b1ed8c2942019812805dd8b21c5a6ae9f2937a586aa6 +size 641657 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/6.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/6.png new file mode 100644 index 0000000000000000000000000000000000000000..2b1dc136bf93d08542fca1111b8a34879b27c6a8 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/6.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa6c364d359addcceb9df92e411781d0f4520a87e8a7de22b820b097a424a55a +size 1545103 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/7.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/7.png new file mode 100644 index 0000000000000000000000000000000000000000..75f413b206832f6e8606be82944a96878f7e974b --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/7.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:833e403f8b3f3fd0a63fe932a5d51dba2c4d08531fc55903fd2e7ba614cbd57f +size 2548160 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/8.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/8.png new file mode 100644 index 0000000000000000000000000000000000000000..73dac9f9d61af8deb076e8af72ec489af1a536e5 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/8.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c0f120783d7177d07ff0d40c013230a6906f362f215423158e0bd3fca46eba2 +size 205726 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/9.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/9.png new file mode 100644 index 0000000000000000000000000000000000000000..bddd651b5b857630b3d8491b14a821d87317c437 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/9.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d98a919cb4a242803579a3c64fd093354ae913a6b7184009913e78418d058ed2 +size 353370 diff --git a/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/image.png b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/image.png new file mode 100644 index 0000000000000000000000000000000000000000..104bfa0da684a877883d0d61da1f555d48e23d7f --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/images/shutterstock_stylish_kidsroom_1640806567/image.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:72785412200dcb9f5c6bc4eaa3018172293f67836627708e6bce78150109af15 +size 24154851 diff --git a/reconstruction/modules/sam-3d-objects/notebook/inference.py b/reconstruction/modules/sam-3d-objects/notebook/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..0525de9c3b431a970abc3a05927a19634f97edf0 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/inference.py @@ -0,0 +1,446 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +import os + +# not ideal to put that here +# Prefer an existing CUDA_HOME (venv / module load). Do not require conda. +if "CUDA_HOME" not in os.environ: + if "CONDA_PREFIX" in os.environ: + os.environ["CUDA_HOME"] = os.environ["CONDA_PREFIX"] +os.environ["LIDRA_SKIP_INIT"] = "true" + +import sys +from typing import Union, Optional, List, Callable +import numpy as np +from PIL import Image +from omegaconf import OmegaConf, DictConfig, ListConfig +from hydra.utils import instantiate, get_method +import torch +import math +import utils3d +import shutil +import subprocess +from PIL import Image +import numpy as np +import matplotlib.pyplot as plt +from copy import deepcopy +import builtins +from pytorch3d.transforms import quaternion_multiply, quaternion_invert + +import sam3d_objects # REMARK(Pierre) : do not remove this import +from sam3d_objects.pipeline.inference_pipeline_pointmap import InferencePipelinePointMap +from sam3d_objects.model.backbone.tdfy_dit.utils import render_utils + +from sam3d_objects.utils.visualization import SceneVisualizer + +__all__ = ["Inference"] + +WHITELIST_FILTERS = [ + lambda target: target.split(".", 1)[0] in {"sam3d_objects", "torch", "torchvision", "moge"}, +] + +BLACKLIST_FILTERS = [ + lambda target: get_method(target) + in { + builtins.exec, + builtins.eval, + builtins.__import__, + os.kill, + os.system, + os.putenv, + os.remove, + os.removedirs, + os.rmdir, + os.fchdir, + os.setuid, + os.fork, + os.forkpty, + os.killpg, + os.rename, + os.renames, + os.truncate, + os.replace, + os.unlink, + os.fchmod, + os.fchown, + os.chmod, + os.chown, + os.chroot, + os.fchdir, + os.lchown, + os.getcwd, + os.chdir, + shutil.rmtree, + shutil.move, + shutil.chown, + subprocess.Popen, + builtins.help, + }, +] + + +class Inference: + # public facing inference API + # only put publicly exposed arguments here + def __init__(self, config_file: str, compile: bool = False): + # load inference pipeline + config = OmegaConf.load(config_file) + config.rendering_engine = "pytorch3d" # overwrite to disable nvdiffrast + config.compile_model = compile + config.workspace_dir = os.path.dirname(config_file) + check_hydra_safety(config, WHITELIST_FILTERS, BLACKLIST_FILTERS) + self._pipeline: InferencePipelinePointMap = instantiate(config) + + def merge_mask_to_rgba(self, image, mask): + mask = mask.astype(np.uint8) * 255 + mask = mask[..., None] + # embed mask in alpha channel + rgba_image = np.concatenate([image[..., :3], mask], axis=-1) + return rgba_image + + def __call__( + self, + image: Union[Image.Image, np.ndarray], + mask: Optional[Union[None, Image.Image, np.ndarray]], + seed: Optional[int] = None, + pointmap=None, + with_mesh_postprocess=True, + with_texture_baking=True, + use_vertex_color=False, + force_layout_post_optimization=False, + disable_shape_icp=False, + ) -> dict: + image = self.merge_mask_to_rgba(image, mask) + return self._pipeline.run( + image, + None, + seed, + stage1_only=False, + with_mesh_postprocess=with_mesh_postprocess, + with_texture_baking=with_texture_baking, + with_layout_postprocess=True, + use_vertex_color=use_vertex_color, + stage1_inference_steps=None, + pointmap=pointmap, + force_layout_post_optimization=force_layout_post_optimization, + disable_shape_icp=disable_shape_icp, + ) + + def run_with_provided_object(self, image, masks, provided_object, with_mesh_postprocess=True, with_texture_baking=True, use_vertex_color=False, seed=None, pointmap=None, force_layout_post_optimization=False, disable_shape_icp=False): + rgba_images = [self.merge_mask_to_rgba(image, mask) for mask in masks] + + processed_provided_object = None + if provided_object is not None: + processed_provided_object = provided_object.copy() + if "mask" in provided_object: + processed_provided_object["rgba_image"] = self.merge_mask_to_rgba(image, provided_object["mask"]) + + return self._pipeline.run_with_provided_object( + rgba_images, + processed_provided_object, + seed, + with_mesh_postprocess=with_mesh_postprocess, + with_texture_baking=with_texture_baking, + with_layout_postprocess=True, + use_vertex_color=use_vertex_color, + pointmap=pointmap, + force_layout_post_optimization=force_layout_post_optimization, + disable_shape_icp=disable_shape_icp, + ) + + +def _yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitchs, rs, fovs): + is_list = isinstance(yaws, list) + if not is_list: + yaws = [yaws] + pitchs = [pitchs] + if not isinstance(rs, list): + rs = [rs] * len(yaws) + if not isinstance(fovs, list): + fovs = [fovs] * len(yaws) + extrinsics = [] + intrinsics = [] + for yaw, pitch, r, fov in zip(yaws, pitchs, rs, fovs): + fov = torch.deg2rad(torch.tensor(float(fov))).cuda() + yaw = torch.tensor(float(yaw)).cuda() + pitch = torch.tensor(float(pitch)).cuda() + orig = ( + torch.tensor( + [ + torch.sin(yaw) * torch.cos(pitch), + torch.sin(pitch), + torch.cos(yaw) * torch.cos(pitch), + ] + ).cuda() + * r + ) + extr = utils3d.torch.extrinsics_look_at( + orig, + torch.tensor([0, 0, 0]).float().cuda(), + torch.tensor([0, 1, 0]).float().cuda(), + ) + intr = utils3d.torch.intrinsics_from_fov_xy(fov, fov) + extrinsics.append(extr) + intrinsics.append(intr) + if not is_list: + extrinsics = extrinsics[0] + intrinsics = intrinsics[0] + return extrinsics, intrinsics + + +def render_video( + sample, + resolution=512, + bg_color=(0, 0, 0), + num_frames=300, + r=2.0, + fov=40, + pitch_deg=0, + yaw_start_deg=-90, + **kwargs, +): + + yaws = ( + torch.linspace(0, 2 * torch.pi, num_frames) + math.radians(yaw_start_deg) + ).tolist() + pitch = [math.radians(pitch_deg)] * num_frames + + extr, intr = _yaw_pitch_r_fov_to_extrinsics_intrinsics(yaws, pitch, r, fov) + + return render_utils.render_frames( + sample, + extr, + intr, + {"resolution": resolution, "bg_color": bg_color, "backend": "gsplat"}, + **kwargs, + ) + + +def ready_gaussian_for_video_rendering(scene_gs, in_place=False, fix_alignment=False): + if fix_alignment: + scene_gs = _fix_gaussian_alignment(scene_gs, in_place=in_place) + scene_gs = normalized_gaussian(scene_gs, in_place=fix_alignment) + return scene_gs + + +def _fix_gaussian_alignment(scene_gs, in_place=False): + if not in_place: + scene_gs = deepcopy(scene_gs) + + device = scene_gs._xyz.device + dtype = scene_gs._xyz.dtype + scene_gs._xyz = ( + scene_gs._xyz + @ torch.tensor( + [ + [-1, 0, 0], + [0, 0, 1], + [0, 1, 0], + ], + device=device, + dtype=dtype, + ).T + ) + return scene_gs + + +def normalized_gaussian(scene_gs, in_place=False, outlier_percentile=None): + if not in_place: + scene_gs = deepcopy(scene_gs) + + orig_xyz = scene_gs.get_xyz + orig_scale = scene_gs.get_scaling + + active_mask = (scene_gs.get_opacity > 0.9).squeeze() + inv_scale = ( + orig_xyz[active_mask].max(dim=0)[0] - orig_xyz[active_mask].min(dim=0)[0] + ).max() + norm_scale = orig_scale / inv_scale + norm_xyz = orig_xyz / inv_scale + + if outlier_percentile is None: + lower_bound_xyz = torch.min(norm_xyz[active_mask], dim=0)[0] + upper_bound_xyz = torch.max(norm_xyz[active_mask], dim=0)[0] + else: + lower_bound_xyz = torch.quantile( + norm_xyz[active_mask], + outlier_percentile, + dim=0, + ) + upper_bound_xyz = torch.quantile( + norm_xyz[active_mask], + 1.0 - outlier_percentile, + dim=0, + ) + + center = (lower_bound_xyz + upper_bound_xyz) / 2 + norm_xyz = norm_xyz - center + scene_gs.from_xyz(norm_xyz) + scene_gs.mininum_kernel_size /= inv_scale.item() + scene_gs.from_scaling(norm_scale) + return scene_gs + + +def make_scene(*outputs, in_place=False): + if not in_place: + outputs = [deepcopy(output) for output in outputs] + + all_outs = [] + minimum_kernel_size = float("inf") + for output in outputs: + # move gaussians to scene frame of reference + PC = SceneVisualizer.object_pointcloud( + points_local=output["gaussian"][0].get_xyz.unsqueeze(0), + quat_l2c=output["rotation"], + trans_l2c=output["translation"], + scale_l2c=output["scale"], + ) + output["gaussian"][0].from_xyz(PC.points_list()[0]) + # must ... ROTATE + output["gaussian"][0].from_rotation( + quaternion_multiply( + quaternion_invert(output["rotation"]), + output["gaussian"][0].get_rotation, + ) + ) + scale = output["gaussian"][0].get_scaling + adjusted_scale = scale * output["scale"] + assert ( + output["scale"][0, 0].item() + == output["scale"][0, 1].item() + == output["scale"][0, 2].item() + ) + output["gaussian"][0].mininum_kernel_size *= output["scale"][0, 0].item() + adjusted_scale = torch.maximum( + adjusted_scale, + torch.tensor( + output["gaussian"][0].mininum_kernel_size * 1.1, + device=adjusted_scale.device, + ), + ) + output["gaussian"][0].from_scaling(adjusted_scale) + minimum_kernel_size = min( + minimum_kernel_size, + output["gaussian"][0].mininum_kernel_size, + ) + all_outs.append(output) + + # merge gaussians + scene_gs = all_outs[0]["gaussian"][0] + scene_gs.mininum_kernel_size = minimum_kernel_size + for out in all_outs[1:]: + out_gs = out["gaussian"][0] + scene_gs._xyz = torch.cat([scene_gs._xyz, out_gs._xyz], dim=0) + scene_gs._features_dc = torch.cat( + [scene_gs._features_dc, out_gs._features_dc], dim=0 + ) + scene_gs._scaling = torch.cat([scene_gs._scaling, out_gs._scaling], dim=0) + scene_gs._rotation = torch.cat([scene_gs._rotation, out_gs._rotation], dim=0) + scene_gs._opacity = torch.cat([scene_gs._opacity, out_gs._opacity], dim=0) + + return scene_gs + + +def check_target( + target: str, + whitelist_filters: List[Callable], + blacklist_filters: List[Callable], +): + if any(filt(target) for filt in whitelist_filters): + if not any(filt(target) for filt in blacklist_filters): + return + raise RuntimeError( + f"target '{target}' is not allowed to be hydra instantiated, if this is a mistake, please do modify the whitelist_filters / blacklist_filters" + ) + + +def check_hydra_safety( + config: DictConfig, + whitelist_filters: List[Callable], + blacklist_filters: List[Callable], +): + to_check = [config] + while len(to_check) > 0: + node = to_check.pop() + if isinstance(node, DictConfig): + to_check.extend(list(node.values())) + if "_target_" in node: + check_target(node["_target_"], whitelist_filters, blacklist_filters) + elif isinstance(node, ListConfig): + to_check.extend(list(node)) + + +def load_image(path): + image = Image.open(path) + image = np.array(image) + image = image.astype(np.uint8) + return image + + +def load_mask(path): + mask = load_image(path) + mask = mask > 0 + if mask.ndim == 3: + mask = mask[..., -1] + return mask + + +def load_single_mask(folder_path, index=0, extension=".png"): + masks = load_masks(folder_path, [index], extension) + return masks[0] + + +def load_masks(folder_path, indices_list=None, extension=".png"): + masks = [] + indices_list = [] if indices_list is None else list(indices_list) + if not len(indices_list) > 0: # get all all masks if not provided + idx = 0 + while os.path.exists(os.path.join(folder_path, f"{idx}{extension}")): + indices_list.append(idx) + idx += 1 + + for idx in indices_list: + mask_path = os.path.join(folder_path, f"{idx}{extension}") + assert os.path.exists(mask_path), f"Mask path {mask_path} does not exist" + mask = load_mask(mask_path) + masks.append(mask) + return masks + + +def display_image(image, masks=None): + import seaborn as sns + + def imshow(image, ax): + ax.axis("off") + ax.imshow(image) + + grid = (1, 1) if masks is None else (2, 2) + fig, axes = plt.subplots(*grid) + if masks is not None: + mask_colors = sns.color_palette("husl", len(masks)) + black_image = np.zeros_like(image[..., :3], dtype=float) # background + mask_display = np.copy(black_image) + mask_union = np.zeros_like(image[..., :3]) + for i, mask in enumerate(masks): + mask_display[mask] = mask_colors[i] + mask_union |= mask[..., None] if mask.ndim == 2 else mask + imshow(black_image, axes[0, 1]) + imshow(mask_display, axes[1, 0]) + imshow(image * mask_union, axes[1, 1]) + + image_axe = axes if masks is None else axes[0, 0] + imshow(image, image_axe) + + fig.tight_layout(pad=0) + fig.show() + + +def interactive_visualizer(ply_path): + import gradio as gr + + with gr.Blocks() as demo: + gr.Markdown("# 3D Gaussian Splatting (black-screen loading might take a while)") + gr.Model3D( + value=ply_path, # splat file + label="3D Scene", + ) + demo.launch(share=True) diff --git a/reconstruction/modules/sam-3d-objects/notebook/mesh_alignment.py b/reconstruction/modules/sam-3d-objects/notebook/mesh_alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..9c6da5aa6b022d3ee10da2b1888be0b169c77867 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/mesh_alignment.py @@ -0,0 +1,498 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +""" +SAM 3D Body (3DB) Mesh Alignment Utilities +Handles alignment of 3DB meshes to SAM 3D Object, same as MoGe point cloud scale. +""" + +import os +import math +import json +import numpy as np +import torch +import trimesh +from PIL import Image +import torch.nn.functional as F +from pytorch3d.structures import Meshes +from pytorch3d.renderer import PerspectiveCameras, RasterizationSettings, MeshRasterizer, TexturesVertex +from moge.model.v1 import MoGeModel + + +def load_3db_mesh(mesh_path, device='cuda'): + """Load 3DB mesh and convert from OpenGL to PyTorch3D coordinates.""" + mesh = trimesh.load(mesh_path) + vertices = np.array(mesh.vertices) + faces = np.array(mesh.faces) + + # Convert from OpenGL to PyTorch3D coordinates + vertices[:, 0] *= -1 # Flip X + vertices[:, 2] *= -1 # Flip Z + + vertices = torch.from_numpy(vertices).float().to(device) + faces = torch.from_numpy(faces).long().to(device) + return vertices, faces + + +def get_moge_pointcloud(image_tensor, device='cuda'): + """Generate MoGe point cloud from image tensor.""" + moge_model = MoGeModel.from_pretrained("Ruicheng/moge-vitl").to(device) + moge_model.eval() + with torch.no_grad(): + moge_output = moge_model.infer(image_tensor) + return moge_output + + +def denormalize_intrinsics(norm_K, height, width): + """Convert normalized intrinsics to absolute pixel coordinates.""" + cx_norm, cy_norm = norm_K[0, 2], norm_K[1, 2] + fx_norm, fy_norm = norm_K[0, 0], norm_K[1, 1] + + fx_abs = fx_norm * width + fy_abs = fy_norm * height + cx_abs = cx_norm * width + cy_abs = cy_norm * height + fx_abs = fy_abs + + return np.array([ + [fx_abs, 0.0, cx_abs], + [0.0, fy_abs, cy_abs], + [0.0, 0.0, 1.0] + ]) + + +def crop_mesh_with_mask(vertices, faces, focal_length, mask, device='cuda'): + """Crop mesh vertices to only those visible in the mask.""" + textures = TexturesVertex(verts_features=torch.ones_like(vertices)[None]) + mesh = Meshes(verts=[vertices], faces=[faces], textures=textures) + + H, W = mask.shape[-2:] + fx = fy = focal_length + cx, cy = W / 2.0, H / 2.0 + + camera = PerspectiveCameras( + focal_length=((fx, fy),), + principal_point=((cx, cy),), + image_size=((H, W),), + in_ndc=False, device=device + ) + + raster_settings = RasterizationSettings( + image_size=(H, W), blur_radius=0.0, faces_per_pixel=1, + cull_backfaces=False, bin_size=0, + ) + + rasterizer = MeshRasterizer(cameras=camera, raster_settings=raster_settings) + fragments = rasterizer(mesh) + + face_indices = fragments.pix_to_face[0, ..., 0] # (H, W) + visible_mask = (mask > 0) & (face_indices >= 0) + visible_face_ids = face_indices[visible_mask] + + visible_faces = faces[visible_face_ids] + visible_vert_ids = torch.unique(visible_faces) + verts_cropped = vertices[visible_vert_ids] + + return verts_cropped, visible_mask + + +def extract_target_points(pointmap, visible_mask): + """Extract target points from MoGe pointmap using visible mask.""" + target_points = pointmap[visible_mask.bool()] + + # Convert from MoGe coordinates to PyTorch3D coordinates + target_points[:, 0] *= -1 + target_points[:, 1] *= -1 + + # Remove flying points using adaptive quantile filtering + z_range = torch.max(target_points[:, 2]) - torch.min(target_points[:, 2]) + if z_range > 6.0: + thresh = 0.90 + elif z_range > 2.0: + thresh = 0.93 + else: + thresh = 0.95 + + depth_quantile = torch.quantile(target_points[:, 2], thresh) + target_points = target_points[target_points[:, 2] <= depth_quantile] + + # Remove infinite values + finite_mask = torch.isfinite(target_points).all(dim=1) + target_points = target_points[finite_mask] + + return target_points + + +def align_mesh_to_pointcloud(vertices, target_points): + """Align mesh vertices to target point cloud using scale and translation.""" + if target_points.shape[0] == 0: + print("[WARNING] No target points for alignment!") + return vertices, torch.tensor(1.0), torch.zeros(3) + + # Scale alignment based on height + height_src = torch.max(vertices[:, 1]) - torch.min(vertices[:, 1]) + height_tgt = torch.max(target_points[:, 1]) - torch.min(target_points[:, 1]) + scale_factor = height_tgt / height_src + + vertices_scaled = vertices * scale_factor + + # Translation alignment based on centers + center_src = torch.mean(vertices_scaled, dim=0) + center_tgt = torch.mean(target_points, dim=0) + translation = center_tgt - center_src + + vertices_aligned = vertices_scaled + translation + return vertices_aligned, scale_factor, translation + + +def load_mask_for_alignment(mask_path): + """Load mask image as numpy array.""" + mask = Image.open(mask_path).convert('L') + mask_array = np.array(mask) / 255.0 + return mask_array + + +def load_focal_length_from_json(json_path): + """Load focal length from JSON file.""" + try: + with open(json_path, 'r') as f: + data = json.load(f) + focal_length = data.get('focal_length') + if focal_length is None: + raise ValueError("'focal_length' key not found in JSON file") + print(f"[INFO] Loaded focal length from {json_path}: {focal_length}") + return focal_length + except Exception as e: + print(f"[ERROR] Failed to load focal length from {json_path}: {e}") + raise + + +def process_3db_alignment(mesh_path, mask_path, image_path, device='cuda', focal_length_json_path=None): + """Complete pipeline for aligning 3DB mesh to MoGe scale.""" + print(f"[INFO] Processing alignment...") + + # Load input data + vertices, faces = load_3db_mesh(mesh_path, device) + + # Load and preprocess image + image = Image.open(image_path).convert('RGB') + image_tensor = torch.from_numpy(np.array(image)).float().permute(2, 0, 1) / 255.0 + image_tensor = image_tensor.to(device) + + # Load mask and resize to match image + H, W = image_tensor.shape[1:] + mask = load_mask_for_alignment(mask_path) + if mask.shape != (H, W): + mask = Image.fromarray((mask * 255).astype(np.uint8)) + mask = mask.resize((W, H), Image.NEAREST) + mask = np.array(mask) / 255.0 + mask = torch.from_numpy(mask).float().to(device) + + # Generate MoGe point cloud + print("[INFO] Generating MoGe point cloud...") + moge_output = get_moge_pointcloud(image_tensor, device) + + # Load focal length from JSON if provided, otherwise compute from MoGe intrinsics + if focal_length_json_path is not None: + focal_length = load_focal_length_from_json(focal_length_json_path) + else: + # Compute camera parameters from MoGe intrinsics (fallback) + intrinsics = denormalize_intrinsics(moge_output['intrinsics'].cpu().numpy(), H, W) + focal_length = intrinsics[1, 1] # Use fy + print(f"[INFO] Using computed focal length from MoGe: {focal_length}") + + # Crop mesh using mask + print("[INFO] Cropping mesh with mask...") + verts_cropped, visible_mask = crop_mesh_with_mask(vertices, faces, focal_length, mask, device) + + # Extract target points from MoGe + print("[INFO] Extracting target points...") + target_points = extract_target_points(moge_output['points'], visible_mask) + + if target_points.shape[0] == 0: + print("[ERROR] No valid target points found!") + return None + + # Perform alignment + print("[INFO] Aligning mesh to point cloud...") + aligned_vertices, scale_factor, translation = align_mesh_to_pointcloud(verts_cropped, target_points) + + # Apply alignment to full mesh + full_aligned_vertices = (vertices * scale_factor) + translation + + # Convert back to OpenGL coordinates for final output + final_vertices_opengl = full_aligned_vertices.cpu().numpy() + final_vertices_opengl[:, 0] *= -1 + final_vertices_opengl[:, 2] *= -1 + + results = { + 'aligned_vertices_opengl': final_vertices_opengl, + 'faces': faces.cpu().numpy(), + 'scale_factor': scale_factor.item(), + 'translation': translation.cpu().numpy(), + 'focal_length': focal_length, + 'target_points_count': target_points.shape[0], + 'cropped_vertices_count': verts_cropped.shape[0] + } + + print(f"[INFO] Alignment completed - Scale: {scale_factor.item():.4f}, Target points: {target_points.shape[0]}") + return results + + +def process_and_save_alignment(mesh_path, mask_path, image_path, output_dir, device='cuda', focal_length_json_path=None): + """ + Complete pipeline for processing 3DB alignment and saving the result. + + Args: + mesh_path: Path to input 3DB mesh (.ply) + mask_path: Path to mask image (.png) + image_path: Path to input image (.jpg) + output_dir: Directory to save aligned mesh + device: Device to use ('cuda' or 'cpu') + focal_length_json_path: Optional path to focal length JSON file + + Returns: + tuple: (success: bool, output_mesh_path: str or None, result_info: dict or None) + """ + try: + print("[INFO] Starting 3DB mesh alignment pipeline...") + + # Ensure output directory exists + os.makedirs(output_dir, exist_ok=True) + + # Process alignment + result = process_3db_alignment( + mesh_path=mesh_path, + mask_path=mask_path, + image_path=image_path, + device=device, + focal_length_json_path=focal_length_json_path + ) + + if result is not None: + # Save aligned mesh + output_mesh_path = os.path.join(output_dir, 'human_aligned.ply') + aligned_mesh = trimesh.Trimesh( + vertices=result['aligned_vertices_opengl'], + faces=result['faces'] + ) + aligned_mesh.export(output_mesh_path) + + print(f" SUCCESS! Saved aligned mesh to: {output_mesh_path}") + return True, output_mesh_path, result + else: + print(" ERROR: Failed to process mesh alignment") + return False, None, None + + except Exception as e: + print(f" ERROR: Exception during processing: {e}") + import traceback + traceback.print_exc() + return False, None, None + + finally: + print(" Processing complete!") + + +def visualize_meshes_interactive(aligned_mesh_path, dfy_mesh_path, output_dir=None, share=True, height=600): + """ + Interactive Gradio-based 3D visualization of aligned human and object meshes. + + Args: + aligned_mesh_path: Path to aligned mesh PLY file + dfy_mesh_path: Path to 3Dfy Object file + output_dir: Directory to save combined GLB file (defaults to same dir as aligned_mesh_path) + share: Whether to create a public shareable link (default: True) + height: Height of the 3D viewer in pixels (default: 600) + + Returns: + tuple: (demo, combined_glb_path) - Gradio demo object and path to combined GLB file + """ + import gradio as gr + import numpy as np + + print("Loading meshes for interactive visualization...") + + try: + # Load aligned mesh (PLY) + aligned_mesh = trimesh.load(aligned_mesh_path) + print(f"Loaded aligned mesh: {len(aligned_mesh.vertices)} vertices") + + # Load 3Dfy mesh (PLY) + dfy_scene = trimesh.load(dfy_mesh_path) + + if hasattr(dfy_scene, 'dump'): + dfy_meshes = [geom for geom in dfy_scene.geometry.values() if hasattr(geom, 'vertices')] + if len(dfy_meshes) == 1: + dfy_mesh = dfy_meshes[0] + elif len(dfy_meshes) > 1: + dfy_mesh = trimesh.util.concatenate(dfy_meshes) + else: + raise ValueError("No valid meshes in PLY file") + else: + dfy_mesh = dfy_scene + + print(f"Loaded 3Dfy mesh: {len(dfy_mesh.vertices)} vertices") + + # Create combined scene + scene = trimesh.Scene() + + # Add both meshes with different colors + aligned_copy = aligned_mesh.copy() + aligned_copy.visual.vertex_colors = [255, 0, 0, 200] # Red for aligned human + scene.add_geometry(aligned_copy, node_name="sam3d_aligned_human") + + dfy_copy = dfy_mesh.copy() + dfy_copy.visual.vertex_colors = [0, 0, 255, 200] # Blue for 3Dfy object + scene.add_geometry(dfy_copy, node_name="dfy_object") + + # Determine output path + if output_dir is None: + output_dir = os.path.dirname(aligned_mesh_path) + os.makedirs(output_dir, exist_ok=True) + + # Save combined PLY by concatenating both meshes + combined_ply_path = os.path.join(output_dir, 'combined_scene.ply') + + # Ccombine the geometries for PLY output + if isinstance(dfy_mesh, trimesh.points.PointCloud): + # Convert point cloud to vertices-only mesh for combination + dfy_vertices = dfy_mesh.vertices + human_vertices = aligned_mesh.vertices + + # Combine vertices from both + all_vertices = np.vstack([human_vertices, dfy_vertices]) + + # Create colors: red for human, blue for object + human_colors = np.array([[255, 0, 0, 200]] * len(human_vertices)) + object_colors = np.array([[0, 0, 255, 200]] * len(dfy_vertices)) + all_colors = np.vstack([human_colors, object_colors]) + + # Create combined point cloud + combined_cloud = trimesh.points.PointCloud(vertices=all_vertices, colors=all_colors) + combined_cloud.export(combined_ply_path) + else: + # Both are meshes, use scene export + scene.export(combined_ply_path) + + print(f"Exported combined scene to: {combined_ply_path}") + + # Also save GLB for Gradio viewer (NOTE: GLB may not show point cloud object properly) + combined_glb_path = os.path.join(output_dir, 'combined_scene.glb') + scene.export(combined_glb_path) + print(f"Exported GLB for Gradio viewer to: {combined_glb_path}") + print("NOTE: Use PLY for complete data, GLB is for Gradio visualization only") + + # Create interactive Gradio viewer + with gr.Blocks() as demo: + gr.Markdown("# 3D Mesh Alignment Visualization") + gr.Markdown("**Red**: SAM 3D Body Aligned Human | **Blue**: SAM 3D Object") + gr.Model3D( + value=combined_glb_path, + label="Combined 3D Scene (Interactive)", + height=height + ) + + # Launch the viewer + print("Launching interactive 3D viewer...") + demo.launch(share=share) + + return demo, combined_glb_path + + except Exception as e: + print(f"ERROR in visualization: {e}") + import traceback + traceback.print_exc() + return None, None + + +def visualize_meshes_comparison(aligned_mesh_path, dfy_mesh_path, use_interactive=False): + """ + Simple visualization of both meshes in a single 3D plot. + + DEPRECATED: Use visualize_meshes_interactive() for better interactive visualization. + + Args: + aligned_mesh_path: Path to aligned mesh PLY file + dfy_mesh_path: Path to 3Dfy GLB file + use_interactive: Whether to attempt trimesh scene viewer (default: False) + + Returns: + tuple: (aligned_mesh, dfy_mesh) trimesh objects or (None, None) if failed + """ + import matplotlib.pyplot as plt + + print("Loading meshes for visualization...") + + try: + # Load aligned mesh (PLY) + aligned_mesh = trimesh.load(aligned_mesh_path) + print(f"Loaded aligned mesh: {len(aligned_mesh.vertices)} vertices") + + # Load 3Dfy mesh (GLB - handle scene structure) + dfy_scene = trimesh.load(dfy_mesh_path) + + if hasattr(dfy_scene, 'dump'): # It's a scene + dfy_meshes = [geom for geom in dfy_scene.geometry.values() if hasattr(geom, 'vertices')] + if len(dfy_meshes) == 1: + dfy_mesh = dfy_meshes[0] + elif len(dfy_meshes) > 1: + dfy_mesh = trimesh.util.concatenate(dfy_meshes) + else: + raise ValueError("No valid meshes in GLB file") + else: + dfy_mesh = dfy_scene + + print(f"Loaded 3Dfy mesh: {len(dfy_mesh.vertices)} vertices") + + # Create single 3D plot with both meshes + fig = plt.figure(figsize=(12, 10)) + ax = fig.add_subplot(111, projection='3d') + + # Plot both meshes in the same space + ax.scatter(dfy_mesh.vertices[:, 0], + dfy_mesh.vertices[:, 1], + dfy_mesh.vertices[:, 2], + c='blue', s=0.1, alpha=0.6, label='3Dfy Original') + + ax.scatter(aligned_mesh.vertices[:, 0], + aligned_mesh.vertices[:, 1], + aligned_mesh.vertices[:, 2], + c='red', s=0.1, alpha=0.6, label='SAM 3D Body Aligned') + + ax.set_title('Mesh Comparison: 3Dfy vs SAM 3D Body Aligned', fontsize=16, fontweight='bold') + ax.set_xlabel('X') + ax.set_ylabel('Y') + ax.set_zlabel('Z') + ax.legend() + + plt.tight_layout() + plt.show() + + # Optional trimesh scene viewer + if use_interactive: + try: + print("Creating trimesh scene...") + scene = trimesh.Scene() + + # Add both meshes with different colors + aligned_copy = aligned_mesh.copy() + aligned_copy.visual.vertex_colors = [255, 0, 0, 200] # Red + scene.add_geometry(aligned_copy, node_name="sam3d_aligned") + + dfy_copy = dfy_mesh.copy() + dfy_copy.visual.vertex_colors = [0, 0, 255, 200] # Blue + scene.add_geometry(dfy_copy, node_name="dfy_original") + + print("Opening interactive trimesh viewer...") + scene.show() + + except Exception as e: + print(f"Trimesh viewer not available: {e}") + + print("Visualization complete") + return aligned_mesh, dfy_mesh + + except Exception as e: + print(f"ERROR in visualization: {e}") + import traceback + traceback.print_exc() + return None, None \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/notebook/meshes/.gitignore b/reconstruction/modules/sam-3d-objects/notebook/meshes/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c96a04f008ee21e260b28f7701595ed59e2839e3 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/meshes/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/focal_length.json b/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/focal_length.json new file mode 100644 index 0000000000000000000000000000000000000000..a7a42bec8a66404e402cf818d34c290a12de1456 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/focal_length.json @@ -0,0 +1,3 @@ +{ + "focal_length": 1623.0897216796875 +} \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/human.ply b/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/human.ply new file mode 100644 index 0000000000000000000000000000000000000000..951a8f90b561427aa916a60df565dbe8ca308fcc --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/human.ply @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:713f81aa7216da33128d38172cd9451d28d7f7de505a7c0d4342519946f799cd +size 774686 diff --git a/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/mask_human.png b/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/mask_human.png new file mode 100644 index 0000000000000000000000000000000000000000..8f6f890a8f1c15daf264bb5bae30167f16b325aa --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3DB_results/mask_human.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:76cf87585fcf8de0eccbfcffa84fbde3734d047f8c00cf8af09d61c9433a7a3b +size 7202 diff --git a/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3Dfy_results/0.glb b/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3Dfy_results/0.glb new file mode 100644 index 0000000000000000000000000000000000000000..f898272477bf9ddc04fcb1f3af195d6d6f73ea38 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/notebook/meshes/human_object/3Dfy_results/0.glb @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42cbb25cbf6471839a908378fdeda7d0ad4cb21a53249aadcb5a2ee3222e3a28 +size 4090136 diff --git a/reconstruction/modules/sam-3d-objects/patching/hydra b/reconstruction/modules/sam-3d-objects/patching/hydra new file mode 100644 index 0000000000000000000000000000000000000000..bb9c4c2669132141d23cae6632ced41813b55e45 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/patching/hydra @@ -0,0 +1,16 @@ +#!/usr/bin/env python + +import os +import hydra +import urllib.request + +if hydra.__version__ != "1.3.2": + raise RuntimeError("different hydra version has been found, cannot patch") + +hydra_root = os.path.dirname(hydra.__file__) +utils_path = os.path.join(hydra_root, "core", "utils.py") + +urllib.request.urlretrieve( + "https://raw.githubusercontent.com/gleize/hydra/78f00766b5f37672aa7232ebbf01bdd74246bd60/hydra/core/utils.py", + utils_path, +) diff --git a/reconstruction/modules/sam-3d-objects/pyproject.toml b/reconstruction/modules/sam-3d-objects/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..f9421022fdf45615053f421a496dde0892a518cb --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/pyproject.toml @@ -0,0 +1,30 @@ +[build-system] +requires = ["hatchling", "hatch-requirements-txt"] +build-backend = "hatchling.build" + +[tool.hatch.envs.default.env-vars] +PIP_EXTRA_INDEX_URL = "https://pypi.ngc.nvidia.com https://download.pytorch.org/whl/cu121" + +[tool.hatch.metadata] +# for git-referenced dependencies +allow-direct-references = true + +[project] +name = "sam3d_objects" +version = "0.0.1" +# required for "hatch-requirements-txt" to work +dynamic = ["dependencies", "optional-dependencies"] + +[tool.hatch.build] +ignore-vcs = true +include = ["**/*.py"] +exclude = ["conftest.py", "*_test.py"] +packages = ["sam3d_objects"] + +[tool.hatch.metadata.hooks.requirements_txt] +files = ["requirements.txt"] + +[tool.hatch.metadata.hooks.requirements_txt.optional-dependencies] +p3d = ["requirements.p3d.txt"] +inference = ["requirements.inference.txt"] +dev = ["requirements.dev.txt"] diff --git a/reconstruction/modules/sam-3d-objects/requirements.dev.txt b/reconstruction/modules/sam-3d-objects/requirements.dev.txt new file mode 100644 index 0000000000000000000000000000000000000000..b00f80e73db54fe890a92f0adc12d8b9382a2398 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/requirements.dev.txt @@ -0,0 +1,4 @@ +pytest +findpydeps +pipdeptree +lovely_tensors diff --git a/reconstruction/modules/sam-3d-objects/requirements.inference.txt b/reconstruction/modules/sam-3d-objects/requirements.inference.txt new file mode 100644 index 0000000000000000000000000000000000000000..ca5784151bc3b242fc380c05c4e8758444bd17a5 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/requirements.inference.txt @@ -0,0 +1,4 @@ +kaolin==0.17.0 +gsplat @ git+https://github.com/nerfstudio-project/gsplat.git@2323de5905d5e90e035f792fe65bad0fedd413e7 +seaborn==0.13.2 +gradio==5.49.0 \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/requirements.p3d.txt b/reconstruction/modules/sam-3d-objects/requirements.p3d.txt new file mode 100644 index 0000000000000000000000000000000000000000..e91c068ade19578ba31d688ca6786aff59c8490c --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/requirements.p3d.txt @@ -0,0 +1,2 @@ +pytorch3d @ git+https://github.com/facebookresearch/pytorch3d.git@75ebeeaea0908c5527e7b1e305fbc7681382db47 +flash_attn==2.8.3 \ No newline at end of file diff --git a/reconstruction/modules/sam-3d-objects/requirements.txt b/reconstruction/modules/sam-3d-objects/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..9b4d16d98b5ca3932e662f47cf1904db254dcc9d --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/requirements.txt @@ -0,0 +1,88 @@ +astor==0.8.1 +async-timeout==4.0.3 +auto_gptq==0.7.1 +autoflake==2.3.1 +av==12.0.0 +bitsandbytes==0.43.0 +black==24.3.0 +bpy==4.3.0 +colorama==0.4.6 +conda-pack==0.7.1 +crcmod==1.7 +cuda-python==12.1.0 +dataclasses==0.6 +decord==0.6.0 +deprecation==2.1.0 +easydict==1.13 +einops-exts==0.0.4 +exceptiongroup==1.2.0 +fastavro==1.9.4 +fasteners==0.19 +flake8==7.0.0 +Flask==3.0.3 +fqdn==1.5.1 +ftfy==6.2.0 +fvcore==0.1.5.post20221221 +gdown==5.2.0 +h5py==3.12.1 +hdfs==2.7.3 +httplib2==0.22.0 +hydra-core==1.3.2 +hydra-submitit-launcher==1.2.0 +igraph==0.11.8 +imath==0.0.2 +isoduration==20.11.0 +jsonlines==4.0.0 +jsonpickle==3.0.4 +jsonpointer==2.4 +jupyter==1.1.1 +librosa==0.10.1 +lightning==2.3.3 +loguru==0.7.2 +mosaicml-streaming==0.7.5 +nvidia-cuda-nvcc-cu12==12.1.105 +nvidia-pyindex==1.0.9 +objsize==0.7.0 +open3d==0.18.0 +opencv-python==4.9.0.80 +OpenEXR==3.3.3 +optimum==1.18.1 +optree==0.14.1 +orjson==3.10.0 +panda3d-gltf==1.2.1 +pdoc3==0.10.0 +peft==0.10.0 +pip-system-certs==4.0 +point-cloud-utils==0.29.5 +polyscope==2.3.0 +pycocotools==2.0.7 +pydot==1.4.2 +pymeshfix==0.17.0 +pymongo==4.6.3 +pyrender==0.1.45 +PySocks==1.7.1 +pytest==8.1.1 +python-pycg==0.9.2 +randomname==0.2.1 +roma==1.5.1 +rootutils==1.0.7 +Rtree==1.3.0 +sagemaker==2.242.0 +scikit-image==0.23.1 +sentence-transformers==2.6.1 +simplejson==3.19.2 +smplx==0.1.28 +spconv-cu121==2.3.8 +tensorboard==2.16.2 +timm==0.9.16 +tomli==2.0.1 +torchaudio==2.5.1+cu121 +uri-template==1.3.0 +usort==1.0.8.post1 +wandb==0.20.0 +webcolors==1.13 +webdataset==0.2.86 +Werkzeug==3.0.6 +xatlas==0.0.9 +xformers==0.0.28.post3 +MoGe @ git+https://github.com/microsoft/MoGe.git@a8c37341bc0325ca99b9d57981cc3bb2bd3e255b diff --git a/reconstruction/modules/sam-3d-objects/sam3d_objects/__init__.py b/reconstruction/modules/sam-3d-objects/sam3d_objects/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a700544f5c8388939eff112e419a851dbabf7671 --- /dev/null +++ b/reconstruction/modules/sam-3d-objects/sam3d_objects/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +import os + +# Allow skipping initialization for lightweight tools +if not os.environ.get('LIDRA_SKIP_INIT'): + import sam3d_objects.init