Upload third-party source (skip LFS pointer assets) (part 8)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- third-party/InterFormer/mmseg.yaml +257 -0
- third-party/InterFormer/mmseg/datasets/transforms/__init__.py +30 -0
- third-party/InterFormer/mmseg/datasets/transforms/__pycache__/__init__.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/datasets/transforms/__pycache__/formatting.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/datasets/transforms/__pycache__/loading.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/datasets/transforms/__pycache__/transforms.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/datasets/transforms/formatting.py +112 -0
- third-party/InterFormer/mmseg/datasets/transforms/loading.py +771 -0
- third-party/InterFormer/mmseg/datasets/transforms/transforms.py +2537 -0
- third-party/InterFormer/mmseg/datasets/voc.py +40 -0
- third-party/InterFormer/mmseg/engine/__init__.py +12 -0
- third-party/InterFormer/mmseg/engine/__pycache__/__init__.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/engine/hooks/__init__.py +4 -0
- third-party/InterFormer/mmseg/engine/hooks/__pycache__/__init__.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/engine/hooks/__pycache__/visualization_hook.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/engine/hooks/visualization_hook.py +129 -0
- third-party/InterFormer/mmseg/engine/optimizers/__init__.py +9 -0
- third-party/InterFormer/mmseg/engine/optimizers/__pycache__/__init__.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/engine/optimizers/__pycache__/force_default_constructor.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/engine/optimizers/__pycache__/layer_decay_optimizer_constructor.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/engine/optimizers/force_default_constructor.py +255 -0
- third-party/InterFormer/mmseg/engine/optimizers/layer_decay_optimizer_constructor.py +207 -0
- third-party/InterFormer/mmseg/engine/schedulers/__init__.py +4 -0
- third-party/InterFormer/mmseg/engine/schedulers/__pycache__/__init__.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/engine/schedulers/__pycache__/poly_ratio_scheduler.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/engine/schedulers/poly_ratio_scheduler.py +62 -0
- third-party/InterFormer/mmseg/evaluation/__init__.py +4 -0
- third-party/InterFormer/mmseg/evaluation/__pycache__/__init__.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/evaluation/metrics/__init__.py +6 -0
- third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/__init__.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/citys_metric.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/depth_metric.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/iou_metric.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/evaluation/metrics/citys_metric.py +158 -0
- third-party/InterFormer/mmseg/evaluation/metrics/depth_metric.py +212 -0
- third-party/InterFormer/mmseg/evaluation/metrics/iou_metric.py +286 -0
- third-party/InterFormer/mmseg/models/__init__.py +16 -0
- third-party/InterFormer/mmseg/models/__pycache__/__init__.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/models/__pycache__/builder.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/models/__pycache__/data_preprocessor.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/models/assigners/__init__.py +12 -0
- third-party/InterFormer/mmseg/models/assigners/__pycache__/__init__.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/models/assigners/__pycache__/base_assigner.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/models/assigners/__pycache__/hungarian_assigner.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/models/assigners/__pycache__/match_cost.cpython-38.pyc +0 -0
- third-party/InterFormer/mmseg/models/assigners/base_assigner.py +18 -0
- third-party/InterFormer/mmseg/models/assigners/hungarian_assigner.py +86 -0
- third-party/InterFormer/mmseg/models/assigners/match_cost.py +231 -0
- third-party/InterFormer/mmseg/models/backbones/__init__.py +35 -0
- third-party/InterFormer/mmseg/models/backbones/__pycache__/__init__.cpython-38.pyc +0 -0
third-party/InterFormer/mmseg.yaml
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: mmseg
|
| 2 |
+
channels:
|
| 3 |
+
- pytorch
|
| 4 |
+
- nvidia
|
| 5 |
+
- defaults
|
| 6 |
+
dependencies:
|
| 7 |
+
- _libgcc_mutex=0.1=main
|
| 8 |
+
- _openmp_mutex=5.1=1_gnu
|
| 9 |
+
- blas=1.0=mkl
|
| 10 |
+
- brotlipy=0.7.0=py310h7f8727e_1002
|
| 11 |
+
- bzip2=1.0.8=h7b6447c_0
|
| 12 |
+
- ca-certificates=2023.05.30=h06a4308_0
|
| 13 |
+
- certifi=2023.5.7=py310h06a4308_0
|
| 14 |
+
- cffi=1.15.1=py310h5eee18b_3
|
| 15 |
+
- charset-normalizer=2.0.4=pyhd3eb1b0_0
|
| 16 |
+
- cryptography=39.0.1=py310h9ce1e76_2
|
| 17 |
+
- cuda=11.6.1=0
|
| 18 |
+
- cuda-cccl=11.6.55=hf6102b2_0
|
| 19 |
+
- cuda-command-line-tools=11.6.2=0
|
| 20 |
+
- cuda-compiler=11.6.2=0
|
| 21 |
+
- cuda-cudart=11.6.55=he381448_0
|
| 22 |
+
- cuda-cudart-dev=11.6.55=h42ad0f4_0
|
| 23 |
+
- cuda-cuobjdump=11.6.124=h2eeebcb_0
|
| 24 |
+
- cuda-cupti=11.6.124=h86345e5_0
|
| 25 |
+
- cuda-cuxxfilt=11.6.124=hecbf4f6_0
|
| 26 |
+
- cuda-driver-dev=11.6.55=0
|
| 27 |
+
- cuda-gdb=12.1.105=0
|
| 28 |
+
- cuda-libraries=11.6.1=0
|
| 29 |
+
- cuda-libraries-dev=11.6.1=0
|
| 30 |
+
- cuda-memcheck=11.8.86=0
|
| 31 |
+
- cuda-nsight=12.1.105=0
|
| 32 |
+
- cuda-nsight-compute=12.1.1=0
|
| 33 |
+
- cuda-nvcc=11.6.124=hbba6d2d_0
|
| 34 |
+
- cuda-nvdisasm=12.1.105=0
|
| 35 |
+
- cuda-nvml-dev=11.6.55=haa9ef22_0
|
| 36 |
+
- cuda-nvprof=12.1.105=0
|
| 37 |
+
- cuda-nvprune=11.6.124=he22ec0a_0
|
| 38 |
+
- cuda-nvrtc=11.6.124=h020bade_0
|
| 39 |
+
- cuda-nvrtc-dev=11.6.124=h249d397_0
|
| 40 |
+
- cuda-nvtx=11.6.124=h0630a44_0
|
| 41 |
+
- cuda-nvvp=12.1.105=0
|
| 42 |
+
- cuda-runtime=11.6.1=0
|
| 43 |
+
- cuda-samples=11.6.101=h8efea70_0
|
| 44 |
+
- cuda-sanitizer-api=12.1.105=0
|
| 45 |
+
- cuda-toolkit=11.6.1=0
|
| 46 |
+
- cuda-tools=11.6.1=0
|
| 47 |
+
- cuda-visual-tools=11.6.1=0
|
| 48 |
+
- ffmpeg=4.2.2=h20bf706_0
|
| 49 |
+
- freetype=2.12.1=h4a9f257_0
|
| 50 |
+
- gds-tools=1.6.1.9=0
|
| 51 |
+
- giflib=5.2.1=h5eee18b_3
|
| 52 |
+
- gmp=6.2.1=h295c915_3
|
| 53 |
+
- gnutls=3.6.15=he1e5248_0
|
| 54 |
+
- idna=3.4=py310h06a4308_0
|
| 55 |
+
- intel-openmp=2023.1.0=hdb19cb5_46305
|
| 56 |
+
- jpeg=9e=h5eee18b_1
|
| 57 |
+
- lame=3.100=h7b6447c_0
|
| 58 |
+
- lcms2=2.12=h3be6417_0
|
| 59 |
+
- ld_impl_linux-64=2.38=h1181459_1
|
| 60 |
+
- lerc=3.0=h295c915_0
|
| 61 |
+
- libcublas=11.9.2.110=h5e84587_0
|
| 62 |
+
- libcublas-dev=11.9.2.110=h5c901ab_0
|
| 63 |
+
- libcufft=10.7.1.112=hf425ae0_0
|
| 64 |
+
- libcufft-dev=10.7.1.112=ha5ce4c0_0
|
| 65 |
+
- libcufile=1.6.1.9=0
|
| 66 |
+
- libcufile-dev=1.6.1.9=0
|
| 67 |
+
- libcurand=10.3.2.106=0
|
| 68 |
+
- libcurand-dev=10.3.2.106=0
|
| 69 |
+
- libcusolver=11.3.4.124=h33c3c4e_0
|
| 70 |
+
- libcusparse=11.7.2.124=h7538f96_0
|
| 71 |
+
- libcusparse-dev=11.7.2.124=hbbe9722_0
|
| 72 |
+
- libdeflate=1.17=h5eee18b_0
|
| 73 |
+
- libffi=3.4.4=h6a678d5_0
|
| 74 |
+
- libgcc-ng=11.2.0=h1234567_1
|
| 75 |
+
- libgomp=11.2.0=h1234567_1
|
| 76 |
+
- libidn2=2.3.4=h5eee18b_0
|
| 77 |
+
- libnpp=11.6.3.124=hd2722f0_0
|
| 78 |
+
- libnpp-dev=11.6.3.124=h3c42840_0
|
| 79 |
+
- libnvjpeg=11.6.2.124=hd473ad6_0
|
| 80 |
+
- libnvjpeg-dev=11.6.2.124=hb5906b9_0
|
| 81 |
+
- libopus=1.3.1=h7b6447c_0
|
| 82 |
+
- libpng=1.6.39=h5eee18b_0
|
| 83 |
+
- libstdcxx-ng=11.2.0=h1234567_1
|
| 84 |
+
- libtasn1=4.19.0=h5eee18b_0
|
| 85 |
+
- libtiff=4.5.0=h6a678d5_2
|
| 86 |
+
- libunistring=0.9.10=h27cfd23_0
|
| 87 |
+
- libuuid=1.41.5=h5eee18b_0
|
| 88 |
+
- libvpx=1.7.0=h439df22_0
|
| 89 |
+
- libwebp=1.2.4=h11a3e52_1
|
| 90 |
+
- libwebp-base=1.2.4=h5eee18b_1
|
| 91 |
+
- lz4-c=1.9.4=h6a678d5_0
|
| 92 |
+
- mkl=2023.1.0=h6d00ec8_46342
|
| 93 |
+
- mkl-service=2.4.0=py310h5eee18b_1
|
| 94 |
+
- mkl_fft=1.3.6=py310h1128e8f_1
|
| 95 |
+
- mkl_random=1.2.2=py310h1128e8f_1
|
| 96 |
+
- ncurses=6.4=h6a678d5_0
|
| 97 |
+
- nettle=3.7.3=hbbd107a_1
|
| 98 |
+
- nsight-compute=2023.1.1.4=0
|
| 99 |
+
- numpy=1.25.0=py310h5f9d8c6_0
|
| 100 |
+
- numpy-base=1.25.0=py310hb5e798b_0
|
| 101 |
+
- openh264=2.1.1=h4ff587b_0
|
| 102 |
+
- openssl=3.0.9=h7f8727e_0
|
| 103 |
+
- pillow=9.4.0=py310h6a678d5_0
|
| 104 |
+
- pip=23.1.2=py310h06a4308_0
|
| 105 |
+
- pycparser=2.21=pyhd3eb1b0_0
|
| 106 |
+
- pyopenssl=23.0.0=py310h06a4308_0
|
| 107 |
+
- pysocks=1.7.1=py310h06a4308_0
|
| 108 |
+
- python=3.10.11=h955ad1f_3
|
| 109 |
+
- pytorch=1.13.1=py3.10_cuda11.6_cudnn8.3.2_0
|
| 110 |
+
- pytorch-cuda=11.6=h867d48c_1
|
| 111 |
+
- pytorch-mutex=1.0=cuda
|
| 112 |
+
- readline=8.2=h5eee18b_0
|
| 113 |
+
- sqlite=3.41.2=h5eee18b_0
|
| 114 |
+
- tbb=2021.8.0=hdb19cb5_0
|
| 115 |
+
- tk=8.6.12=h1ccaba5_0
|
| 116 |
+
- torchaudio=0.13.1=py310_cu116
|
| 117 |
+
- torchvision=0.14.1=py310_cu116
|
| 118 |
+
- typing_extensions=4.6.3=py310h06a4308_0
|
| 119 |
+
- urllib3=1.26.16=py310h06a4308_0
|
| 120 |
+
- x264=1!157.20191217=h7b6447c_0
|
| 121 |
+
- xz=5.4.2=h5eee18b_0
|
| 122 |
+
- zlib=1.2.13=h5eee18b_0
|
| 123 |
+
- zstd=1.5.5=hc292b87_0
|
| 124 |
+
- pip:
|
| 125 |
+
- absl-py==2.1.0
|
| 126 |
+
- addict==2.4.0
|
| 127 |
+
- aiohappyeyeballs==2.6.1
|
| 128 |
+
- aiohttp==3.12.15
|
| 129 |
+
- aiosignal==1.4.0
|
| 130 |
+
- aliyun-python-sdk-core==2.15.1
|
| 131 |
+
- aliyun-python-sdk-kms==2.16.3
|
| 132 |
+
- asttokens==2.4.1
|
| 133 |
+
- async-timeout==5.0.1
|
| 134 |
+
- attrs==25.3.0
|
| 135 |
+
- basicsr==0.0.0
|
| 136 |
+
- beautifulsoup4==4.12.3
|
| 137 |
+
- cachetools==5.3.3
|
| 138 |
+
- click==8.1.7
|
| 139 |
+
- colorama==0.4.6
|
| 140 |
+
- contourpy==1.2.1
|
| 141 |
+
- crcmod==1.7
|
| 142 |
+
- cycler==0.12.1
|
| 143 |
+
- datasets==4.0.0
|
| 144 |
+
- decorator==5.1.1
|
| 145 |
+
- dill==0.3.8
|
| 146 |
+
- einops==0.8.0
|
| 147 |
+
- exceptiongroup==1.2.2
|
| 148 |
+
- executing==2.0.1
|
| 149 |
+
- filelock==3.14.0
|
| 150 |
+
- fonttools==4.51.0
|
| 151 |
+
- frozenlist==1.7.0
|
| 152 |
+
- fsspec==2024.5.0
|
| 153 |
+
- ftfy==6.2.0
|
| 154 |
+
- future==1.0.0
|
| 155 |
+
- fvcore==0.1.5.post20221221
|
| 156 |
+
- gdown==5.2.0
|
| 157 |
+
- google-auth==2.29.0
|
| 158 |
+
- google-auth-oauthlib==1.0.0
|
| 159 |
+
- grpcio==1.63.0
|
| 160 |
+
- h5py==3.11.0
|
| 161 |
+
- hf-xet==1.1.7
|
| 162 |
+
- huggingface-hub==0.34.4
|
| 163 |
+
- imageio==2.34.1
|
| 164 |
+
- importlib-metadata==7.1.0
|
| 165 |
+
- iopath==0.1.10
|
| 166 |
+
- ipdb==0.13.13
|
| 167 |
+
- ipython==8.26.0
|
| 168 |
+
- jedi==0.19.1
|
| 169 |
+
- jmespath==0.10.0
|
| 170 |
+
- kiwisolver==1.4.5
|
| 171 |
+
- lazy-loader==0.4
|
| 172 |
+
- lmdb==1.7.2
|
| 173 |
+
- markdown==3.6
|
| 174 |
+
- markdown-it-py==3.0.0
|
| 175 |
+
- markupsafe==2.1.5
|
| 176 |
+
- matplotlib==3.9.0
|
| 177 |
+
- matplotlib-inline==0.1.7
|
| 178 |
+
- mdurl==0.1.2
|
| 179 |
+
- mmcv==2.0.0
|
| 180 |
+
- mmdet==3.3.0
|
| 181 |
+
- mmengine==0.10.4
|
| 182 |
+
- mmsegmentation==1.2.2
|
| 183 |
+
- model-index==0.1.11
|
| 184 |
+
- modelscope==1.30.0
|
| 185 |
+
- multidict==6.6.4
|
| 186 |
+
- multiprocess==0.70.16
|
| 187 |
+
- networkx==3.3
|
| 188 |
+
- oauthlib==3.2.2
|
| 189 |
+
- omegaconf==2.4.0.dev3
|
| 190 |
+
- opencv-python==4.9.0.80
|
| 191 |
+
- opendatalab==0.0.10
|
| 192 |
+
- openmim==0.3.9
|
| 193 |
+
- openxlab==0.0.38
|
| 194 |
+
- ordered-set==4.1.0
|
| 195 |
+
- oss2==2.17.0
|
| 196 |
+
- packaging==24.0
|
| 197 |
+
- pandas==2.2.2
|
| 198 |
+
- parso==0.8.4
|
| 199 |
+
- pexpect==4.9.0
|
| 200 |
+
- platformdirs==4.2.2
|
| 201 |
+
- portalocker==3.2.0
|
| 202 |
+
- prettytable==3.10.0
|
| 203 |
+
- prompt-toolkit==3.0.47
|
| 204 |
+
- propcache==0.3.2
|
| 205 |
+
- protobuf==3.20.3
|
| 206 |
+
- psutil==6.0.0
|
| 207 |
+
- ptyprocess==0.7.0
|
| 208 |
+
- pure-eval==0.2.2
|
| 209 |
+
- pyarrow==21.0.0
|
| 210 |
+
- pyasn1==0.6.0
|
| 211 |
+
- pyasn1-modules==0.4.0
|
| 212 |
+
- pycocotools==2.0.7
|
| 213 |
+
- pycryptodome==3.20.0
|
| 214 |
+
- pygments==2.18.0
|
| 215 |
+
- pyparsing==3.1.2
|
| 216 |
+
- python-dateutil==2.9.0.post0
|
| 217 |
+
- pytz==2023.4
|
| 218 |
+
- pyyaml==6.0.1
|
| 219 |
+
- regex==2024.5.15
|
| 220 |
+
- requests==2.32.4
|
| 221 |
+
- requests-oauthlib==2.0.0
|
| 222 |
+
- rich==13.4.2
|
| 223 |
+
- rsa==4.9
|
| 224 |
+
- safetensors==0.4.3
|
| 225 |
+
- scikit-image==0.23.2
|
| 226 |
+
- scipy==1.13.0
|
| 227 |
+
- seaborn==0.13.2
|
| 228 |
+
- setuptools==60.2.0
|
| 229 |
+
- shapely==2.0.4
|
| 230 |
+
- six==1.16.0
|
| 231 |
+
- smmap==5.0.1
|
| 232 |
+
- soupsieve==2.6
|
| 233 |
+
- stack-data==0.6.3
|
| 234 |
+
- tabulate==0.9.0
|
| 235 |
+
- tb-nightly==2.21.0a20250719
|
| 236 |
+
- tensorboard==2.13.0
|
| 237 |
+
- tensorboard-data-server==0.7.0
|
| 238 |
+
- tensorboardx==2.6
|
| 239 |
+
- termcolor==2.3.0
|
| 240 |
+
- terminaltables==3.1.10
|
| 241 |
+
- thop==0.1.1-2209072238
|
| 242 |
+
- threadpoolctl==3.1.0
|
| 243 |
+
- tifffile==2024.5.10
|
| 244 |
+
- timm==1.0.3
|
| 245 |
+
- tomli==2.0.1
|
| 246 |
+
- tqdm==4.67.1
|
| 247 |
+
- traitlets==5.14.3
|
| 248 |
+
- tzdata==2024.1
|
| 249 |
+
- wcwidth==0.2.13
|
| 250 |
+
- werkzeug==3.0.3
|
| 251 |
+
- wheel==0.26.0
|
| 252 |
+
- xxhash==3.5.0
|
| 253 |
+
- yacs==0.1.8
|
| 254 |
+
- yapf==0.40.2
|
| 255 |
+
- yarl==1.20.1
|
| 256 |
+
- zipp==3.18.2
|
| 257 |
+
prefix: /home/suyuejiao/anaconda3/envs/mmseg
|
third-party/InterFormer/mmseg/datasets/transforms/__init__.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .formatting import PackSegInputs
|
| 3 |
+
from .loading import (LoadAnnotations, LoadBiomedicalAnnotation,
|
| 4 |
+
LoadBiomedicalData, LoadBiomedicalImageFromFile,
|
| 5 |
+
LoadDepthAnnotation, LoadImageFromNDArray,
|
| 6 |
+
LoadMultipleRSImageFromFile, LoadSingleRSImageFromFile)
|
| 7 |
+
# yapf: disable
|
| 8 |
+
from .transforms import (CLAHE, AdjustGamma, Albu, BioMedical3DPad,
|
| 9 |
+
BioMedical3DRandomCrop, BioMedical3DRandomFlip,
|
| 10 |
+
BioMedicalGaussianBlur, BioMedicalGaussianNoise,
|
| 11 |
+
BioMedicalRandomGamma, ConcatCDInput, GenerateEdge,
|
| 12 |
+
PhotoMetricDistortion, RandomCrop, RandomCutOut,
|
| 13 |
+
RandomDepthMix, RandomFlip, RandomMosaic,
|
| 14 |
+
RandomRotate, RandomRotFlip, Rerange, Resize,
|
| 15 |
+
ResizeShortestEdge, ResizeToMultiple, RGB2Gray,
|
| 16 |
+
SegRescale)
|
| 17 |
+
|
| 18 |
+
# yapf: enable
|
| 19 |
+
__all__ = [
|
| 20 |
+
'LoadAnnotations', 'RandomCrop', 'BioMedical3DRandomCrop', 'SegRescale',
|
| 21 |
+
'PhotoMetricDistortion', 'RandomRotate', 'AdjustGamma', 'CLAHE', 'Rerange',
|
| 22 |
+
'RGB2Gray', 'RandomCutOut', 'RandomMosaic', 'PackSegInputs',
|
| 23 |
+
'ResizeToMultiple', 'LoadImageFromNDArray', 'LoadBiomedicalImageFromFile',
|
| 24 |
+
'LoadBiomedicalAnnotation', 'LoadBiomedicalData', 'GenerateEdge',
|
| 25 |
+
'ResizeShortestEdge', 'BioMedicalGaussianNoise', 'BioMedicalGaussianBlur',
|
| 26 |
+
'BioMedical3DRandomFlip', 'BioMedicalRandomGamma', 'BioMedical3DPad',
|
| 27 |
+
'RandomRotFlip', 'Albu', 'LoadSingleRSImageFromFile', 'ConcatCDInput',
|
| 28 |
+
'LoadMultipleRSImageFromFile', 'LoadDepthAnnotation', 'RandomDepthMix',
|
| 29 |
+
'RandomFlip', 'Resize'
|
| 30 |
+
]
|
third-party/InterFormer/mmseg/datasets/transforms/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (1.47 kB). View file
|
|
|
third-party/InterFormer/mmseg/datasets/transforms/__pycache__/formatting.cpython-38.pyc
ADDED
|
Binary file (3.75 kB). View file
|
|
|
third-party/InterFormer/mmseg/datasets/transforms/__pycache__/loading.cpython-38.pyc
ADDED
|
Binary file (21 kB). View file
|
|
|
third-party/InterFormer/mmseg/datasets/transforms/__pycache__/transforms.cpython-38.pyc
ADDED
|
Binary file (76.4 kB). View file
|
|
|
third-party/InterFormer/mmseg/datasets/transforms/formatting.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import warnings
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from mmcv.transforms import to_tensor
|
| 6 |
+
from mmcv.transforms.base import BaseTransform
|
| 7 |
+
from mmengine.structures import PixelData
|
| 8 |
+
|
| 9 |
+
from mmseg.registry import TRANSFORMS
|
| 10 |
+
from mmseg.structures import SegDataSample
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@TRANSFORMS.register_module()
|
| 14 |
+
class PackSegInputs(BaseTransform):
|
| 15 |
+
"""Pack the inputs data for the semantic segmentation.
|
| 16 |
+
|
| 17 |
+
The ``img_meta`` item is always populated. The contents of the
|
| 18 |
+
``img_meta`` dictionary depends on ``meta_keys``. By default this includes:
|
| 19 |
+
|
| 20 |
+
- ``img_path``: filename of the image
|
| 21 |
+
|
| 22 |
+
- ``ori_shape``: original shape of the image as a tuple (h, w, c)
|
| 23 |
+
|
| 24 |
+
- ``img_shape``: shape of the image input to the network as a tuple \
|
| 25 |
+
(h, w, c). Note that images may be zero padded on the \
|
| 26 |
+
bottom/right if the batch tensor is larger than this shape.
|
| 27 |
+
|
| 28 |
+
- ``pad_shape``: shape of padded images
|
| 29 |
+
|
| 30 |
+
- ``scale_factor``: a float indicating the preprocessing scale
|
| 31 |
+
|
| 32 |
+
- ``flip``: a boolean indicating if image flip transform was used
|
| 33 |
+
|
| 34 |
+
- ``flip_direction``: the flipping direction
|
| 35 |
+
|
| 36 |
+
Args:
|
| 37 |
+
meta_keys (Sequence[str], optional): Meta keys to be packed from
|
| 38 |
+
``SegDataSample`` and collected in ``data[img_metas]``.
|
| 39 |
+
Default: ``('img_path', 'ori_shape',
|
| 40 |
+
'img_shape', 'pad_shape', 'scale_factor', 'flip',
|
| 41 |
+
'flip_direction')``
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self,
|
| 45 |
+
meta_keys=('img_path', 'seg_map_path', 'ori_shape',
|
| 46 |
+
'img_shape', 'pad_shape', 'scale_factor', 'flip',
|
| 47 |
+
'flip_direction', 'reduce_zero_label')):
|
| 48 |
+
self.meta_keys = meta_keys
|
| 49 |
+
|
| 50 |
+
def transform(self, results: dict) -> dict:
|
| 51 |
+
"""Method to pack the input data.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
results (dict): Result dict from the data pipeline.
|
| 55 |
+
|
| 56 |
+
Returns:
|
| 57 |
+
dict:
|
| 58 |
+
|
| 59 |
+
- 'inputs' (obj:`torch.Tensor`): The forward data of models.
|
| 60 |
+
- 'data_sample' (obj:`SegDataSample`): The annotation info of the
|
| 61 |
+
sample.
|
| 62 |
+
"""
|
| 63 |
+
packed_results = dict()
|
| 64 |
+
if 'img' in results:
|
| 65 |
+
img = results['img']
|
| 66 |
+
if len(img.shape) < 3:
|
| 67 |
+
img = np.expand_dims(img, -1)
|
| 68 |
+
if not img.flags.c_contiguous:
|
| 69 |
+
img = to_tensor(np.ascontiguousarray(img.transpose(2, 0, 1)))
|
| 70 |
+
else:
|
| 71 |
+
img = img.transpose(2, 0, 1)
|
| 72 |
+
img = to_tensor(img).contiguous()
|
| 73 |
+
packed_results['inputs'] = img
|
| 74 |
+
|
| 75 |
+
data_sample = SegDataSample()
|
| 76 |
+
if 'gt_seg_map' in results:
|
| 77 |
+
if len(results['gt_seg_map'].shape) == 2:
|
| 78 |
+
data = to_tensor(results['gt_seg_map'][None,
|
| 79 |
+
...].astype(np.int64))
|
| 80 |
+
else:
|
| 81 |
+
warnings.warn('Please pay attention your ground truth '
|
| 82 |
+
'segmentation map, usually the segmentation '
|
| 83 |
+
'map is 2D, but got '
|
| 84 |
+
f'{results["gt_seg_map"].shape}')
|
| 85 |
+
data = to_tensor(results['gt_seg_map'].astype(np.int64))
|
| 86 |
+
gt_sem_seg_data = dict(data=data)
|
| 87 |
+
data_sample.gt_sem_seg = PixelData(**gt_sem_seg_data)
|
| 88 |
+
|
| 89 |
+
if 'gt_edge_map' in results:
|
| 90 |
+
gt_edge_data = dict(
|
| 91 |
+
data=to_tensor(results['gt_edge_map'][None,
|
| 92 |
+
...].astype(np.int64)))
|
| 93 |
+
data_sample.set_data(dict(gt_edge_map=PixelData(**gt_edge_data)))
|
| 94 |
+
|
| 95 |
+
if 'gt_depth_map' in results:
|
| 96 |
+
gt_depth_data = dict(
|
| 97 |
+
data=to_tensor(results['gt_depth_map'][None, ...]))
|
| 98 |
+
data_sample.set_data(dict(gt_depth_map=PixelData(**gt_depth_data)))
|
| 99 |
+
|
| 100 |
+
img_meta = {}
|
| 101 |
+
for key in self.meta_keys:
|
| 102 |
+
if key in results:
|
| 103 |
+
img_meta[key] = results[key]
|
| 104 |
+
data_sample.set_metainfo(img_meta)
|
| 105 |
+
packed_results['data_samples'] = data_sample
|
| 106 |
+
|
| 107 |
+
return packed_results
|
| 108 |
+
|
| 109 |
+
def __repr__(self) -> str:
|
| 110 |
+
repr_str = self.__class__.__name__
|
| 111 |
+
repr_str += f'(meta_keys={self.meta_keys})'
|
| 112 |
+
return repr_str
|
third-party/InterFormer/mmseg/datasets/transforms/loading.py
ADDED
|
@@ -0,0 +1,771 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import warnings
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Dict, Optional, Union
|
| 5 |
+
|
| 6 |
+
import mmcv
|
| 7 |
+
import mmengine.fileio as fileio
|
| 8 |
+
import numpy as np
|
| 9 |
+
from mmcv.transforms import BaseTransform
|
| 10 |
+
from mmcv.transforms import LoadAnnotations as MMCV_LoadAnnotations
|
| 11 |
+
from mmcv.transforms import LoadImageFromFile
|
| 12 |
+
|
| 13 |
+
from mmseg.registry import TRANSFORMS
|
| 14 |
+
from mmseg.utils import datafrombytes
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
from osgeo import gdal
|
| 18 |
+
except ImportError:
|
| 19 |
+
gdal = None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@TRANSFORMS.register_module()
|
| 23 |
+
class LoadAnnotations(MMCV_LoadAnnotations):
|
| 24 |
+
"""Load annotations for semantic segmentation provided by dataset.
|
| 25 |
+
|
| 26 |
+
The annotation format is as the following:
|
| 27 |
+
|
| 28 |
+
.. code-block:: python
|
| 29 |
+
|
| 30 |
+
{
|
| 31 |
+
# Filename of semantic segmentation ground truth file.
|
| 32 |
+
'seg_map_path': 'a/b/c'
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
After this module, the annotation has been changed to the format below:
|
| 36 |
+
|
| 37 |
+
.. code-block:: python
|
| 38 |
+
|
| 39 |
+
{
|
| 40 |
+
# in str
|
| 41 |
+
'seg_fields': List
|
| 42 |
+
# In uint8 type.
|
| 43 |
+
'gt_seg_map': np.ndarray (H, W)
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
Required Keys:
|
| 47 |
+
|
| 48 |
+
- seg_map_path (str): Path of semantic segmentation ground truth file.
|
| 49 |
+
|
| 50 |
+
Added Keys:
|
| 51 |
+
|
| 52 |
+
- seg_fields (List)
|
| 53 |
+
- gt_seg_map (np.uint8)
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
reduce_zero_label (bool, optional): Whether reduce all label value
|
| 57 |
+
by 1. Usually used for datasets where 0 is background label.
|
| 58 |
+
Defaults to None.
|
| 59 |
+
imdecode_backend (str): The image decoding backend type. The backend
|
| 60 |
+
argument for :func:``mmcv.imfrombytes``.
|
| 61 |
+
See :fun:``mmcv.imfrombytes`` for details.
|
| 62 |
+
Defaults to 'pillow'.
|
| 63 |
+
backend_args (dict): Arguments to instantiate a file backend.
|
| 64 |
+
See https://mmengine.readthedocs.io/en/latest/api/fileio.htm
|
| 65 |
+
for details. Defaults to None.
|
| 66 |
+
Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(
|
| 70 |
+
self,
|
| 71 |
+
reduce_zero_label=None,
|
| 72 |
+
backend_args=None,
|
| 73 |
+
imdecode_backend='pillow',
|
| 74 |
+
) -> None:
|
| 75 |
+
super().__init__(
|
| 76 |
+
with_bbox=False,
|
| 77 |
+
with_label=False,
|
| 78 |
+
with_seg=True,
|
| 79 |
+
with_keypoints=False,
|
| 80 |
+
imdecode_backend=imdecode_backend,
|
| 81 |
+
backend_args=backend_args)
|
| 82 |
+
self.reduce_zero_label = reduce_zero_label
|
| 83 |
+
if self.reduce_zero_label is not None:
|
| 84 |
+
warnings.warn('`reduce_zero_label` will be deprecated, '
|
| 85 |
+
'if you would like to ignore the zero label, please '
|
| 86 |
+
'set `reduce_zero_label=True` when dataset '
|
| 87 |
+
'initialized')
|
| 88 |
+
self.imdecode_backend = imdecode_backend
|
| 89 |
+
|
| 90 |
+
def _load_seg_map(self, results: dict) -> None:
|
| 91 |
+
"""Private function to load semantic segmentation annotations.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
results (dict): Result dict from :obj:``mmcv.BaseDataset``.
|
| 95 |
+
|
| 96 |
+
Returns:
|
| 97 |
+
dict: The dict contains loaded semantic segmentation annotations.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
img_bytes = fileio.get(
|
| 101 |
+
results['seg_map_path'], backend_args=self.backend_args)
|
| 102 |
+
gt_semantic_seg = mmcv.imfrombytes(
|
| 103 |
+
img_bytes, flag='unchanged',
|
| 104 |
+
backend=self.imdecode_backend).squeeze().astype(np.uint8)
|
| 105 |
+
|
| 106 |
+
# reduce zero_label
|
| 107 |
+
if self.reduce_zero_label is None:
|
| 108 |
+
self.reduce_zero_label = results['reduce_zero_label']
|
| 109 |
+
assert self.reduce_zero_label == results['reduce_zero_label'], \
|
| 110 |
+
'Initialize dataset with `reduce_zero_label` as ' \
|
| 111 |
+
f'{results["reduce_zero_label"]} but when load annotation ' \
|
| 112 |
+
f'the `reduce_zero_label` is {self.reduce_zero_label}'
|
| 113 |
+
if self.reduce_zero_label:
|
| 114 |
+
# avoid using underflow conversion
|
| 115 |
+
gt_semantic_seg[gt_semantic_seg == 0] = 255
|
| 116 |
+
gt_semantic_seg = gt_semantic_seg - 1
|
| 117 |
+
gt_semantic_seg[gt_semantic_seg == 254] = 255
|
| 118 |
+
# modify if custom classes
|
| 119 |
+
if results.get('label_map', None) is not None:
|
| 120 |
+
# Add deep copy to solve bug of repeatedly
|
| 121 |
+
# replace `gt_semantic_seg`, which is reported in
|
| 122 |
+
# https://github.com/open-mmlab/mmsegmentation/pull/1445/
|
| 123 |
+
gt_semantic_seg_copy = gt_semantic_seg.copy()
|
| 124 |
+
for old_id, new_id in results['label_map'].items():
|
| 125 |
+
gt_semantic_seg[gt_semantic_seg_copy == old_id] = new_id
|
| 126 |
+
results['gt_seg_map'] = gt_semantic_seg
|
| 127 |
+
results['seg_fields'].append('gt_seg_map')
|
| 128 |
+
|
| 129 |
+
def __repr__(self) -> str:
|
| 130 |
+
repr_str = self.__class__.__name__
|
| 131 |
+
repr_str += f'(reduce_zero_label={self.reduce_zero_label}, '
|
| 132 |
+
repr_str += f"imdecode_backend='{self.imdecode_backend}', "
|
| 133 |
+
repr_str += f'backend_args={self.backend_args})'
|
| 134 |
+
return repr_str
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@TRANSFORMS.register_module()
|
| 138 |
+
class LoadImageFromNDArray(LoadImageFromFile):
|
| 139 |
+
"""Load an image from ``results['img']``.
|
| 140 |
+
|
| 141 |
+
Similar with :obj:`LoadImageFromFile`, but the image has been loaded as
|
| 142 |
+
:obj:`np.ndarray` in ``results['img']``. Can be used when loading image
|
| 143 |
+
from webcam.
|
| 144 |
+
|
| 145 |
+
Required Keys:
|
| 146 |
+
|
| 147 |
+
- img
|
| 148 |
+
|
| 149 |
+
Modified Keys:
|
| 150 |
+
|
| 151 |
+
- img
|
| 152 |
+
- img_path
|
| 153 |
+
- img_shape
|
| 154 |
+
- ori_shape
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
to_float32 (bool): Whether to convert the loaded image to a float32
|
| 158 |
+
numpy array. If set to False, the loaded image is an uint8 array.
|
| 159 |
+
Defaults to False.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
def transform(self, results: dict) -> dict:
|
| 163 |
+
"""Transform function to add image meta information.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
results (dict): Result dict with Webcam read image in
|
| 167 |
+
``results['img']``.
|
| 168 |
+
|
| 169 |
+
Returns:
|
| 170 |
+
dict: The dict contains loaded image and meta information.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
img = results['img']
|
| 174 |
+
if self.to_float32:
|
| 175 |
+
img = img.astype(np.float32)
|
| 176 |
+
|
| 177 |
+
results['img_path'] = None
|
| 178 |
+
results['img'] = img
|
| 179 |
+
results['img_shape'] = img.shape[:2]
|
| 180 |
+
results['ori_shape'] = img.shape[:2]
|
| 181 |
+
return results
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@TRANSFORMS.register_module()
|
| 185 |
+
class LoadBiomedicalImageFromFile(BaseTransform):
|
| 186 |
+
"""Load an biomedical mage from file.
|
| 187 |
+
|
| 188 |
+
Required Keys:
|
| 189 |
+
|
| 190 |
+
- img_path
|
| 191 |
+
|
| 192 |
+
Added Keys:
|
| 193 |
+
|
| 194 |
+
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X) by default,
|
| 195 |
+
N is the number of modalities, and data type is float32
|
| 196 |
+
if set to_float32 = True, or float64 if decode_backend is 'nifti' and
|
| 197 |
+
to_float32 is False.
|
| 198 |
+
- img_shape
|
| 199 |
+
- ori_shape
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
decode_backend (str): The data decoding backend type. Options are
|
| 203 |
+
'numpy'and 'nifti', and there is a convention that when backend is
|
| 204 |
+
'nifti' the axis of data loaded is XYZ, and when backend is
|
| 205 |
+
'numpy', the the axis is ZYX. The data will be transposed if the
|
| 206 |
+
backend is 'nifti'. Defaults to 'nifti'.
|
| 207 |
+
to_xyz (bool): Whether transpose data from Z, Y, X to X, Y, Z.
|
| 208 |
+
Defaults to False.
|
| 209 |
+
to_float32 (bool): Whether to convert the loaded image to a float32
|
| 210 |
+
numpy array. If set to False, the loaded image is an float64 array.
|
| 211 |
+
Defaults to True.
|
| 212 |
+
backend_args (dict, Optional): Arguments to instantiate a file backend.
|
| 213 |
+
See https://mmengine.readthedocs.io/en/latest/api/fileio.htm
|
| 214 |
+
for details. Defaults to None.
|
| 215 |
+
Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required.
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
def __init__(self,
|
| 219 |
+
decode_backend: str = 'nifti',
|
| 220 |
+
to_xyz: bool = False,
|
| 221 |
+
to_float32: bool = True,
|
| 222 |
+
backend_args: Optional[dict] = None) -> None:
|
| 223 |
+
self.decode_backend = decode_backend
|
| 224 |
+
self.to_xyz = to_xyz
|
| 225 |
+
self.to_float32 = to_float32
|
| 226 |
+
self.backend_args = backend_args.copy() if backend_args else None
|
| 227 |
+
|
| 228 |
+
def transform(self, results: Dict) -> Dict:
|
| 229 |
+
"""Functions to load image.
|
| 230 |
+
|
| 231 |
+
Args:
|
| 232 |
+
results (dict): Result dict from :obj:``mmcv.BaseDataset``.
|
| 233 |
+
|
| 234 |
+
Returns:
|
| 235 |
+
dict: The dict contains loaded image and meta information.
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
filename = results['img_path']
|
| 239 |
+
|
| 240 |
+
data_bytes = fileio.get(filename, self.backend_args)
|
| 241 |
+
img = datafrombytes(data_bytes, backend=self.decode_backend)
|
| 242 |
+
|
| 243 |
+
if self.to_float32:
|
| 244 |
+
img = img.astype(np.float32)
|
| 245 |
+
|
| 246 |
+
if len(img.shape) == 3:
|
| 247 |
+
img = img[None, ...]
|
| 248 |
+
|
| 249 |
+
if self.decode_backend == 'nifti':
|
| 250 |
+
img = img.transpose(0, 3, 2, 1)
|
| 251 |
+
|
| 252 |
+
if self.to_xyz:
|
| 253 |
+
img = img.transpose(0, 3, 2, 1)
|
| 254 |
+
|
| 255 |
+
results['img'] = img
|
| 256 |
+
results['img_shape'] = img.shape[1:]
|
| 257 |
+
results['ori_shape'] = img.shape[1:]
|
| 258 |
+
return results
|
| 259 |
+
|
| 260 |
+
def __repr__(self):
|
| 261 |
+
repr_str = (f'{self.__class__.__name__}('
|
| 262 |
+
f"decode_backend='{self.decode_backend}', "
|
| 263 |
+
f'to_xyz={self.to_xyz}, '
|
| 264 |
+
f'to_float32={self.to_float32}, '
|
| 265 |
+
f'backend_args={self.backend_args})')
|
| 266 |
+
return repr_str
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
@TRANSFORMS.register_module()
|
| 270 |
+
class LoadBiomedicalAnnotation(BaseTransform):
|
| 271 |
+
"""Load ``seg_map`` annotation provided by biomedical dataset.
|
| 272 |
+
|
| 273 |
+
The annotation format is as the following:
|
| 274 |
+
|
| 275 |
+
.. code-block:: python
|
| 276 |
+
|
| 277 |
+
{
|
| 278 |
+
'gt_seg_map': np.ndarray (X, Y, Z) or (Z, Y, X)
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
Required Keys:
|
| 282 |
+
|
| 283 |
+
- seg_map_path
|
| 284 |
+
|
| 285 |
+
Added Keys:
|
| 286 |
+
|
| 287 |
+
- gt_seg_map (np.ndarray): Biomedical seg map with shape (Z, Y, X) by
|
| 288 |
+
default, and data type is float32 if set to_float32 = True, or
|
| 289 |
+
float64 if decode_backend is 'nifti' and to_float32 is False.
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
decode_backend (str): The data decoding backend type. Options are
|
| 293 |
+
'numpy'and 'nifti', and there is a convention that when backend is
|
| 294 |
+
'nifti' the axis of data loaded is XYZ, and when backend is
|
| 295 |
+
'numpy', the the axis is ZYX. The data will be transposed if the
|
| 296 |
+
backend is 'nifti'. Defaults to 'nifti'.
|
| 297 |
+
to_xyz (bool): Whether transpose data from Z, Y, X to X, Y, Z.
|
| 298 |
+
Defaults to False.
|
| 299 |
+
to_float32 (bool): Whether to convert the loaded seg map to a float32
|
| 300 |
+
numpy array. If set to False, the loaded image is an float64 array.
|
| 301 |
+
Defaults to True.
|
| 302 |
+
backend_args (dict, Optional): Arguments to instantiate a file backend.
|
| 303 |
+
See :class:`mmengine.fileio` for details.
|
| 304 |
+
Defaults to None.
|
| 305 |
+
Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required.
|
| 306 |
+
"""
|
| 307 |
+
|
| 308 |
+
def __init__(self,
|
| 309 |
+
decode_backend: str = 'nifti',
|
| 310 |
+
to_xyz: bool = False,
|
| 311 |
+
to_float32: bool = True,
|
| 312 |
+
backend_args: Optional[dict] = None) -> None:
|
| 313 |
+
super().__init__()
|
| 314 |
+
self.decode_backend = decode_backend
|
| 315 |
+
self.to_xyz = to_xyz
|
| 316 |
+
self.to_float32 = to_float32
|
| 317 |
+
self.backend_args = backend_args.copy() if backend_args else None
|
| 318 |
+
|
| 319 |
+
def transform(self, results: Dict) -> Dict:
|
| 320 |
+
"""Functions to load image.
|
| 321 |
+
|
| 322 |
+
Args:
|
| 323 |
+
results (dict): Result dict from :obj:``mmcv.BaseDataset``.
|
| 324 |
+
|
| 325 |
+
Returns:
|
| 326 |
+
dict: The dict contains loaded image and meta information.
|
| 327 |
+
"""
|
| 328 |
+
data_bytes = fileio.get(results['seg_map_path'], self.backend_args)
|
| 329 |
+
gt_seg_map = datafrombytes(data_bytes, backend=self.decode_backend)
|
| 330 |
+
|
| 331 |
+
if self.to_float32:
|
| 332 |
+
gt_seg_map = gt_seg_map.astype(np.float32)
|
| 333 |
+
|
| 334 |
+
if self.decode_backend == 'nifti':
|
| 335 |
+
gt_seg_map = gt_seg_map.transpose(2, 1, 0)
|
| 336 |
+
|
| 337 |
+
if self.to_xyz:
|
| 338 |
+
gt_seg_map = gt_seg_map.transpose(2, 1, 0)
|
| 339 |
+
|
| 340 |
+
results['gt_seg_map'] = gt_seg_map
|
| 341 |
+
return results
|
| 342 |
+
|
| 343 |
+
def __repr__(self):
|
| 344 |
+
repr_str = (f'{self.__class__.__name__}('
|
| 345 |
+
f"decode_backend='{self.decode_backend}', "
|
| 346 |
+
f'to_xyz={self.to_xyz}, '
|
| 347 |
+
f'to_float32={self.to_float32}, '
|
| 348 |
+
f'backend_args={self.backend_args})')
|
| 349 |
+
return repr_str
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
@TRANSFORMS.register_module()
|
| 353 |
+
class LoadBiomedicalData(BaseTransform):
|
| 354 |
+
"""Load an biomedical image and annotation from file.
|
| 355 |
+
|
| 356 |
+
The loading data format is as the following:
|
| 357 |
+
|
| 358 |
+
.. code-block:: python
|
| 359 |
+
|
| 360 |
+
{
|
| 361 |
+
'img': np.ndarray data[:-1, X, Y, Z]
|
| 362 |
+
'seg_map': np.ndarray data[-1, X, Y, Z]
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
Required Keys:
|
| 367 |
+
|
| 368 |
+
- img_path
|
| 369 |
+
|
| 370 |
+
Added Keys:
|
| 371 |
+
|
| 372 |
+
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X) by default,
|
| 373 |
+
N is the number of modalities.
|
| 374 |
+
- gt_seg_map (np.ndarray, optional): Biomedical seg map with shape
|
| 375 |
+
(Z, Y, X) by default.
|
| 376 |
+
- img_shape
|
| 377 |
+
- ori_shape
|
| 378 |
+
|
| 379 |
+
Args:
|
| 380 |
+
with_seg (bool): Whether to parse and load the semantic segmentation
|
| 381 |
+
annotation. Defaults to False.
|
| 382 |
+
decode_backend (str): The data decoding backend type. Options are
|
| 383 |
+
'numpy'and 'nifti', and there is a convention that when backend is
|
| 384 |
+
'nifti' the axis of data loaded is XYZ, and when backend is
|
| 385 |
+
'numpy', the the axis is ZYX. The data will be transposed if the
|
| 386 |
+
backend is 'nifti'. Defaults to 'nifti'.
|
| 387 |
+
to_xyz (bool): Whether transpose data from Z, Y, X to X, Y, Z.
|
| 388 |
+
Defaults to False.
|
| 389 |
+
backend_args (dict, Optional): Arguments to instantiate a file backend.
|
| 390 |
+
See https://mmengine.readthedocs.io/en/latest/api/fileio.htm
|
| 391 |
+
for details. Defaults to None.
|
| 392 |
+
Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required.
|
| 393 |
+
"""
|
| 394 |
+
|
| 395 |
+
def __init__(self,
|
| 396 |
+
with_seg=False,
|
| 397 |
+
decode_backend: str = 'numpy',
|
| 398 |
+
to_xyz: bool = False,
|
| 399 |
+
backend_args: Optional[dict] = None) -> None: # noqa
|
| 400 |
+
self.with_seg = with_seg
|
| 401 |
+
self.decode_backend = decode_backend
|
| 402 |
+
self.to_xyz = to_xyz
|
| 403 |
+
self.backend_args = backend_args.copy() if backend_args else None
|
| 404 |
+
|
| 405 |
+
def transform(self, results: Dict) -> Dict:
|
| 406 |
+
"""Functions to load image.
|
| 407 |
+
|
| 408 |
+
Args:
|
| 409 |
+
results (dict): Result dict from :obj:``mmcv.BaseDataset``.
|
| 410 |
+
|
| 411 |
+
Returns:
|
| 412 |
+
dict: The dict contains loaded image and meta information.
|
| 413 |
+
"""
|
| 414 |
+
data_bytes = fileio.get(results['img_path'], self.backend_args)
|
| 415 |
+
data = datafrombytes(data_bytes, backend=self.decode_backend)
|
| 416 |
+
# img is 4D data (N, X, Y, Z), N is the number of protocol
|
| 417 |
+
img = data[:-1, :]
|
| 418 |
+
|
| 419 |
+
if self.decode_backend == 'nifti':
|
| 420 |
+
img = img.transpose(0, 3, 2, 1)
|
| 421 |
+
|
| 422 |
+
if self.to_xyz:
|
| 423 |
+
img = img.transpose(0, 3, 2, 1)
|
| 424 |
+
|
| 425 |
+
results['img'] = img
|
| 426 |
+
results['img_shape'] = img.shape[1:]
|
| 427 |
+
results['ori_shape'] = img.shape[1:]
|
| 428 |
+
|
| 429 |
+
if self.with_seg:
|
| 430 |
+
gt_seg_map = data[-1, :]
|
| 431 |
+
if self.decode_backend == 'nifti':
|
| 432 |
+
gt_seg_map = gt_seg_map.transpose(2, 1, 0)
|
| 433 |
+
|
| 434 |
+
if self.to_xyz:
|
| 435 |
+
gt_seg_map = gt_seg_map.transpose(2, 1, 0)
|
| 436 |
+
results['gt_seg_map'] = gt_seg_map
|
| 437 |
+
return results
|
| 438 |
+
|
| 439 |
+
def __repr__(self) -> str:
|
| 440 |
+
repr_str = (f'{self.__class__.__name__}('
|
| 441 |
+
f'with_seg={self.with_seg}, '
|
| 442 |
+
f"decode_backend='{self.decode_backend}', "
|
| 443 |
+
f'to_xyz={self.to_xyz}, '
|
| 444 |
+
f'backend_args={self.backend_args})')
|
| 445 |
+
return repr_str
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
@TRANSFORMS.register_module()
|
| 449 |
+
class InferencerLoader(BaseTransform):
|
| 450 |
+
"""Load an image from ``results['img']``.
|
| 451 |
+
|
| 452 |
+
Similar with :obj:`LoadImageFromFile`, but the image has been loaded as
|
| 453 |
+
:obj:`np.ndarray` in ``results['img']``. Can be used when loading image
|
| 454 |
+
from webcam.
|
| 455 |
+
|
| 456 |
+
Required Keys:
|
| 457 |
+
|
| 458 |
+
- img
|
| 459 |
+
|
| 460 |
+
Modified Keys:
|
| 461 |
+
|
| 462 |
+
- img
|
| 463 |
+
- img_path
|
| 464 |
+
- img_shape
|
| 465 |
+
- ori_shape
|
| 466 |
+
|
| 467 |
+
Args:
|
| 468 |
+
to_float32 (bool): Whether to convert the loaded image to a float32
|
| 469 |
+
numpy array. If set to False, the loaded image is an uint8 array.
|
| 470 |
+
Defaults to False.
|
| 471 |
+
"""
|
| 472 |
+
|
| 473 |
+
def __init__(self, **kwargs) -> None:
|
| 474 |
+
super().__init__()
|
| 475 |
+
self.from_file = TRANSFORMS.build(
|
| 476 |
+
dict(type='LoadImageFromFile', **kwargs))
|
| 477 |
+
self.from_ndarray = TRANSFORMS.build(
|
| 478 |
+
dict(type='LoadImageFromNDArray', **kwargs))
|
| 479 |
+
|
| 480 |
+
def transform(self, single_input: Union[str, np.ndarray, dict]) -> dict:
|
| 481 |
+
"""Transform function to add image meta information.
|
| 482 |
+
|
| 483 |
+
Args:
|
| 484 |
+
results (dict): Result dict with Webcam read image in
|
| 485 |
+
``results['img']``.
|
| 486 |
+
|
| 487 |
+
Returns:
|
| 488 |
+
dict: The dict contains loaded image and meta information.
|
| 489 |
+
"""
|
| 490 |
+
if isinstance(single_input, str):
|
| 491 |
+
inputs = dict(img_path=single_input)
|
| 492 |
+
elif isinstance(single_input, np.ndarray):
|
| 493 |
+
inputs = dict(img=single_input)
|
| 494 |
+
elif isinstance(single_input, dict):
|
| 495 |
+
inputs = single_input
|
| 496 |
+
else:
|
| 497 |
+
raise NotImplementedError
|
| 498 |
+
|
| 499 |
+
if 'img' in inputs:
|
| 500 |
+
return self.from_ndarray(inputs)
|
| 501 |
+
return self.from_file(inputs)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
@TRANSFORMS.register_module()
|
| 505 |
+
class LoadSingleRSImageFromFile(BaseTransform):
|
| 506 |
+
"""Load a Remote Sensing mage from file.
|
| 507 |
+
|
| 508 |
+
Required Keys:
|
| 509 |
+
|
| 510 |
+
- img_path
|
| 511 |
+
|
| 512 |
+
Modified Keys:
|
| 513 |
+
|
| 514 |
+
- img
|
| 515 |
+
- img_shape
|
| 516 |
+
- ori_shape
|
| 517 |
+
|
| 518 |
+
Args:
|
| 519 |
+
to_float32 (bool): Whether to convert the loaded image to a float32
|
| 520 |
+
numpy array. If set to False, the loaded image is a float64 array.
|
| 521 |
+
Defaults to True.
|
| 522 |
+
"""
|
| 523 |
+
|
| 524 |
+
def __init__(self, to_float32: bool = True):
|
| 525 |
+
self.to_float32 = to_float32
|
| 526 |
+
|
| 527 |
+
if gdal is None:
|
| 528 |
+
raise RuntimeError('gdal is not installed')
|
| 529 |
+
|
| 530 |
+
def transform(self, results: Dict) -> Dict:
|
| 531 |
+
"""Functions to load image.
|
| 532 |
+
|
| 533 |
+
Args:
|
| 534 |
+
results (dict): Result dict from :obj:``mmcv.BaseDataset``.
|
| 535 |
+
|
| 536 |
+
Returns:
|
| 537 |
+
dict: The dict contains loaded image and meta information.
|
| 538 |
+
"""
|
| 539 |
+
|
| 540 |
+
filename = results['img_path']
|
| 541 |
+
ds = gdal.Open(filename)
|
| 542 |
+
if ds is None:
|
| 543 |
+
raise Exception(f'Unable to open file: {filename}')
|
| 544 |
+
img = np.einsum('ijk->jki', ds.ReadAsArray())
|
| 545 |
+
|
| 546 |
+
if self.to_float32:
|
| 547 |
+
img = img.astype(np.float32)
|
| 548 |
+
|
| 549 |
+
results['img'] = img
|
| 550 |
+
results['img_shape'] = img.shape[:2]
|
| 551 |
+
results['ori_shape'] = img.shape[:2]
|
| 552 |
+
return results
|
| 553 |
+
|
| 554 |
+
def __repr__(self):
|
| 555 |
+
repr_str = (f'{self.__class__.__name__}('
|
| 556 |
+
f'to_float32={self.to_float32})')
|
| 557 |
+
return repr_str
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
@TRANSFORMS.register_module()
|
| 561 |
+
class LoadMultipleRSImageFromFile(BaseTransform):
|
| 562 |
+
"""Load two Remote Sensing mage from file.
|
| 563 |
+
|
| 564 |
+
Required Keys:
|
| 565 |
+
|
| 566 |
+
- img_path
|
| 567 |
+
- img_path2
|
| 568 |
+
|
| 569 |
+
Modified Keys:
|
| 570 |
+
|
| 571 |
+
- img
|
| 572 |
+
- img2
|
| 573 |
+
- img_shape
|
| 574 |
+
- ori_shape
|
| 575 |
+
|
| 576 |
+
Args:
|
| 577 |
+
to_float32 (bool): Whether to convert the loaded image to a float32
|
| 578 |
+
numpy array. If set to False, the loaded image is a float64 array.
|
| 579 |
+
Defaults to True.
|
| 580 |
+
"""
|
| 581 |
+
|
| 582 |
+
def __init__(self, to_float32: bool = True):
|
| 583 |
+
if gdal is None:
|
| 584 |
+
raise RuntimeError('gdal is not installed')
|
| 585 |
+
self.to_float32 = to_float32
|
| 586 |
+
|
| 587 |
+
def transform(self, results: Dict) -> Dict:
|
| 588 |
+
"""Functions to load image.
|
| 589 |
+
|
| 590 |
+
Args:
|
| 591 |
+
results (dict): Result dict from :obj:``mmcv.BaseDataset``.
|
| 592 |
+
|
| 593 |
+
Returns:
|
| 594 |
+
dict: The dict contains loaded image and meta information.
|
| 595 |
+
"""
|
| 596 |
+
|
| 597 |
+
filename = results['img_path']
|
| 598 |
+
filename2 = results['img_path2']
|
| 599 |
+
|
| 600 |
+
ds = gdal.Open(filename)
|
| 601 |
+
ds2 = gdal.Open(filename2)
|
| 602 |
+
|
| 603 |
+
if ds is None:
|
| 604 |
+
raise Exception(f'Unable to open file: {filename}')
|
| 605 |
+
if ds2 is None:
|
| 606 |
+
raise Exception(f'Unable to open file: {filename2}')
|
| 607 |
+
|
| 608 |
+
img = np.einsum('ijk->jki', ds.ReadAsArray())
|
| 609 |
+
img2 = np.einsum('ijk->jki', ds2.ReadAsArray())
|
| 610 |
+
|
| 611 |
+
if self.to_float32:
|
| 612 |
+
img = img.astype(np.float32)
|
| 613 |
+
img2 = img2.astype(np.float32)
|
| 614 |
+
|
| 615 |
+
if img.shape != img2.shape:
|
| 616 |
+
raise Exception(f'Image shapes do not match:'
|
| 617 |
+
f' {img.shape} vs {img2.shape}')
|
| 618 |
+
|
| 619 |
+
results['img'] = img
|
| 620 |
+
results['img2'] = img2
|
| 621 |
+
results['img_shape'] = img.shape[:2]
|
| 622 |
+
results['ori_shape'] = img.shape[:2]
|
| 623 |
+
return results
|
| 624 |
+
|
| 625 |
+
def __repr__(self):
|
| 626 |
+
repr_str = (f'{self.__class__.__name__}('
|
| 627 |
+
f'to_float32={self.to_float32})')
|
| 628 |
+
return repr_str
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
@TRANSFORMS.register_module()
|
| 632 |
+
class LoadDepthAnnotation(BaseTransform):
|
| 633 |
+
"""Load ``depth_map`` annotation provided by depth estimation dataset.
|
| 634 |
+
|
| 635 |
+
The annotation format is as the following:
|
| 636 |
+
|
| 637 |
+
.. code-block:: python
|
| 638 |
+
|
| 639 |
+
{
|
| 640 |
+
'gt_depth_map': np.ndarray [Y, X]
|
| 641 |
+
}
|
| 642 |
+
|
| 643 |
+
Required Keys:
|
| 644 |
+
|
| 645 |
+
- seg_depth_path
|
| 646 |
+
|
| 647 |
+
Added Keys:
|
| 648 |
+
|
| 649 |
+
- gt_depth_map (np.ndarray): Depth map with shape (Y, X) by
|
| 650 |
+
default, and data type is float32 if set to_float32 = True.
|
| 651 |
+
- depth_rescale_factor (float): The rescale factor of depth map, which
|
| 652 |
+
can be used to recover the original value of depth map.
|
| 653 |
+
|
| 654 |
+
Args:
|
| 655 |
+
decode_backend (str): The data decoding backend type. Options are
|
| 656 |
+
'numpy', 'nifti', and 'cv2'. Defaults to 'cv2'.
|
| 657 |
+
to_float32 (bool): Whether to convert the loaded depth map to a float32
|
| 658 |
+
numpy array. If set to False, the loaded image is an uint16 array.
|
| 659 |
+
Defaults to True.
|
| 660 |
+
depth_rescale_factor (float): Factor to rescale the depth value to
|
| 661 |
+
limit the range. Defaults to 1.0.
|
| 662 |
+
backend_args (dict, Optional): Arguments to instantiate a file backend.
|
| 663 |
+
See :class:`mmengine.fileio` for details.
|
| 664 |
+
Defaults to None.
|
| 665 |
+
Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required.
|
| 666 |
+
"""
|
| 667 |
+
|
| 668 |
+
def __init__(self,
|
| 669 |
+
decode_backend: str = 'cv2',
|
| 670 |
+
to_float32: bool = True,
|
| 671 |
+
depth_rescale_factor: float = 1.0,
|
| 672 |
+
backend_args: Optional[dict] = None) -> None:
|
| 673 |
+
super().__init__()
|
| 674 |
+
self.decode_backend = decode_backend
|
| 675 |
+
self.to_float32 = to_float32
|
| 676 |
+
self.depth_rescale_factor = depth_rescale_factor
|
| 677 |
+
self.backend_args = backend_args.copy() if backend_args else None
|
| 678 |
+
|
| 679 |
+
def transform(self, results: Dict) -> Dict:
|
| 680 |
+
"""Functions to load depth map.
|
| 681 |
+
|
| 682 |
+
Args:
|
| 683 |
+
results (dict): Result dict from :obj:``mmcv.BaseDataset``.
|
| 684 |
+
|
| 685 |
+
Returns:
|
| 686 |
+
dict: The dict contains loaded depth map.
|
| 687 |
+
"""
|
| 688 |
+
data_bytes = fileio.get(results['depth_map_path'], self.backend_args)
|
| 689 |
+
gt_depth_map = datafrombytes(data_bytes, backend=self.decode_backend)
|
| 690 |
+
|
| 691 |
+
if self.to_float32:
|
| 692 |
+
gt_depth_map = gt_depth_map.astype(np.float32)
|
| 693 |
+
|
| 694 |
+
gt_depth_map *= self.depth_rescale_factor
|
| 695 |
+
results['gt_depth_map'] = gt_depth_map
|
| 696 |
+
results['seg_fields'].append('gt_depth_map')
|
| 697 |
+
results['depth_rescale_factor'] = self.depth_rescale_factor
|
| 698 |
+
return results
|
| 699 |
+
|
| 700 |
+
def __repr__(self):
|
| 701 |
+
repr_str = (f'{self.__class__.__name__}('
|
| 702 |
+
f"decode_backend='{self.decode_backend}', "
|
| 703 |
+
f'to_float32={self.to_float32}, '
|
| 704 |
+
f'backend_args={self.backend_args})')
|
| 705 |
+
return repr_str
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
@TRANSFORMS.register_module()
|
| 709 |
+
class LoadImageFromNpyFile(LoadImageFromFile):
|
| 710 |
+
"""Load an image from ``results['img_path']``.
|
| 711 |
+
|
| 712 |
+
Required Keys:
|
| 713 |
+
|
| 714 |
+
- img_path
|
| 715 |
+
|
| 716 |
+
Modified Keys:
|
| 717 |
+
|
| 718 |
+
- img
|
| 719 |
+
- img_shape
|
| 720 |
+
- ori_shape
|
| 721 |
+
|
| 722 |
+
Args:
|
| 723 |
+
to_float32 (bool): Whether to convert the loaded image to a float32
|
| 724 |
+
numpy array. If set to False, the loaded image is an uint8 array.
|
| 725 |
+
Defaults to False.
|
| 726 |
+
"""
|
| 727 |
+
|
| 728 |
+
def transform(self, results: dict) -> Optional[dict]:
|
| 729 |
+
"""Functions to load image.
|
| 730 |
+
|
| 731 |
+
Args:
|
| 732 |
+
results (dict): Result dict from
|
| 733 |
+
:class:`mmengine.dataset.BaseDataset`.
|
| 734 |
+
|
| 735 |
+
Returns:
|
| 736 |
+
dict: The dict contains loaded image and meta information.
|
| 737 |
+
"""
|
| 738 |
+
|
| 739 |
+
filename = results['img_path']
|
| 740 |
+
|
| 741 |
+
try:
|
| 742 |
+
if Path(filename).suffix in ['.npy', '.npz']:
|
| 743 |
+
img = np.load(filename)
|
| 744 |
+
else:
|
| 745 |
+
if self.file_client_args is not None:
|
| 746 |
+
file_client = fileio.FileClient.infer_client(
|
| 747 |
+
self.file_client_args, filename)
|
| 748 |
+
img_bytes = file_client.get(filename)
|
| 749 |
+
else:
|
| 750 |
+
img_bytes = fileio.get(
|
| 751 |
+
filename, backend_args=self.backend_args)
|
| 752 |
+
img = mmcv.imfrombytes(
|
| 753 |
+
img_bytes,
|
| 754 |
+
flag=self.color_type,
|
| 755 |
+
backend=self.imdecode_backend)
|
| 756 |
+
except Exception as e:
|
| 757 |
+
if self.ignore_empty:
|
| 758 |
+
return None
|
| 759 |
+
else:
|
| 760 |
+
raise e
|
| 761 |
+
|
| 762 |
+
# in some cases, images are not read successfully, the img would be
|
| 763 |
+
# `None`, refer to https://github.com/open-mmlab/mmpretrain/issues/1427
|
| 764 |
+
assert img is not None, f'failed to load image: {filename}'
|
| 765 |
+
if self.to_float32:
|
| 766 |
+
img = img.astype(np.float32)
|
| 767 |
+
|
| 768 |
+
results['img'] = img
|
| 769 |
+
results['img_shape'] = img.shape[:2]
|
| 770 |
+
results['ori_shape'] = img.shape[:2]
|
| 771 |
+
return results
|
third-party/InterFormer/mmseg/datasets/transforms/transforms.py
ADDED
|
@@ -0,0 +1,2537 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import copy
|
| 3 |
+
import inspect
|
| 4 |
+
import warnings
|
| 5 |
+
from typing import Dict, List, Optional, Sequence, Tuple, Union
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import mmcv
|
| 9 |
+
import mmengine
|
| 10 |
+
import numpy as np
|
| 11 |
+
from mmcv.transforms import RandomFlip as MMCV_RandomFlip
|
| 12 |
+
from mmcv.transforms import Resize as MMCV_Resize
|
| 13 |
+
from mmcv.transforms.base import BaseTransform
|
| 14 |
+
from mmcv.transforms.utils import cache_randomness
|
| 15 |
+
from mmengine.utils import is_tuple_of
|
| 16 |
+
from numpy import random
|
| 17 |
+
from scipy.ndimage import gaussian_filter
|
| 18 |
+
|
| 19 |
+
from mmseg.datasets.dataset_wrappers import MultiImageMixDataset
|
| 20 |
+
from mmseg.registry import TRANSFORMS
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
import albumentations
|
| 24 |
+
from albumentations import Compose
|
| 25 |
+
ALBU_INSTALLED = True
|
| 26 |
+
except ImportError:
|
| 27 |
+
albumentations = None
|
| 28 |
+
Compose = None
|
| 29 |
+
ALBU_INSTALLED = False
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@TRANSFORMS.register_module()
|
| 33 |
+
class ResizeToMultiple(BaseTransform):
|
| 34 |
+
"""Resize images & seg to multiple of divisor.
|
| 35 |
+
|
| 36 |
+
Required Keys:
|
| 37 |
+
|
| 38 |
+
- img
|
| 39 |
+
- gt_seg_map
|
| 40 |
+
|
| 41 |
+
Modified Keys:
|
| 42 |
+
|
| 43 |
+
- img
|
| 44 |
+
- img_shape
|
| 45 |
+
- pad_shape
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
size_divisor (int): images and gt seg maps need to resize to multiple
|
| 49 |
+
of size_divisor. Default: 32.
|
| 50 |
+
interpolation (str, optional): The interpolation mode of image resize.
|
| 51 |
+
Default: None
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, size_divisor=32, interpolation=None):
|
| 55 |
+
self.size_divisor = size_divisor
|
| 56 |
+
self.interpolation = interpolation
|
| 57 |
+
|
| 58 |
+
def transform(self, results: dict) -> dict:
|
| 59 |
+
"""Call function to resize images, semantic segmentation map to
|
| 60 |
+
multiple of size divisor.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
results (dict): Result dict from loading pipeline.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
dict: Resized results, 'img_shape', 'pad_shape' keys are updated.
|
| 67 |
+
"""
|
| 68 |
+
# Align image to multiple of size divisor.
|
| 69 |
+
img = results['img']
|
| 70 |
+
img = mmcv.imresize_to_multiple(
|
| 71 |
+
img,
|
| 72 |
+
self.size_divisor,
|
| 73 |
+
scale_factor=1,
|
| 74 |
+
interpolation=self.interpolation
|
| 75 |
+
if self.interpolation else 'bilinear')
|
| 76 |
+
|
| 77 |
+
results['img'] = img
|
| 78 |
+
results['img_shape'] = img.shape[:2]
|
| 79 |
+
results['pad_shape'] = img.shape[:2]
|
| 80 |
+
|
| 81 |
+
# Align segmentation map to multiple of size divisor.
|
| 82 |
+
for key in results.get('seg_fields', []):
|
| 83 |
+
gt_seg = results[key]
|
| 84 |
+
gt_seg = mmcv.imresize_to_multiple(
|
| 85 |
+
gt_seg,
|
| 86 |
+
self.size_divisor,
|
| 87 |
+
scale_factor=1,
|
| 88 |
+
interpolation='nearest')
|
| 89 |
+
results[key] = gt_seg
|
| 90 |
+
|
| 91 |
+
return results
|
| 92 |
+
|
| 93 |
+
def __repr__(self):
|
| 94 |
+
repr_str = self.__class__.__name__
|
| 95 |
+
repr_str += (f'(size_divisor={self.size_divisor}, '
|
| 96 |
+
f'interpolation={self.interpolation})')
|
| 97 |
+
return repr_str
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@TRANSFORMS.register_module()
|
| 101 |
+
class Rerange(BaseTransform):
|
| 102 |
+
"""Rerange the image pixel value.
|
| 103 |
+
|
| 104 |
+
Required Keys:
|
| 105 |
+
|
| 106 |
+
- img
|
| 107 |
+
|
| 108 |
+
Modified Keys:
|
| 109 |
+
|
| 110 |
+
- img
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
min_value (float or int): Minimum value of the reranged image.
|
| 114 |
+
Default: 0.
|
| 115 |
+
max_value (float or int): Maximum value of the reranged image.
|
| 116 |
+
Default: 255.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def __init__(self, min_value=0, max_value=255):
|
| 120 |
+
assert isinstance(min_value, float) or isinstance(min_value, int)
|
| 121 |
+
assert isinstance(max_value, float) or isinstance(max_value, int)
|
| 122 |
+
assert min_value < max_value
|
| 123 |
+
self.min_value = min_value
|
| 124 |
+
self.max_value = max_value
|
| 125 |
+
|
| 126 |
+
def transform(self, results: dict) -> dict:
|
| 127 |
+
"""Call function to rerange images.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
results (dict): Result dict from loading pipeline.
|
| 131 |
+
Returns:
|
| 132 |
+
dict: Reranged results.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
img = results['img']
|
| 136 |
+
img_min_value = np.min(img)
|
| 137 |
+
img_max_value = np.max(img)
|
| 138 |
+
|
| 139 |
+
assert img_min_value < img_max_value
|
| 140 |
+
# rerange to [0, 1]
|
| 141 |
+
img = (img - img_min_value) / (img_max_value - img_min_value)
|
| 142 |
+
# rerange to [min_value, max_value]
|
| 143 |
+
img = img * (self.max_value - self.min_value) + self.min_value
|
| 144 |
+
results['img'] = img
|
| 145 |
+
|
| 146 |
+
return results
|
| 147 |
+
|
| 148 |
+
def __repr__(self):
|
| 149 |
+
repr_str = self.__class__.__name__
|
| 150 |
+
repr_str += f'(min_value={self.min_value}, max_value={self.max_value})'
|
| 151 |
+
return repr_str
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@TRANSFORMS.register_module()
|
| 155 |
+
class CLAHE(BaseTransform):
|
| 156 |
+
"""Use CLAHE method to process the image.
|
| 157 |
+
|
| 158 |
+
See `ZUIDERVELD,K. Contrast Limited Adaptive Histogram Equalization[J].
|
| 159 |
+
Graphics Gems, 1994:474-485.` for more information.
|
| 160 |
+
|
| 161 |
+
Required Keys:
|
| 162 |
+
|
| 163 |
+
- img
|
| 164 |
+
|
| 165 |
+
Modified Keys:
|
| 166 |
+
|
| 167 |
+
- img
|
| 168 |
+
|
| 169 |
+
Args:
|
| 170 |
+
clip_limit (float): Threshold for contrast limiting. Default: 40.0.
|
| 171 |
+
tile_grid_size (tuple[int]): Size of grid for histogram equalization.
|
| 172 |
+
Input image will be divided into equally sized rectangular tiles.
|
| 173 |
+
It defines the number of tiles in row and column. Default: (8, 8).
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
def __init__(self, clip_limit=40.0, tile_grid_size=(8, 8)):
|
| 177 |
+
assert isinstance(clip_limit, (float, int))
|
| 178 |
+
self.clip_limit = clip_limit
|
| 179 |
+
assert is_tuple_of(tile_grid_size, int)
|
| 180 |
+
assert len(tile_grid_size) == 2
|
| 181 |
+
self.tile_grid_size = tile_grid_size
|
| 182 |
+
|
| 183 |
+
def transform(self, results: dict) -> dict:
|
| 184 |
+
"""Call function to Use CLAHE method process images.
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
results (dict): Result dict from loading pipeline.
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
dict: Processed results.
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
for i in range(results['img'].shape[2]):
|
| 194 |
+
results['img'][:, :, i] = mmcv.clahe(
|
| 195 |
+
np.array(results['img'][:, :, i], dtype=np.uint8),
|
| 196 |
+
self.clip_limit, self.tile_grid_size)
|
| 197 |
+
|
| 198 |
+
return results
|
| 199 |
+
|
| 200 |
+
def __repr__(self):
|
| 201 |
+
repr_str = self.__class__.__name__
|
| 202 |
+
repr_str += f'(clip_limit={self.clip_limit}, ' \
|
| 203 |
+
f'tile_grid_size={self.tile_grid_size})'
|
| 204 |
+
return repr_str
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
@TRANSFORMS.register_module()
|
| 208 |
+
class RandomCrop(BaseTransform):
|
| 209 |
+
"""Random crop the image & seg.
|
| 210 |
+
|
| 211 |
+
Required Keys:
|
| 212 |
+
|
| 213 |
+
- img
|
| 214 |
+
- gt_seg_map
|
| 215 |
+
|
| 216 |
+
Modified Keys:
|
| 217 |
+
|
| 218 |
+
- img
|
| 219 |
+
- img_shape
|
| 220 |
+
- gt_seg_map
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
crop_size (Union[int, Tuple[int, int]]): Expected size after cropping
|
| 225 |
+
with the format of (h, w). If set to an integer, then cropping
|
| 226 |
+
width and height are equal to this integer.
|
| 227 |
+
cat_max_ratio (float): The maximum ratio that single category could
|
| 228 |
+
occupy.
|
| 229 |
+
ignore_index (int): The label index to be ignored. Default: 255
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
def __init__(self,
|
| 233 |
+
crop_size: Union[int, Tuple[int, int]],
|
| 234 |
+
cat_max_ratio: float = 1.,
|
| 235 |
+
ignore_index: int = 255):
|
| 236 |
+
super().__init__()
|
| 237 |
+
assert isinstance(crop_size, int) or (
|
| 238 |
+
isinstance(crop_size, tuple) and len(crop_size) == 2
|
| 239 |
+
), 'The expected crop_size is an integer, or a tuple containing two '
|
| 240 |
+
'intergers'
|
| 241 |
+
|
| 242 |
+
if isinstance(crop_size, int):
|
| 243 |
+
crop_size = (crop_size, crop_size)
|
| 244 |
+
assert crop_size[0] > 0 and crop_size[1] > 0
|
| 245 |
+
self.crop_size = crop_size
|
| 246 |
+
self.cat_max_ratio = cat_max_ratio
|
| 247 |
+
self.ignore_index = ignore_index
|
| 248 |
+
|
| 249 |
+
@cache_randomness
|
| 250 |
+
def crop_bbox(self, results: dict) -> tuple:
|
| 251 |
+
"""get a crop bounding box.
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
results (dict): Result dict from loading pipeline.
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
tuple: Coordinates of the cropped image.
|
| 258 |
+
"""
|
| 259 |
+
|
| 260 |
+
def generate_crop_bbox(img: np.ndarray) -> tuple:
|
| 261 |
+
"""Randomly get a crop bounding box.
|
| 262 |
+
|
| 263 |
+
Args:
|
| 264 |
+
img (np.ndarray): Original input image.
|
| 265 |
+
|
| 266 |
+
Returns:
|
| 267 |
+
tuple: Coordinates of the cropped image.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
margin_h = max(img.shape[0] - self.crop_size[0], 0)
|
| 271 |
+
margin_w = max(img.shape[1] - self.crop_size[1], 0)
|
| 272 |
+
offset_h = np.random.randint(0, margin_h + 1)
|
| 273 |
+
offset_w = np.random.randint(0, margin_w + 1)
|
| 274 |
+
crop_y1, crop_y2 = offset_h, offset_h + self.crop_size[0]
|
| 275 |
+
crop_x1, crop_x2 = offset_w, offset_w + self.crop_size[1]
|
| 276 |
+
|
| 277 |
+
return crop_y1, crop_y2, crop_x1, crop_x2
|
| 278 |
+
|
| 279 |
+
img = results['img']
|
| 280 |
+
crop_bbox = generate_crop_bbox(img)
|
| 281 |
+
if self.cat_max_ratio < 1.:
|
| 282 |
+
# Repeat 10 times
|
| 283 |
+
for _ in range(10):
|
| 284 |
+
seg_temp = self.crop(results['gt_seg_map'], crop_bbox)
|
| 285 |
+
labels, cnt = np.unique(seg_temp, return_counts=True)
|
| 286 |
+
cnt = cnt[labels != self.ignore_index]
|
| 287 |
+
if len(cnt) > 1 and np.max(cnt) / np.sum(
|
| 288 |
+
cnt) < self.cat_max_ratio:
|
| 289 |
+
break
|
| 290 |
+
crop_bbox = generate_crop_bbox(img)
|
| 291 |
+
|
| 292 |
+
return crop_bbox
|
| 293 |
+
|
| 294 |
+
def crop(self, img: np.ndarray, crop_bbox: tuple) -> np.ndarray:
|
| 295 |
+
"""Crop from ``img``
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
img (np.ndarray): Original input image.
|
| 299 |
+
crop_bbox (tuple): Coordinates of the cropped image.
|
| 300 |
+
|
| 301 |
+
Returns:
|
| 302 |
+
np.ndarray: The cropped image.
|
| 303 |
+
"""
|
| 304 |
+
|
| 305 |
+
crop_y1, crop_y2, crop_x1, crop_x2 = crop_bbox
|
| 306 |
+
img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...]
|
| 307 |
+
return img
|
| 308 |
+
|
| 309 |
+
def transform(self, results: dict) -> dict:
|
| 310 |
+
"""Transform function to randomly crop images, semantic segmentation
|
| 311 |
+
maps.
|
| 312 |
+
|
| 313 |
+
Args:
|
| 314 |
+
results (dict): Result dict from loading pipeline.
|
| 315 |
+
|
| 316 |
+
Returns:
|
| 317 |
+
dict: Randomly cropped results, 'img_shape' key in result dict is
|
| 318 |
+
updated according to crop size.
|
| 319 |
+
"""
|
| 320 |
+
|
| 321 |
+
img = results['img']
|
| 322 |
+
crop_bbox = self.crop_bbox(results)
|
| 323 |
+
|
| 324 |
+
# crop the image
|
| 325 |
+
img = self.crop(img, crop_bbox)
|
| 326 |
+
|
| 327 |
+
# crop semantic seg
|
| 328 |
+
for key in results.get('seg_fields', []):
|
| 329 |
+
results[key] = self.crop(results[key], crop_bbox)
|
| 330 |
+
|
| 331 |
+
results['img'] = img
|
| 332 |
+
results['img_shape'] = img.shape[:2]
|
| 333 |
+
return results
|
| 334 |
+
|
| 335 |
+
def __repr__(self):
|
| 336 |
+
return self.__class__.__name__ + f'(crop_size={self.crop_size})'
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@TRANSFORMS.register_module()
|
| 340 |
+
class RandomRotate(BaseTransform):
|
| 341 |
+
"""Rotate the image & seg.
|
| 342 |
+
|
| 343 |
+
Required Keys:
|
| 344 |
+
|
| 345 |
+
- img
|
| 346 |
+
- gt_seg_map
|
| 347 |
+
|
| 348 |
+
Modified Keys:
|
| 349 |
+
|
| 350 |
+
- img
|
| 351 |
+
- gt_seg_map
|
| 352 |
+
|
| 353 |
+
Args:
|
| 354 |
+
prob (float): The rotation probability.
|
| 355 |
+
degree (float, tuple[float]): Range of degrees to select from. If
|
| 356 |
+
degree is a number instead of tuple like (min, max),
|
| 357 |
+
the range of degree will be (``-degree``, ``+degree``)
|
| 358 |
+
pad_val (float, optional): Padding value of image. Default: 0.
|
| 359 |
+
seg_pad_val (float, optional): Padding value of segmentation map.
|
| 360 |
+
Default: 255.
|
| 361 |
+
center (tuple[float], optional): Center point (w, h) of the rotation in
|
| 362 |
+
the source image. If not specified, the center of the image will be
|
| 363 |
+
used. Default: None.
|
| 364 |
+
auto_bound (bool): Whether to adjust the image size to cover the whole
|
| 365 |
+
rotated image. Default: False
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
def __init__(self,
|
| 369 |
+
prob,
|
| 370 |
+
degree,
|
| 371 |
+
pad_val=0,
|
| 372 |
+
seg_pad_val=255,
|
| 373 |
+
center=None,
|
| 374 |
+
auto_bound=False):
|
| 375 |
+
self.prob = prob
|
| 376 |
+
assert prob >= 0 and prob <= 1
|
| 377 |
+
if isinstance(degree, (float, int)):
|
| 378 |
+
assert degree > 0, f'degree {degree} should be positive'
|
| 379 |
+
self.degree = (-degree, degree)
|
| 380 |
+
else:
|
| 381 |
+
self.degree = degree
|
| 382 |
+
assert len(self.degree) == 2, f'degree {self.degree} should be a ' \
|
| 383 |
+
f'tuple of (min, max)'
|
| 384 |
+
self.pal_val = pad_val
|
| 385 |
+
self.seg_pad_val = seg_pad_val
|
| 386 |
+
self.center = center
|
| 387 |
+
self.auto_bound = auto_bound
|
| 388 |
+
|
| 389 |
+
@cache_randomness
|
| 390 |
+
def generate_degree(self):
|
| 391 |
+
return np.random.rand() < self.prob, np.random.uniform(
|
| 392 |
+
min(*self.degree), max(*self.degree))
|
| 393 |
+
|
| 394 |
+
def transform(self, results: dict) -> dict:
|
| 395 |
+
"""Call function to rotate image, semantic segmentation maps.
|
| 396 |
+
|
| 397 |
+
Args:
|
| 398 |
+
results (dict): Result dict from loading pipeline.
|
| 399 |
+
|
| 400 |
+
Returns:
|
| 401 |
+
dict: Rotated results.
|
| 402 |
+
"""
|
| 403 |
+
|
| 404 |
+
rotate, degree = self.generate_degree()
|
| 405 |
+
if rotate:
|
| 406 |
+
# rotate image
|
| 407 |
+
results['img'] = mmcv.imrotate(
|
| 408 |
+
results['img'],
|
| 409 |
+
angle=degree,
|
| 410 |
+
border_value=self.pal_val,
|
| 411 |
+
center=self.center,
|
| 412 |
+
auto_bound=self.auto_bound)
|
| 413 |
+
|
| 414 |
+
# rotate segs
|
| 415 |
+
for key in results.get('seg_fields', []):
|
| 416 |
+
results[key] = mmcv.imrotate(
|
| 417 |
+
results[key],
|
| 418 |
+
angle=degree,
|
| 419 |
+
border_value=self.seg_pad_val,
|
| 420 |
+
center=self.center,
|
| 421 |
+
auto_bound=self.auto_bound,
|
| 422 |
+
interpolation='nearest')
|
| 423 |
+
return results
|
| 424 |
+
|
| 425 |
+
def __repr__(self):
|
| 426 |
+
repr_str = self.__class__.__name__
|
| 427 |
+
repr_str += f'(prob={self.prob}, ' \
|
| 428 |
+
f'degree={self.degree}, ' \
|
| 429 |
+
f'pad_val={self.pal_val}, ' \
|
| 430 |
+
f'seg_pad_val={self.seg_pad_val}, ' \
|
| 431 |
+
f'center={self.center}, ' \
|
| 432 |
+
f'auto_bound={self.auto_bound})'
|
| 433 |
+
return repr_str
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
@TRANSFORMS.register_module()
|
| 437 |
+
class RGB2Gray(BaseTransform):
|
| 438 |
+
"""Convert RGB image to grayscale image.
|
| 439 |
+
|
| 440 |
+
Required Keys:
|
| 441 |
+
|
| 442 |
+
- img
|
| 443 |
+
|
| 444 |
+
Modified Keys:
|
| 445 |
+
|
| 446 |
+
- img
|
| 447 |
+
- img_shape
|
| 448 |
+
|
| 449 |
+
This transform calculate the weighted mean of input image channels with
|
| 450 |
+
``weights`` and then expand the channels to ``out_channels``. When
|
| 451 |
+
``out_channels`` is None, the number of output channels is the same as
|
| 452 |
+
input channels.
|
| 453 |
+
|
| 454 |
+
Args:
|
| 455 |
+
out_channels (int): Expected number of output channels after
|
| 456 |
+
transforming. Default: None.
|
| 457 |
+
weights (tuple[float]): The weights to calculate the weighted mean.
|
| 458 |
+
Default: (0.299, 0.587, 0.114).
|
| 459 |
+
"""
|
| 460 |
+
|
| 461 |
+
def __init__(self, out_channels=None, weights=(0.299, 0.587, 0.114)):
|
| 462 |
+
assert out_channels is None or out_channels > 0
|
| 463 |
+
self.out_channels = out_channels
|
| 464 |
+
assert isinstance(weights, tuple)
|
| 465 |
+
for item in weights:
|
| 466 |
+
assert isinstance(item, (float, int))
|
| 467 |
+
self.weights = weights
|
| 468 |
+
|
| 469 |
+
def transform(self, results: dict) -> dict:
|
| 470 |
+
"""Call function to convert RGB image to grayscale image.
|
| 471 |
+
|
| 472 |
+
Args:
|
| 473 |
+
results (dict): Result dict from loading pipeline.
|
| 474 |
+
|
| 475 |
+
Returns:
|
| 476 |
+
dict: Result dict with grayscale image.
|
| 477 |
+
"""
|
| 478 |
+
img = results['img']
|
| 479 |
+
assert len(img.shape) == 3
|
| 480 |
+
assert img.shape[2] == len(self.weights)
|
| 481 |
+
weights = np.array(self.weights).reshape((1, 1, -1))
|
| 482 |
+
img = (img * weights).sum(2, keepdims=True)
|
| 483 |
+
if self.out_channels is None:
|
| 484 |
+
img = img.repeat(weights.shape[2], axis=2)
|
| 485 |
+
else:
|
| 486 |
+
img = img.repeat(self.out_channels, axis=2)
|
| 487 |
+
|
| 488 |
+
results['img'] = img
|
| 489 |
+
results['img_shape'] = img.shape
|
| 490 |
+
|
| 491 |
+
return results
|
| 492 |
+
|
| 493 |
+
def __repr__(self):
|
| 494 |
+
repr_str = self.__class__.__name__
|
| 495 |
+
repr_str += f'(out_channels={self.out_channels}, ' \
|
| 496 |
+
f'weights={self.weights})'
|
| 497 |
+
return repr_str
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
@TRANSFORMS.register_module()
|
| 501 |
+
class AdjustGamma(BaseTransform):
|
| 502 |
+
"""Using gamma correction to process the image.
|
| 503 |
+
|
| 504 |
+
Required Keys:
|
| 505 |
+
|
| 506 |
+
- img
|
| 507 |
+
|
| 508 |
+
Modified Keys:
|
| 509 |
+
|
| 510 |
+
- img
|
| 511 |
+
|
| 512 |
+
Args:
|
| 513 |
+
gamma (float or int): Gamma value used in gamma correction.
|
| 514 |
+
Default: 1.0.
|
| 515 |
+
"""
|
| 516 |
+
|
| 517 |
+
def __init__(self, gamma=1.0):
|
| 518 |
+
assert isinstance(gamma, float) or isinstance(gamma, int)
|
| 519 |
+
assert gamma > 0
|
| 520 |
+
self.gamma = gamma
|
| 521 |
+
inv_gamma = 1.0 / gamma
|
| 522 |
+
self.table = np.array([(i / 255.0)**inv_gamma * 255
|
| 523 |
+
for i in np.arange(256)]).astype('uint8')
|
| 524 |
+
|
| 525 |
+
def transform(self, results: dict) -> dict:
|
| 526 |
+
"""Call function to process the image with gamma correction.
|
| 527 |
+
|
| 528 |
+
Args:
|
| 529 |
+
results (dict): Result dict from loading pipeline.
|
| 530 |
+
|
| 531 |
+
Returns:
|
| 532 |
+
dict: Processed results.
|
| 533 |
+
"""
|
| 534 |
+
|
| 535 |
+
results['img'] = mmcv.lut_transform(
|
| 536 |
+
np.array(results['img'], dtype=np.uint8), self.table)
|
| 537 |
+
|
| 538 |
+
return results
|
| 539 |
+
|
| 540 |
+
def __repr__(self):
|
| 541 |
+
return self.__class__.__name__ + f'(gamma={self.gamma})'
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
@TRANSFORMS.register_module()
|
| 545 |
+
class SegRescale(BaseTransform):
|
| 546 |
+
"""Rescale semantic segmentation maps.
|
| 547 |
+
|
| 548 |
+
Required Keys:
|
| 549 |
+
|
| 550 |
+
- gt_seg_map
|
| 551 |
+
|
| 552 |
+
Modified Keys:
|
| 553 |
+
|
| 554 |
+
- gt_seg_map
|
| 555 |
+
|
| 556 |
+
Args:
|
| 557 |
+
scale_factor (float): The scale factor of the final output.
|
| 558 |
+
"""
|
| 559 |
+
|
| 560 |
+
def __init__(self, scale_factor=1):
|
| 561 |
+
self.scale_factor = scale_factor
|
| 562 |
+
|
| 563 |
+
def transform(self, results: dict) -> dict:
|
| 564 |
+
"""Call function to scale the semantic segmentation map.
|
| 565 |
+
|
| 566 |
+
Args:
|
| 567 |
+
results (dict): Result dict from loading pipeline.
|
| 568 |
+
|
| 569 |
+
Returns:
|
| 570 |
+
dict: Result dict with semantic segmentation map scaled.
|
| 571 |
+
"""
|
| 572 |
+
for key in results.get('seg_fields', []):
|
| 573 |
+
if self.scale_factor != 1:
|
| 574 |
+
results[key] = mmcv.imrescale(
|
| 575 |
+
results[key], self.scale_factor, interpolation='nearest')
|
| 576 |
+
return results
|
| 577 |
+
|
| 578 |
+
def __repr__(self):
|
| 579 |
+
return self.__class__.__name__ + f'(scale_factor={self.scale_factor})'
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
@TRANSFORMS.register_module()
|
| 583 |
+
class PhotoMetricDistortion(BaseTransform):
|
| 584 |
+
"""Apply photometric distortion to image sequentially, every transformation
|
| 585 |
+
is applied with a probability of 0.5. The position of random contrast is in
|
| 586 |
+
second or second to last.
|
| 587 |
+
|
| 588 |
+
1. random brightness
|
| 589 |
+
2. random contrast (mode 0)
|
| 590 |
+
3. convert color from BGR to HSV
|
| 591 |
+
4. random saturation
|
| 592 |
+
5. random hue
|
| 593 |
+
6. convert color from HSV to BGR
|
| 594 |
+
7. random contrast (mode 1)
|
| 595 |
+
|
| 596 |
+
Required Keys:
|
| 597 |
+
|
| 598 |
+
- img
|
| 599 |
+
|
| 600 |
+
Modified Keys:
|
| 601 |
+
|
| 602 |
+
- img
|
| 603 |
+
|
| 604 |
+
Args:
|
| 605 |
+
brightness_delta (int): delta of brightness.
|
| 606 |
+
contrast_range (tuple): range of contrast.
|
| 607 |
+
saturation_range (tuple): range of saturation.
|
| 608 |
+
hue_delta (int): delta of hue.
|
| 609 |
+
"""
|
| 610 |
+
|
| 611 |
+
def __init__(self,
|
| 612 |
+
brightness_delta: int = 32,
|
| 613 |
+
contrast_range: Sequence[float] = (0.5, 1.5),
|
| 614 |
+
saturation_range: Sequence[float] = (0.5, 1.5),
|
| 615 |
+
hue_delta: int = 18):
|
| 616 |
+
self.brightness_delta = brightness_delta
|
| 617 |
+
self.contrast_lower, self.contrast_upper = contrast_range
|
| 618 |
+
self.saturation_lower, self.saturation_upper = saturation_range
|
| 619 |
+
self.hue_delta = hue_delta
|
| 620 |
+
|
| 621 |
+
def convert(self,
|
| 622 |
+
img: np.ndarray,
|
| 623 |
+
alpha: int = 1,
|
| 624 |
+
beta: int = 0) -> np.ndarray:
|
| 625 |
+
"""Multiple with alpha and add beat with clip.
|
| 626 |
+
|
| 627 |
+
Args:
|
| 628 |
+
img (np.ndarray): The input image.
|
| 629 |
+
alpha (int): Image weights, change the contrast/saturation
|
| 630 |
+
of the image. Default: 1
|
| 631 |
+
beta (int): Image bias, change the brightness of the
|
| 632 |
+
image. Default: 0
|
| 633 |
+
|
| 634 |
+
Returns:
|
| 635 |
+
np.ndarray: The transformed image.
|
| 636 |
+
"""
|
| 637 |
+
|
| 638 |
+
img = img.astype(np.float32) * alpha + beta
|
| 639 |
+
img = np.clip(img, 0, 255)
|
| 640 |
+
return img.astype(np.uint8)
|
| 641 |
+
|
| 642 |
+
def brightness(self, img: np.ndarray) -> np.ndarray:
|
| 643 |
+
"""Brightness distortion.
|
| 644 |
+
|
| 645 |
+
Args:
|
| 646 |
+
img (np.ndarray): The input image.
|
| 647 |
+
Returns:
|
| 648 |
+
np.ndarray: Image after brightness change.
|
| 649 |
+
"""
|
| 650 |
+
|
| 651 |
+
if random.randint(2):
|
| 652 |
+
return self.convert(
|
| 653 |
+
img,
|
| 654 |
+
beta=random.uniform(-self.brightness_delta,
|
| 655 |
+
self.brightness_delta))
|
| 656 |
+
return img
|
| 657 |
+
|
| 658 |
+
def contrast(self, img: np.ndarray) -> np.ndarray:
|
| 659 |
+
"""Contrast distortion.
|
| 660 |
+
|
| 661 |
+
Args:
|
| 662 |
+
img (np.ndarray): The input image.
|
| 663 |
+
Returns:
|
| 664 |
+
np.ndarray: Image after contrast change.
|
| 665 |
+
"""
|
| 666 |
+
|
| 667 |
+
if random.randint(2):
|
| 668 |
+
return self.convert(
|
| 669 |
+
img,
|
| 670 |
+
alpha=random.uniform(self.contrast_lower, self.contrast_upper))
|
| 671 |
+
return img
|
| 672 |
+
|
| 673 |
+
def saturation(self, img: np.ndarray) -> np.ndarray:
|
| 674 |
+
"""Saturation distortion.
|
| 675 |
+
|
| 676 |
+
Args:
|
| 677 |
+
img (np.ndarray): The input image.
|
| 678 |
+
Returns:
|
| 679 |
+
np.ndarray: Image after saturation change.
|
| 680 |
+
"""
|
| 681 |
+
|
| 682 |
+
if random.randint(2):
|
| 683 |
+
img = mmcv.bgr2hsv(img)
|
| 684 |
+
img[:, :, 1] = self.convert(
|
| 685 |
+
img[:, :, 1],
|
| 686 |
+
alpha=random.uniform(self.saturation_lower,
|
| 687 |
+
self.saturation_upper))
|
| 688 |
+
img = mmcv.hsv2bgr(img)
|
| 689 |
+
return img
|
| 690 |
+
|
| 691 |
+
def hue(self, img: np.ndarray) -> np.ndarray:
|
| 692 |
+
"""Hue distortion.
|
| 693 |
+
|
| 694 |
+
Args:
|
| 695 |
+
img (np.ndarray): The input image.
|
| 696 |
+
Returns:
|
| 697 |
+
np.ndarray: Image after hue change.
|
| 698 |
+
"""
|
| 699 |
+
|
| 700 |
+
if random.randint(2):
|
| 701 |
+
img = mmcv.bgr2hsv(img)
|
| 702 |
+
img[:, :,
|
| 703 |
+
0] = (img[:, :, 0].astype(int) +
|
| 704 |
+
random.randint(-self.hue_delta, self.hue_delta)) % 180
|
| 705 |
+
img = mmcv.hsv2bgr(img)
|
| 706 |
+
return img
|
| 707 |
+
|
| 708 |
+
def transform(self, results: dict) -> dict:
|
| 709 |
+
"""Transform function to perform photometric distortion on images.
|
| 710 |
+
|
| 711 |
+
Args:
|
| 712 |
+
results (dict): Result dict from loading pipeline.
|
| 713 |
+
|
| 714 |
+
Returns:
|
| 715 |
+
dict: Result dict with images distorted.
|
| 716 |
+
"""
|
| 717 |
+
|
| 718 |
+
img = results['img']
|
| 719 |
+
# random brightness
|
| 720 |
+
img = self.brightness(img)
|
| 721 |
+
|
| 722 |
+
# mode == 0 --> do random contrast first
|
| 723 |
+
# mode == 1 --> do random contrast last
|
| 724 |
+
mode = random.randint(2)
|
| 725 |
+
if mode == 1:
|
| 726 |
+
img = self.contrast(img)
|
| 727 |
+
|
| 728 |
+
# random saturation
|
| 729 |
+
img = self.saturation(img)
|
| 730 |
+
|
| 731 |
+
# random hue
|
| 732 |
+
img = self.hue(img)
|
| 733 |
+
|
| 734 |
+
# random contrast
|
| 735 |
+
if mode == 0:
|
| 736 |
+
img = self.contrast(img)
|
| 737 |
+
|
| 738 |
+
results['img'] = img
|
| 739 |
+
return results
|
| 740 |
+
|
| 741 |
+
def __repr__(self):
|
| 742 |
+
repr_str = self.__class__.__name__
|
| 743 |
+
repr_str += (f'(brightness_delta={self.brightness_delta}, '
|
| 744 |
+
f'contrast_range=({self.contrast_lower}, '
|
| 745 |
+
f'{self.contrast_upper}), '
|
| 746 |
+
f'saturation_range=({self.saturation_lower}, '
|
| 747 |
+
f'{self.saturation_upper}), '
|
| 748 |
+
f'hue_delta={self.hue_delta})')
|
| 749 |
+
return repr_str
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
@TRANSFORMS.register_module()
|
| 753 |
+
class RandomCutOut(BaseTransform):
|
| 754 |
+
"""CutOut operation.
|
| 755 |
+
|
| 756 |
+
Randomly drop some regions of image used in
|
| 757 |
+
`Cutout <https://arxiv.org/abs/1708.04552>`_.
|
| 758 |
+
|
| 759 |
+
Required Keys:
|
| 760 |
+
|
| 761 |
+
- img
|
| 762 |
+
- gt_seg_map
|
| 763 |
+
|
| 764 |
+
Modified Keys:
|
| 765 |
+
|
| 766 |
+
- img
|
| 767 |
+
- gt_seg_map
|
| 768 |
+
|
| 769 |
+
Args:
|
| 770 |
+
prob (float): cutout probability.
|
| 771 |
+
n_holes (int | tuple[int, int]): Number of regions to be dropped.
|
| 772 |
+
If it is given as a list, number of holes will be randomly
|
| 773 |
+
selected from the closed interval [`n_holes[0]`, `n_holes[1]`].
|
| 774 |
+
cutout_shape (tuple[int, int] | list[tuple[int, int]]): The candidate
|
| 775 |
+
shape of dropped regions. It can be `tuple[int, int]` to use a
|
| 776 |
+
fixed cutout shape, or `list[tuple[int, int]]` to randomly choose
|
| 777 |
+
shape from the list.
|
| 778 |
+
cutout_ratio (tuple[float, float] | list[tuple[float, float]]): The
|
| 779 |
+
candidate ratio of dropped regions. It can be `tuple[float, float]`
|
| 780 |
+
to use a fixed ratio or `list[tuple[float, float]]` to randomly
|
| 781 |
+
choose ratio from the list. Please note that `cutout_shape`
|
| 782 |
+
and `cutout_ratio` cannot be both given at the same time.
|
| 783 |
+
fill_in (tuple[float, float, float] | tuple[int, int, int]): The value
|
| 784 |
+
of pixel to fill in the dropped regions. Default: (0, 0, 0).
|
| 785 |
+
seg_fill_in (int): The labels of pixel to fill in the dropped regions.
|
| 786 |
+
If seg_fill_in is None, skip. Default: None.
|
| 787 |
+
"""
|
| 788 |
+
|
| 789 |
+
def __init__(self,
|
| 790 |
+
prob,
|
| 791 |
+
n_holes,
|
| 792 |
+
cutout_shape=None,
|
| 793 |
+
cutout_ratio=None,
|
| 794 |
+
fill_in=(0, 0, 0),
|
| 795 |
+
seg_fill_in=None):
|
| 796 |
+
|
| 797 |
+
assert 0 <= prob and prob <= 1
|
| 798 |
+
assert (cutout_shape is None) ^ (cutout_ratio is None), \
|
| 799 |
+
'Either cutout_shape or cutout_ratio should be specified.'
|
| 800 |
+
assert (isinstance(cutout_shape, (list, tuple))
|
| 801 |
+
or isinstance(cutout_ratio, (list, tuple)))
|
| 802 |
+
if isinstance(n_holes, tuple):
|
| 803 |
+
assert len(n_holes) == 2 and 0 <= n_holes[0] < n_holes[1]
|
| 804 |
+
else:
|
| 805 |
+
n_holes = (n_holes, n_holes)
|
| 806 |
+
if seg_fill_in is not None:
|
| 807 |
+
assert (isinstance(seg_fill_in, int) and 0 <= seg_fill_in
|
| 808 |
+
and seg_fill_in <= 255)
|
| 809 |
+
self.prob = prob
|
| 810 |
+
self.n_holes = n_holes
|
| 811 |
+
self.fill_in = fill_in
|
| 812 |
+
self.seg_fill_in = seg_fill_in
|
| 813 |
+
self.with_ratio = cutout_ratio is not None
|
| 814 |
+
self.candidates = cutout_ratio if self.with_ratio else cutout_shape
|
| 815 |
+
if not isinstance(self.candidates, list):
|
| 816 |
+
self.candidates = [self.candidates]
|
| 817 |
+
|
| 818 |
+
@cache_randomness
|
| 819 |
+
def do_cutout(self):
|
| 820 |
+
return np.random.rand() < self.prob
|
| 821 |
+
|
| 822 |
+
@cache_randomness
|
| 823 |
+
def generate_patches(self, results):
|
| 824 |
+
cutout = self.do_cutout()
|
| 825 |
+
|
| 826 |
+
h, w, _ = results['img'].shape
|
| 827 |
+
if cutout:
|
| 828 |
+
n_holes = np.random.randint(self.n_holes[0], self.n_holes[1] + 1)
|
| 829 |
+
else:
|
| 830 |
+
n_holes = 0
|
| 831 |
+
x1_lst = []
|
| 832 |
+
y1_lst = []
|
| 833 |
+
index_lst = []
|
| 834 |
+
for _ in range(n_holes):
|
| 835 |
+
x1_lst.append(np.random.randint(0, w))
|
| 836 |
+
y1_lst.append(np.random.randint(0, h))
|
| 837 |
+
index_lst.append(np.random.randint(0, len(self.candidates)))
|
| 838 |
+
return cutout, n_holes, x1_lst, y1_lst, index_lst
|
| 839 |
+
|
| 840 |
+
def transform(self, results: dict) -> dict:
|
| 841 |
+
"""Call function to drop some regions of image."""
|
| 842 |
+
cutout, n_holes, x1_lst, y1_lst, index_lst = self.generate_patches(
|
| 843 |
+
results)
|
| 844 |
+
if cutout:
|
| 845 |
+
h, w, c = results['img'].shape
|
| 846 |
+
for i in range(n_holes):
|
| 847 |
+
x1 = x1_lst[i]
|
| 848 |
+
y1 = y1_lst[i]
|
| 849 |
+
index = index_lst[i]
|
| 850 |
+
if not self.with_ratio:
|
| 851 |
+
cutout_w, cutout_h = self.candidates[index]
|
| 852 |
+
else:
|
| 853 |
+
cutout_w = int(self.candidates[index][0] * w)
|
| 854 |
+
cutout_h = int(self.candidates[index][1] * h)
|
| 855 |
+
|
| 856 |
+
x2 = np.clip(x1 + cutout_w, 0, w)
|
| 857 |
+
y2 = np.clip(y1 + cutout_h, 0, h)
|
| 858 |
+
results['img'][y1:y2, x1:x2, :] = self.fill_in
|
| 859 |
+
|
| 860 |
+
if self.seg_fill_in is not None:
|
| 861 |
+
for key in results.get('seg_fields', []):
|
| 862 |
+
results[key][y1:y2, x1:x2] = self.seg_fill_in
|
| 863 |
+
|
| 864 |
+
return results
|
| 865 |
+
|
| 866 |
+
def __repr__(self):
|
| 867 |
+
repr_str = self.__class__.__name__
|
| 868 |
+
repr_str += f'(prob={self.prob}, '
|
| 869 |
+
repr_str += f'n_holes={self.n_holes}, '
|
| 870 |
+
repr_str += (f'cutout_ratio={self.candidates}, ' if self.with_ratio
|
| 871 |
+
else f'cutout_shape={self.candidates}, ')
|
| 872 |
+
repr_str += f'fill_in={self.fill_in}, '
|
| 873 |
+
repr_str += f'seg_fill_in={self.seg_fill_in})'
|
| 874 |
+
return repr_str
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
@TRANSFORMS.register_module()
|
| 878 |
+
class RandomRotFlip(BaseTransform):
|
| 879 |
+
"""Rotate and flip the image & seg or just rotate the image & seg.
|
| 880 |
+
|
| 881 |
+
Required Keys:
|
| 882 |
+
|
| 883 |
+
- img
|
| 884 |
+
- gt_seg_map
|
| 885 |
+
|
| 886 |
+
Modified Keys:
|
| 887 |
+
|
| 888 |
+
- img
|
| 889 |
+
- gt_seg_map
|
| 890 |
+
|
| 891 |
+
Args:
|
| 892 |
+
rotate_prob (float): The probability of rotate image.
|
| 893 |
+
flip_prob (float): The probability of rotate&flip image.
|
| 894 |
+
degree (float, tuple[float]): Range of degrees to select from. If
|
| 895 |
+
degree is a number instead of tuple like (min, max),
|
| 896 |
+
the range of degree will be (``-degree``, ``+degree``)
|
| 897 |
+
"""
|
| 898 |
+
|
| 899 |
+
def __init__(self, rotate_prob=0.5, flip_prob=0.5, degree=(-20, 20)):
|
| 900 |
+
self.rotate_prob = rotate_prob
|
| 901 |
+
self.flip_prob = flip_prob
|
| 902 |
+
assert 0 <= rotate_prob <= 1 and 0 <= flip_prob <= 1
|
| 903 |
+
if isinstance(degree, (float, int)):
|
| 904 |
+
assert degree > 0, f'degree {degree} should be positive'
|
| 905 |
+
self.degree = (-degree, degree)
|
| 906 |
+
else:
|
| 907 |
+
self.degree = degree
|
| 908 |
+
assert len(self.degree) == 2, f'degree {self.degree} should be a ' \
|
| 909 |
+
f'tuple of (min, max)'
|
| 910 |
+
|
| 911 |
+
def random_rot_flip(self, results: dict) -> dict:
|
| 912 |
+
k = np.random.randint(0, 4)
|
| 913 |
+
results['img'] = np.rot90(results['img'], k)
|
| 914 |
+
for key in results.get('seg_fields', []):
|
| 915 |
+
results[key] = np.rot90(results[key], k)
|
| 916 |
+
axis = np.random.randint(0, 2)
|
| 917 |
+
results['img'] = np.flip(results['img'], axis=axis).copy()
|
| 918 |
+
for key in results.get('seg_fields', []):
|
| 919 |
+
results[key] = np.flip(results[key], axis=axis).copy()
|
| 920 |
+
return results
|
| 921 |
+
|
| 922 |
+
def random_rotate(self, results: dict) -> dict:
|
| 923 |
+
angle = np.random.uniform(min(*self.degree), max(*self.degree))
|
| 924 |
+
results['img'] = mmcv.imrotate(results['img'], angle=angle)
|
| 925 |
+
for key in results.get('seg_fields', []):
|
| 926 |
+
results[key] = mmcv.imrotate(results[key], angle=angle)
|
| 927 |
+
return results
|
| 928 |
+
|
| 929 |
+
def transform(self, results: dict) -> dict:
|
| 930 |
+
"""Call function to rotate or rotate & flip image, semantic
|
| 931 |
+
segmentation maps.
|
| 932 |
+
|
| 933 |
+
Args:
|
| 934 |
+
results (dict): Result dict from loading pipeline.
|
| 935 |
+
|
| 936 |
+
Returns:
|
| 937 |
+
dict: Rotated or rotated & flipped results.
|
| 938 |
+
"""
|
| 939 |
+
rotate_flag = 0
|
| 940 |
+
if random.random() < self.rotate_prob:
|
| 941 |
+
results = self.random_rotate(results)
|
| 942 |
+
rotate_flag = 1
|
| 943 |
+
if random.random() < self.flip_prob and rotate_flag == 0:
|
| 944 |
+
results = self.random_rot_flip(results)
|
| 945 |
+
return results
|
| 946 |
+
|
| 947 |
+
def __repr__(self):
|
| 948 |
+
repr_str = self.__class__.__name__
|
| 949 |
+
repr_str += f'(rotate_prob={self.rotate_prob}, ' \
|
| 950 |
+
f'flip_prob={self.flip_prob}, ' \
|
| 951 |
+
f'degree={self.degree})'
|
| 952 |
+
return repr_str
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
@TRANSFORMS.register_module()
|
| 956 |
+
class RandomFlip(MMCV_RandomFlip):
|
| 957 |
+
"""Flip the image & bbox & segmentation map. Added or Updated
|
| 958 |
+
keys: flip, flip_direction, img, gt_bboxes, gt_seg_map, and gt_depth_map.
|
| 959 |
+
There are 3 flip modes:
|
| 960 |
+
|
| 961 |
+
- ``prob`` is float, ``direction`` is string: the image will be
|
| 962 |
+
``direction``ly flipped with probability of ``prob`` .
|
| 963 |
+
E.g., ``prob=0.5``, ``direction='horizontal'``,
|
| 964 |
+
then image will be horizontally flipped with probability of 0.5.
|
| 965 |
+
|
| 966 |
+
- ``prob`` is float, ``direction`` is list of string: the image will
|
| 967 |
+
be ``direction[i]``ly flipped with probability of
|
| 968 |
+
``prob/len(direction)``.
|
| 969 |
+
E.g., ``prob=0.5``, ``direction=['horizontal', 'vertical']``,
|
| 970 |
+
then image will be horizontally flipped with probability of 0.25,
|
| 971 |
+
vertically with probability of 0.25.
|
| 972 |
+
|
| 973 |
+
- ``prob`` is list of float, ``direction`` is list of string:
|
| 974 |
+
given ``len(prob) == len(direction)``, the image will
|
| 975 |
+
be ``direction[i]``ly flipped with probability of ``prob[i]``.
|
| 976 |
+
E.g., ``prob=[0.3, 0.5]``, ``direction=['horizontal',
|
| 977 |
+
'vertical']``, then image will be horizontally flipped with
|
| 978 |
+
probability of 0.3, vertically with probability of 0.5.
|
| 979 |
+
|
| 980 |
+
Required Keys:
|
| 981 |
+
|
| 982 |
+
- img
|
| 983 |
+
- gt_bboxes (optional)
|
| 984 |
+
- gt_seg_map (optional)
|
| 985 |
+
- gt_depth_map (optional)
|
| 986 |
+
|
| 987 |
+
Modified Keys:
|
| 988 |
+
|
| 989 |
+
- img
|
| 990 |
+
- gt_bboxes (optional)
|
| 991 |
+
- gt_seg_map (optional)
|
| 992 |
+
- gt_depth_map (optional)
|
| 993 |
+
|
| 994 |
+
Added Keys:
|
| 995 |
+
|
| 996 |
+
- flip
|
| 997 |
+
- flip_direction
|
| 998 |
+
- swap_seg_labels (optional)
|
| 999 |
+
|
| 1000 |
+
Args:
|
| 1001 |
+
prob (float | list[float], optional): The flipping probability.
|
| 1002 |
+
Defaults to None.
|
| 1003 |
+
direction(str | list[str]): The flipping direction. Options
|
| 1004 |
+
If input is a list, the length must equal ``prob``. Each
|
| 1005 |
+
element in ``prob`` indicates the flip probability of
|
| 1006 |
+
corresponding direction. Defaults to 'horizontal'.
|
| 1007 |
+
swap_seg_labels (list, optional): The label pair need to be swapped
|
| 1008 |
+
for ground truth, like 'left arm' and 'right arm' need to be
|
| 1009 |
+
swapped after horizontal flipping. For example, ``[(1, 5)]``,
|
| 1010 |
+
where 1/5 is the label of the left/right arm. Defaults to None.
|
| 1011 |
+
"""
|
| 1012 |
+
|
| 1013 |
+
def _flip(self, results: dict) -> None:
|
| 1014 |
+
"""Flip images, bounding boxes and semantic segmentation map."""
|
| 1015 |
+
# flip image
|
| 1016 |
+
results['img'] = mmcv.imflip(
|
| 1017 |
+
results['img'], direction=results['flip_direction'])
|
| 1018 |
+
|
| 1019 |
+
img_shape = results['img'].shape[:2]
|
| 1020 |
+
|
| 1021 |
+
# flip bboxes
|
| 1022 |
+
if results.get('gt_bboxes', None) is not None:
|
| 1023 |
+
results['gt_bboxes'] = self._flip_bbox(results['gt_bboxes'],
|
| 1024 |
+
img_shape,
|
| 1025 |
+
results['flip_direction'])
|
| 1026 |
+
|
| 1027 |
+
# flip seg map
|
| 1028 |
+
for key in results.get('seg_fields', []):
|
| 1029 |
+
if results.get(key, None) is not None:
|
| 1030 |
+
results[key] = self._flip_seg_map(
|
| 1031 |
+
results[key], direction=results['flip_direction']).copy()
|
| 1032 |
+
results['swap_seg_labels'] = self.swap_seg_labels
|
| 1033 |
+
|
| 1034 |
+
|
| 1035 |
+
@TRANSFORMS.register_module()
|
| 1036 |
+
class Resize(MMCV_Resize):
|
| 1037 |
+
"""Resize images & seg & depth map.
|
| 1038 |
+
|
| 1039 |
+
This transform resizes the input image according to ``scale`` or
|
| 1040 |
+
``scale_factor``. Seg map, depth map and other relative annotations are
|
| 1041 |
+
then resized with the same scale factor.
|
| 1042 |
+
if ``scale`` and ``scale_factor`` are both set, it will use ``scale`` to
|
| 1043 |
+
resize.
|
| 1044 |
+
|
| 1045 |
+
Required Keys:
|
| 1046 |
+
|
| 1047 |
+
- img
|
| 1048 |
+
- gt_seg_map (optional)
|
| 1049 |
+
- gt_depth_map (optional)
|
| 1050 |
+
|
| 1051 |
+
Modified Keys:
|
| 1052 |
+
|
| 1053 |
+
- img
|
| 1054 |
+
- gt_seg_map
|
| 1055 |
+
- gt_depth_map
|
| 1056 |
+
|
| 1057 |
+
Added Keys:
|
| 1058 |
+
|
| 1059 |
+
- scale
|
| 1060 |
+
- scale_factor
|
| 1061 |
+
- keep_ratio
|
| 1062 |
+
|
| 1063 |
+
Args:
|
| 1064 |
+
scale (int or tuple): Images scales for resizing. Defaults to None
|
| 1065 |
+
scale_factor (float or tuple[float]): Scale factors for resizing.
|
| 1066 |
+
Defaults to None.
|
| 1067 |
+
keep_ratio (bool): Whether to keep the aspect ratio when resizing the
|
| 1068 |
+
image. Defaults to False.
|
| 1069 |
+
clip_object_border (bool): Whether to clip the objects
|
| 1070 |
+
outside the border of the image. In some dataset like MOT17, the gt
|
| 1071 |
+
bboxes are allowed to cross the border of images. Therefore, we
|
| 1072 |
+
don't need to clip the gt bboxes in these cases. Defaults to True.
|
| 1073 |
+
backend (str): Image resize backend, choices are 'cv2' and 'pillow'.
|
| 1074 |
+
These two backends generates slightly different results. Defaults
|
| 1075 |
+
to 'cv2'.
|
| 1076 |
+
interpolation (str): Interpolation method, accepted values are
|
| 1077 |
+
"nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2'
|
| 1078 |
+
backend, "nearest", "bilinear" for 'pillow' backend. Defaults
|
| 1079 |
+
to 'bilinear'.
|
| 1080 |
+
"""
|
| 1081 |
+
|
| 1082 |
+
def _resize_seg(self, results: dict) -> None:
|
| 1083 |
+
"""Resize semantic segmentation map with ``results['scale']``."""
|
| 1084 |
+
for seg_key in results.get('seg_fields', []):
|
| 1085 |
+
if results.get(seg_key, None) is not None:
|
| 1086 |
+
if self.keep_ratio:
|
| 1087 |
+
gt_seg = mmcv.imrescale(
|
| 1088 |
+
results[seg_key],
|
| 1089 |
+
results['scale'],
|
| 1090 |
+
interpolation='nearest',
|
| 1091 |
+
backend=self.backend)
|
| 1092 |
+
else:
|
| 1093 |
+
gt_seg = mmcv.imresize(
|
| 1094 |
+
results[seg_key],
|
| 1095 |
+
results['scale'],
|
| 1096 |
+
interpolation='nearest',
|
| 1097 |
+
backend=self.backend)
|
| 1098 |
+
results[seg_key] = gt_seg
|
| 1099 |
+
|
| 1100 |
+
|
| 1101 |
+
@TRANSFORMS.register_module()
|
| 1102 |
+
class RandomMosaic(BaseTransform):
|
| 1103 |
+
"""Mosaic augmentation. Given 4 images, mosaic transform combines them into
|
| 1104 |
+
one output image. The output image is composed of the parts from each sub-
|
| 1105 |
+
image.
|
| 1106 |
+
|
| 1107 |
+
.. code:: text
|
| 1108 |
+
|
| 1109 |
+
mosaic transform
|
| 1110 |
+
center_x
|
| 1111 |
+
+------------------------------+
|
| 1112 |
+
| pad | pad |
|
| 1113 |
+
| +-----------+ |
|
| 1114 |
+
| | | |
|
| 1115 |
+
| | image1 |--------+ |
|
| 1116 |
+
| | | | |
|
| 1117 |
+
| | | image2 | |
|
| 1118 |
+
center_y |----+-------------+-----------|
|
| 1119 |
+
| | cropped | |
|
| 1120 |
+
|pad | image3 | image4 |
|
| 1121 |
+
| | | |
|
| 1122 |
+
+----|-------------+-----------+
|
| 1123 |
+
| |
|
| 1124 |
+
+-------------+
|
| 1125 |
+
|
| 1126 |
+
The mosaic transform steps are as follows:
|
| 1127 |
+
1. Choose the mosaic center as the intersections of 4 images
|
| 1128 |
+
2. Get the left top image according to the index, and randomly
|
| 1129 |
+
sample another 3 images from the custom dataset.
|
| 1130 |
+
3. Sub image will be cropped if image is larger than mosaic patch
|
| 1131 |
+
|
| 1132 |
+
Required Keys:
|
| 1133 |
+
|
| 1134 |
+
- img
|
| 1135 |
+
- gt_seg_map
|
| 1136 |
+
- mix_results
|
| 1137 |
+
|
| 1138 |
+
Modified Keys:
|
| 1139 |
+
|
| 1140 |
+
- img
|
| 1141 |
+
- img_shape
|
| 1142 |
+
- ori_shape
|
| 1143 |
+
- gt_seg_map
|
| 1144 |
+
|
| 1145 |
+
Args:
|
| 1146 |
+
prob (float): mosaic probability.
|
| 1147 |
+
img_scale (Sequence[int]): Image size after mosaic pipeline of
|
| 1148 |
+
a single image. The size of the output image is four times
|
| 1149 |
+
that of a single image. The output image comprises 4 single images.
|
| 1150 |
+
Default: (640, 640).
|
| 1151 |
+
center_ratio_range (Sequence[float]): Center ratio range of mosaic
|
| 1152 |
+
output. Default: (0.5, 1.5).
|
| 1153 |
+
pad_val (int): Pad value. Default: 0.
|
| 1154 |
+
seg_pad_val (int): Pad value of segmentation map. Default: 255.
|
| 1155 |
+
"""
|
| 1156 |
+
|
| 1157 |
+
def __init__(self,
|
| 1158 |
+
prob,
|
| 1159 |
+
img_scale=(640, 640),
|
| 1160 |
+
center_ratio_range=(0.5, 1.5),
|
| 1161 |
+
pad_val=0,
|
| 1162 |
+
seg_pad_val=255):
|
| 1163 |
+
assert 0 <= prob and prob <= 1
|
| 1164 |
+
assert isinstance(img_scale, tuple)
|
| 1165 |
+
self.prob = prob
|
| 1166 |
+
self.img_scale = img_scale
|
| 1167 |
+
self.center_ratio_range = center_ratio_range
|
| 1168 |
+
self.pad_val = pad_val
|
| 1169 |
+
self.seg_pad_val = seg_pad_val
|
| 1170 |
+
|
| 1171 |
+
@cache_randomness
|
| 1172 |
+
def do_mosaic(self):
|
| 1173 |
+
return np.random.rand() < self.prob
|
| 1174 |
+
|
| 1175 |
+
def transform(self, results: dict) -> dict:
|
| 1176 |
+
"""Call function to make a mosaic of image.
|
| 1177 |
+
|
| 1178 |
+
Args:
|
| 1179 |
+
results (dict): Result dict.
|
| 1180 |
+
|
| 1181 |
+
Returns:
|
| 1182 |
+
dict: Result dict with mosaic transformed.
|
| 1183 |
+
"""
|
| 1184 |
+
mosaic = self.do_mosaic()
|
| 1185 |
+
if mosaic:
|
| 1186 |
+
results = self._mosaic_transform_img(results)
|
| 1187 |
+
results = self._mosaic_transform_seg(results)
|
| 1188 |
+
return results
|
| 1189 |
+
|
| 1190 |
+
def get_indices(self, dataset: MultiImageMixDataset) -> list:
|
| 1191 |
+
"""Call function to collect indices.
|
| 1192 |
+
|
| 1193 |
+
Args:
|
| 1194 |
+
dataset (:obj:`MultiImageMixDataset`): The dataset.
|
| 1195 |
+
|
| 1196 |
+
Returns:
|
| 1197 |
+
list: indices.
|
| 1198 |
+
"""
|
| 1199 |
+
|
| 1200 |
+
indices = [random.randint(0, len(dataset)) for _ in range(3)]
|
| 1201 |
+
return indices
|
| 1202 |
+
|
| 1203 |
+
@cache_randomness
|
| 1204 |
+
def generate_mosaic_center(self):
|
| 1205 |
+
# mosaic center x, y
|
| 1206 |
+
center_x = int(
|
| 1207 |
+
random.uniform(*self.center_ratio_range) * self.img_scale[1])
|
| 1208 |
+
center_y = int(
|
| 1209 |
+
random.uniform(*self.center_ratio_range) * self.img_scale[0])
|
| 1210 |
+
return center_x, center_y
|
| 1211 |
+
|
| 1212 |
+
def _mosaic_transform_img(self, results: dict) -> dict:
|
| 1213 |
+
"""Mosaic transform function.
|
| 1214 |
+
|
| 1215 |
+
Args:
|
| 1216 |
+
results (dict): Result dict.
|
| 1217 |
+
|
| 1218 |
+
Returns:
|
| 1219 |
+
dict: Updated result dict.
|
| 1220 |
+
"""
|
| 1221 |
+
|
| 1222 |
+
assert 'mix_results' in results
|
| 1223 |
+
if len(results['img'].shape) == 3:
|
| 1224 |
+
c = results['img'].shape[2]
|
| 1225 |
+
mosaic_img = np.full(
|
| 1226 |
+
(int(self.img_scale[0] * 2), int(self.img_scale[1] * 2), c),
|
| 1227 |
+
self.pad_val,
|
| 1228 |
+
dtype=results['img'].dtype)
|
| 1229 |
+
else:
|
| 1230 |
+
mosaic_img = np.full(
|
| 1231 |
+
(int(self.img_scale[0] * 2), int(self.img_scale[1] * 2)),
|
| 1232 |
+
self.pad_val,
|
| 1233 |
+
dtype=results['img'].dtype)
|
| 1234 |
+
|
| 1235 |
+
# mosaic center x, y
|
| 1236 |
+
self.center_x, self.center_y = self.generate_mosaic_center()
|
| 1237 |
+
center_position = (self.center_x, self.center_y)
|
| 1238 |
+
|
| 1239 |
+
loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right')
|
| 1240 |
+
for i, loc in enumerate(loc_strs):
|
| 1241 |
+
if loc == 'top_left':
|
| 1242 |
+
result_patch = copy.deepcopy(results)
|
| 1243 |
+
else:
|
| 1244 |
+
result_patch = copy.deepcopy(results['mix_results'][i - 1])
|
| 1245 |
+
|
| 1246 |
+
img_i = result_patch['img']
|
| 1247 |
+
h_i, w_i = img_i.shape[:2]
|
| 1248 |
+
# keep_ratio resize
|
| 1249 |
+
scale_ratio_i = min(self.img_scale[0] / h_i,
|
| 1250 |
+
self.img_scale[1] / w_i)
|
| 1251 |
+
img_i = mmcv.imresize(
|
| 1252 |
+
img_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i)))
|
| 1253 |
+
|
| 1254 |
+
# compute the combine parameters
|
| 1255 |
+
paste_coord, crop_coord = self._mosaic_combine(
|
| 1256 |
+
loc, center_position, img_i.shape[:2][::-1])
|
| 1257 |
+
x1_p, y1_p, x2_p, y2_p = paste_coord
|
| 1258 |
+
x1_c, y1_c, x2_c, y2_c = crop_coord
|
| 1259 |
+
|
| 1260 |
+
# crop and paste image
|
| 1261 |
+
mosaic_img[y1_p:y2_p, x1_p:x2_p] = img_i[y1_c:y2_c, x1_c:x2_c]
|
| 1262 |
+
|
| 1263 |
+
results['img'] = mosaic_img
|
| 1264 |
+
results['img_shape'] = mosaic_img.shape
|
| 1265 |
+
results['ori_shape'] = mosaic_img.shape
|
| 1266 |
+
|
| 1267 |
+
return results
|
| 1268 |
+
|
| 1269 |
+
def _mosaic_transform_seg(self, results: dict) -> dict:
|
| 1270 |
+
"""Mosaic transform function for label annotations.
|
| 1271 |
+
|
| 1272 |
+
Args:
|
| 1273 |
+
results (dict): Result dict.
|
| 1274 |
+
|
| 1275 |
+
Returns:
|
| 1276 |
+
dict: Updated result dict.
|
| 1277 |
+
"""
|
| 1278 |
+
|
| 1279 |
+
assert 'mix_results' in results
|
| 1280 |
+
for key in results.get('seg_fields', []):
|
| 1281 |
+
mosaic_seg = np.full(
|
| 1282 |
+
(int(self.img_scale[0] * 2), int(self.img_scale[1] * 2)),
|
| 1283 |
+
self.seg_pad_val,
|
| 1284 |
+
dtype=results[key].dtype)
|
| 1285 |
+
|
| 1286 |
+
# mosaic center x, y
|
| 1287 |
+
center_position = (self.center_x, self.center_y)
|
| 1288 |
+
|
| 1289 |
+
loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right')
|
| 1290 |
+
for i, loc in enumerate(loc_strs):
|
| 1291 |
+
if loc == 'top_left':
|
| 1292 |
+
result_patch = copy.deepcopy(results)
|
| 1293 |
+
else:
|
| 1294 |
+
result_patch = copy.deepcopy(results['mix_results'][i - 1])
|
| 1295 |
+
|
| 1296 |
+
gt_seg_i = result_patch[key]
|
| 1297 |
+
h_i, w_i = gt_seg_i.shape[:2]
|
| 1298 |
+
# keep_ratio resize
|
| 1299 |
+
scale_ratio_i = min(self.img_scale[0] / h_i,
|
| 1300 |
+
self.img_scale[1] / w_i)
|
| 1301 |
+
gt_seg_i = mmcv.imresize(
|
| 1302 |
+
gt_seg_i,
|
| 1303 |
+
(int(w_i * scale_ratio_i), int(h_i * scale_ratio_i)),
|
| 1304 |
+
interpolation='nearest')
|
| 1305 |
+
|
| 1306 |
+
# compute the combine parameters
|
| 1307 |
+
paste_coord, crop_coord = self._mosaic_combine(
|
| 1308 |
+
loc, center_position, gt_seg_i.shape[:2][::-1])
|
| 1309 |
+
x1_p, y1_p, x2_p, y2_p = paste_coord
|
| 1310 |
+
x1_c, y1_c, x2_c, y2_c = crop_coord
|
| 1311 |
+
|
| 1312 |
+
# crop and paste image
|
| 1313 |
+
mosaic_seg[y1_p:y2_p, x1_p:x2_p] = \
|
| 1314 |
+
gt_seg_i[y1_c:y2_c, x1_c:x2_c]
|
| 1315 |
+
|
| 1316 |
+
results[key] = mosaic_seg
|
| 1317 |
+
|
| 1318 |
+
return results
|
| 1319 |
+
|
| 1320 |
+
def _mosaic_combine(self, loc: str, center_position_xy: Sequence[float],
|
| 1321 |
+
img_shape_wh: Sequence[int]) -> tuple:
|
| 1322 |
+
"""Calculate global coordinate of mosaic image and local coordinate of
|
| 1323 |
+
cropped sub-image.
|
| 1324 |
+
|
| 1325 |
+
Args:
|
| 1326 |
+
loc (str): Index for the sub-image, loc in ('top_left',
|
| 1327 |
+
'top_right', 'bottom_left', 'bottom_right').
|
| 1328 |
+
center_position_xy (Sequence[float]): Mixing center for 4 images,
|
| 1329 |
+
(x, y).
|
| 1330 |
+
img_shape_wh (Sequence[int]): Width and height of sub-image
|
| 1331 |
+
|
| 1332 |
+
Returns:
|
| 1333 |
+
tuple[tuple[float]]: Corresponding coordinate of pasting and
|
| 1334 |
+
cropping
|
| 1335 |
+
- paste_coord (tuple): paste corner coordinate in mosaic image.
|
| 1336 |
+
- crop_coord (tuple): crop corner coordinate in mosaic image.
|
| 1337 |
+
"""
|
| 1338 |
+
|
| 1339 |
+
assert loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right')
|
| 1340 |
+
if loc == 'top_left':
|
| 1341 |
+
# index0 to top left part of image
|
| 1342 |
+
x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \
|
| 1343 |
+
max(center_position_xy[1] - img_shape_wh[1], 0), \
|
| 1344 |
+
center_position_xy[0], \
|
| 1345 |
+
center_position_xy[1]
|
| 1346 |
+
crop_coord = img_shape_wh[0] - (x2 - x1), img_shape_wh[1] - (
|
| 1347 |
+
y2 - y1), img_shape_wh[0], img_shape_wh[1]
|
| 1348 |
+
|
| 1349 |
+
elif loc == 'top_right':
|
| 1350 |
+
# index1 to top right part of image
|
| 1351 |
+
x1, y1, x2, y2 = center_position_xy[0], \
|
| 1352 |
+
max(center_position_xy[1] - img_shape_wh[1], 0), \
|
| 1353 |
+
min(center_position_xy[0] + img_shape_wh[0],
|
| 1354 |
+
self.img_scale[1] * 2), \
|
| 1355 |
+
center_position_xy[1]
|
| 1356 |
+
crop_coord = 0, img_shape_wh[1] - (y2 - y1), min(
|
| 1357 |
+
img_shape_wh[0], x2 - x1), img_shape_wh[1]
|
| 1358 |
+
|
| 1359 |
+
elif loc == 'bottom_left':
|
| 1360 |
+
# index2 to bottom left part of image
|
| 1361 |
+
x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \
|
| 1362 |
+
center_position_xy[1], \
|
| 1363 |
+
center_position_xy[0], \
|
| 1364 |
+
min(self.img_scale[0] * 2, center_position_xy[1] +
|
| 1365 |
+
img_shape_wh[1])
|
| 1366 |
+
crop_coord = img_shape_wh[0] - (x2 - x1), 0, img_shape_wh[0], min(
|
| 1367 |
+
y2 - y1, img_shape_wh[1])
|
| 1368 |
+
|
| 1369 |
+
else:
|
| 1370 |
+
# index3 to bottom right part of image
|
| 1371 |
+
x1, y1, x2, y2 = center_position_xy[0], \
|
| 1372 |
+
center_position_xy[1], \
|
| 1373 |
+
min(center_position_xy[0] + img_shape_wh[0],
|
| 1374 |
+
self.img_scale[1] * 2), \
|
| 1375 |
+
min(self.img_scale[0] * 2, center_position_xy[1] +
|
| 1376 |
+
img_shape_wh[1])
|
| 1377 |
+
crop_coord = 0, 0, min(img_shape_wh[0],
|
| 1378 |
+
x2 - x1), min(y2 - y1, img_shape_wh[1])
|
| 1379 |
+
|
| 1380 |
+
paste_coord = x1, y1, x2, y2
|
| 1381 |
+
return paste_coord, crop_coord
|
| 1382 |
+
|
| 1383 |
+
def __repr__(self):
|
| 1384 |
+
repr_str = self.__class__.__name__
|
| 1385 |
+
repr_str += f'(prob={self.prob}, '
|
| 1386 |
+
repr_str += f'img_scale={self.img_scale}, '
|
| 1387 |
+
repr_str += f'center_ratio_range={self.center_ratio_range}, '
|
| 1388 |
+
repr_str += f'pad_val={self.pad_val}, '
|
| 1389 |
+
repr_str += f'seg_pad_val={self.pad_val})'
|
| 1390 |
+
return repr_str
|
| 1391 |
+
|
| 1392 |
+
|
| 1393 |
+
@TRANSFORMS.register_module()
|
| 1394 |
+
class GenerateEdge(BaseTransform):
|
| 1395 |
+
"""Generate Edge for CE2P approach.
|
| 1396 |
+
|
| 1397 |
+
Edge will be used to calculate loss of
|
| 1398 |
+
`CE2P <https://arxiv.org/abs/1809.05996>`_.
|
| 1399 |
+
|
| 1400 |
+
Modified from https://github.com/liutinglt/CE2P/blob/master/dataset/target_generation.py # noqa:E501
|
| 1401 |
+
|
| 1402 |
+
Required Keys:
|
| 1403 |
+
|
| 1404 |
+
- img_shape
|
| 1405 |
+
- gt_seg_map
|
| 1406 |
+
|
| 1407 |
+
Added Keys:
|
| 1408 |
+
- gt_edge_map (np.ndarray, uint8): The edge annotation generated from the
|
| 1409 |
+
seg map by extracting border between different semantics.
|
| 1410 |
+
|
| 1411 |
+
Args:
|
| 1412 |
+
edge_width (int): The width of edge. Default to 3.
|
| 1413 |
+
ignore_index (int): Index that will be ignored. Default to 255.
|
| 1414 |
+
"""
|
| 1415 |
+
|
| 1416 |
+
def __init__(self, edge_width: int = 3, ignore_index: int = 255) -> None:
|
| 1417 |
+
super().__init__()
|
| 1418 |
+
self.edge_width = edge_width
|
| 1419 |
+
self.ignore_index = ignore_index
|
| 1420 |
+
|
| 1421 |
+
def transform(self, results: Dict) -> Dict:
|
| 1422 |
+
"""Call function to generate edge from segmentation map.
|
| 1423 |
+
|
| 1424 |
+
Args:
|
| 1425 |
+
results (dict): Result dict.
|
| 1426 |
+
|
| 1427 |
+
Returns:
|
| 1428 |
+
dict: Result dict with edge mask.
|
| 1429 |
+
"""
|
| 1430 |
+
h, w = results['img_shape']
|
| 1431 |
+
edge = np.zeros((h, w), dtype=np.uint8)
|
| 1432 |
+
seg_map = results['gt_seg_map']
|
| 1433 |
+
|
| 1434 |
+
# down
|
| 1435 |
+
edge_down = edge[1:h, :]
|
| 1436 |
+
edge_down[(seg_map[1:h, :] != seg_map[:h - 1, :])
|
| 1437 |
+
& (seg_map[1:h, :] != self.ignore_index) &
|
| 1438 |
+
(seg_map[:h - 1, :] != self.ignore_index)] = 1
|
| 1439 |
+
# left
|
| 1440 |
+
edge_left = edge[:, :w - 1]
|
| 1441 |
+
edge_left[(seg_map[:, :w - 1] != seg_map[:, 1:w])
|
| 1442 |
+
& (seg_map[:, :w - 1] != self.ignore_index) &
|
| 1443 |
+
(seg_map[:, 1:w] != self.ignore_index)] = 1
|
| 1444 |
+
# up_left
|
| 1445 |
+
edge_upleft = edge[:h - 1, :w - 1]
|
| 1446 |
+
edge_upleft[(seg_map[:h - 1, :w - 1] != seg_map[1:h, 1:w])
|
| 1447 |
+
& (seg_map[:h - 1, :w - 1] != self.ignore_index) &
|
| 1448 |
+
(seg_map[1:h, 1:w] != self.ignore_index)] = 1
|
| 1449 |
+
# up_right
|
| 1450 |
+
edge_upright = edge[:h - 1, 1:w]
|
| 1451 |
+
edge_upright[(seg_map[:h - 1, 1:w] != seg_map[1:h, :w - 1])
|
| 1452 |
+
& (seg_map[:h - 1, 1:w] != self.ignore_index) &
|
| 1453 |
+
(seg_map[1:h, :w - 1] != self.ignore_index)] = 1
|
| 1454 |
+
|
| 1455 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,
|
| 1456 |
+
(self.edge_width, self.edge_width))
|
| 1457 |
+
edge = cv2.dilate(edge, kernel)
|
| 1458 |
+
|
| 1459 |
+
results['gt_edge_map'] = edge
|
| 1460 |
+
results['edge_width'] = self.edge_width
|
| 1461 |
+
|
| 1462 |
+
return results
|
| 1463 |
+
|
| 1464 |
+
def __repr__(self):
|
| 1465 |
+
repr_str = self.__class__.__name__
|
| 1466 |
+
repr_str += f'edge_width={self.edge_width}, '
|
| 1467 |
+
repr_str += f'ignore_index={self.ignore_index})'
|
| 1468 |
+
return repr_str
|
| 1469 |
+
|
| 1470 |
+
|
| 1471 |
+
@TRANSFORMS.register_module()
|
| 1472 |
+
class ResizeShortestEdge(BaseTransform):
|
| 1473 |
+
"""Resize the image and mask while keeping the aspect ratio unchanged.
|
| 1474 |
+
|
| 1475 |
+
Modified from https://github.com/facebookresearch/detectron2/blob/main/detectron2/data/transforms/augmentation_impl.py#L130 # noqa:E501
|
| 1476 |
+
Copyright (c) Facebook, Inc. and its affiliates.
|
| 1477 |
+
Licensed under the Apache-2.0 License
|
| 1478 |
+
|
| 1479 |
+
This transform attempts to scale the shorter edge to the given
|
| 1480 |
+
`scale`, as long as the longer edge does not exceed `max_size`.
|
| 1481 |
+
If `max_size` is reached, then downscale so that the longer
|
| 1482 |
+
edge does not exceed `max_size`.
|
| 1483 |
+
|
| 1484 |
+
Required Keys:
|
| 1485 |
+
|
| 1486 |
+
- img
|
| 1487 |
+
- gt_seg_map (optional)
|
| 1488 |
+
|
| 1489 |
+
Modified Keys:
|
| 1490 |
+
|
| 1491 |
+
- img
|
| 1492 |
+
- img_shape
|
| 1493 |
+
- gt_seg_map (optional))
|
| 1494 |
+
|
| 1495 |
+
Added Keys:
|
| 1496 |
+
|
| 1497 |
+
- scale
|
| 1498 |
+
- scale_factor
|
| 1499 |
+
- keep_ratio
|
| 1500 |
+
|
| 1501 |
+
|
| 1502 |
+
Args:
|
| 1503 |
+
scale (Union[int, Tuple[int, int]]): The target short edge length.
|
| 1504 |
+
If it's tuple, will select the min value as the short edge length.
|
| 1505 |
+
max_size (int): The maximum allowed longest edge length.
|
| 1506 |
+
"""
|
| 1507 |
+
|
| 1508 |
+
def __init__(self, scale: Union[int, Tuple[int, int]],
|
| 1509 |
+
max_size: int) -> None:
|
| 1510 |
+
super().__init__()
|
| 1511 |
+
self.scale = scale
|
| 1512 |
+
self.max_size = max_size
|
| 1513 |
+
|
| 1514 |
+
# Create a empty Resize object
|
| 1515 |
+
self.resize = TRANSFORMS.build({
|
| 1516 |
+
'type': 'Resize',
|
| 1517 |
+
'scale': 0,
|
| 1518 |
+
'keep_ratio': True
|
| 1519 |
+
})
|
| 1520 |
+
|
| 1521 |
+
def _get_output_shape(self, img, short_edge_length) -> Tuple[int, int]:
|
| 1522 |
+
"""Compute the target image shape with the given `short_edge_length`.
|
| 1523 |
+
|
| 1524 |
+
Args:
|
| 1525 |
+
img (np.ndarray): The input image.
|
| 1526 |
+
short_edge_length (Union[int, Tuple[int, int]]): The target short
|
| 1527 |
+
edge length. If it's tuple, will select the min value as the
|
| 1528 |
+
short edge length.
|
| 1529 |
+
"""
|
| 1530 |
+
h, w = img.shape[:2]
|
| 1531 |
+
if isinstance(short_edge_length, int):
|
| 1532 |
+
size = short_edge_length * 1.0
|
| 1533 |
+
elif isinstance(short_edge_length, tuple):
|
| 1534 |
+
size = min(short_edge_length) * 1.0
|
| 1535 |
+
scale = size / min(h, w)
|
| 1536 |
+
if h < w:
|
| 1537 |
+
new_h, new_w = size, scale * w
|
| 1538 |
+
else:
|
| 1539 |
+
new_h, new_w = scale * h, size
|
| 1540 |
+
|
| 1541 |
+
if max(new_h, new_w) > self.max_size:
|
| 1542 |
+
scale = self.max_size * 1.0 / max(new_h, new_w)
|
| 1543 |
+
new_h *= scale
|
| 1544 |
+
new_w *= scale
|
| 1545 |
+
|
| 1546 |
+
new_h = int(new_h + 0.5)
|
| 1547 |
+
new_w = int(new_w + 0.5)
|
| 1548 |
+
return (new_w, new_h)
|
| 1549 |
+
|
| 1550 |
+
def transform(self, results: Dict) -> Dict:
|
| 1551 |
+
self.resize.scale = self._get_output_shape(results['img'], self.scale)
|
| 1552 |
+
return self.resize(results)
|
| 1553 |
+
|
| 1554 |
+
|
| 1555 |
+
@TRANSFORMS.register_module()
|
| 1556 |
+
class BioMedical3DRandomCrop(BaseTransform):
|
| 1557 |
+
"""Crop the input patch for medical image & segmentation mask.
|
| 1558 |
+
|
| 1559 |
+
Required Keys:
|
| 1560 |
+
|
| 1561 |
+
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X),
|
| 1562 |
+
N is the number of modalities, and data type is float32.
|
| 1563 |
+
- gt_seg_map (np.ndarray, optional): Biomedical semantic segmentation mask
|
| 1564 |
+
with shape (Z, Y, X).
|
| 1565 |
+
|
| 1566 |
+
Modified Keys:
|
| 1567 |
+
|
| 1568 |
+
- img
|
| 1569 |
+
- img_shape
|
| 1570 |
+
- gt_seg_map (optional)
|
| 1571 |
+
|
| 1572 |
+
Args:
|
| 1573 |
+
crop_shape (Union[int, Tuple[int, int, int]]): Expected size after
|
| 1574 |
+
cropping with the format of (z, y, x). If set to an integer,
|
| 1575 |
+
then cropping width and height are equal to this integer.
|
| 1576 |
+
keep_foreground (bool): If keep_foreground is True, it will sample a
|
| 1577 |
+
voxel of foreground classes randomly, and will take it as the
|
| 1578 |
+
center of the crop bounding-box. Default to True.
|
| 1579 |
+
"""
|
| 1580 |
+
|
| 1581 |
+
def __init__(self,
|
| 1582 |
+
crop_shape: Union[int, Tuple[int, int, int]],
|
| 1583 |
+
keep_foreground: bool = True):
|
| 1584 |
+
super().__init__()
|
| 1585 |
+
assert isinstance(crop_shape, int) or (
|
| 1586 |
+
isinstance(crop_shape, tuple) and len(crop_shape) == 3
|
| 1587 |
+
), 'The expected crop_shape is an integer, or a tuple containing '
|
| 1588 |
+
'three integers'
|
| 1589 |
+
|
| 1590 |
+
if isinstance(crop_shape, int):
|
| 1591 |
+
crop_shape = (crop_shape, crop_shape, crop_shape)
|
| 1592 |
+
assert crop_shape[0] > 0 and crop_shape[1] > 0 and crop_shape[2] > 0
|
| 1593 |
+
self.crop_shape = crop_shape
|
| 1594 |
+
self.keep_foreground = keep_foreground
|
| 1595 |
+
|
| 1596 |
+
def random_sample_location(self, seg_map: np.ndarray) -> dict:
|
| 1597 |
+
"""sample foreground voxel when keep_foreground is True.
|
| 1598 |
+
|
| 1599 |
+
Args:
|
| 1600 |
+
seg_map (np.ndarray): gt seg map.
|
| 1601 |
+
|
| 1602 |
+
Returns:
|
| 1603 |
+
dict: Coordinates of selected foreground voxel.
|
| 1604 |
+
"""
|
| 1605 |
+
num_samples = 10000
|
| 1606 |
+
# at least 1% of the class voxels need to be selected,
|
| 1607 |
+
# otherwise it may be too sparse
|
| 1608 |
+
min_percent_coverage = 0.01
|
| 1609 |
+
class_locs = {}
|
| 1610 |
+
foreground_classes = []
|
| 1611 |
+
all_classes = np.unique(seg_map)
|
| 1612 |
+
for c in all_classes:
|
| 1613 |
+
if c == 0:
|
| 1614 |
+
# to avoid the segmentation mask full of background 0
|
| 1615 |
+
# and the class_locs is just void dictionary {} when it return
|
| 1616 |
+
# there add a void list for background 0.
|
| 1617 |
+
class_locs[c] = []
|
| 1618 |
+
else:
|
| 1619 |
+
all_locs = np.argwhere(seg_map == c)
|
| 1620 |
+
target_num_samples = min(num_samples, len(all_locs))
|
| 1621 |
+
target_num_samples = max(
|
| 1622 |
+
target_num_samples,
|
| 1623 |
+
int(np.ceil(len(all_locs) * min_percent_coverage)))
|
| 1624 |
+
|
| 1625 |
+
selected = all_locs[np.random.choice(
|
| 1626 |
+
len(all_locs), target_num_samples, replace=False)]
|
| 1627 |
+
class_locs[c] = selected
|
| 1628 |
+
foreground_classes.append(c)
|
| 1629 |
+
|
| 1630 |
+
selected_voxel = None
|
| 1631 |
+
if len(foreground_classes) > 0:
|
| 1632 |
+
selected_class = np.random.choice(foreground_classes)
|
| 1633 |
+
voxels_of_that_class = class_locs[selected_class]
|
| 1634 |
+
selected_voxel = voxels_of_that_class[np.random.choice(
|
| 1635 |
+
len(voxels_of_that_class))]
|
| 1636 |
+
|
| 1637 |
+
return selected_voxel
|
| 1638 |
+
|
| 1639 |
+
def random_generate_crop_bbox(self, margin_z: int, margin_y: int,
|
| 1640 |
+
margin_x: int) -> tuple:
|
| 1641 |
+
"""Randomly get a crop bounding box.
|
| 1642 |
+
|
| 1643 |
+
Args:
|
| 1644 |
+
seg_map (np.ndarray): Ground truth segmentation map.
|
| 1645 |
+
|
| 1646 |
+
Returns:
|
| 1647 |
+
tuple: Coordinates of the cropped image.
|
| 1648 |
+
"""
|
| 1649 |
+
offset_z = np.random.randint(0, margin_z + 1)
|
| 1650 |
+
offset_y = np.random.randint(0, margin_y + 1)
|
| 1651 |
+
offset_x = np.random.randint(0, margin_x + 1)
|
| 1652 |
+
crop_z1, crop_z2 = offset_z, offset_z + self.crop_shape[0]
|
| 1653 |
+
crop_y1, crop_y2 = offset_y, offset_y + self.crop_shape[1]
|
| 1654 |
+
crop_x1, crop_x2 = offset_x, offset_x + self.crop_shape[2]
|
| 1655 |
+
|
| 1656 |
+
return crop_z1, crop_z2, crop_y1, crop_y2, crop_x1, crop_x2
|
| 1657 |
+
|
| 1658 |
+
def generate_margin(self, results: dict) -> tuple:
|
| 1659 |
+
"""Generate margin of crop bounding-box.
|
| 1660 |
+
|
| 1661 |
+
If keep_foreground is True, it will sample a voxel of foreground
|
| 1662 |
+
classes randomly, and will take it as the center of the bounding-box,
|
| 1663 |
+
and return the margin between of the bounding-box and image.
|
| 1664 |
+
If keep_foreground is False, it will return the difference from crop
|
| 1665 |
+
shape and image shape.
|
| 1666 |
+
|
| 1667 |
+
Args:
|
| 1668 |
+
results (dict): Result dict from loading pipeline.
|
| 1669 |
+
|
| 1670 |
+
Returns:
|
| 1671 |
+
tuple: The margin for 3 dimensions of crop bounding-box and image.
|
| 1672 |
+
"""
|
| 1673 |
+
|
| 1674 |
+
seg_map = results['gt_seg_map']
|
| 1675 |
+
if self.keep_foreground:
|
| 1676 |
+
selected_voxel = self.random_sample_location(seg_map)
|
| 1677 |
+
if selected_voxel is None:
|
| 1678 |
+
# this only happens if some image does not contain
|
| 1679 |
+
# foreground voxels at all
|
| 1680 |
+
warnings.warn(f'case does not contain any foreground classes'
|
| 1681 |
+
f': {results["img_path"]}')
|
| 1682 |
+
margin_z = max(seg_map.shape[0] - self.crop_shape[0], 0)
|
| 1683 |
+
margin_y = max(seg_map.shape[1] - self.crop_shape[1], 0)
|
| 1684 |
+
margin_x = max(seg_map.shape[2] - self.crop_shape[2], 0)
|
| 1685 |
+
else:
|
| 1686 |
+
margin_z = max(0, selected_voxel[0] - self.crop_shape[0] // 2)
|
| 1687 |
+
margin_y = max(0, selected_voxel[1] - self.crop_shape[1] // 2)
|
| 1688 |
+
margin_x = max(0, selected_voxel[2] - self.crop_shape[2] // 2)
|
| 1689 |
+
margin_z = max(
|
| 1690 |
+
0, min(seg_map.shape[0] - self.crop_shape[0], margin_z))
|
| 1691 |
+
margin_y = max(
|
| 1692 |
+
0, min(seg_map.shape[1] - self.crop_shape[1], margin_y))
|
| 1693 |
+
margin_x = max(
|
| 1694 |
+
0, min(seg_map.shape[2] - self.crop_shape[2], margin_x))
|
| 1695 |
+
else:
|
| 1696 |
+
margin_z = max(seg_map.shape[0] - self.crop_shape[0], 0)
|
| 1697 |
+
margin_y = max(seg_map.shape[1] - self.crop_shape[1], 0)
|
| 1698 |
+
margin_x = max(seg_map.shape[2] - self.crop_shape[2], 0)
|
| 1699 |
+
|
| 1700 |
+
return margin_z, margin_y, margin_x
|
| 1701 |
+
|
| 1702 |
+
def crop(self, img: np.ndarray, crop_bbox: tuple) -> np.ndarray:
|
| 1703 |
+
"""Crop from ``img``
|
| 1704 |
+
|
| 1705 |
+
Args:
|
| 1706 |
+
img (np.ndarray): Original input image.
|
| 1707 |
+
crop_bbox (tuple): Coordinates of the cropped image.
|
| 1708 |
+
|
| 1709 |
+
Returns:
|
| 1710 |
+
np.ndarray: The cropped image.
|
| 1711 |
+
"""
|
| 1712 |
+
crop_z1, crop_z2, crop_y1, crop_y2, crop_x1, crop_x2 = crop_bbox
|
| 1713 |
+
if len(img.shape) == 3:
|
| 1714 |
+
# crop seg map
|
| 1715 |
+
img = img[crop_z1:crop_z2, crop_y1:crop_y2, crop_x1:crop_x2]
|
| 1716 |
+
else:
|
| 1717 |
+
# crop image
|
| 1718 |
+
assert len(img.shape) == 4
|
| 1719 |
+
img = img[:, crop_z1:crop_z2, crop_y1:crop_y2, crop_x1:crop_x2]
|
| 1720 |
+
return img
|
| 1721 |
+
|
| 1722 |
+
def transform(self, results: dict) -> dict:
|
| 1723 |
+
"""Transform function to randomly crop images, semantic segmentation
|
| 1724 |
+
maps.
|
| 1725 |
+
|
| 1726 |
+
Args:
|
| 1727 |
+
results (dict): Result dict from loading pipeline.
|
| 1728 |
+
|
| 1729 |
+
Returns:
|
| 1730 |
+
dict: Randomly cropped results, 'img_shape' key in result dict is
|
| 1731 |
+
updated according to crop size.
|
| 1732 |
+
"""
|
| 1733 |
+
margin = self.generate_margin(results)
|
| 1734 |
+
crop_bbox = self.random_generate_crop_bbox(*margin)
|
| 1735 |
+
|
| 1736 |
+
# crop the image
|
| 1737 |
+
img = results['img']
|
| 1738 |
+
results['img'] = self.crop(img, crop_bbox)
|
| 1739 |
+
results['img_shape'] = results['img'].shape[1:]
|
| 1740 |
+
|
| 1741 |
+
# crop semantic seg
|
| 1742 |
+
seg_map = results['gt_seg_map']
|
| 1743 |
+
results['gt_seg_map'] = self.crop(seg_map, crop_bbox)
|
| 1744 |
+
|
| 1745 |
+
return results
|
| 1746 |
+
|
| 1747 |
+
def __repr__(self):
|
| 1748 |
+
return self.__class__.__name__ + f'(crop_shape={self.crop_shape})'
|
| 1749 |
+
|
| 1750 |
+
|
| 1751 |
+
@TRANSFORMS.register_module()
|
| 1752 |
+
class BioMedicalGaussianNoise(BaseTransform):
|
| 1753 |
+
"""Add random Gaussian noise to image.
|
| 1754 |
+
|
| 1755 |
+
Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/transforms/noise_transforms.py#L53 # noqa:E501
|
| 1756 |
+
|
| 1757 |
+
Copyright (c) German Cancer Research Center (DKFZ)
|
| 1758 |
+
Licensed under the Apache License, Version 2.0
|
| 1759 |
+
|
| 1760 |
+
Required Keys:
|
| 1761 |
+
|
| 1762 |
+
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X),
|
| 1763 |
+
N is the number of modalities, and data type is float32.
|
| 1764 |
+
|
| 1765 |
+
Modified Keys:
|
| 1766 |
+
|
| 1767 |
+
- img
|
| 1768 |
+
|
| 1769 |
+
Args:
|
| 1770 |
+
prob (float): Probability to add Gaussian noise for
|
| 1771 |
+
each sample. Default to 0.1.
|
| 1772 |
+
mean (float): Mean or “centre” of the distribution. Default to 0.0.
|
| 1773 |
+
std (float): Standard deviation of distribution. Default to 0.1.
|
| 1774 |
+
"""
|
| 1775 |
+
|
| 1776 |
+
def __init__(self,
|
| 1777 |
+
prob: float = 0.1,
|
| 1778 |
+
mean: float = 0.0,
|
| 1779 |
+
std: float = 0.1) -> None:
|
| 1780 |
+
super().__init__()
|
| 1781 |
+
assert 0.0 <= prob <= 1.0 and std >= 0.0
|
| 1782 |
+
self.prob = prob
|
| 1783 |
+
self.mean = mean
|
| 1784 |
+
self.std = std
|
| 1785 |
+
|
| 1786 |
+
def transform(self, results: Dict) -> Dict:
|
| 1787 |
+
"""Call function to add random Gaussian noise to image.
|
| 1788 |
+
|
| 1789 |
+
Args:
|
| 1790 |
+
results (dict): Result dict.
|
| 1791 |
+
|
| 1792 |
+
Returns:
|
| 1793 |
+
dict: Result dict with random Gaussian noise.
|
| 1794 |
+
"""
|
| 1795 |
+
if np.random.rand() < self.prob:
|
| 1796 |
+
rand_std = np.random.uniform(0, self.std)
|
| 1797 |
+
noise = np.random.normal(
|
| 1798 |
+
self.mean, rand_std, size=results['img'].shape)
|
| 1799 |
+
# noise is float64 array, convert to the results['img'].dtype
|
| 1800 |
+
noise = noise.astype(results['img'].dtype)
|
| 1801 |
+
results['img'] = results['img'] + noise
|
| 1802 |
+
return results
|
| 1803 |
+
|
| 1804 |
+
def __repr__(self):
|
| 1805 |
+
repr_str = self.__class__.__name__
|
| 1806 |
+
repr_str += f'(prob={self.prob}, '
|
| 1807 |
+
repr_str += f'mean={self.mean}, '
|
| 1808 |
+
repr_str += f'std={self.std})'
|
| 1809 |
+
return repr_str
|
| 1810 |
+
|
| 1811 |
+
|
| 1812 |
+
@TRANSFORMS.register_module()
|
| 1813 |
+
class BioMedicalGaussianBlur(BaseTransform):
|
| 1814 |
+
"""Add Gaussian blur with random sigma to image.
|
| 1815 |
+
|
| 1816 |
+
Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/transforms/noise_transforms.py#L81 # noqa:E501
|
| 1817 |
+
|
| 1818 |
+
Copyright (c) German Cancer Research Center (DKFZ)
|
| 1819 |
+
Licensed under the Apache License, Version 2.0
|
| 1820 |
+
|
| 1821 |
+
Required Keys:
|
| 1822 |
+
|
| 1823 |
+
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X),
|
| 1824 |
+
N is the number of modalities, and data type is float32.
|
| 1825 |
+
|
| 1826 |
+
Modified Keys:
|
| 1827 |
+
|
| 1828 |
+
- img
|
| 1829 |
+
|
| 1830 |
+
Args:
|
| 1831 |
+
sigma_range (Tuple[float, float]|float): range to randomly
|
| 1832 |
+
select sigma value. Default to (0.5, 1.0).
|
| 1833 |
+
prob (float): Probability to apply Gaussian blur
|
| 1834 |
+
for each sample. Default to 0.2.
|
| 1835 |
+
prob_per_channel (float): Probability to apply Gaussian blur
|
| 1836 |
+
for each channel (axis N of the image). Default to 0.5.
|
| 1837 |
+
different_sigma_per_channel (bool): whether to use different
|
| 1838 |
+
sigma for each channel (axis N of the image). Default to True.
|
| 1839 |
+
different_sigma_per_axis (bool): whether to use different
|
| 1840 |
+
sigma for axis Z, X and Y of the image. Default to True.
|
| 1841 |
+
"""
|
| 1842 |
+
|
| 1843 |
+
def __init__(self,
|
| 1844 |
+
sigma_range: Tuple[float, float] = (0.5, 1.0),
|
| 1845 |
+
prob: float = 0.2,
|
| 1846 |
+
prob_per_channel: float = 0.5,
|
| 1847 |
+
different_sigma_per_channel: bool = True,
|
| 1848 |
+
different_sigma_per_axis: bool = True) -> None:
|
| 1849 |
+
super().__init__()
|
| 1850 |
+
assert 0.0 <= prob <= 1.0
|
| 1851 |
+
assert 0.0 <= prob_per_channel <= 1.0
|
| 1852 |
+
assert isinstance(sigma_range, Sequence) and len(sigma_range) == 2
|
| 1853 |
+
self.sigma_range = sigma_range
|
| 1854 |
+
self.prob = prob
|
| 1855 |
+
self.prob_per_channel = prob_per_channel
|
| 1856 |
+
self.different_sigma_per_channel = different_sigma_per_channel
|
| 1857 |
+
self.different_sigma_per_axis = different_sigma_per_axis
|
| 1858 |
+
|
| 1859 |
+
def _get_valid_sigma(self, value_range) -> Tuple[float, ...]:
|
| 1860 |
+
"""Ensure the `value_range` to be either a single value or a sequence
|
| 1861 |
+
of two values. If the `value_range` is a sequence, generate a random
|
| 1862 |
+
value with `[value_range[0], value_range[1]]` based on uniform
|
| 1863 |
+
sampling.
|
| 1864 |
+
|
| 1865 |
+
Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/augmentations/utils.py#L625 # noqa:E501
|
| 1866 |
+
|
| 1867 |
+
Args:
|
| 1868 |
+
value_range (tuple|list|float|int): the input value range
|
| 1869 |
+
"""
|
| 1870 |
+
if (isinstance(value_range, (list, tuple))):
|
| 1871 |
+
if (value_range[0] == value_range[1]):
|
| 1872 |
+
value = value_range[0]
|
| 1873 |
+
else:
|
| 1874 |
+
orig_type = type(value_range[0])
|
| 1875 |
+
value = np.random.uniform(value_range[0], value_range[1])
|
| 1876 |
+
value = orig_type(value)
|
| 1877 |
+
return value
|
| 1878 |
+
|
| 1879 |
+
def _gaussian_blur(self, data_sample: np.ndarray) -> np.ndarray:
|
| 1880 |
+
"""Random generate sigma and apply Gaussian Blur to the data
|
| 1881 |
+
Args:
|
| 1882 |
+
data_sample (np.ndarray): data sample with multiple modalities,
|
| 1883 |
+
the data shape is (N, Z, Y, X)
|
| 1884 |
+
"""
|
| 1885 |
+
sigma = None
|
| 1886 |
+
for c in range(data_sample.shape[0]):
|
| 1887 |
+
if np.random.rand() < self.prob_per_channel:
|
| 1888 |
+
# if no `sigma` is generated, generate one
|
| 1889 |
+
# if `self.different_sigma_per_channel` is True,
|
| 1890 |
+
# re-generate random sigma for each channel
|
| 1891 |
+
if (sigma is None or self.different_sigma_per_channel):
|
| 1892 |
+
if (not self.different_sigma_per_axis):
|
| 1893 |
+
sigma = self._get_valid_sigma(self.sigma_range)
|
| 1894 |
+
else:
|
| 1895 |
+
sigma = [
|
| 1896 |
+
self._get_valid_sigma(self.sigma_range)
|
| 1897 |
+
for _ in data_sample.shape[1:]
|
| 1898 |
+
]
|
| 1899 |
+
# apply gaussian filter with `sigma`
|
| 1900 |
+
data_sample[c] = gaussian_filter(
|
| 1901 |
+
data_sample[c], sigma, order=0)
|
| 1902 |
+
return data_sample
|
| 1903 |
+
|
| 1904 |
+
def transform(self, results: Dict) -> Dict:
|
| 1905 |
+
"""Call function to add random Gaussian blur to image.
|
| 1906 |
+
|
| 1907 |
+
Args:
|
| 1908 |
+
results (dict): Result dict.
|
| 1909 |
+
|
| 1910 |
+
Returns:
|
| 1911 |
+
dict: Result dict with random Gaussian noise.
|
| 1912 |
+
"""
|
| 1913 |
+
if np.random.rand() < self.prob:
|
| 1914 |
+
results['img'] = self._gaussian_blur(results['img'])
|
| 1915 |
+
return results
|
| 1916 |
+
|
| 1917 |
+
def __repr__(self):
|
| 1918 |
+
repr_str = self.__class__.__name__
|
| 1919 |
+
repr_str += f'(prob={self.prob}, '
|
| 1920 |
+
repr_str += f'prob_per_channel={self.prob_per_channel}, '
|
| 1921 |
+
repr_str += f'sigma_range={self.sigma_range}, '
|
| 1922 |
+
repr_str += 'different_sigma_per_channel=' \
|
| 1923 |
+
f'{self.different_sigma_per_channel}, '
|
| 1924 |
+
repr_str += 'different_sigma_per_axis=' \
|
| 1925 |
+
f'{self.different_sigma_per_axis})'
|
| 1926 |
+
return repr_str
|
| 1927 |
+
|
| 1928 |
+
|
| 1929 |
+
@TRANSFORMS.register_module()
|
| 1930 |
+
class BioMedicalRandomGamma(BaseTransform):
|
| 1931 |
+
"""Using random gamma correction to process the biomedical image.
|
| 1932 |
+
|
| 1933 |
+
Modified from
|
| 1934 |
+
https://github.com/MIC-DKFZ/batchgenerators/blob/master/batchgenerators/transforms/color_transforms.py#L132 # noqa:E501
|
| 1935 |
+
With licence: Apache 2.0
|
| 1936 |
+
|
| 1937 |
+
Required Keys:
|
| 1938 |
+
|
| 1939 |
+
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X),
|
| 1940 |
+
N is the number of modalities, and data type is float32.
|
| 1941 |
+
|
| 1942 |
+
Modified Keys:
|
| 1943 |
+
- img
|
| 1944 |
+
|
| 1945 |
+
Args:
|
| 1946 |
+
prob (float): The probability to perform this transform. Default: 0.5.
|
| 1947 |
+
gamma_range (Tuple[float]): Range of gamma values. Default: (0.5, 2).
|
| 1948 |
+
invert_image (bool): Whether invert the image before applying gamma
|
| 1949 |
+
augmentation. Default: False.
|
| 1950 |
+
per_channel (bool): Whether perform the transform each channel
|
| 1951 |
+
individually. Default: False
|
| 1952 |
+
retain_stats (bool): Gamma transformation will alter the mean and std
|
| 1953 |
+
of the data in the patch. If retain_stats=True, the data will be
|
| 1954 |
+
transformed to match the mean and standard deviation before gamma
|
| 1955 |
+
augmentation. Default: False.
|
| 1956 |
+
"""
|
| 1957 |
+
|
| 1958 |
+
def __init__(self,
|
| 1959 |
+
prob: float = 0.5,
|
| 1960 |
+
gamma_range: Tuple[float] = (0.5, 2),
|
| 1961 |
+
invert_image: bool = False,
|
| 1962 |
+
per_channel: bool = False,
|
| 1963 |
+
retain_stats: bool = False):
|
| 1964 |
+
assert 0 <= prob and prob <= 1
|
| 1965 |
+
assert isinstance(gamma_range, tuple) and len(gamma_range) == 2
|
| 1966 |
+
assert isinstance(invert_image, bool)
|
| 1967 |
+
assert isinstance(per_channel, bool)
|
| 1968 |
+
assert isinstance(retain_stats, bool)
|
| 1969 |
+
self.prob = prob
|
| 1970 |
+
self.gamma_range = gamma_range
|
| 1971 |
+
self.invert_image = invert_image
|
| 1972 |
+
self.per_channel = per_channel
|
| 1973 |
+
self.retain_stats = retain_stats
|
| 1974 |
+
|
| 1975 |
+
@cache_randomness
|
| 1976 |
+
def _do_gamma(self):
|
| 1977 |
+
"""Whether do adjust gamma for image."""
|
| 1978 |
+
return np.random.rand() < self.prob
|
| 1979 |
+
|
| 1980 |
+
def _adjust_gamma(self, img: np.array):
|
| 1981 |
+
"""Gamma adjustment for image.
|
| 1982 |
+
|
| 1983 |
+
Args:
|
| 1984 |
+
img (np.array): Input image before gamma adjust.
|
| 1985 |
+
|
| 1986 |
+
Returns:
|
| 1987 |
+
np.arrays: Image after gamma adjust.
|
| 1988 |
+
"""
|
| 1989 |
+
|
| 1990 |
+
if self.invert_image:
|
| 1991 |
+
img = -img
|
| 1992 |
+
|
| 1993 |
+
def _do_adjust(img):
|
| 1994 |
+
if retain_stats_here:
|
| 1995 |
+
img_mean = img.mean()
|
| 1996 |
+
img_std = img.std()
|
| 1997 |
+
if np.random.random() < 0.5 and self.gamma_range[0] < 1:
|
| 1998 |
+
gamma = np.random.uniform(self.gamma_range[0], 1)
|
| 1999 |
+
else:
|
| 2000 |
+
gamma = np.random.uniform(
|
| 2001 |
+
max(self.gamma_range[0], 1), self.gamma_range[1])
|
| 2002 |
+
img_min = img.min()
|
| 2003 |
+
img_range = img.max() - img_min # range
|
| 2004 |
+
img = np.power(((img - img_min) / float(img_range + 1e-7)),
|
| 2005 |
+
gamma) * img_range + img_min
|
| 2006 |
+
if retain_stats_here:
|
| 2007 |
+
img = img - img.mean()
|
| 2008 |
+
img = img / (img.std() + 1e-8) * img_std
|
| 2009 |
+
img = img + img_mean
|
| 2010 |
+
return img
|
| 2011 |
+
|
| 2012 |
+
if not self.per_channel:
|
| 2013 |
+
retain_stats_here = self.retain_stats
|
| 2014 |
+
img = _do_adjust(img)
|
| 2015 |
+
else:
|
| 2016 |
+
for c in range(img.shape[0]):
|
| 2017 |
+
img[c] = _do_adjust(img[c])
|
| 2018 |
+
if self.invert_image:
|
| 2019 |
+
img = -img
|
| 2020 |
+
return img
|
| 2021 |
+
|
| 2022 |
+
def transform(self, results: dict) -> dict:
|
| 2023 |
+
"""Call function to perform random gamma correction
|
| 2024 |
+
Args:
|
| 2025 |
+
results (dict): Result dict from loading pipeline.
|
| 2026 |
+
|
| 2027 |
+
Returns:
|
| 2028 |
+
dict: Result dict with random gamma correction performed.
|
| 2029 |
+
"""
|
| 2030 |
+
do_gamma = self._do_gamma()
|
| 2031 |
+
|
| 2032 |
+
if do_gamma:
|
| 2033 |
+
results['img'] = self._adjust_gamma(results['img'])
|
| 2034 |
+
else:
|
| 2035 |
+
pass
|
| 2036 |
+
return results
|
| 2037 |
+
|
| 2038 |
+
def __repr__(self):
|
| 2039 |
+
repr_str = self.__class__.__name__
|
| 2040 |
+
repr_str += f'(prob={self.prob}, '
|
| 2041 |
+
repr_str += f'gamma_range={self.gamma_range},'
|
| 2042 |
+
repr_str += f'invert_image={self.invert_image},'
|
| 2043 |
+
repr_str += f'per_channel={self.per_channel},'
|
| 2044 |
+
repr_str += f'retain_stats={self.retain_stats}'
|
| 2045 |
+
return repr_str
|
| 2046 |
+
|
| 2047 |
+
|
| 2048 |
+
@TRANSFORMS.register_module()
|
| 2049 |
+
class BioMedical3DPad(BaseTransform):
|
| 2050 |
+
"""Pad the biomedical 3d image & biomedical 3d semantic segmentation maps.
|
| 2051 |
+
|
| 2052 |
+
Required Keys:
|
| 2053 |
+
|
| 2054 |
+
- img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default,
|
| 2055 |
+
N is the number of modalities.
|
| 2056 |
+
- gt_seg_map (np.ndarray, optional): Biomedical seg map with shape
|
| 2057 |
+
(Z, Y, X) by default.
|
| 2058 |
+
|
| 2059 |
+
Modified Keys:
|
| 2060 |
+
|
| 2061 |
+
- img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default,
|
| 2062 |
+
N is the number of modalities.
|
| 2063 |
+
- gt_seg_map (np.ndarray, optional): Biomedical seg map with shape
|
| 2064 |
+
(Z, Y, X) by default.
|
| 2065 |
+
|
| 2066 |
+
Added Keys:
|
| 2067 |
+
|
| 2068 |
+
- pad_shape (Tuple[int, int, int]): The padded shape.
|
| 2069 |
+
|
| 2070 |
+
Args:
|
| 2071 |
+
pad_shape (Tuple[int, int, int]): Fixed padding size.
|
| 2072 |
+
Expected padding shape (Z, Y, X).
|
| 2073 |
+
pad_val (float): Padding value for biomedical image.
|
| 2074 |
+
The padding mode is set to "constant". The value
|
| 2075 |
+
to be filled in padding area. Default: 0.
|
| 2076 |
+
seg_pad_val (int): Padding value for biomedical 3d semantic
|
| 2077 |
+
segmentation maps. The padding mode is set to "constant".
|
| 2078 |
+
The value to be filled in padding area. Default: 0.
|
| 2079 |
+
"""
|
| 2080 |
+
|
| 2081 |
+
def __init__(self,
|
| 2082 |
+
pad_shape: Tuple[int, int, int],
|
| 2083 |
+
pad_val: float = 0.,
|
| 2084 |
+
seg_pad_val: int = 0) -> None:
|
| 2085 |
+
|
| 2086 |
+
# check pad_shape
|
| 2087 |
+
assert pad_shape is not None
|
| 2088 |
+
if not isinstance(pad_shape, tuple):
|
| 2089 |
+
assert len(pad_shape) == 3
|
| 2090 |
+
|
| 2091 |
+
self.pad_shape = pad_shape
|
| 2092 |
+
self.pad_val = pad_val
|
| 2093 |
+
self.seg_pad_val = seg_pad_val
|
| 2094 |
+
|
| 2095 |
+
def _pad_img(self, results: dict) -> None:
|
| 2096 |
+
"""Pad images according to ``self.pad_shape``
|
| 2097 |
+
|
| 2098 |
+
Args:
|
| 2099 |
+
results (dict): Result dict from loading pipeline.
|
| 2100 |
+
|
| 2101 |
+
Returns:
|
| 2102 |
+
dict: The dict contains the padded image and shape
|
| 2103 |
+
information.
|
| 2104 |
+
"""
|
| 2105 |
+
padded_img = self._to_pad(
|
| 2106 |
+
results['img'], pad_shape=self.pad_shape, pad_val=self.pad_val)
|
| 2107 |
+
|
| 2108 |
+
results['img'] = padded_img
|
| 2109 |
+
results['pad_shape'] = padded_img.shape[1:]
|
| 2110 |
+
|
| 2111 |
+
def _pad_seg(self, results: dict) -> None:
|
| 2112 |
+
"""Pad semantic segmentation map according to ``self.pad_shape`` if
|
| 2113 |
+
``gt_seg_map`` is not None in results dict.
|
| 2114 |
+
|
| 2115 |
+
Args:
|
| 2116 |
+
results (dict): Result dict from loading pipeline.
|
| 2117 |
+
|
| 2118 |
+
Returns:
|
| 2119 |
+
dict: Update the padded gt seg map in dict.
|
| 2120 |
+
"""
|
| 2121 |
+
if results.get('gt_seg_map', None) is not None:
|
| 2122 |
+
pad_gt_seg = self._to_pad(
|
| 2123 |
+
results['gt_seg_map'][None, ...],
|
| 2124 |
+
pad_shape=results['pad_shape'],
|
| 2125 |
+
pad_val=self.seg_pad_val)
|
| 2126 |
+
results['gt_seg_map'] = pad_gt_seg[1:]
|
| 2127 |
+
|
| 2128 |
+
@staticmethod
|
| 2129 |
+
def _to_pad(img: np.ndarray,
|
| 2130 |
+
pad_shape: Tuple[int, int, int],
|
| 2131 |
+
pad_val: Union[int, float] = 0) -> np.ndarray:
|
| 2132 |
+
"""Pad the given 3d image to a certain shape with specified padding
|
| 2133 |
+
value.
|
| 2134 |
+
|
| 2135 |
+
Args:
|
| 2136 |
+
img (ndarray): Biomedical image with shape (N, Z, Y, X)
|
| 2137 |
+
to be padded. N is the number of modalities.
|
| 2138 |
+
pad_shape (Tuple[int,int,int]): Expected padding shape (Z, Y, X).
|
| 2139 |
+
pad_val (float, int): Values to be filled in padding areas
|
| 2140 |
+
and the padding_mode is set to 'constant'. Default: 0.
|
| 2141 |
+
|
| 2142 |
+
Returns:
|
| 2143 |
+
ndarray: The padded image.
|
| 2144 |
+
"""
|
| 2145 |
+
# compute pad width
|
| 2146 |
+
d = max(pad_shape[0] - img.shape[1], 0)
|
| 2147 |
+
pad_d = (d // 2, d - d // 2)
|
| 2148 |
+
h = max(pad_shape[1] - img.shape[2], 0)
|
| 2149 |
+
pad_h = (h // 2, h - h // 2)
|
| 2150 |
+
w = max(pad_shape[2] - img.shape[2], 0)
|
| 2151 |
+
pad_w = (w // 2, w - w // 2)
|
| 2152 |
+
|
| 2153 |
+
pad_list = [(0, 0), pad_d, pad_h, pad_w]
|
| 2154 |
+
|
| 2155 |
+
img = np.pad(img, pad_list, mode='constant', constant_values=pad_val)
|
| 2156 |
+
return img
|
| 2157 |
+
|
| 2158 |
+
def transform(self, results: dict) -> dict:
|
| 2159 |
+
"""Call function to pad images, semantic segmentation maps.
|
| 2160 |
+
|
| 2161 |
+
Args:
|
| 2162 |
+
results (dict): Result dict from loading pipeline.
|
| 2163 |
+
|
| 2164 |
+
Returns:
|
| 2165 |
+
dict: Updated result dict.
|
| 2166 |
+
"""
|
| 2167 |
+
self._pad_img(results)
|
| 2168 |
+
self._pad_seg(results)
|
| 2169 |
+
|
| 2170 |
+
return results
|
| 2171 |
+
|
| 2172 |
+
def __repr__(self):
|
| 2173 |
+
repr_str = self.__class__.__name__
|
| 2174 |
+
repr_str += f'pad_shape={self.pad_shape}, '
|
| 2175 |
+
repr_str += f'pad_val={self.pad_val}), '
|
| 2176 |
+
repr_str += f'seg_pad_val={self.seg_pad_val})'
|
| 2177 |
+
return repr_str
|
| 2178 |
+
|
| 2179 |
+
|
| 2180 |
+
@TRANSFORMS.register_module()
|
| 2181 |
+
class BioMedical3DRandomFlip(BaseTransform):
|
| 2182 |
+
"""Flip biomedical 3D images and segmentations.
|
| 2183 |
+
|
| 2184 |
+
Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/master/batchgenerators/transforms/spatial_transforms.py # noqa:E501
|
| 2185 |
+
|
| 2186 |
+
Copyright 2021 Division of
|
| 2187 |
+
Medical Image Computing, German Cancer Research Center (DKFZ) and Applied
|
| 2188 |
+
Computer Vision Lab, Helmholtz Imaging Platform.
|
| 2189 |
+
Licensed under the Apache-2.0 License.
|
| 2190 |
+
|
| 2191 |
+
Required Keys:
|
| 2192 |
+
|
| 2193 |
+
- img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default,
|
| 2194 |
+
N is the number of modalities.
|
| 2195 |
+
- gt_seg_map (np.ndarray, optional): Biomedical seg map with shape
|
| 2196 |
+
(Z, Y, X) by default.
|
| 2197 |
+
|
| 2198 |
+
Modified Keys:
|
| 2199 |
+
|
| 2200 |
+
- img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default,
|
| 2201 |
+
N is the number of modalities.
|
| 2202 |
+
- gt_seg_map (np.ndarray, optional): Biomedical seg map with shape
|
| 2203 |
+
(Z, Y, X) by default.
|
| 2204 |
+
|
| 2205 |
+
Added Keys:
|
| 2206 |
+
|
| 2207 |
+
- do_flip
|
| 2208 |
+
- flip_axes
|
| 2209 |
+
|
| 2210 |
+
Args:
|
| 2211 |
+
prob (float): Flipping probability.
|
| 2212 |
+
axes (Tuple[int, ...]): Flipping axes with order 'ZXY'.
|
| 2213 |
+
swap_label_pairs (Optional[List[Tuple[int, int]]]):
|
| 2214 |
+
The segmentation label pairs that are swapped when flipping.
|
| 2215 |
+
"""
|
| 2216 |
+
|
| 2217 |
+
def __init__(self,
|
| 2218 |
+
prob: float,
|
| 2219 |
+
axes: Tuple[int, ...],
|
| 2220 |
+
swap_label_pairs: Optional[List[Tuple[int, int]]] = None):
|
| 2221 |
+
self.prob = prob
|
| 2222 |
+
self.axes = axes
|
| 2223 |
+
self.swap_label_pairs = swap_label_pairs
|
| 2224 |
+
assert prob >= 0 and prob <= 1
|
| 2225 |
+
if axes is not None:
|
| 2226 |
+
assert max(axes) <= 2
|
| 2227 |
+
|
| 2228 |
+
@staticmethod
|
| 2229 |
+
def _flip(img, direction: Tuple[bool, bool, bool]) -> np.ndarray:
|
| 2230 |
+
if direction[0]:
|
| 2231 |
+
img[:, :] = img[:, ::-1]
|
| 2232 |
+
if direction[1]:
|
| 2233 |
+
img[:, :, :] = img[:, :, ::-1]
|
| 2234 |
+
if direction[2]:
|
| 2235 |
+
img[:, :, :, :] = img[:, :, :, ::-1]
|
| 2236 |
+
return img
|
| 2237 |
+
|
| 2238 |
+
def _do_flip(self, img: np.ndarray) -> Tuple[bool, bool, bool]:
|
| 2239 |
+
"""Call function to determine which axis to flip.
|
| 2240 |
+
|
| 2241 |
+
Args:
|
| 2242 |
+
img (np.ndarry): Image or segmentation map array.
|
| 2243 |
+
Returns:
|
| 2244 |
+
tuple: Flip action, whether to flip on the z, x, and y axes.
|
| 2245 |
+
"""
|
| 2246 |
+
flip_c, flip_x, flip_y = False, False, False
|
| 2247 |
+
if self.axes is not None:
|
| 2248 |
+
flip_c = 0 in self.axes and np.random.rand() < self.prob
|
| 2249 |
+
flip_x = 1 in self.axes and np.random.rand() < self.prob
|
| 2250 |
+
if len(img.shape) == 4:
|
| 2251 |
+
flip_y = 2 in self.axes and np.random.rand() < self.prob
|
| 2252 |
+
return flip_c, flip_x, flip_y
|
| 2253 |
+
|
| 2254 |
+
def _swap_label(self, seg: np.ndarray) -> np.ndarray:
|
| 2255 |
+
out = seg.copy()
|
| 2256 |
+
for first, second in self.swap_label_pairs:
|
| 2257 |
+
first_area = (seg == first)
|
| 2258 |
+
second_area = (seg == second)
|
| 2259 |
+
out[first_area] = second
|
| 2260 |
+
out[second_area] = first
|
| 2261 |
+
return out
|
| 2262 |
+
|
| 2263 |
+
def transform(self, results: Dict) -> Dict:
|
| 2264 |
+
"""Call function to flip and swap pair labels.
|
| 2265 |
+
|
| 2266 |
+
Args:
|
| 2267 |
+
results (dict): Result dict.
|
| 2268 |
+
Returns:
|
| 2269 |
+
dict: Flipped results, 'do_flip', 'flip_axes' keys are added into
|
| 2270 |
+
result dict.
|
| 2271 |
+
"""
|
| 2272 |
+
# get actual flipped axis
|
| 2273 |
+
if 'do_flip' not in results:
|
| 2274 |
+
results['do_flip'] = self._do_flip(results['img'])
|
| 2275 |
+
if 'flip_axes' not in results:
|
| 2276 |
+
results['flip_axes'] = self.axes
|
| 2277 |
+
# flip image
|
| 2278 |
+
results['img'] = self._flip(
|
| 2279 |
+
results['img'], direction=results['do_flip'])
|
| 2280 |
+
# flip seg
|
| 2281 |
+
if results['gt_seg_map'] is not None:
|
| 2282 |
+
if results['gt_seg_map'].shape != results['img'].shape:
|
| 2283 |
+
results['gt_seg_map'] = results['gt_seg_map'][None, :]
|
| 2284 |
+
results['gt_seg_map'] = self._flip(
|
| 2285 |
+
results['gt_seg_map'], direction=results['do_flip'])
|
| 2286 |
+
results['gt_seg_map'] = results['gt_seg_map'].squeeze()
|
| 2287 |
+
# swap label pairs
|
| 2288 |
+
if self.swap_label_pairs is not None:
|
| 2289 |
+
results['gt_seg_map'] = self._swap_label(results['gt_seg_map'])
|
| 2290 |
+
return results
|
| 2291 |
+
|
| 2292 |
+
def __repr__(self):
|
| 2293 |
+
repr_str = self.__class__.__name__
|
| 2294 |
+
repr_str += f'(prob={self.prob}, axes={self.axes}, ' \
|
| 2295 |
+
f'swap_label_pairs={self.swap_label_pairs})'
|
| 2296 |
+
return repr_str
|
| 2297 |
+
|
| 2298 |
+
|
| 2299 |
+
@TRANSFORMS.register_module()
|
| 2300 |
+
class Albu(BaseTransform):
|
| 2301 |
+
"""Albumentation augmentation. Adds custom transformations from
|
| 2302 |
+
Albumentations library. Please, visit
|
| 2303 |
+
`https://albumentations.readthedocs.io` to get more information. An example
|
| 2304 |
+
of ``transforms`` is as followed:
|
| 2305 |
+
|
| 2306 |
+
.. code-block::
|
| 2307 |
+
[
|
| 2308 |
+
dict(
|
| 2309 |
+
type='ShiftScaleRotate',
|
| 2310 |
+
shift_limit=0.0625,
|
| 2311 |
+
scale_limit=0.0,
|
| 2312 |
+
rotate_limit=0,
|
| 2313 |
+
interpolation=1,
|
| 2314 |
+
p=0.5),
|
| 2315 |
+
dict(
|
| 2316 |
+
type='RandomBrightnessContrast',
|
| 2317 |
+
brightness_limit=[0.1, 0.3],
|
| 2318 |
+
contrast_limit=[0.1, 0.3],
|
| 2319 |
+
p=0.2),
|
| 2320 |
+
dict(type='ChannelShuffle', p=0.1),
|
| 2321 |
+
dict(
|
| 2322 |
+
type='OneOf',
|
| 2323 |
+
transforms=[
|
| 2324 |
+
dict(type='Blur', blur_limit=3, p=1.0),
|
| 2325 |
+
dict(type='MedianBlur', blur_limit=3, p=1.0)
|
| 2326 |
+
],
|
| 2327 |
+
p=0.1),
|
| 2328 |
+
]
|
| 2329 |
+
Args:
|
| 2330 |
+
transforms (list[dict]): A list of albu transformations
|
| 2331 |
+
keymap (dict): Contains {'input key':'albumentation-style key'}
|
| 2332 |
+
additional_targets(dict): Allows applying same augmentations to \
|
| 2333 |
+
multiple objects of same type.
|
| 2334 |
+
update_pad_shape (bool): Whether to update padding shape according to \
|
| 2335 |
+
the output shape of the last transform
|
| 2336 |
+
bgr_to_rgb (bool): Whether to convert the band order to RGB
|
| 2337 |
+
"""
|
| 2338 |
+
|
| 2339 |
+
def __init__(self,
|
| 2340 |
+
transforms: List[dict],
|
| 2341 |
+
keymap: Optional[dict] = None,
|
| 2342 |
+
additional_targets: Optional[dict] = None,
|
| 2343 |
+
update_pad_shape: bool = False,
|
| 2344 |
+
bgr_to_rgb: bool = True):
|
| 2345 |
+
if not ALBU_INSTALLED:
|
| 2346 |
+
raise ImportError(
|
| 2347 |
+
'albumentations is not installed, '
|
| 2348 |
+
'we suggest install albumentation by '
|
| 2349 |
+
'"pip install albumentations>=0.3.2 --no-binary qudida,albumentations"' # noqa
|
| 2350 |
+
)
|
| 2351 |
+
|
| 2352 |
+
# Args will be modified later, copying it will be safer
|
| 2353 |
+
transforms = copy.deepcopy(transforms)
|
| 2354 |
+
|
| 2355 |
+
self.transforms = transforms
|
| 2356 |
+
self.keymap = keymap
|
| 2357 |
+
self.additional_targets = additional_targets
|
| 2358 |
+
self.update_pad_shape = update_pad_shape
|
| 2359 |
+
self.bgr_to_rgb = bgr_to_rgb
|
| 2360 |
+
|
| 2361 |
+
self.aug = Compose([self.albu_builder(t) for t in self.transforms],
|
| 2362 |
+
additional_targets=self.additional_targets)
|
| 2363 |
+
|
| 2364 |
+
if not keymap:
|
| 2365 |
+
self.keymap_to_albu = {'img': 'image', 'gt_seg_map': 'mask'}
|
| 2366 |
+
else:
|
| 2367 |
+
self.keymap_to_albu = copy.deepcopy(keymap)
|
| 2368 |
+
self.keymap_back = {v: k for k, v in self.keymap_to_albu.items()}
|
| 2369 |
+
|
| 2370 |
+
def albu_builder(self, cfg: dict) -> object:
|
| 2371 |
+
"""Build a callable object from a dict containing albu arguments.
|
| 2372 |
+
|
| 2373 |
+
Args:
|
| 2374 |
+
cfg (dict): Config dict. It should at least contain the key "type".
|
| 2375 |
+
|
| 2376 |
+
Returns:
|
| 2377 |
+
Callable: A callable object.
|
| 2378 |
+
"""
|
| 2379 |
+
|
| 2380 |
+
assert isinstance(cfg, dict) and 'type' in cfg
|
| 2381 |
+
args = cfg.copy()
|
| 2382 |
+
|
| 2383 |
+
obj_type = args.pop('type')
|
| 2384 |
+
if mmengine.is_str(obj_type):
|
| 2385 |
+
if not ALBU_INSTALLED:
|
| 2386 |
+
raise ImportError(
|
| 2387 |
+
'albumentations is not installed, '
|
| 2388 |
+
'we suggest install albumentation by '
|
| 2389 |
+
'"pip install albumentations>=0.3.2 --no-binary qudida,albumentations"' # noqa
|
| 2390 |
+
)
|
| 2391 |
+
obj_cls = getattr(albumentations, obj_type)
|
| 2392 |
+
elif inspect.isclass(obj_type):
|
| 2393 |
+
obj_cls = obj_type
|
| 2394 |
+
else:
|
| 2395 |
+
raise TypeError(
|
| 2396 |
+
f'type must be a valid type or str, but got {type(obj_type)}')
|
| 2397 |
+
|
| 2398 |
+
if 'transforms' in args:
|
| 2399 |
+
args['transforms'] = [
|
| 2400 |
+
self.albu_builder(t) for t in args['transforms']
|
| 2401 |
+
]
|
| 2402 |
+
|
| 2403 |
+
return obj_cls(**args)
|
| 2404 |
+
|
| 2405 |
+
@staticmethod
|
| 2406 |
+
def mapper(d: dict, keymap: dict):
|
| 2407 |
+
"""Dictionary mapper.
|
| 2408 |
+
|
| 2409 |
+
Renames keys according to keymap provided.
|
| 2410 |
+
Args:
|
| 2411 |
+
d (dict): old dict
|
| 2412 |
+
keymap (dict): {'old_key':'new_key'}
|
| 2413 |
+
Returns:
|
| 2414 |
+
dict: new dict.
|
| 2415 |
+
"""
|
| 2416 |
+
|
| 2417 |
+
updated_dict = {}
|
| 2418 |
+
for k, _ in zip(d.keys(), d.values()):
|
| 2419 |
+
new_k = keymap.get(k, k)
|
| 2420 |
+
updated_dict[new_k] = d[k]
|
| 2421 |
+
return updated_dict
|
| 2422 |
+
|
| 2423 |
+
def transform(self, results):
|
| 2424 |
+
# dict to albumentations format
|
| 2425 |
+
results = self.mapper(results, self.keymap_to_albu)
|
| 2426 |
+
|
| 2427 |
+
# Convert to RGB since Albumentations works with RGB images
|
| 2428 |
+
if self.bgr_to_rgb:
|
| 2429 |
+
results['image'] = cv2.cvtColor(results['image'],
|
| 2430 |
+
cv2.COLOR_BGR2RGB)
|
| 2431 |
+
if self.additional_targets:
|
| 2432 |
+
for key, value in self.additional_targets.items():
|
| 2433 |
+
if value == 'image':
|
| 2434 |
+
results[key] = cv2.cvtColor(results[key],
|
| 2435 |
+
cv2.COLOR_BGR2RGB)
|
| 2436 |
+
|
| 2437 |
+
# Apply Transform
|
| 2438 |
+
results = self.aug(**results)
|
| 2439 |
+
|
| 2440 |
+
# Convert back to BGR
|
| 2441 |
+
if self.bgr_to_rgb:
|
| 2442 |
+
results['image'] = cv2.cvtColor(results['image'],
|
| 2443 |
+
cv2.COLOR_RGB2BGR)
|
| 2444 |
+
if self.additional_targets:
|
| 2445 |
+
for key, value in self.additional_targets.items():
|
| 2446 |
+
if value == 'image':
|
| 2447 |
+
results[key] = cv2.cvtColor(results['image2'],
|
| 2448 |
+
cv2.COLOR_RGB2BGR)
|
| 2449 |
+
|
| 2450 |
+
# back to the original format
|
| 2451 |
+
results = self.mapper(results, self.keymap_back)
|
| 2452 |
+
|
| 2453 |
+
# update final shape
|
| 2454 |
+
if self.update_pad_shape:
|
| 2455 |
+
results['pad_shape'] = results['img'].shape
|
| 2456 |
+
|
| 2457 |
+
return results
|
| 2458 |
+
|
| 2459 |
+
def __repr__(self):
|
| 2460 |
+
repr_str = self.__class__.__name__ + f'(transforms={self.transforms})'
|
| 2461 |
+
return repr_str
|
| 2462 |
+
|
| 2463 |
+
|
| 2464 |
+
@TRANSFORMS.register_module()
|
| 2465 |
+
class ConcatCDInput(BaseTransform):
|
| 2466 |
+
"""Concat images for change detection.
|
| 2467 |
+
|
| 2468 |
+
Required Keys:
|
| 2469 |
+
|
| 2470 |
+
- img
|
| 2471 |
+
- img2
|
| 2472 |
+
|
| 2473 |
+
Args:
|
| 2474 |
+
input_keys (tuple): Input image keys for change detection.
|
| 2475 |
+
Default: ('img', 'img2').
|
| 2476 |
+
"""
|
| 2477 |
+
|
| 2478 |
+
def __init__(self, input_keys=('img', 'img2')):
|
| 2479 |
+
self.input_keys = input_keys
|
| 2480 |
+
|
| 2481 |
+
def transform(self, results: dict) -> dict:
|
| 2482 |
+
img = []
|
| 2483 |
+
for input_key in self.input_keys:
|
| 2484 |
+
img.append(results.pop(input_key))
|
| 2485 |
+
results['img'] = np.concatenate(img, axis=2)
|
| 2486 |
+
return results
|
| 2487 |
+
|
| 2488 |
+
def __repr__(self):
|
| 2489 |
+
repr_str = self.__class__.__name__
|
| 2490 |
+
repr_str += f'(input_keys={self.input_keys}, '
|
| 2491 |
+
return repr_str
|
| 2492 |
+
|
| 2493 |
+
|
| 2494 |
+
@TRANSFORMS.register_module()
|
| 2495 |
+
class RandomDepthMix(BaseTransform):
|
| 2496 |
+
"""This class implements the RandomDepthMix transform.
|
| 2497 |
+
|
| 2498 |
+
Args:
|
| 2499 |
+
prob (float): Probability of applying the transformation.
|
| 2500 |
+
Defaults to 0.25.
|
| 2501 |
+
mix_scale_ratio (float): Ratio to scale the mix width.
|
| 2502 |
+
Defaults to 0.75.
|
| 2503 |
+
"""
|
| 2504 |
+
|
| 2505 |
+
def __init__(
|
| 2506 |
+
self,
|
| 2507 |
+
prob: float = 0.25,
|
| 2508 |
+
mix_scale_ratio: float = 0.75,
|
| 2509 |
+
):
|
| 2510 |
+
super().__init__()
|
| 2511 |
+
|
| 2512 |
+
self.prob = prob
|
| 2513 |
+
self.mix_scale_ratio = mix_scale_ratio
|
| 2514 |
+
|
| 2515 |
+
def transform(self, results: dict) -> dict:
|
| 2516 |
+
if random.random() > self.prob:
|
| 2517 |
+
return results
|
| 2518 |
+
|
| 2519 |
+
h, w = results['img_shape'][:2]
|
| 2520 |
+
left = int(w * random.random())
|
| 2521 |
+
width_ratio = self.mix_scale_ratio * random.random()
|
| 2522 |
+
width = int(max(1, (w - left) * width_ratio))
|
| 2523 |
+
|
| 2524 |
+
img = results['img']
|
| 2525 |
+
depth_rescale_factor = results.get('depth_rescale_factor', 1)
|
| 2526 |
+
depth_map = results['gt_depth_map'] / depth_rescale_factor
|
| 2527 |
+
|
| 2528 |
+
if img.ndim == 3:
|
| 2529 |
+
for c in range(img.shape[-1]):
|
| 2530 |
+
img[:, left:left + width, c] = depth_map[:, left:left + width]
|
| 2531 |
+
elif img.ndim == 2:
|
| 2532 |
+
img[:, left:left + width] = depth_map[:, left:left + width]
|
| 2533 |
+
else:
|
| 2534 |
+
raise ValueError(f'Invalid image shape ({img.shape})')
|
| 2535 |
+
|
| 2536 |
+
results['img'] = img
|
| 2537 |
+
return results
|
third-party/InterFormer/mmseg/datasets/voc.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import os.path as osp
|
| 3 |
+
|
| 4 |
+
import mmengine.fileio as fileio
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import DATASETS
|
| 7 |
+
from .basesegdataset import BaseSegDataset
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@DATASETS.register_module()
|
| 11 |
+
class PascalVOCDataset(BaseSegDataset):
|
| 12 |
+
"""Pascal VOC dataset.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
split (str): Split txt file for Pascal VOC.
|
| 16 |
+
"""
|
| 17 |
+
METAINFO = dict(
|
| 18 |
+
classes=('background', 'aeroplane', 'bicycle', 'bird', 'boat',
|
| 19 |
+
'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable',
|
| 20 |
+
'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep',
|
| 21 |
+
'sofa', 'train', 'tvmonitor'),
|
| 22 |
+
palette=[[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0],
|
| 23 |
+
[0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128],
|
| 24 |
+
[64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0],
|
| 25 |
+
[64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128],
|
| 26 |
+
[0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0],
|
| 27 |
+
[0, 64, 128]])
|
| 28 |
+
|
| 29 |
+
def __init__(self,
|
| 30 |
+
ann_file,
|
| 31 |
+
img_suffix='.jpg',
|
| 32 |
+
seg_map_suffix='.png',
|
| 33 |
+
**kwargs) -> None:
|
| 34 |
+
super().__init__(
|
| 35 |
+
img_suffix=img_suffix,
|
| 36 |
+
seg_map_suffix=seg_map_suffix,
|
| 37 |
+
ann_file=ann_file,
|
| 38 |
+
**kwargs)
|
| 39 |
+
assert fileio.exists(self.data_prefix['img_path'],
|
| 40 |
+
self.backend_args) and osp.isfile(self.ann_file)
|
third-party/InterFormer/mmseg/engine/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .hooks import SegVisualizationHook
|
| 3 |
+
from .optimizers import (ForceDefaultOptimWrapperConstructor,
|
| 4 |
+
LayerDecayOptimizerConstructor,
|
| 5 |
+
LearningRateDecayOptimizerConstructor)
|
| 6 |
+
from .schedulers import PolyLRRatio
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
'LearningRateDecayOptimizerConstructor', 'LayerDecayOptimizerConstructor',
|
| 10 |
+
'SegVisualizationHook', 'PolyLRRatio',
|
| 11 |
+
'ForceDefaultOptimWrapperConstructor'
|
| 12 |
+
]
|
third-party/InterFormer/mmseg/engine/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (479 Bytes). View file
|
|
|
third-party/InterFormer/mmseg/engine/hooks/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .visualization_hook import SegVisualizationHook
|
| 3 |
+
|
| 4 |
+
__all__ = ['SegVisualizationHook']
|
third-party/InterFormer/mmseg/engine/hooks/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (255 Bytes). View file
|
|
|
third-party/InterFormer/mmseg/engine/hooks/__pycache__/visualization_hook.cpython-38.pyc
ADDED
|
Binary file (4.46 kB). View file
|
|
|
third-party/InterFormer/mmseg/engine/hooks/visualization_hook.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import os.path as osp
|
| 3 |
+
import warnings
|
| 4 |
+
from typing import Optional, Sequence
|
| 5 |
+
|
| 6 |
+
import mmcv
|
| 7 |
+
from mmengine.fileio import get
|
| 8 |
+
from mmengine.hooks import Hook
|
| 9 |
+
from mmengine.runner import Runner
|
| 10 |
+
from mmengine.visualization import Visualizer
|
| 11 |
+
|
| 12 |
+
from mmseg.registry import HOOKS
|
| 13 |
+
from mmseg.structures import SegDataSample
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@HOOKS.register_module()
|
| 17 |
+
class SegVisualizationHook(Hook):
|
| 18 |
+
"""Segmentation Visualization Hook. Used to visualize validation and
|
| 19 |
+
testing process prediction results.
|
| 20 |
+
|
| 21 |
+
In the testing phase:
|
| 22 |
+
|
| 23 |
+
1. If ``show`` is True, it means that only the prediction results are
|
| 24 |
+
visualized without storing data, so ``vis_backends`` needs to
|
| 25 |
+
be excluded.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
draw (bool): whether to draw prediction results. If it is False,
|
| 29 |
+
it means that no drawing will be done. Defaults to False.
|
| 30 |
+
interval (int): The interval of visualization. Defaults to 50.
|
| 31 |
+
show (bool): Whether to display the drawn image. Default to False.
|
| 32 |
+
wait_time (float): The interval of show (s). Defaults to 0.
|
| 33 |
+
backend_args (dict, Optional): Arguments to instantiate a file backend.
|
| 34 |
+
See https://mmengine.readthedocs.io/en/latest/api/fileio.htm
|
| 35 |
+
for details. Defaults to None.
|
| 36 |
+
Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(self,
|
| 40 |
+
draw: bool = False,
|
| 41 |
+
interval: int = 50,
|
| 42 |
+
show: bool = False,
|
| 43 |
+
wait_time: float = 0.,
|
| 44 |
+
backend_args: Optional[dict] = None):
|
| 45 |
+
self._visualizer: Visualizer = Visualizer.get_current_instance()
|
| 46 |
+
self.interval = interval
|
| 47 |
+
self.show = show
|
| 48 |
+
if self.show:
|
| 49 |
+
# No need to think about vis backends.
|
| 50 |
+
self._visualizer._vis_backends = {}
|
| 51 |
+
warnings.warn('The show is True, it means that only '
|
| 52 |
+
'the prediction results are visualized '
|
| 53 |
+
'without storing data, so vis_backends '
|
| 54 |
+
'needs to be excluded.')
|
| 55 |
+
|
| 56 |
+
self.wait_time = wait_time
|
| 57 |
+
self.backend_args = backend_args.copy() if backend_args else None
|
| 58 |
+
self.draw = draw
|
| 59 |
+
if not self.draw:
|
| 60 |
+
warnings.warn('The draw is False, it means that the '
|
| 61 |
+
'hook for visualization will not take '
|
| 62 |
+
'effect. The results will NOT be '
|
| 63 |
+
'visualized or stored.')
|
| 64 |
+
self._test_index = 0
|
| 65 |
+
|
| 66 |
+
def after_val_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
|
| 67 |
+
outputs: Sequence[SegDataSample]) -> None:
|
| 68 |
+
"""Run after every ``self.interval`` validation iterations.
|
| 69 |
+
|
| 70 |
+
Args:
|
| 71 |
+
runner (:obj:`Runner`): The runner of the validation process.
|
| 72 |
+
batch_idx (int): The index of the current batch in the val loop.
|
| 73 |
+
data_batch (dict): Data from dataloader.
|
| 74 |
+
outputs (Sequence[:obj:`SegDataSample`]]): A batch of data samples
|
| 75 |
+
that contain annotations and predictions.
|
| 76 |
+
"""
|
| 77 |
+
if self.draw is False:
|
| 78 |
+
return
|
| 79 |
+
|
| 80 |
+
# There is no guarantee that the same batch of images
|
| 81 |
+
# is visualized for each evaluation.
|
| 82 |
+
total_curr_iter = runner.iter + batch_idx
|
| 83 |
+
|
| 84 |
+
# Visualize only the first data
|
| 85 |
+
img_path = outputs[0].img_path
|
| 86 |
+
img_bytes = get(img_path, backend_args=self.backend_args)
|
| 87 |
+
img = mmcv.imfrombytes(img_bytes, channel_order='rgb')
|
| 88 |
+
window_name = f'val_{osp.basename(img_path)}'
|
| 89 |
+
|
| 90 |
+
if total_curr_iter % self.interval == 0:
|
| 91 |
+
self._visualizer.add_datasample(
|
| 92 |
+
window_name,
|
| 93 |
+
img,
|
| 94 |
+
data_sample=outputs[0],
|
| 95 |
+
show=self.show,
|
| 96 |
+
wait_time=self.wait_time,
|
| 97 |
+
step=total_curr_iter)
|
| 98 |
+
|
| 99 |
+
def after_test_iter(self, runner: Runner, batch_idx: int, data_batch: dict,
|
| 100 |
+
outputs: Sequence[SegDataSample]) -> None:
|
| 101 |
+
"""Run after every testing iterations.
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
runner (:obj:`Runner`): The runner of the testing process.
|
| 105 |
+
batch_idx (int): The index of the current batch in the val loop.
|
| 106 |
+
data_batch (dict): Data from dataloader.
|
| 107 |
+
outputs (Sequence[:obj:`SegDataSample`]): A batch of data samples
|
| 108 |
+
that contain annotations and predictions.
|
| 109 |
+
"""
|
| 110 |
+
if self.draw is False:
|
| 111 |
+
return
|
| 112 |
+
|
| 113 |
+
for data_sample in outputs:
|
| 114 |
+
self._test_index += 1
|
| 115 |
+
|
| 116 |
+
img_path = data_sample.img_path
|
| 117 |
+
window_name = f'test_{osp.basename(img_path)}'
|
| 118 |
+
|
| 119 |
+
img_path = data_sample.img_path
|
| 120 |
+
img_bytes = get(img_path, backend_args=self.backend_args)
|
| 121 |
+
img = mmcv.imfrombytes(img_bytes, channel_order='rgb')
|
| 122 |
+
|
| 123 |
+
self._visualizer.add_datasample(
|
| 124 |
+
window_name,
|
| 125 |
+
img,
|
| 126 |
+
data_sample=data_sample,
|
| 127 |
+
show=self.show,
|
| 128 |
+
wait_time=self.wait_time,
|
| 129 |
+
step=self._test_index)
|
third-party/InterFormer/mmseg/engine/optimizers/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .force_default_constructor import ForceDefaultOptimWrapperConstructor
|
| 3 |
+
from .layer_decay_optimizer_constructor import (
|
| 4 |
+
LayerDecayOptimizerConstructor, LearningRateDecayOptimizerConstructor)
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
'LearningRateDecayOptimizerConstructor', 'LayerDecayOptimizerConstructor',
|
| 8 |
+
'ForceDefaultOptimWrapperConstructor'
|
| 9 |
+
]
|
third-party/InterFormer/mmseg/engine/optimizers/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (438 Bytes). View file
|
|
|
third-party/InterFormer/mmseg/engine/optimizers/__pycache__/force_default_constructor.cpython-38.pyc
ADDED
|
Binary file (9.68 kB). View file
|
|
|
third-party/InterFormer/mmseg/engine/optimizers/__pycache__/layer_decay_optimizer_constructor.cpython-38.pyc
ADDED
|
Binary file (5.95 kB). View file
|
|
|
third-party/InterFormer/mmseg/engine/optimizers/force_default_constructor.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import logging
|
| 3 |
+
from typing import List, Optional, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
from mmengine.logging import print_log
|
| 8 |
+
from mmengine.optim import DefaultOptimWrapperConstructor
|
| 9 |
+
from mmengine.utils.dl_utils import mmcv_full_available
|
| 10 |
+
from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm, _InstanceNorm
|
| 11 |
+
from torch.nn import GroupNorm, LayerNorm
|
| 12 |
+
|
| 13 |
+
from mmseg.registry import OPTIM_WRAPPER_CONSTRUCTORS
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@OPTIM_WRAPPER_CONSTRUCTORS.register_module()
|
| 17 |
+
class ForceDefaultOptimWrapperConstructor(DefaultOptimWrapperConstructor):
|
| 18 |
+
"""Default constructor with forced optimizer settings.
|
| 19 |
+
|
| 20 |
+
This constructor extends the default constructor to add an option for
|
| 21 |
+
forcing default optimizer settings. This is useful for ensuring that
|
| 22 |
+
certain parameters or layers strictly adhere to pre-defined default
|
| 23 |
+
settings, regardless of any custom settings specified.
|
| 24 |
+
|
| 25 |
+
By default, each parameter share the same optimizer settings, and we
|
| 26 |
+
provide an argument ``paramwise_cfg`` to specify parameter-wise settings.
|
| 27 |
+
It is a dict and may contain various fields like 'custom_keys',
|
| 28 |
+
'bias_lr_mult', etc., as well as the additional field
|
| 29 |
+
`force_default_settings` which allows for enforcing default settings on
|
| 30 |
+
optimizer parameters.
|
| 31 |
+
|
| 32 |
+
- ``custom_keys`` (dict): Specified parameters-wise settings by keys. If
|
| 33 |
+
one of the keys in ``custom_keys`` is a substring of the name of one
|
| 34 |
+
parameter, then the setting of the parameter will be specified by
|
| 35 |
+
``custom_keys[key]`` and other setting like ``bias_lr_mult`` etc. will
|
| 36 |
+
be ignored. It should be noted that the aforementioned ``key`` is the
|
| 37 |
+
longest key that is a substring of the name of the parameter. If there
|
| 38 |
+
are multiple matched keys with the same length, then the key with lower
|
| 39 |
+
alphabet order will be chosen.
|
| 40 |
+
``custom_keys[key]`` should be a dict and may contain fields ``lr_mult``
|
| 41 |
+
and ``decay_mult``. See Example 2 below.
|
| 42 |
+
- ``bias_lr_mult`` (float): It will be multiplied to the learning
|
| 43 |
+
rate for all bias parameters (except for those in normalization
|
| 44 |
+
layers and offset layers of DCN).
|
| 45 |
+
- ``bias_decay_mult`` (float): It will be multiplied to the weight
|
| 46 |
+
decay for all bias parameters (except for those in
|
| 47 |
+
normalization layers, depthwise conv layers, offset layers of DCN).
|
| 48 |
+
- ``norm_decay_mult`` (float): It will be multiplied to the weight
|
| 49 |
+
decay for all weight and bias parameters of normalization
|
| 50 |
+
layers.
|
| 51 |
+
- ``flat_decay_mult`` (float): It will be multiplied to the weight
|
| 52 |
+
decay for all one-dimensional parameters
|
| 53 |
+
- ``dwconv_decay_mult`` (float): It will be multiplied to the weight
|
| 54 |
+
decay for all weight and bias parameters of depthwise conv
|
| 55 |
+
layers.
|
| 56 |
+
- ``dcn_offset_lr_mult`` (float): It will be multiplied to the learning
|
| 57 |
+
rate for parameters of offset layer in the deformable convs
|
| 58 |
+
of a model.
|
| 59 |
+
- ``bypass_duplicate`` (bool): If true, the duplicate parameters
|
| 60 |
+
would not be added into optimizer. Defaults to False.
|
| 61 |
+
- ``force_default_settings`` (bool): If true, this will override any
|
| 62 |
+
custom settings defined by ``custom_keys`` and enforce the use of
|
| 63 |
+
default settings for optimizer parameters like ``bias_lr_mult``.
|
| 64 |
+
This is particularly useful when you want to ensure that certain layers
|
| 65 |
+
or parameters adhere strictly to the pre-defined default settings.
|
| 66 |
+
|
| 67 |
+
Note:
|
| 68 |
+
|
| 69 |
+
1. If the option ``dcn_offset_lr_mult`` is used, the constructor will
|
| 70 |
+
override the effect of ``bias_lr_mult`` in the bias of offset layer.
|
| 71 |
+
So be careful when using both ``bias_lr_mult`` and
|
| 72 |
+
``dcn_offset_lr_mult``. If you wish to apply both of them to the offset
|
| 73 |
+
layer in deformable convs, set ``dcn_offset_lr_mult`` to the original
|
| 74 |
+
``dcn_offset_lr_mult`` * ``bias_lr_mult``.
|
| 75 |
+
|
| 76 |
+
2. If the option ``dcn_offset_lr_mult`` is used, the constructor will
|
| 77 |
+
apply it to all the DCN layers in the model. So be careful when the
|
| 78 |
+
model contains multiple DCN layers in places other than backbone.
|
| 79 |
+
|
| 80 |
+
3. When the option ``force_default_settings`` is true, it will override
|
| 81 |
+
any custom settings provided in ``custom_keys``. This ensures that the
|
| 82 |
+
default settings for the optimizer parameters are used.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
optim_wrapper_cfg (dict): The config dict of the optimizer wrapper.
|
| 86 |
+
|
| 87 |
+
Required fields of ``optim_wrapper_cfg`` are
|
| 88 |
+
|
| 89 |
+
- ``type``: class name of the OptimizerWrapper
|
| 90 |
+
- ``optimizer``: The configuration of optimizer.
|
| 91 |
+
|
| 92 |
+
Optional fields of ``optim_wrapper_cfg`` are
|
| 93 |
+
|
| 94 |
+
- any arguments of the corresponding optimizer wrapper type,
|
| 95 |
+
e.g., accumulative_counts, clip_grad, etc.
|
| 96 |
+
|
| 97 |
+
Required fields of ``optimizer`` are
|
| 98 |
+
|
| 99 |
+
- `type`: class name of the optimizer.
|
| 100 |
+
|
| 101 |
+
Optional fields of ``optimizer`` are
|
| 102 |
+
|
| 103 |
+
- any arguments of the corresponding optimizer type, e.g.,
|
| 104 |
+
lr, weight_decay, momentum, etc.
|
| 105 |
+
|
| 106 |
+
paramwise_cfg (dict, optional): Parameter-wise options.
|
| 107 |
+
|
| 108 |
+
Example 1:
|
| 109 |
+
>>> model = torch.nn.modules.Conv1d(1, 1, 1)
|
| 110 |
+
>>> optim_wrapper_cfg = dict(
|
| 111 |
+
>>> dict(type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01,
|
| 112 |
+
>>> momentum=0.9, weight_decay=0.0001))
|
| 113 |
+
>>> paramwise_cfg = dict(norm_decay_mult=0.)
|
| 114 |
+
>>> optim_wrapper_builder = DefaultOptimWrapperConstructor(
|
| 115 |
+
>>> optim_wrapper_cfg, paramwise_cfg)
|
| 116 |
+
>>> optim_wrapper = optim_wrapper_builder(model)
|
| 117 |
+
|
| 118 |
+
Example 2:
|
| 119 |
+
>>> # assume model have attribute model.backbone and model.cls_head
|
| 120 |
+
>>> optim_wrapper_cfg = dict(type='OptimWrapper', optimizer=dict(
|
| 121 |
+
>>> type='SGD', lr=0.01, weight_decay=0.95))
|
| 122 |
+
>>> paramwise_cfg = dict(custom_keys={
|
| 123 |
+
>>> 'backbone': dict(lr_mult=0.1, decay_mult=0.9)})
|
| 124 |
+
>>> optim_wrapper_builder = DefaultOptimWrapperConstructor(
|
| 125 |
+
>>> optim_wrapper_cfg, paramwise_cfg)
|
| 126 |
+
>>> optim_wrapper = optim_wrapper_builder(model)
|
| 127 |
+
>>> # Then the `lr` and `weight_decay` for model.backbone is
|
| 128 |
+
>>> # (0.01 * 0.1, 0.95 * 0.9). `lr` and `weight_decay` for
|
| 129 |
+
>>> # model.cls_head is (0.01, 0.95).
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
def add_params(self,
|
| 133 |
+
params: List[dict],
|
| 134 |
+
module: nn.Module,
|
| 135 |
+
prefix: str = '',
|
| 136 |
+
is_dcn_module: Optional[Union[int, float]] = None) -> None:
|
| 137 |
+
"""Add all parameters of module to the params list.
|
| 138 |
+
|
| 139 |
+
The parameters of the given module will be added to the list of param
|
| 140 |
+
groups, with specific rules defined by paramwise_cfg.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
params (list[dict]): A list of param groups, it will be modified
|
| 144 |
+
in place.
|
| 145 |
+
module (nn.Module): The module to be added.
|
| 146 |
+
prefix (str): The prefix of the module
|
| 147 |
+
is_dcn_module (int|float|None): If the current module is a
|
| 148 |
+
submodule of DCN, `is_dcn_module` will be passed to
|
| 149 |
+
control conv_offset layer's learning rate. Defaults to None.
|
| 150 |
+
"""
|
| 151 |
+
# get param-wise options
|
| 152 |
+
custom_keys = self.paramwise_cfg.get('custom_keys', {})
|
| 153 |
+
# first sort with alphabet order and then sort with reversed len of str
|
| 154 |
+
sorted_keys = sorted(sorted(custom_keys.keys()), key=len, reverse=True)
|
| 155 |
+
|
| 156 |
+
bias_lr_mult = self.paramwise_cfg.get('bias_lr_mult', None)
|
| 157 |
+
bias_decay_mult = self.paramwise_cfg.get('bias_decay_mult', None)
|
| 158 |
+
norm_decay_mult = self.paramwise_cfg.get('norm_decay_mult', None)
|
| 159 |
+
dwconv_decay_mult = self.paramwise_cfg.get('dwconv_decay_mult', None)
|
| 160 |
+
flat_decay_mult = self.paramwise_cfg.get('flat_decay_mult', None)
|
| 161 |
+
bypass_duplicate = self.paramwise_cfg.get('bypass_duplicate', False)
|
| 162 |
+
dcn_offset_lr_mult = self.paramwise_cfg.get('dcn_offset_lr_mult', None)
|
| 163 |
+
force_default_settings = self.paramwise_cfg.get(
|
| 164 |
+
'force_default_settings', False)
|
| 165 |
+
|
| 166 |
+
# special rules for norm layers and depth-wise conv layers
|
| 167 |
+
is_norm = isinstance(module,
|
| 168 |
+
(_BatchNorm, _InstanceNorm, GroupNorm, LayerNorm))
|
| 169 |
+
is_dwconv = (
|
| 170 |
+
isinstance(module, torch.nn.Conv2d)
|
| 171 |
+
and module.in_channels == module.groups)
|
| 172 |
+
|
| 173 |
+
for name, param in module.named_parameters(recurse=False):
|
| 174 |
+
param_group = {'params': [param]}
|
| 175 |
+
if bypass_duplicate and self._is_in(param_group, params):
|
| 176 |
+
print_log(
|
| 177 |
+
f'{prefix} is duplicate. It is skipped since '
|
| 178 |
+
f'bypass_duplicate={bypass_duplicate}',
|
| 179 |
+
logger='current',
|
| 180 |
+
level=logging.WARNING)
|
| 181 |
+
continue
|
| 182 |
+
if not param.requires_grad:
|
| 183 |
+
params.append(param_group)
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
# if the parameter match one of the custom keys, ignore other rules
|
| 187 |
+
is_custom = False
|
| 188 |
+
for key in sorted_keys:
|
| 189 |
+
if key in f'{prefix}.{name}':
|
| 190 |
+
is_custom = True
|
| 191 |
+
lr_mult = custom_keys[key].get('lr_mult', 1.)
|
| 192 |
+
param_group['lr'] = self.base_lr * lr_mult
|
| 193 |
+
if self.base_wd is not None:
|
| 194 |
+
decay_mult = custom_keys[key].get('decay_mult', 1.)
|
| 195 |
+
param_group['weight_decay'] = self.base_wd * decay_mult
|
| 196 |
+
# add custom settings to param_group
|
| 197 |
+
for k, v in custom_keys[key].items():
|
| 198 |
+
param_group[k] = v
|
| 199 |
+
break
|
| 200 |
+
|
| 201 |
+
if not is_custom or force_default_settings:
|
| 202 |
+
# bias_lr_mult affects all bias parameters
|
| 203 |
+
# except for norm.bias dcn.conv_offset.bias
|
| 204 |
+
if name == 'bias' and not (
|
| 205 |
+
is_norm or is_dcn_module) and bias_lr_mult is not None:
|
| 206 |
+
param_group['lr'] = self.base_lr * bias_lr_mult
|
| 207 |
+
|
| 208 |
+
if (prefix.find('conv_offset') != -1 and is_dcn_module
|
| 209 |
+
and dcn_offset_lr_mult is not None
|
| 210 |
+
and isinstance(module, torch.nn.Conv2d)):
|
| 211 |
+
# deal with both dcn_offset's bias & weight
|
| 212 |
+
param_group['lr'] = self.base_lr * dcn_offset_lr_mult
|
| 213 |
+
|
| 214 |
+
# apply weight decay policies
|
| 215 |
+
if self.base_wd is not None:
|
| 216 |
+
# norm decay
|
| 217 |
+
if is_norm and norm_decay_mult is not None:
|
| 218 |
+
param_group[
|
| 219 |
+
'weight_decay'] = self.base_wd * norm_decay_mult
|
| 220 |
+
# bias lr and decay
|
| 221 |
+
elif (name == 'bias' and not is_dcn_module
|
| 222 |
+
and bias_decay_mult is not None):
|
| 223 |
+
param_group[
|
| 224 |
+
'weight_decay'] = self.base_wd * bias_decay_mult
|
| 225 |
+
# depth-wise conv
|
| 226 |
+
elif is_dwconv and dwconv_decay_mult is not None:
|
| 227 |
+
param_group[
|
| 228 |
+
'weight_decay'] = self.base_wd * dwconv_decay_mult
|
| 229 |
+
# flatten parameters except dcn offset
|
| 230 |
+
elif (param.ndim == 1 and not is_dcn_module
|
| 231 |
+
and flat_decay_mult is not None):
|
| 232 |
+
param_group[
|
| 233 |
+
'weight_decay'] = self.base_wd * flat_decay_mult
|
| 234 |
+
params.append(param_group)
|
| 235 |
+
for key, value in param_group.items():
|
| 236 |
+
if key == 'params':
|
| 237 |
+
continue
|
| 238 |
+
full_name = f'{prefix}.{name}' if prefix else name
|
| 239 |
+
print_log(
|
| 240 |
+
f'paramwise_options -- {full_name}:{key}={value}',
|
| 241 |
+
logger='current')
|
| 242 |
+
|
| 243 |
+
if mmcv_full_available():
|
| 244 |
+
from mmcv.ops import DeformConv2d, ModulatedDeformConv2d
|
| 245 |
+
is_dcn_module = isinstance(module,
|
| 246 |
+
(DeformConv2d, ModulatedDeformConv2d))
|
| 247 |
+
else:
|
| 248 |
+
is_dcn_module = False
|
| 249 |
+
for child_name, child_mod in module.named_children():
|
| 250 |
+
child_prefix = f'{prefix}.{child_name}' if prefix else child_name
|
| 251 |
+
self.add_params(
|
| 252 |
+
params,
|
| 253 |
+
child_mod,
|
| 254 |
+
prefix=child_prefix,
|
| 255 |
+
is_dcn_module=is_dcn_module)
|
third-party/InterFormer/mmseg/engine/optimizers/layer_decay_optimizer_constructor.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import json
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
from mmengine.dist import get_dist_info
|
| 6 |
+
from mmengine.logging import print_log
|
| 7 |
+
from mmengine.optim import DefaultOptimWrapperConstructor
|
| 8 |
+
|
| 9 |
+
from mmseg.registry import OPTIM_WRAPPER_CONSTRUCTORS
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_layer_id_for_convnext(var_name, max_layer_id):
|
| 13 |
+
"""Get the layer id to set the different learning rates in ``layer_wise``
|
| 14 |
+
decay_type.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
var_name (str): The key of the model.
|
| 18 |
+
max_layer_id (int): Maximum number of backbone layers.
|
| 19 |
+
|
| 20 |
+
Returns:
|
| 21 |
+
int: The id number corresponding to different learning rate in
|
| 22 |
+
``LearningRateDecayOptimizerConstructor``.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
if var_name in ('backbone.cls_token', 'backbone.mask_token',
|
| 26 |
+
'backbone.pos_embed'):
|
| 27 |
+
return 0
|
| 28 |
+
elif var_name.startswith('backbone.downsample_layers'):
|
| 29 |
+
stage_id = int(var_name.split('.')[2])
|
| 30 |
+
if stage_id == 0:
|
| 31 |
+
layer_id = 0
|
| 32 |
+
elif stage_id == 1:
|
| 33 |
+
layer_id = 2
|
| 34 |
+
elif stage_id == 2:
|
| 35 |
+
layer_id = 3
|
| 36 |
+
elif stage_id == 3:
|
| 37 |
+
layer_id = max_layer_id
|
| 38 |
+
return layer_id
|
| 39 |
+
elif var_name.startswith('backbone.stages'):
|
| 40 |
+
stage_id = int(var_name.split('.')[2])
|
| 41 |
+
block_id = int(var_name.split('.')[3])
|
| 42 |
+
if stage_id == 0:
|
| 43 |
+
layer_id = 1
|
| 44 |
+
elif stage_id == 1:
|
| 45 |
+
layer_id = 2
|
| 46 |
+
elif stage_id == 2:
|
| 47 |
+
layer_id = 3 + block_id // 3
|
| 48 |
+
elif stage_id == 3:
|
| 49 |
+
layer_id = max_layer_id
|
| 50 |
+
return layer_id
|
| 51 |
+
else:
|
| 52 |
+
return max_layer_id + 1
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_stage_id_for_convnext(var_name, max_stage_id):
|
| 56 |
+
"""Get the stage id to set the different learning rates in ``stage_wise``
|
| 57 |
+
decay_type.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
var_name (str): The key of the model.
|
| 61 |
+
max_stage_id (int): Maximum number of backbone layers.
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
int: The id number corresponding to different learning rate in
|
| 65 |
+
``LearningRateDecayOptimizerConstructor``.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
if var_name in ('backbone.cls_token', 'backbone.mask_token',
|
| 69 |
+
'backbone.pos_embed'):
|
| 70 |
+
return 0
|
| 71 |
+
elif var_name.startswith('backbone.downsample_layers'):
|
| 72 |
+
return 0
|
| 73 |
+
elif var_name.startswith('backbone.stages'):
|
| 74 |
+
stage_id = int(var_name.split('.')[2])
|
| 75 |
+
return stage_id + 1
|
| 76 |
+
else:
|
| 77 |
+
return max_stage_id - 1
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def get_layer_id_for_vit(var_name, max_layer_id):
|
| 81 |
+
"""Get the layer id to set the different learning rates.
|
| 82 |
+
|
| 83 |
+
Args:
|
| 84 |
+
var_name (str): The key of the model.
|
| 85 |
+
num_max_layer (int): Maximum number of backbone layers.
|
| 86 |
+
|
| 87 |
+
Returns:
|
| 88 |
+
int: Returns the layer id of the key.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
if var_name in ('backbone.cls_token', 'backbone.mask_token',
|
| 92 |
+
'backbone.pos_embed'):
|
| 93 |
+
return 0
|
| 94 |
+
elif var_name.startswith('backbone.patch_embed'):
|
| 95 |
+
return 0
|
| 96 |
+
elif var_name.startswith('backbone.layers'):
|
| 97 |
+
layer_id = int(var_name.split('.')[2])
|
| 98 |
+
return layer_id + 1
|
| 99 |
+
else:
|
| 100 |
+
return max_layer_id - 1
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@OPTIM_WRAPPER_CONSTRUCTORS.register_module()
|
| 104 |
+
class LearningRateDecayOptimizerConstructor(DefaultOptimWrapperConstructor):
|
| 105 |
+
"""Different learning rates are set for different layers of backbone.
|
| 106 |
+
|
| 107 |
+
Note: Currently, this optimizer constructor is built for ConvNeXt,
|
| 108 |
+
BEiT and MAE.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
def add_params(self, params, module, **kwargs):
|
| 112 |
+
"""Add all parameters of module to the params list.
|
| 113 |
+
|
| 114 |
+
The parameters of the given module will be added to the list of param
|
| 115 |
+
groups, with specific rules defined by paramwise_cfg.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
params (list[dict]): A list of param groups, it will be modified
|
| 119 |
+
in place.
|
| 120 |
+
module (nn.Module): The module to be added.
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
parameter_groups = {}
|
| 124 |
+
print_log(f'self.paramwise_cfg is {self.paramwise_cfg}')
|
| 125 |
+
num_layers = self.paramwise_cfg.get('num_layers') + 2
|
| 126 |
+
decay_rate = self.paramwise_cfg.get('decay_rate')
|
| 127 |
+
decay_type = self.paramwise_cfg.get('decay_type', 'layer_wise')
|
| 128 |
+
print_log('Build LearningRateDecayOptimizerConstructor '
|
| 129 |
+
f'{decay_type} {decay_rate} - {num_layers}')
|
| 130 |
+
weight_decay = self.base_wd
|
| 131 |
+
for name, param in module.named_parameters():
|
| 132 |
+
if not param.requires_grad:
|
| 133 |
+
continue # frozen weights
|
| 134 |
+
if len(param.shape) == 1 or name.endswith('.bias') or name in (
|
| 135 |
+
'pos_embed', 'cls_token'):
|
| 136 |
+
group_name = 'no_decay'
|
| 137 |
+
this_weight_decay = 0.
|
| 138 |
+
else:
|
| 139 |
+
group_name = 'decay'
|
| 140 |
+
this_weight_decay = weight_decay
|
| 141 |
+
if 'layer_wise' in decay_type:
|
| 142 |
+
if 'ConvNeXt' in module.backbone.__class__.__name__:
|
| 143 |
+
layer_id = get_layer_id_for_convnext(
|
| 144 |
+
name, self.paramwise_cfg.get('num_layers'))
|
| 145 |
+
print_log(f'set param {name} as id {layer_id}')
|
| 146 |
+
elif 'BEiT' in module.backbone.__class__.__name__ or \
|
| 147 |
+
'MAE' in module.backbone.__class__.__name__:
|
| 148 |
+
layer_id = get_layer_id_for_vit(name, num_layers)
|
| 149 |
+
print_log(f'set param {name} as id {layer_id}')
|
| 150 |
+
else:
|
| 151 |
+
raise NotImplementedError()
|
| 152 |
+
elif decay_type == 'stage_wise':
|
| 153 |
+
if 'ConvNeXt' in module.backbone.__class__.__name__:
|
| 154 |
+
layer_id = get_stage_id_for_convnext(name, num_layers)
|
| 155 |
+
print_log(f'set param {name} as id {layer_id}')
|
| 156 |
+
else:
|
| 157 |
+
raise NotImplementedError()
|
| 158 |
+
group_name = f'layer_{layer_id}_{group_name}'
|
| 159 |
+
|
| 160 |
+
if group_name not in parameter_groups:
|
| 161 |
+
scale = decay_rate**(num_layers - layer_id - 1)
|
| 162 |
+
|
| 163 |
+
parameter_groups[group_name] = {
|
| 164 |
+
'weight_decay': this_weight_decay,
|
| 165 |
+
'params': [],
|
| 166 |
+
'param_names': [],
|
| 167 |
+
'lr_scale': scale,
|
| 168 |
+
'group_name': group_name,
|
| 169 |
+
'lr': scale * self.base_lr,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
parameter_groups[group_name]['params'].append(param)
|
| 173 |
+
parameter_groups[group_name]['param_names'].append(name)
|
| 174 |
+
rank, _ = get_dist_info()
|
| 175 |
+
if rank == 0:
|
| 176 |
+
to_display = {}
|
| 177 |
+
for key in parameter_groups:
|
| 178 |
+
to_display[key] = {
|
| 179 |
+
'param_names': parameter_groups[key]['param_names'],
|
| 180 |
+
'lr_scale': parameter_groups[key]['lr_scale'],
|
| 181 |
+
'lr': parameter_groups[key]['lr'],
|
| 182 |
+
'weight_decay': parameter_groups[key]['weight_decay'],
|
| 183 |
+
}
|
| 184 |
+
print_log(f'Param groups = {json.dumps(to_display, indent=2)}')
|
| 185 |
+
params.extend(parameter_groups.values())
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@OPTIM_WRAPPER_CONSTRUCTORS.register_module()
|
| 189 |
+
class LayerDecayOptimizerConstructor(LearningRateDecayOptimizerConstructor):
|
| 190 |
+
"""Different learning rates are set for different layers of backbone.
|
| 191 |
+
|
| 192 |
+
Note: Currently, this optimizer constructor is built for BEiT,
|
| 193 |
+
and it will be deprecated.
|
| 194 |
+
Please use ``LearningRateDecayOptimizerConstructor`` instead.
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
def __init__(self, optim_wrapper_cfg, paramwise_cfg):
|
| 198 |
+
warnings.warn('DeprecationWarning: Original '
|
| 199 |
+
'LayerDecayOptimizerConstructor of BEiT '
|
| 200 |
+
'will be deprecated. Please use '
|
| 201 |
+
'LearningRateDecayOptimizerConstructor instead, '
|
| 202 |
+
'and set decay_type = layer_wise_vit in paramwise_cfg.')
|
| 203 |
+
paramwise_cfg.update({'decay_type': 'layer_wise_vit'})
|
| 204 |
+
warnings.warn('DeprecationWarning: Layer_decay_rate will '
|
| 205 |
+
'be deleted, please use decay_rate instead.')
|
| 206 |
+
paramwise_cfg['decay_rate'] = paramwise_cfg.pop('layer_decay_rate')
|
| 207 |
+
super().__init__(optim_wrapper_cfg, paramwise_cfg)
|
third-party/InterFormer/mmseg/engine/schedulers/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .poly_ratio_scheduler import PolyLRRatio
|
| 3 |
+
|
| 4 |
+
__all__ = ['PolyLRRatio']
|
third-party/InterFormer/mmseg/engine/schedulers/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (253 Bytes). View file
|
|
|
third-party/InterFormer/mmseg/engine/schedulers/__pycache__/poly_ratio_scheduler.cpython-38.pyc
ADDED
|
Binary file (2.77 kB). View file
|
|
|
third-party/InterFormer/mmseg/engine/schedulers/poly_ratio_scheduler.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
from mmengine.optim.scheduler import PolyLR
|
| 5 |
+
|
| 6 |
+
from mmseg.registry import PARAM_SCHEDULERS
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@PARAM_SCHEDULERS.register_module()
|
| 10 |
+
class PolyLRRatio(PolyLR):
|
| 11 |
+
"""Implements polynomial learning rate decay with ratio.
|
| 12 |
+
|
| 13 |
+
This scheduler adjusts the learning rate of each parameter group
|
| 14 |
+
following a polynomial decay equation. The decay can occur in
|
| 15 |
+
conjunction with external parameter adjustments made outside this
|
| 16 |
+
scheduler.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
optimizer (Optimizer or OptimWrapper): Wrapped optimizer.
|
| 20 |
+
eta_min (float): Minimum learning rate at the end of scheduling.
|
| 21 |
+
Defaults to 0.
|
| 22 |
+
eta_min_ratio (float, optional): The ratio of the minimum parameter
|
| 23 |
+
value to the base parameter value. Either `eta_min` or
|
| 24 |
+
`eta_min_ratio` should be specified. Defaults to None.
|
| 25 |
+
power (float): The power of the polynomial. Defaults to 1.0.
|
| 26 |
+
begin (int): Step at which to start updating the parameters.
|
| 27 |
+
Defaults to 0.
|
| 28 |
+
end (int): Step at which to stop updating the parameters.
|
| 29 |
+
Defaults to INF.
|
| 30 |
+
last_step (int): The index of last step. Used for resume without
|
| 31 |
+
state dict. Defaults to -1.
|
| 32 |
+
by_epoch (bool): Whether the scheduled parameters are updated by
|
| 33 |
+
epochs. Defaults to True.
|
| 34 |
+
verbose (bool): Whether to print the value for each update.
|
| 35 |
+
Defaults to False.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(self, eta_min_ratio: Optional[int] = None, *args, **kwargs):
|
| 39 |
+
super().__init__(*args, **kwargs)
|
| 40 |
+
|
| 41 |
+
self.eta_min_ratio = eta_min_ratio
|
| 42 |
+
|
| 43 |
+
def _get_value(self):
|
| 44 |
+
"""Compute value using chainable form of the scheduler."""
|
| 45 |
+
|
| 46 |
+
if self.last_step == 0:
|
| 47 |
+
return [
|
| 48 |
+
group[self.param_name] for group in self.optimizer.param_groups
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
param_groups_value = []
|
| 52 |
+
for base_value, param_group in zip(self.base_values,
|
| 53 |
+
self.optimizer.param_groups):
|
| 54 |
+
eta_min = self.eta_min if self.eta_min_ratio is None else \
|
| 55 |
+
base_value * self.eta_min_ratio
|
| 56 |
+
step_ratio = (1 - 1 /
|
| 57 |
+
(self.total_iters - self.last_step + 1))**self.power
|
| 58 |
+
step_value = (param_group[self.param_name] -
|
| 59 |
+
eta_min) * step_ratio + eta_min
|
| 60 |
+
param_groups_value.append(step_value)
|
| 61 |
+
|
| 62 |
+
return param_groups_value
|
third-party/InterFormer/mmseg/evaluation/__init__.py
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .metrics import CityscapesMetric, DepthMetric, IoUMetric
|
| 3 |
+
|
| 4 |
+
__all__ = ['IoUMetric', 'CityscapesMetric', 'DepthMetric']
|
third-party/InterFormer/mmseg/evaluation/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (294 Bytes). View file
|
|
|
third-party/InterFormer/mmseg/evaluation/metrics/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .citys_metric import CityscapesMetric
|
| 3 |
+
from .depth_metric import DepthMetric
|
| 4 |
+
from .iou_metric import IoUMetric
|
| 5 |
+
|
| 6 |
+
__all__ = ['IoUMetric', 'CityscapesMetric', 'DepthMetric']
|
third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (357 Bytes). View file
|
|
|
third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/citys_metric.cpython-38.pyc
ADDED
|
Binary file (5.73 kB). View file
|
|
|
third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/depth_metric.cpython-38.pyc
ADDED
|
Binary file (7.42 kB). View file
|
|
|
third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/iou_metric.cpython-38.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
third-party/InterFormer/mmseg/evaluation/metrics/citys_metric.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import os.path as osp
|
| 3 |
+
import shutil
|
| 4 |
+
from collections import OrderedDict
|
| 5 |
+
from typing import Dict, Optional, Sequence
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
|
| 9 |
+
import cityscapesscripts.evaluation.evalPixelLevelSemanticLabeling as CSEval # noqa
|
| 10 |
+
import cityscapesscripts.helpers.labels as CSLabels
|
| 11 |
+
except ImportError:
|
| 12 |
+
CSLabels = None
|
| 13 |
+
CSEval = None
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
from mmengine.dist import is_main_process, master_only
|
| 17 |
+
from mmengine.evaluator import BaseMetric
|
| 18 |
+
from mmengine.logging import MMLogger, print_log
|
| 19 |
+
from mmengine.utils import mkdir_or_exist
|
| 20 |
+
from PIL import Image
|
| 21 |
+
|
| 22 |
+
from mmseg.registry import METRICS
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@METRICS.register_module()
|
| 26 |
+
class CityscapesMetric(BaseMetric):
|
| 27 |
+
"""Cityscapes evaluation metric.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
output_dir (str): The directory for output prediction
|
| 31 |
+
ignore_index (int): Index that will be ignored in evaluation.
|
| 32 |
+
Default: 255.
|
| 33 |
+
format_only (bool): Only format result for results commit without
|
| 34 |
+
perform evaluation. It is useful when you want to format the result
|
| 35 |
+
to a specific format and submit it to the test server.
|
| 36 |
+
Defaults to False.
|
| 37 |
+
keep_results (bool): Whether to keep the results. When ``format_only``
|
| 38 |
+
is True, ``keep_results`` must be True. Defaults to False.
|
| 39 |
+
collect_device (str): Device name used for collecting results from
|
| 40 |
+
different ranks during distributed training. Must be 'cpu' or
|
| 41 |
+
'gpu'. Defaults to 'cpu'.
|
| 42 |
+
prefix (str, optional): The prefix that will be added in the metric
|
| 43 |
+
names to disambiguate homonymous metrics of different evaluators.
|
| 44 |
+
If prefix is not provided in the argument, self.default_prefix
|
| 45 |
+
will be used instead. Defaults to None.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
def __init__(self,
|
| 49 |
+
output_dir: str,
|
| 50 |
+
ignore_index: int = 255,
|
| 51 |
+
format_only: bool = False,
|
| 52 |
+
keep_results: bool = False,
|
| 53 |
+
collect_device: str = 'cpu',
|
| 54 |
+
prefix: Optional[str] = None,
|
| 55 |
+
**kwargs) -> None:
|
| 56 |
+
super().__init__(collect_device=collect_device, prefix=prefix)
|
| 57 |
+
if CSEval is None:
|
| 58 |
+
raise ImportError('Please run "pip install cityscapesscripts" to '
|
| 59 |
+
'install cityscapesscripts first.')
|
| 60 |
+
self.output_dir = output_dir
|
| 61 |
+
self.ignore_index = ignore_index
|
| 62 |
+
|
| 63 |
+
self.format_only = format_only
|
| 64 |
+
if format_only:
|
| 65 |
+
assert keep_results, (
|
| 66 |
+
'When format_only is True, the results must be keep, please '
|
| 67 |
+
f'set keep_results as True, but got {keep_results}')
|
| 68 |
+
self.keep_results = keep_results
|
| 69 |
+
self.prefix = prefix
|
| 70 |
+
if is_main_process():
|
| 71 |
+
mkdir_or_exist(self.output_dir)
|
| 72 |
+
|
| 73 |
+
@master_only
|
| 74 |
+
def __del__(self) -> None:
|
| 75 |
+
"""Clean up."""
|
| 76 |
+
if not self.keep_results:
|
| 77 |
+
shutil.rmtree(self.output_dir)
|
| 78 |
+
|
| 79 |
+
def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None:
|
| 80 |
+
"""Process one batch of data and data_samples.
|
| 81 |
+
|
| 82 |
+
The processed results should be stored in ``self.results``, which will
|
| 83 |
+
be used to computed the metrics when all batches have been processed.
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
data_batch (dict): A batch of data from the dataloader.
|
| 87 |
+
data_samples (Sequence[dict]): A batch of outputs from the model.
|
| 88 |
+
"""
|
| 89 |
+
mkdir_or_exist(self.output_dir)
|
| 90 |
+
|
| 91 |
+
for data_sample in data_samples:
|
| 92 |
+
pred_label = data_sample['pred_sem_seg']['data'][0].cpu().numpy()
|
| 93 |
+
# when evaluating with official cityscapesscripts,
|
| 94 |
+
# labelIds should be used
|
| 95 |
+
pred_label = self._convert_to_label_id(pred_label)
|
| 96 |
+
basename = osp.splitext(osp.basename(data_sample['img_path']))[0]
|
| 97 |
+
png_filename = osp.abspath(
|
| 98 |
+
osp.join(self.output_dir, f'{basename}.png'))
|
| 99 |
+
output = Image.fromarray(pred_label.astype(np.uint8)).convert('P')
|
| 100 |
+
output.save(png_filename)
|
| 101 |
+
if self.format_only:
|
| 102 |
+
# format_only always for test dataset without ground truth
|
| 103 |
+
gt_filename = ''
|
| 104 |
+
else:
|
| 105 |
+
# when evaluating with official cityscapesscripts,
|
| 106 |
+
# **_gtFine_labelIds.png is used
|
| 107 |
+
gt_filename = data_sample['seg_map_path'].replace(
|
| 108 |
+
'labelTrainIds.png', 'labelIds.png')
|
| 109 |
+
self.results.append((png_filename, gt_filename))
|
| 110 |
+
|
| 111 |
+
def compute_metrics(self, results: list) -> Dict[str, float]:
|
| 112 |
+
"""Compute the metrics from processed results.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
results (list): Testing results of the dataset.
|
| 116 |
+
|
| 117 |
+
Returns:
|
| 118 |
+
dict[str: float]: Cityscapes evaluation results.
|
| 119 |
+
"""
|
| 120 |
+
logger: MMLogger = MMLogger.get_current_instance()
|
| 121 |
+
if self.format_only:
|
| 122 |
+
logger.info(f'results are saved to {osp.dirname(self.output_dir)}')
|
| 123 |
+
return OrderedDict()
|
| 124 |
+
|
| 125 |
+
msg = 'Evaluating in Cityscapes style'
|
| 126 |
+
if logger is None:
|
| 127 |
+
msg = '\n' + msg
|
| 128 |
+
print_log(msg, logger=logger)
|
| 129 |
+
|
| 130 |
+
eval_results = dict()
|
| 131 |
+
print_log(
|
| 132 |
+
f'Evaluating results under {self.output_dir} ...', logger=logger)
|
| 133 |
+
|
| 134 |
+
CSEval.args.evalInstLevelScore = True
|
| 135 |
+
CSEval.args.predictionPath = osp.abspath(self.output_dir)
|
| 136 |
+
CSEval.args.evalPixelAccuracy = True
|
| 137 |
+
CSEval.args.JSONOutput = False
|
| 138 |
+
|
| 139 |
+
pred_list, gt_list = zip(*results)
|
| 140 |
+
metric = dict()
|
| 141 |
+
eval_results.update(
|
| 142 |
+
CSEval.evaluateImgLists(pred_list, gt_list, CSEval.args))
|
| 143 |
+
metric['averageScoreCategories'] = eval_results[
|
| 144 |
+
'averageScoreCategories']
|
| 145 |
+
metric['averageScoreInstCategories'] = eval_results[
|
| 146 |
+
'averageScoreInstCategories']
|
| 147 |
+
return metric
|
| 148 |
+
|
| 149 |
+
@staticmethod
|
| 150 |
+
def _convert_to_label_id(result):
|
| 151 |
+
"""Convert trainId to id for cityscapes."""
|
| 152 |
+
if isinstance(result, str):
|
| 153 |
+
result = np.load(result)
|
| 154 |
+
result_copy = result.copy()
|
| 155 |
+
for trainId, label in CSLabels.trainId2label.items():
|
| 156 |
+
result_copy[result == trainId] = label.id
|
| 157 |
+
|
| 158 |
+
return result_copy
|
third-party/InterFormer/mmseg/evaluation/metrics/depth_metric.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import os.path as osp
|
| 3 |
+
from collections import OrderedDict, defaultdict
|
| 4 |
+
from typing import Dict, List, Optional, Sequence
|
| 5 |
+
|
| 6 |
+
import cv2
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from mmengine.dist import is_main_process
|
| 10 |
+
from mmengine.evaluator import BaseMetric
|
| 11 |
+
from mmengine.logging import MMLogger, print_log
|
| 12 |
+
from mmengine.utils import mkdir_or_exist
|
| 13 |
+
from prettytable import PrettyTable
|
| 14 |
+
from torch import Tensor
|
| 15 |
+
|
| 16 |
+
from mmseg.registry import METRICS
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@METRICS.register_module()
|
| 20 |
+
class DepthMetric(BaseMetric):
|
| 21 |
+
"""Depth estimation evaluation metric.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
depth_metrics (List[str], optional): List of metrics to compute. If
|
| 25 |
+
not specified, defaults to all metrics in self.METRICS.
|
| 26 |
+
min_depth_eval (float): Minimum depth value for evaluation.
|
| 27 |
+
Defaults to 0.0.
|
| 28 |
+
max_depth_eval (float): Maximum depth value for evaluation.
|
| 29 |
+
Defaults to infinity.
|
| 30 |
+
crop_type (str, optional): Specifies the type of cropping to be used
|
| 31 |
+
during evaluation. This option can affect how the evaluation mask
|
| 32 |
+
is generated. Currently, 'nyu_crop' is supported, but other
|
| 33 |
+
types can be added in future. Defaults to None if no cropping
|
| 34 |
+
should be applied.
|
| 35 |
+
depth_scale_factor (float): Factor to scale the depth values.
|
| 36 |
+
Defaults to 1.0.
|
| 37 |
+
collect_device (str): Device name used for collecting results from
|
| 38 |
+
different ranks during distributed training. Must be 'cpu' or
|
| 39 |
+
'gpu'. Defaults to 'cpu'.
|
| 40 |
+
output_dir (str): The directory for output prediction. Defaults to
|
| 41 |
+
None.
|
| 42 |
+
format_only (bool): Only format result for results commit without
|
| 43 |
+
perform evaluation. It is useful when you want to save the result
|
| 44 |
+
to a specific format and submit it to the test server.
|
| 45 |
+
Defaults to False.
|
| 46 |
+
prefix (str, optional): The prefix that will be added in the metric
|
| 47 |
+
names to disambiguate homonymous metrics of different evaluators.
|
| 48 |
+
If prefix is not provided in the argument, self.default_prefix
|
| 49 |
+
will be used instead. Defaults to None.
|
| 50 |
+
"""
|
| 51 |
+
METRICS = ('d1', 'd2', 'd3', 'abs_rel', 'sq_rel', 'rmse', 'rmse_log',
|
| 52 |
+
'log10', 'silog')
|
| 53 |
+
|
| 54 |
+
def __init__(self,
|
| 55 |
+
depth_metrics: Optional[List[str]] = None,
|
| 56 |
+
min_depth_eval: float = 0.0,
|
| 57 |
+
max_depth_eval: float = float('inf'),
|
| 58 |
+
crop_type: Optional[str] = None,
|
| 59 |
+
depth_scale_factor: float = 1.0,
|
| 60 |
+
collect_device: str = 'cpu',
|
| 61 |
+
output_dir: Optional[str] = None,
|
| 62 |
+
format_only: bool = False,
|
| 63 |
+
prefix: Optional[str] = None,
|
| 64 |
+
**kwargs) -> None:
|
| 65 |
+
super().__init__(collect_device=collect_device, prefix=prefix)
|
| 66 |
+
|
| 67 |
+
if depth_metrics is None:
|
| 68 |
+
self.metrics = self.METRICS
|
| 69 |
+
elif isinstance(depth_metrics, [tuple, list]):
|
| 70 |
+
for metric in depth_metrics:
|
| 71 |
+
assert metric in self.METRICS, f'the metric {metric} is not ' \
|
| 72 |
+
f'supported. Please use metrics in {self.METRICS}'
|
| 73 |
+
self.metrics = depth_metrics
|
| 74 |
+
|
| 75 |
+
# Validate crop_type, if provided
|
| 76 |
+
assert crop_type in [
|
| 77 |
+
None, 'nyu_crop'
|
| 78 |
+
], (f'Invalid value for crop_type: {crop_type}. Supported values are '
|
| 79 |
+
'None or \'nyu_crop\'.')
|
| 80 |
+
self.crop_type = crop_type
|
| 81 |
+
self.min_depth_eval = min_depth_eval
|
| 82 |
+
self.max_depth_eval = max_depth_eval
|
| 83 |
+
self.output_dir = output_dir
|
| 84 |
+
if self.output_dir and is_main_process():
|
| 85 |
+
mkdir_or_exist(self.output_dir)
|
| 86 |
+
self.format_only = format_only
|
| 87 |
+
self.depth_scale_factor = depth_scale_factor
|
| 88 |
+
|
| 89 |
+
def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None:
|
| 90 |
+
"""Process one batch of data and data_samples.
|
| 91 |
+
|
| 92 |
+
The processed results should be stored in ``self.results``, which will
|
| 93 |
+
be used to compute the metrics when all batches have been processed.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
data_batch (dict): A batch of data from the dataloader.
|
| 97 |
+
data_samples (Sequence[dict]): A batch of outputs from the model.
|
| 98 |
+
"""
|
| 99 |
+
for data_sample in data_samples:
|
| 100 |
+
pred_label = data_sample['pred_depth_map']['data'].squeeze()
|
| 101 |
+
# format_only always for test dataset without ground truth
|
| 102 |
+
if not self.format_only:
|
| 103 |
+
gt_depth = data_sample['gt_depth_map']['data'].squeeze().to(
|
| 104 |
+
pred_label)
|
| 105 |
+
|
| 106 |
+
eval_mask = self._get_eval_mask(gt_depth)
|
| 107 |
+
self.results.append(
|
| 108 |
+
(gt_depth[eval_mask], pred_label[eval_mask]))
|
| 109 |
+
# format_result
|
| 110 |
+
if self.output_dir is not None:
|
| 111 |
+
basename = osp.splitext(osp.basename(
|
| 112 |
+
data_sample['img_path']))[0]
|
| 113 |
+
png_filename = osp.abspath(
|
| 114 |
+
osp.join(self.output_dir, f'{basename}.png'))
|
| 115 |
+
output_mask = pred_label.cpu().numpy(
|
| 116 |
+
) * self.depth_scale_factor
|
| 117 |
+
|
| 118 |
+
cv2.imwrite(png_filename, output_mask.astype(np.uint16),
|
| 119 |
+
[cv2.IMWRITE_PNG_COMPRESSION, 0])
|
| 120 |
+
|
| 121 |
+
def _get_eval_mask(self, gt_depth: Tensor):
|
| 122 |
+
"""Generates an evaluation mask based on ground truth depth and
|
| 123 |
+
cropping.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
gt_depth (Tensor): Ground truth depth map.
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
Tensor: Boolean mask where evaluation should be performed.
|
| 130 |
+
"""
|
| 131 |
+
valid_mask = torch.logical_and(gt_depth > self.min_depth_eval,
|
| 132 |
+
gt_depth < self.max_depth_eval)
|
| 133 |
+
|
| 134 |
+
if self.crop_type == 'nyu_crop':
|
| 135 |
+
# this implementation is adapted from
|
| 136 |
+
# https://github.com/zhyever/Monocular-Depth-Estimation-Toolbox/blob/main/depth/datasets/nyu.py # noqa
|
| 137 |
+
crop_mask = torch.zeros_like(valid_mask)
|
| 138 |
+
crop_mask[45:471, 41:601] = 1
|
| 139 |
+
else:
|
| 140 |
+
crop_mask = torch.ones_like(valid_mask)
|
| 141 |
+
|
| 142 |
+
eval_mask = torch.logical_and(valid_mask, crop_mask)
|
| 143 |
+
return eval_mask
|
| 144 |
+
|
| 145 |
+
@staticmethod
|
| 146 |
+
def _calc_all_metrics(gt_depth, pred_depth):
|
| 147 |
+
"""Computes final evaluation metrics based on accumulated results."""
|
| 148 |
+
assert gt_depth.shape == pred_depth.shape
|
| 149 |
+
|
| 150 |
+
thresh = torch.max((gt_depth / pred_depth), (pred_depth / gt_depth))
|
| 151 |
+
diff = pred_depth - gt_depth
|
| 152 |
+
diff_log = torch.log(pred_depth) - torch.log(gt_depth)
|
| 153 |
+
|
| 154 |
+
d1 = torch.sum(thresh < 1.25).float() / len(thresh)
|
| 155 |
+
d2 = torch.sum(thresh < 1.25**2).float() / len(thresh)
|
| 156 |
+
d3 = torch.sum(thresh < 1.25**3).float() / len(thresh)
|
| 157 |
+
|
| 158 |
+
abs_rel = torch.mean(torch.abs(diff) / gt_depth)
|
| 159 |
+
sq_rel = torch.mean(torch.pow(diff, 2) / gt_depth)
|
| 160 |
+
|
| 161 |
+
rmse = torch.sqrt(torch.mean(torch.pow(diff, 2)))
|
| 162 |
+
rmse_log = torch.sqrt(torch.mean(torch.pow(diff_log, 2)))
|
| 163 |
+
|
| 164 |
+
log10 = torch.mean(
|
| 165 |
+
torch.abs(torch.log10(pred_depth) - torch.log10(gt_depth)))
|
| 166 |
+
silog = torch.sqrt(
|
| 167 |
+
torch.pow(diff_log, 2).mean() -
|
| 168 |
+
0.5 * torch.pow(diff_log.mean(), 2))
|
| 169 |
+
|
| 170 |
+
return {
|
| 171 |
+
'd1': d1.item(),
|
| 172 |
+
'd2': d2.item(),
|
| 173 |
+
'd3': d3.item(),
|
| 174 |
+
'abs_rel': abs_rel.item(),
|
| 175 |
+
'sq_rel': sq_rel.item(),
|
| 176 |
+
'rmse': rmse.item(),
|
| 177 |
+
'rmse_log': rmse_log.item(),
|
| 178 |
+
'log10': log10.item(),
|
| 179 |
+
'silog': silog.item()
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
def compute_metrics(self, results: list) -> Dict[str, float]:
|
| 183 |
+
"""Compute the metrics from processed results.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
results (list): The processed results of each batch.
|
| 187 |
+
|
| 188 |
+
Returns:
|
| 189 |
+
Dict[str, float]: The computed metrics. The keys are the names of
|
| 190 |
+
the metrics, and the values are corresponding results. The keys
|
| 191 |
+
are identical with self.metrics.
|
| 192 |
+
"""
|
| 193 |
+
logger: MMLogger = MMLogger.get_current_instance()
|
| 194 |
+
if self.format_only:
|
| 195 |
+
logger.info(f'results are saved to {osp.dirname(self.output_dir)}')
|
| 196 |
+
return OrderedDict()
|
| 197 |
+
|
| 198 |
+
metrics = defaultdict(list)
|
| 199 |
+
for gt_depth, pred_depth in results:
|
| 200 |
+
for key, value in self._calc_all_metrics(gt_depth,
|
| 201 |
+
pred_depth).items():
|
| 202 |
+
metrics[key].append(value)
|
| 203 |
+
metrics = {k: sum(metrics[k]) / len(metrics[k]) for k in self.metrics}
|
| 204 |
+
|
| 205 |
+
table_data = PrettyTable()
|
| 206 |
+
for key, val in metrics.items():
|
| 207 |
+
table_data.add_column(key, [round(val, 5)])
|
| 208 |
+
|
| 209 |
+
print_log('results:', logger)
|
| 210 |
+
print_log('\n' + table_data.get_string(), logger=logger)
|
| 211 |
+
|
| 212 |
+
return metrics
|
third-party/InterFormer/mmseg/evaluation/metrics/iou_metric.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
import os.path as osp
|
| 3 |
+
from collections import OrderedDict
|
| 4 |
+
from typing import Dict, List, Optional, Sequence
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from mmengine.dist import is_main_process
|
| 9 |
+
from mmengine.evaluator import BaseMetric
|
| 10 |
+
from mmengine.logging import MMLogger, print_log
|
| 11 |
+
from mmengine.utils import mkdir_or_exist
|
| 12 |
+
from PIL import Image
|
| 13 |
+
from prettytable import PrettyTable
|
| 14 |
+
|
| 15 |
+
from mmseg.registry import METRICS
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@METRICS.register_module()
|
| 19 |
+
class IoUMetric(BaseMetric):
|
| 20 |
+
"""IoU evaluation metric.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
ignore_index (int): Index that will be ignored in evaluation.
|
| 24 |
+
Default: 255.
|
| 25 |
+
iou_metrics (list[str] | str): Metrics to be calculated, the options
|
| 26 |
+
includes 'mIoU', 'mDice' and 'mFscore'.
|
| 27 |
+
nan_to_num (int, optional): If specified, NaN values will be replaced
|
| 28 |
+
by the numbers defined by the user. Default: None.
|
| 29 |
+
beta (int): Determines the weight of recall in the combined score.
|
| 30 |
+
Default: 1.
|
| 31 |
+
collect_device (str): Device name used for collecting results from
|
| 32 |
+
different ranks during distributed training. Must be 'cpu' or
|
| 33 |
+
'gpu'. Defaults to 'cpu'.
|
| 34 |
+
output_dir (str): The directory for output prediction. Defaults to
|
| 35 |
+
None.
|
| 36 |
+
format_only (bool): Only format result for results commit without
|
| 37 |
+
perform evaluation. It is useful when you want to save the result
|
| 38 |
+
to a specific format and submit it to the test server.
|
| 39 |
+
Defaults to False.
|
| 40 |
+
prefix (str, optional): The prefix that will be added in the metric
|
| 41 |
+
names to disambiguate homonymous metrics of different evaluators.
|
| 42 |
+
If prefix is not provided in the argument, self.default_prefix
|
| 43 |
+
will be used instead. Defaults to None.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self,
|
| 47 |
+
ignore_index: int = 255,
|
| 48 |
+
iou_metrics: List[str] = ['mIoU'],
|
| 49 |
+
nan_to_num: Optional[int] = None,
|
| 50 |
+
beta: int = 1,
|
| 51 |
+
collect_device: str = 'cpu',
|
| 52 |
+
output_dir: Optional[str] = None,
|
| 53 |
+
format_only: bool = False,
|
| 54 |
+
prefix: Optional[str] = None,
|
| 55 |
+
**kwargs) -> None:
|
| 56 |
+
super().__init__(collect_device=collect_device, prefix=prefix)
|
| 57 |
+
|
| 58 |
+
self.ignore_index = ignore_index
|
| 59 |
+
self.metrics = iou_metrics
|
| 60 |
+
self.nan_to_num = nan_to_num
|
| 61 |
+
self.beta = beta
|
| 62 |
+
self.output_dir = output_dir
|
| 63 |
+
if self.output_dir and is_main_process():
|
| 64 |
+
mkdir_or_exist(self.output_dir)
|
| 65 |
+
self.format_only = format_only
|
| 66 |
+
|
| 67 |
+
def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None:
|
| 68 |
+
"""Process one batch of data and data_samples.
|
| 69 |
+
|
| 70 |
+
The processed results should be stored in ``self.results``, which will
|
| 71 |
+
be used to compute the metrics when all batches have been processed.
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
data_batch (dict): A batch of data from the dataloader.
|
| 75 |
+
data_samples (Sequence[dict]): A batch of outputs from the model.
|
| 76 |
+
"""
|
| 77 |
+
num_classes = len(self.dataset_meta['classes'])
|
| 78 |
+
for data_sample in data_samples:
|
| 79 |
+
pred_label = data_sample['pred_sem_seg']['data'].squeeze()
|
| 80 |
+
# format_only always for test dataset without ground truth
|
| 81 |
+
if not self.format_only:
|
| 82 |
+
label = data_sample['gt_sem_seg']['data'].squeeze().to(
|
| 83 |
+
pred_label)
|
| 84 |
+
self.results.append(
|
| 85 |
+
self.intersect_and_union(pred_label, label, num_classes,
|
| 86 |
+
self.ignore_index))
|
| 87 |
+
# format_result
|
| 88 |
+
if self.output_dir is not None:
|
| 89 |
+
basename = osp.splitext(osp.basename(
|
| 90 |
+
data_sample['img_path']))[0]
|
| 91 |
+
png_filename = osp.abspath(
|
| 92 |
+
osp.join(self.output_dir, f'{basename}.png'))
|
| 93 |
+
output_mask = pred_label.cpu().numpy()
|
| 94 |
+
# The index range of official ADE20k dataset is from 0 to 150.
|
| 95 |
+
# But the index range of output is from 0 to 149.
|
| 96 |
+
# That is because we set reduce_zero_label=True.
|
| 97 |
+
if data_sample.get('reduce_zero_label', False):
|
| 98 |
+
output_mask = output_mask + 1
|
| 99 |
+
output = Image.fromarray(output_mask.astype(np.uint8))
|
| 100 |
+
output.save(png_filename)
|
| 101 |
+
|
| 102 |
+
def compute_metrics(self, results: list) -> Dict[str, float]:
|
| 103 |
+
"""Compute the metrics from processed results.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
results (list): The processed results of each batch.
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
Dict[str, float]: The computed metrics. The keys are the names of
|
| 110 |
+
the metrics, and the values are corresponding results. The key
|
| 111 |
+
mainly includes aAcc, mIoU, mAcc, mDice, mFscore, mPrecision,
|
| 112 |
+
mRecall.
|
| 113 |
+
"""
|
| 114 |
+
logger: MMLogger = MMLogger.get_current_instance()
|
| 115 |
+
if self.format_only:
|
| 116 |
+
logger.info(f'results are saved to {osp.dirname(self.output_dir)}')
|
| 117 |
+
return OrderedDict()
|
| 118 |
+
# convert list of tuples to tuple of lists, e.g.
|
| 119 |
+
# [(A_1, B_1, C_1, D_1), ..., (A_n, B_n, C_n, D_n)] to
|
| 120 |
+
# ([A_1, ..., A_n], ..., [D_1, ..., D_n])
|
| 121 |
+
results = tuple(zip(*results))
|
| 122 |
+
assert len(results) == 4
|
| 123 |
+
|
| 124 |
+
total_area_intersect = sum(results[0])
|
| 125 |
+
total_area_union = sum(results[1])
|
| 126 |
+
total_area_pred_label = sum(results[2])
|
| 127 |
+
total_area_label = sum(results[3])
|
| 128 |
+
ret_metrics = self.total_area_to_metrics(
|
| 129 |
+
total_area_intersect, total_area_union, total_area_pred_label,
|
| 130 |
+
total_area_label, self.metrics, self.nan_to_num, self.beta)
|
| 131 |
+
|
| 132 |
+
class_names = self.dataset_meta['classes']
|
| 133 |
+
|
| 134 |
+
# summary table
|
| 135 |
+
ret_metrics_summary = OrderedDict({
|
| 136 |
+
ret_metric: np.round(np.nanmean(ret_metric_value) * 100, 2)
|
| 137 |
+
for ret_metric, ret_metric_value in ret_metrics.items()
|
| 138 |
+
})
|
| 139 |
+
metrics = dict()
|
| 140 |
+
for key, val in ret_metrics_summary.items():
|
| 141 |
+
if key == 'aAcc':
|
| 142 |
+
metrics[key] = val
|
| 143 |
+
else:
|
| 144 |
+
metrics['m' + key] = val
|
| 145 |
+
|
| 146 |
+
# each class table
|
| 147 |
+
ret_metrics.pop('aAcc', None)
|
| 148 |
+
ret_metrics_class = OrderedDict({
|
| 149 |
+
ret_metric: np.round(ret_metric_value * 100, 2)
|
| 150 |
+
for ret_metric, ret_metric_value in ret_metrics.items()
|
| 151 |
+
})
|
| 152 |
+
ret_metrics_class.update({'Class': class_names})
|
| 153 |
+
ret_metrics_class.move_to_end('Class', last=False)
|
| 154 |
+
class_table_data = PrettyTable()
|
| 155 |
+
for key, val in ret_metrics_class.items():
|
| 156 |
+
class_table_data.add_column(key, val)
|
| 157 |
+
|
| 158 |
+
print_log('per class results:', logger)
|
| 159 |
+
print_log('\n' + class_table_data.get_string(), logger=logger)
|
| 160 |
+
|
| 161 |
+
return metrics
|
| 162 |
+
|
| 163 |
+
@staticmethod
|
| 164 |
+
def intersect_and_union(pred_label: torch.tensor, label: torch.tensor,
|
| 165 |
+
num_classes: int, ignore_index: int):
|
| 166 |
+
"""Calculate Intersection and Union.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
pred_label (torch.tensor): Prediction segmentation map
|
| 170 |
+
or predict result filename. The shape is (H, W).
|
| 171 |
+
label (torch.tensor): Ground truth segmentation map
|
| 172 |
+
or label filename. The shape is (H, W).
|
| 173 |
+
num_classes (int): Number of categories.
|
| 174 |
+
ignore_index (int): Index that will be ignored in evaluation.
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
torch.Tensor: The intersection of prediction and ground truth
|
| 178 |
+
histogram on all classes.
|
| 179 |
+
torch.Tensor: The union of prediction and ground truth histogram on
|
| 180 |
+
all classes.
|
| 181 |
+
torch.Tensor: The prediction histogram on all classes.
|
| 182 |
+
torch.Tensor: The ground truth histogram on all classes.
|
| 183 |
+
"""
|
| 184 |
+
|
| 185 |
+
mask = (label != ignore_index)
|
| 186 |
+
pred_label = pred_label[mask]
|
| 187 |
+
label = label[mask]
|
| 188 |
+
|
| 189 |
+
intersect = pred_label[pred_label == label]
|
| 190 |
+
area_intersect = torch.histc(
|
| 191 |
+
intersect.float(), bins=(num_classes), min=0,
|
| 192 |
+
max=num_classes - 1).cpu()
|
| 193 |
+
area_pred_label = torch.histc(
|
| 194 |
+
pred_label.float(), bins=(num_classes), min=0,
|
| 195 |
+
max=num_classes - 1).cpu()
|
| 196 |
+
area_label = torch.histc(
|
| 197 |
+
label.float(), bins=(num_classes), min=0,
|
| 198 |
+
max=num_classes - 1).cpu()
|
| 199 |
+
area_union = area_pred_label + area_label - area_intersect
|
| 200 |
+
return area_intersect, area_union, area_pred_label, area_label
|
| 201 |
+
|
| 202 |
+
@staticmethod
|
| 203 |
+
def total_area_to_metrics(total_area_intersect: np.ndarray,
|
| 204 |
+
total_area_union: np.ndarray,
|
| 205 |
+
total_area_pred_label: np.ndarray,
|
| 206 |
+
total_area_label: np.ndarray,
|
| 207 |
+
metrics: List[str] = ['mIoU'],
|
| 208 |
+
nan_to_num: Optional[int] = None,
|
| 209 |
+
beta: int = 1):
|
| 210 |
+
"""Calculate evaluation metrics
|
| 211 |
+
Args:
|
| 212 |
+
total_area_intersect (np.ndarray): The intersection of prediction
|
| 213 |
+
and ground truth histogram on all classes.
|
| 214 |
+
total_area_union (np.ndarray): The union of prediction and ground
|
| 215 |
+
truth histogram on all classes.
|
| 216 |
+
total_area_pred_label (np.ndarray): The prediction histogram on
|
| 217 |
+
all classes.
|
| 218 |
+
total_area_label (np.ndarray): The ground truth histogram on
|
| 219 |
+
all classes.
|
| 220 |
+
metrics (List[str] | str): Metrics to be evaluated, 'mIoU' and
|
| 221 |
+
'mDice'.
|
| 222 |
+
nan_to_num (int, optional): If specified, NaN values will be
|
| 223 |
+
replaced by the numbers defined by the user. Default: None.
|
| 224 |
+
beta (int): Determines the weight of recall in the combined score.
|
| 225 |
+
Default: 1.
|
| 226 |
+
Returns:
|
| 227 |
+
Dict[str, np.ndarray]: per category evaluation metrics,
|
| 228 |
+
shape (num_classes, ).
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
def f_score(precision, recall, beta=1):
|
| 232 |
+
"""calculate the f-score value.
|
| 233 |
+
|
| 234 |
+
Args:
|
| 235 |
+
precision (float | torch.Tensor): The precision value.
|
| 236 |
+
recall (float | torch.Tensor): The recall value.
|
| 237 |
+
beta (int): Determines the weight of recall in the combined
|
| 238 |
+
score. Default: 1.
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
[torch.tensor]: The f-score value.
|
| 242 |
+
"""
|
| 243 |
+
score = (1 + beta**2) * (precision * recall) / (
|
| 244 |
+
(beta**2 * precision) + recall)
|
| 245 |
+
return score
|
| 246 |
+
|
| 247 |
+
if isinstance(metrics, str):
|
| 248 |
+
metrics = [metrics]
|
| 249 |
+
allowed_metrics = ['mIoU', 'mDice', 'mFscore']
|
| 250 |
+
if not set(metrics).issubset(set(allowed_metrics)):
|
| 251 |
+
raise KeyError(f'metrics {metrics} is not supported')
|
| 252 |
+
|
| 253 |
+
all_acc = total_area_intersect.sum() / total_area_label.sum()
|
| 254 |
+
ret_metrics = OrderedDict({'aAcc': all_acc})
|
| 255 |
+
for metric in metrics:
|
| 256 |
+
if metric == 'mIoU':
|
| 257 |
+
iou = total_area_intersect / total_area_union
|
| 258 |
+
acc = total_area_intersect / total_area_label
|
| 259 |
+
ret_metrics['IoU'] = iou
|
| 260 |
+
ret_metrics['Acc'] = acc
|
| 261 |
+
elif metric == 'mDice':
|
| 262 |
+
dice = 2 * total_area_intersect / (
|
| 263 |
+
total_area_pred_label + total_area_label)
|
| 264 |
+
acc = total_area_intersect / total_area_label
|
| 265 |
+
ret_metrics['Dice'] = dice
|
| 266 |
+
ret_metrics['Acc'] = acc
|
| 267 |
+
elif metric == 'mFscore':
|
| 268 |
+
precision = total_area_intersect / total_area_pred_label
|
| 269 |
+
recall = total_area_intersect / total_area_label
|
| 270 |
+
f_value = torch.tensor([
|
| 271 |
+
f_score(x[0], x[1], beta) for x in zip(precision, recall)
|
| 272 |
+
])
|
| 273 |
+
ret_metrics['Fscore'] = f_value
|
| 274 |
+
ret_metrics['Precision'] = precision
|
| 275 |
+
ret_metrics['Recall'] = recall
|
| 276 |
+
|
| 277 |
+
ret_metrics = {
|
| 278 |
+
metric: value.numpy()
|
| 279 |
+
for metric, value in ret_metrics.items()
|
| 280 |
+
}
|
| 281 |
+
if nan_to_num is not None:
|
| 282 |
+
ret_metrics = OrderedDict({
|
| 283 |
+
metric: np.nan_to_num(metric_value, nan=nan_to_num)
|
| 284 |
+
for metric, metric_value in ret_metrics.items()
|
| 285 |
+
})
|
| 286 |
+
return ret_metrics
|
third-party/InterFormer/mmseg/models/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .assigners import * # noqa: F401,F403
|
| 3 |
+
from .backbones import * # noqa: F401,F403
|
| 4 |
+
from .builder import (BACKBONES, HEADS, LOSSES, SEGMENTORS, build_backbone,
|
| 5 |
+
build_head, build_loss, build_segmentor)
|
| 6 |
+
from .data_preprocessor import SegDataPreProcessor
|
| 7 |
+
from .decode_heads import * # noqa: F401,F403
|
| 8 |
+
from .losses import * # noqa: F401,F403
|
| 9 |
+
from .necks import * # noqa: F401,F403
|
| 10 |
+
from .segmentors import * # noqa: F401,F403
|
| 11 |
+
from .text_encoder import * # noqa: F401,F403
|
| 12 |
+
|
| 13 |
+
__all__ = [
|
| 14 |
+
'BACKBONES', 'HEADS', 'LOSSES', 'SEGMENTORS', 'build_backbone',
|
| 15 |
+
'build_head', 'build_loss', 'build_segmentor', 'SegDataPreProcessor'
|
| 16 |
+
]
|
third-party/InterFormer/mmseg/models/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (661 Bytes). View file
|
|
|
third-party/InterFormer/mmseg/models/__pycache__/builder.cpython-38.pyc
ADDED
|
Binary file (1.85 kB). View file
|
|
|
third-party/InterFormer/mmseg/models/__pycache__/data_preprocessor.cpython-38.pyc
ADDED
|
Binary file (5.59 kB). View file
|
|
|
third-party/InterFormer/mmseg/models/assigners/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .base_assigner import BaseAssigner
|
| 3 |
+
from .hungarian_assigner import HungarianAssigner
|
| 4 |
+
from .match_cost import ClassificationCost, CrossEntropyLossCost, DiceCost
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
'BaseAssigner',
|
| 8 |
+
'HungarianAssigner',
|
| 9 |
+
'ClassificationCost',
|
| 10 |
+
'CrossEntropyLossCost',
|
| 11 |
+
'DiceCost',
|
| 12 |
+
]
|
third-party/InterFormer/mmseg/models/assigners/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (447 Bytes). View file
|
|
|
third-party/InterFormer/mmseg/models/assigners/__pycache__/base_assigner.cpython-38.pyc
ADDED
|
Binary file (913 Bytes). View file
|
|
|
third-party/InterFormer/mmseg/models/assigners/__pycache__/hungarian_assigner.cpython-38.pyc
ADDED
|
Binary file (3.43 kB). View file
|
|
|
third-party/InterFormer/mmseg/models/assigners/__pycache__/match_cost.cpython-38.pyc
ADDED
|
Binary file (8.2 kB). View file
|
|
|
third-party/InterFormer/mmseg/models/assigners/base_assigner.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from abc import ABCMeta, abstractmethod
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from mmengine.structures import InstanceData
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class BaseAssigner(metaclass=ABCMeta):
|
| 9 |
+
"""Base assigner that assigns masks to ground truth class labels."""
|
| 10 |
+
|
| 11 |
+
@abstractmethod
|
| 12 |
+
def assign(self,
|
| 13 |
+
pred_instances: InstanceData,
|
| 14 |
+
gt_instances: InstanceData,
|
| 15 |
+
gt_instances_ignore: Optional[InstanceData] = None,
|
| 16 |
+
**kwargs):
|
| 17 |
+
"""Assign masks to either a ground truth class label or a negative
|
| 18 |
+
label."""
|
third-party/InterFormer/mmseg/models/assigners/hungarian_assigner.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from typing import List, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from mmengine import ConfigDict
|
| 6 |
+
from mmengine.structures import InstanceData
|
| 7 |
+
from scipy.optimize import linear_sum_assignment
|
| 8 |
+
from torch.cuda.amp import autocast
|
| 9 |
+
|
| 10 |
+
from mmseg.registry import TASK_UTILS
|
| 11 |
+
from .base_assigner import BaseAssigner
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@TASK_UTILS.register_module()
|
| 15 |
+
class HungarianAssigner(BaseAssigner):
|
| 16 |
+
"""Computes one-to-one matching between prediction masks and ground truth.
|
| 17 |
+
|
| 18 |
+
This class uses bipartite matching-based assignment to computes an
|
| 19 |
+
assignment between the prediction masks and the ground truth. The
|
| 20 |
+
assignment result is based on the weighted sum of match costs. The
|
| 21 |
+
Hungarian algorithm is used to calculate the best matching with the
|
| 22 |
+
minimum cost. The prediction masks that are not matched are classified
|
| 23 |
+
as background.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
match_costs (ConfigDict|List[ConfigDict]): Match cost configs.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(
|
| 30 |
+
self, match_costs: Union[List[Union[dict, ConfigDict]], dict,
|
| 31 |
+
ConfigDict]
|
| 32 |
+
) -> None:
|
| 33 |
+
|
| 34 |
+
if isinstance(match_costs, dict):
|
| 35 |
+
match_costs = [match_costs]
|
| 36 |
+
elif isinstance(match_costs, list):
|
| 37 |
+
assert len(match_costs) > 0, \
|
| 38 |
+
'match_costs must not be a empty list.'
|
| 39 |
+
|
| 40 |
+
self.match_costs = [
|
| 41 |
+
TASK_UTILS.build(match_cost) for match_cost in match_costs
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
def assign(self, pred_instances: InstanceData, gt_instances: InstanceData,
|
| 45 |
+
**kwargs):
|
| 46 |
+
"""Computes one-to-one matching based on the weighted costs.
|
| 47 |
+
|
| 48 |
+
This method assign each query prediction to a ground truth or
|
| 49 |
+
background. The assignment first calculates the cost for each
|
| 50 |
+
category assigned to each query mask, and then uses the
|
| 51 |
+
Hungarian algorithm to calculate the minimum cost as the best
|
| 52 |
+
match.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
pred_instances (InstanceData): Instances of model
|
| 56 |
+
predictions. It includes "masks", with shape
|
| 57 |
+
(n, h, w) or (n, l), and "cls", with shape (n, num_classes+1)
|
| 58 |
+
gt_instances (InstanceData): Ground truth of instance
|
| 59 |
+
annotations. It includes "labels", with shape (k, ),
|
| 60 |
+
and "masks", with shape (k, h, w) or (k, l).
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
matched_quiery_inds (Tensor): The indexes of matched quieres.
|
| 64 |
+
matched_label_inds (Tensor): The indexes of matched labels.
|
| 65 |
+
"""
|
| 66 |
+
# compute weighted cost
|
| 67 |
+
cost_list = []
|
| 68 |
+
with autocast(enabled=False):
|
| 69 |
+
for match_cost in self.match_costs:
|
| 70 |
+
cost = match_cost(
|
| 71 |
+
pred_instances=pred_instances, gt_instances=gt_instances)
|
| 72 |
+
cost_list.append(cost)
|
| 73 |
+
cost = torch.stack(cost_list).sum(dim=0)
|
| 74 |
+
|
| 75 |
+
device = cost.device
|
| 76 |
+
# do Hungarian matching on CPU using linear_sum_assignment
|
| 77 |
+
cost = cost.detach().cpu()
|
| 78 |
+
if linear_sum_assignment is None:
|
| 79 |
+
raise ImportError('Please run "pip install scipy" '
|
| 80 |
+
'to install scipy first.')
|
| 81 |
+
|
| 82 |
+
matched_quiery_inds, matched_label_inds = linear_sum_assignment(cost)
|
| 83 |
+
matched_quiery_inds = torch.from_numpy(matched_quiery_inds).to(device)
|
| 84 |
+
matched_label_inds = torch.from_numpy(matched_label_inds).to(device)
|
| 85 |
+
|
| 86 |
+
return matched_quiery_inds, matched_label_inds
|
third-party/InterFormer/mmseg/models/assigners/match_cost.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from abc import abstractmethod
|
| 3 |
+
from typing import Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from mmengine.structures import InstanceData
|
| 8 |
+
from torch import Tensor
|
| 9 |
+
|
| 10 |
+
from mmseg.registry import TASK_UTILS
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class BaseMatchCost:
|
| 14 |
+
"""Base match cost class.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
weight (Union[float, int]): Cost weight. Defaults to 1.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self, weight: Union[float, int] = 1.) -> None:
|
| 21 |
+
self.weight = weight
|
| 22 |
+
|
| 23 |
+
@abstractmethod
|
| 24 |
+
def __call__(self, pred_instances: InstanceData,
|
| 25 |
+
gt_instances: InstanceData, **kwargs) -> Tensor:
|
| 26 |
+
"""Compute match cost.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
pred_instances (InstanceData): Instances of model predictions.
|
| 30 |
+
It often includes "labels" and "scores".
|
| 31 |
+
gt_instances (InstanceData): Ground truth of instance
|
| 32 |
+
annotations. It usually includes "labels".
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
Tensor: Match Cost matrix of shape (num_preds, num_gts).
|
| 36 |
+
"""
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@TASK_UTILS.register_module()
|
| 41 |
+
class ClassificationCost(BaseMatchCost):
|
| 42 |
+
"""ClsSoftmaxCost.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
weight (Union[float, int]): Cost weight. Defaults to 1.
|
| 46 |
+
|
| 47 |
+
Examples:
|
| 48 |
+
>>> from mmseg.models.assigners import ClassificationCost
|
| 49 |
+
>>> import torch
|
| 50 |
+
>>> self = ClassificationCost()
|
| 51 |
+
>>> cls_pred = torch.rand(4, 3)
|
| 52 |
+
>>> gt_labels = torch.tensor([0, 1, 2])
|
| 53 |
+
>>> factor = torch.tensor([10, 8, 10, 8])
|
| 54 |
+
>>> self(cls_pred, gt_labels)
|
| 55 |
+
tensor([[-0.3430, -0.3525, -0.3045],
|
| 56 |
+
[-0.3077, -0.2931, -0.3992],
|
| 57 |
+
[-0.3664, -0.3455, -0.2881],
|
| 58 |
+
[-0.3343, -0.2701, -0.3956]])
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def __init__(self, weight: Union[float, int] = 1) -> None:
|
| 62 |
+
super().__init__(weight=weight)
|
| 63 |
+
|
| 64 |
+
def __call__(self, pred_instances: InstanceData,
|
| 65 |
+
gt_instances: InstanceData, **kwargs) -> Tensor:
|
| 66 |
+
"""Compute match cost.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
pred_instances (InstanceData): "scores" inside is
|
| 70 |
+
predicted classification logits, of shape
|
| 71 |
+
(num_queries, num_class).
|
| 72 |
+
gt_instances (InstanceData): "labels" inside should have
|
| 73 |
+
shape (num_gt, ).
|
| 74 |
+
|
| 75 |
+
Returns:
|
| 76 |
+
Tensor: Match Cost matrix of shape (num_preds, num_gts).
|
| 77 |
+
"""
|
| 78 |
+
assert hasattr(pred_instances, 'scores'), \
|
| 79 |
+
"pred_instances must contain 'scores'"
|
| 80 |
+
assert hasattr(gt_instances, 'labels'), \
|
| 81 |
+
"gt_instances must contain 'labels'"
|
| 82 |
+
pred_scores = pred_instances.scores
|
| 83 |
+
gt_labels = gt_instances.labels
|
| 84 |
+
|
| 85 |
+
pred_scores = pred_scores.softmax(-1)
|
| 86 |
+
cls_cost = -pred_scores[:, gt_labels]
|
| 87 |
+
|
| 88 |
+
return cls_cost * self.weight
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@TASK_UTILS.register_module()
|
| 92 |
+
class DiceCost(BaseMatchCost):
|
| 93 |
+
"""Cost of mask assignments based on dice losses.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
pred_act (bool): Whether to apply sigmoid to mask_pred.
|
| 97 |
+
Defaults to False.
|
| 98 |
+
eps (float): Defaults to 1e-3.
|
| 99 |
+
naive_dice (bool): If True, use the naive dice loss
|
| 100 |
+
in which the power of the number in the denominator is
|
| 101 |
+
the first power. If False, use the second power that
|
| 102 |
+
is adopted by K-Net and SOLO. Defaults to True.
|
| 103 |
+
weight (Union[float, int]): Cost weight. Defaults to 1.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def __init__(self,
|
| 107 |
+
pred_act: bool = False,
|
| 108 |
+
eps: float = 1e-3,
|
| 109 |
+
naive_dice: bool = True,
|
| 110 |
+
weight: Union[float, int] = 1.) -> None:
|
| 111 |
+
super().__init__(weight=weight)
|
| 112 |
+
self.pred_act = pred_act
|
| 113 |
+
self.eps = eps
|
| 114 |
+
self.naive_dice = naive_dice
|
| 115 |
+
|
| 116 |
+
def _binary_mask_dice_loss(self, mask_preds: Tensor,
|
| 117 |
+
gt_masks: Tensor) -> Tensor:
|
| 118 |
+
"""
|
| 119 |
+
Args:
|
| 120 |
+
mask_preds (Tensor): Mask prediction in shape (num_queries, *).
|
| 121 |
+
gt_masks (Tensor): Ground truth in shape (num_gt, *)
|
| 122 |
+
store 0 or 1, 0 for negative class and 1 for
|
| 123 |
+
positive class.
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
Tensor: Dice cost matrix in shape (num_queries, num_gt).
|
| 127 |
+
"""
|
| 128 |
+
mask_preds = mask_preds.flatten(1)
|
| 129 |
+
gt_masks = gt_masks.flatten(1).float()
|
| 130 |
+
numerator = 2 * torch.einsum('nc,mc->nm', mask_preds, gt_masks)
|
| 131 |
+
if self.naive_dice:
|
| 132 |
+
denominator = mask_preds.sum(-1)[:, None] + \
|
| 133 |
+
gt_masks.sum(-1)[None, :]
|
| 134 |
+
else:
|
| 135 |
+
denominator = mask_preds.pow(2).sum(1)[:, None] + \
|
| 136 |
+
gt_masks.pow(2).sum(1)[None, :]
|
| 137 |
+
loss = 1 - (numerator + self.eps) / (denominator + self.eps)
|
| 138 |
+
return loss
|
| 139 |
+
|
| 140 |
+
def __call__(self, pred_instances: InstanceData,
|
| 141 |
+
gt_instances: InstanceData, **kwargs) -> Tensor:
|
| 142 |
+
"""Compute match cost.
|
| 143 |
+
|
| 144 |
+
Args:
|
| 145 |
+
pred_instances (InstanceData): Predicted instances which
|
| 146 |
+
must contain "masks".
|
| 147 |
+
gt_instances (InstanceData): Ground truth which must contain
|
| 148 |
+
"mask".
|
| 149 |
+
|
| 150 |
+
Returns:
|
| 151 |
+
Tensor: Match Cost matrix of shape (num_preds, num_gts).
|
| 152 |
+
"""
|
| 153 |
+
assert hasattr(pred_instances, 'masks'), \
|
| 154 |
+
"pred_instances must contain 'masks'"
|
| 155 |
+
assert hasattr(gt_instances, 'masks'), \
|
| 156 |
+
"gt_instances must contain 'masks'"
|
| 157 |
+
pred_masks = pred_instances.masks
|
| 158 |
+
gt_masks = gt_instances.masks
|
| 159 |
+
|
| 160 |
+
if self.pred_act:
|
| 161 |
+
pred_masks = pred_masks.sigmoid()
|
| 162 |
+
dice_cost = self._binary_mask_dice_loss(pred_masks, gt_masks)
|
| 163 |
+
return dice_cost * self.weight
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@TASK_UTILS.register_module()
|
| 167 |
+
class CrossEntropyLossCost(BaseMatchCost):
|
| 168 |
+
"""CrossEntropyLossCost.
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
use_sigmoid (bool): Whether the prediction uses sigmoid
|
| 172 |
+
of softmax. Defaults to True.
|
| 173 |
+
weight (Union[float, int]): Cost weight. Defaults to 1.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
def __init__(self,
|
| 177 |
+
use_sigmoid: bool = True,
|
| 178 |
+
weight: Union[float, int] = 1.) -> None:
|
| 179 |
+
super().__init__(weight=weight)
|
| 180 |
+
self.use_sigmoid = use_sigmoid
|
| 181 |
+
|
| 182 |
+
def _binary_cross_entropy(self, cls_pred: Tensor,
|
| 183 |
+
gt_labels: Tensor) -> Tensor:
|
| 184 |
+
"""
|
| 185 |
+
Args:
|
| 186 |
+
cls_pred (Tensor): The prediction with shape (num_queries, 1, *) or
|
| 187 |
+
(num_queries, *).
|
| 188 |
+
gt_labels (Tensor): The learning label of prediction with
|
| 189 |
+
shape (num_gt, *).
|
| 190 |
+
|
| 191 |
+
Returns:
|
| 192 |
+
Tensor: Cross entropy cost matrix in shape (num_queries, num_gt).
|
| 193 |
+
"""
|
| 194 |
+
cls_pred = cls_pred.flatten(1).float()
|
| 195 |
+
gt_labels = gt_labels.flatten(1).float()
|
| 196 |
+
n = cls_pred.shape[1]
|
| 197 |
+
pos = F.binary_cross_entropy_with_logits(
|
| 198 |
+
cls_pred, torch.ones_like(cls_pred), reduction='none')
|
| 199 |
+
neg = F.binary_cross_entropy_with_logits(
|
| 200 |
+
cls_pred, torch.zeros_like(cls_pred), reduction='none')
|
| 201 |
+
cls_cost = torch.einsum('nc,mc->nm', pos, gt_labels) + \
|
| 202 |
+
torch.einsum('nc,mc->nm', neg, 1 - gt_labels)
|
| 203 |
+
cls_cost = cls_cost / n
|
| 204 |
+
|
| 205 |
+
return cls_cost
|
| 206 |
+
|
| 207 |
+
def __call__(self, pred_instances: InstanceData,
|
| 208 |
+
gt_instances: InstanceData, **kwargs) -> Tensor:
|
| 209 |
+
"""Compute match cost.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
pred_instances (:obj:`InstanceData`): Predicted instances which
|
| 213 |
+
must contain ``masks``.
|
| 214 |
+
gt_instances (:obj:`InstanceData`): Ground truth which must contain
|
| 215 |
+
``masks``.
|
| 216 |
+
|
| 217 |
+
Returns:
|
| 218 |
+
Tensor: Match Cost matrix of shape (num_preds, num_gts).
|
| 219 |
+
"""
|
| 220 |
+
assert hasattr(pred_instances, 'masks'), \
|
| 221 |
+
"pred_instances must contain 'masks'"
|
| 222 |
+
assert hasattr(gt_instances, 'masks'), \
|
| 223 |
+
"gt_instances must contain 'masks'"
|
| 224 |
+
pred_masks = pred_instances.masks
|
| 225 |
+
gt_masks = gt_instances.masks
|
| 226 |
+
if self.use_sigmoid:
|
| 227 |
+
cls_cost = self._binary_cross_entropy(pred_masks, gt_masks)
|
| 228 |
+
else:
|
| 229 |
+
raise NotImplementedError
|
| 230 |
+
|
| 231 |
+
return cls_cost * self.weight
|
third-party/InterFormer/mmseg/models/backbones/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
| 2 |
+
from .beit import BEiT
|
| 3 |
+
from .bisenetv1 import BiSeNetV1
|
| 4 |
+
from .bisenetv2 import BiSeNetV2
|
| 5 |
+
from .cgnet import CGNet
|
| 6 |
+
from .ddrnet import DDRNet
|
| 7 |
+
from .erfnet import ERFNet
|
| 8 |
+
from .fast_scnn import FastSCNN
|
| 9 |
+
from .hrnet import HRNet
|
| 10 |
+
from .icnet import ICNet
|
| 11 |
+
from .mae import MAE
|
| 12 |
+
from .mit import MixVisionTransformer
|
| 13 |
+
from .mobilenet_v2 import MobileNetV2
|
| 14 |
+
from .mobilenet_v3 import MobileNetV3
|
| 15 |
+
from .mscan import MSCAN
|
| 16 |
+
from .pidnet import PIDNet
|
| 17 |
+
from .resnest import ResNeSt
|
| 18 |
+
from .resnet import ResNet, ResNetV1c, ResNetV1d
|
| 19 |
+
from .resnext import ResNeXt
|
| 20 |
+
from .stdc import STDCContextPathNet, STDCNet
|
| 21 |
+
from .swin import SwinTransformer
|
| 22 |
+
from .timm_backbone import TIMMBackbone
|
| 23 |
+
from .twins import PCPVT, SVT
|
| 24 |
+
from .unet import UNet
|
| 25 |
+
from .vit import VisionTransformer
|
| 26 |
+
from .vpd import VPD
|
| 27 |
+
|
| 28 |
+
__all__ = [
|
| 29 |
+
'ResNet', 'ResNetV1c', 'ResNetV1d', 'ResNeXt', 'HRNet', 'FastSCNN',
|
| 30 |
+
'ResNeSt', 'MobileNetV2', 'UNet', 'CGNet', 'MobileNetV3',
|
| 31 |
+
'VisionTransformer', 'SwinTransformer', 'MixVisionTransformer',
|
| 32 |
+
'BiSeNetV1', 'BiSeNetV2', 'ICNet', 'TIMMBackbone', 'ERFNet', 'PCPVT',
|
| 33 |
+
'SVT', 'STDCNet', 'STDCContextPathNet', 'BEiT', 'MAE', 'PIDNet', 'MSCAN',
|
| 34 |
+
'DDRNet', 'VPD'
|
| 35 |
+
]
|
third-party/InterFormer/mmseg/models/backbones/__pycache__/__init__.cpython-38.pyc
ADDED
|
Binary file (1.51 kB). View file
|
|
|