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
Files changed (50)
- third-party/InterFormer/mmseg.yamlAdded+257
- third-party/InterFormer/mmseg/datasets/transforms/__init__.pyAdded+30
- third-party/InterFormer/mmseg/datasets/transforms/__pycache__/__init__.cpython-38.pycAdded
- third-party/InterFormer/mmseg/datasets/transforms/__pycache__/formatting.cpython-38.pycAdded
- third-party/InterFormer/mmseg/datasets/transforms/__pycache__/loading.cpython-38.pycAdded
- third-party/InterFormer/mmseg/datasets/transforms/__pycache__/transforms.cpython-38.pycAdded
- third-party/InterFormer/mmseg/datasets/transforms/formatting.pyAdded+112
- third-party/InterFormer/mmseg/datasets/transforms/loading.pyAdded+771
- third-party/InterFormer/mmseg/datasets/transforms/transforms.pyAdded+2537
- third-party/InterFormer/mmseg/datasets/voc.pyAdded+40
- third-party/InterFormer/mmseg/engine/__init__.pyAdded+12
- third-party/InterFormer/mmseg/engine/__pycache__/__init__.cpython-38.pycAdded
- third-party/InterFormer/mmseg/engine/hooks/__init__.pyAdded+4
- third-party/InterFormer/mmseg/engine/hooks/__pycache__/__init__.cpython-38.pycAdded
- third-party/InterFormer/mmseg/engine/hooks/__pycache__/visualization_hook.cpython-38.pycAdded
- third-party/InterFormer/mmseg/engine/hooks/visualization_hook.pyAdded+129
- third-party/InterFormer/mmseg/engine/optimizers/__init__.pyAdded+9
- third-party/InterFormer/mmseg/engine/optimizers/__pycache__/__init__.cpython-38.pycAdded
- third-party/InterFormer/mmseg/engine/optimizers/__pycache__/force_default_constructor.cpython-38.pycAdded
- third-party/InterFormer/mmseg/engine/optimizers/__pycache__/layer_decay_optimizer_constructor.cpython-38.pycAdded
- third-party/InterFormer/mmseg/engine/optimizers/force_default_constructor.pyAdded+255
- third-party/InterFormer/mmseg/engine/optimizers/layer_decay_optimizer_constructor.pyAdded+207
- third-party/InterFormer/mmseg/engine/schedulers/__init__.pyAdded+4
- third-party/InterFormer/mmseg/engine/schedulers/__pycache__/__init__.cpython-38.pycAdded
- third-party/InterFormer/mmseg/engine/schedulers/__pycache__/poly_ratio_scheduler.cpython-38.pycAdded
- third-party/InterFormer/mmseg/engine/schedulers/poly_ratio_scheduler.pyAdded+62
- third-party/InterFormer/mmseg/evaluation/__init__.pyAdded+4
- third-party/InterFormer/mmseg/evaluation/__pycache__/__init__.cpython-38.pycAdded
- third-party/InterFormer/mmseg/evaluation/metrics/__init__.pyAdded+6
- third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/__init__.cpython-38.pycAdded
- third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/citys_metric.cpython-38.pycAdded
- third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/depth_metric.cpython-38.pycAdded
- third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/iou_metric.cpython-38.pycAdded
- third-party/InterFormer/mmseg/evaluation/metrics/citys_metric.pyAdded+158
- third-party/InterFormer/mmseg/evaluation/metrics/depth_metric.pyAdded+212
- third-party/InterFormer/mmseg/evaluation/metrics/iou_metric.pyAdded+286
- third-party/InterFormer/mmseg/models/__init__.pyAdded+16
- third-party/InterFormer/mmseg/models/__pycache__/__init__.cpython-38.pycAdded
- third-party/InterFormer/mmseg/models/__pycache__/builder.cpython-38.pycAdded
- third-party/InterFormer/mmseg/models/__pycache__/data_preprocessor.cpython-38.pycAdded
- third-party/InterFormer/mmseg/models/assigners/__init__.pyAdded+12
- third-party/InterFormer/mmseg/models/assigners/__pycache__/__init__.cpython-38.pycAdded
- third-party/InterFormer/mmseg/models/assigners/__pycache__/base_assigner.cpython-38.pycAdded
- third-party/InterFormer/mmseg/models/assigners/__pycache__/hungarian_assigner.cpython-38.pycAdded
- third-party/InterFormer/mmseg/models/assigners/__pycache__/match_cost.cpython-38.pycAdded
- third-party/InterFormer/mmseg/models/assigners/base_assigner.pyAdded+18
- third-party/InterFormer/mmseg/models/assigners/hungarian_assigner.pyAdded+86
- third-party/InterFormer/mmseg/models/assigners/match_cost.pyAdded+231
- third-party/InterFormer/mmseg/models/backbones/__init__.pyAdded+35
- third-party/InterFormer/mmseg/models/backbones/__pycache__/__init__.cpython-38.pycAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257name: mmsegchannels: - pytorch - nvidia - defaultsdependencies: - _libgcc_mutex=0.1=main - _openmp_mutex=5.1=1_gnu - blas=1.0=mkl - brotlipy=0.7.0=py310h7f8727e_1002 - bzip2=1.0.8=h7b6447c_0 - ca-certificates=2023.05.30=h06a4308_0 - certifi=2023.5.7=py310h06a4308_0 - cffi=1.15.1=py310h5eee18b_3 - charset-normalizer=2.0.4=pyhd3eb1b0_0 - cryptography=39.0.1=py310h9ce1e76_2 - cuda=11.6.1=0 - cuda-cccl=11.6.55=hf6102b2_0 - cuda-command-line-tools=11.6.2=0 - cuda-compiler=11.6.2=0 - cuda-cudart=11.6.55=he381448_0 - cuda-cudart-dev=11.6.55=h42ad0f4_0 - cuda-cuobjdump=11.6.124=h2eeebcb_0 - cuda-cupti=11.6.124=h86345e5_0 - cuda-cuxxfilt=11.6.124=hecbf4f6_0 - cuda-driver-dev=11.6.55=0 - cuda-gdb=12.1.105=0 - cuda-libraries=11.6.1=0 - cuda-libraries-dev=11.6.1=0 - cuda-memcheck=11.8.86=0 - cuda-nsight=12.1.105=0 - cuda-nsight-compute=12.1.1=0 - cuda-nvcc=11.6.124=hbba6d2d_0 - cuda-nvdisasm=12.1.105=0 - cuda-nvml-dev=11.6.55=haa9ef22_0 - cuda-nvprof=12.1.105=0 - cuda-nvprune=11.6.124=he22ec0a_0 - cuda-nvrtc=11.6.124=h020bade_0 - cuda-nvrtc-dev=11.6.124=h249d397_0 - cuda-nvtx=11.6.124=h0630a44_0 - cuda-nvvp=12.1.105=0 - cuda-runtime=11.6.1=0 - cuda-samples=11.6.101=h8efea70_0 - cuda-sanitizer-api=12.1.105=0 - cuda-toolkit=11.6.1=0 - cuda-tools=11.6.1=0 - cuda-visual-tools=11.6.1=0 - ffmpeg=4.2.2=h20bf706_0 - freetype=2.12.1=h4a9f257_0 - gds-tools=1.6.1.9=0 - giflib=5.2.1=h5eee18b_3 - gmp=6.2.1=h295c915_3 - gnutls=3.6.15=he1e5248_0 - idna=3.4=py310h06a4308_0 - intel-openmp=2023.1.0=hdb19cb5_46305 - jpeg=9e=h5eee18b_1 - lame=3.100=h7b6447c_0 - lcms2=2.12=h3be6417_0 - ld_impl_linux-64=2.38=h1181459_1 - lerc=3.0=h295c915_0 - libcublas=11.9.2.110=h5e84587_0 - libcublas-dev=11.9.2.110=h5c901ab_0 - libcufft=10.7.1.112=hf425ae0_0 - libcufft-dev=10.7.1.112=ha5ce4c0_0 - libcufile=1.6.1.9=0 - libcufile-dev=1.6.1.9=0 - libcurand=10.3.2.106=0 - libcurand-dev=10.3.2.106=0 - libcusolver=11.3.4.124=h33c3c4e_0 - libcusparse=11.7.2.124=h7538f96_0 - libcusparse-dev=11.7.2.124=hbbe9722_0 - libdeflate=1.17=h5eee18b_0 - libffi=3.4.4=h6a678d5_0 - libgcc-ng=11.2.0=h1234567_1 - libgomp=11.2.0=h1234567_1 - libidn2=2.3.4=h5eee18b_0 - libnpp=11.6.3.124=hd2722f0_0 - libnpp-dev=11.6.3.124=h3c42840_0 - libnvjpeg=11.6.2.124=hd473ad6_0 - libnvjpeg-dev=11.6.2.124=hb5906b9_0 - libopus=1.3.1=h7b6447c_0 - libpng=1.6.39=h5eee18b_0 - libstdcxx-ng=11.2.0=h1234567_1 - libtasn1=4.19.0=h5eee18b_0 - libtiff=4.5.0=h6a678d5_2 - libunistring=0.9.10=h27cfd23_0 - libuuid=1.41.5=h5eee18b_0 - libvpx=1.7.0=h439df22_0 - libwebp=1.2.4=h11a3e52_1 - libwebp-base=1.2.4=h5eee18b_1 - lz4-c=1.9.4=h6a678d5_0 - mkl=2023.1.0=h6d00ec8_46342 - mkl-service=2.4.0=py310h5eee18b_1 - mkl_fft=1.3.6=py310h1128e8f_1 - mkl_random=1.2.2=py310h1128e8f_1 - ncurses=6.4=h6a678d5_0 - nettle=3.7.3=hbbd107a_1 - nsight-compute=2023.1.1.4=0 - numpy=1.25.0=py310h5f9d8c6_0 - numpy-base=1.25.0=py310hb5e798b_0 - openh264=2.1.1=h4ff587b_0 - openssl=3.0.9=h7f8727e_0 - pillow=9.4.0=py310h6a678d5_0 - pip=23.1.2=py310h06a4308_0 - pycparser=2.21=pyhd3eb1b0_0 - pyopenssl=23.0.0=py310h06a4308_0 - pysocks=1.7.1=py310h06a4308_0 - python=3.10.11=h955ad1f_3 - pytorch=1.13.1=py3.10_cuda11.6_cudnn8.3.2_0 - pytorch-cuda=11.6=h867d48c_1 - pytorch-mutex=1.0=cuda - readline=8.2=h5eee18b_0 - sqlite=3.41.2=h5eee18b_0 - tbb=2021.8.0=hdb19cb5_0 - tk=8.6.12=h1ccaba5_0 - torchaudio=0.13.1=py310_cu116 - torchvision=0.14.1=py310_cu116 - typing_extensions=4.6.3=py310h06a4308_0 - urllib3=1.26.16=py310h06a4308_0 - x264=1!157.20191217=h7b6447c_0 - xz=5.4.2=h5eee18b_0 - zlib=1.2.13=h5eee18b_0 - zstd=1.5.5=hc292b87_0 - pip: - absl-py==2.1.0 - addict==2.4.0 - aiohappyeyeballs==2.6.1 - aiohttp==3.12.15 - aiosignal==1.4.0 - aliyun-python-sdk-core==2.15.1 - aliyun-python-sdk-kms==2.16.3 - asttokens==2.4.1 - async-timeout==5.0.1 - attrs==25.3.0 - basicsr==0.0.0 - beautifulsoup4==4.12.3 - cachetools==5.3.3 - click==8.1.7 - colorama==0.4.6 - contourpy==1.2.1 - crcmod==1.7 - cycler==0.12.1 - datasets==4.0.0 - decorator==5.1.1 - dill==0.3.8 - einops==0.8.0 - exceptiongroup==1.2.2 - executing==2.0.1 - filelock==3.14.0 - fonttools==4.51.0 - frozenlist==1.7.0 - fsspec==2024.5.0 - ftfy==6.2.0 - future==1.0.0 - fvcore==0.1.5.post20221221 - gdown==5.2.0 - google-auth==2.29.0 - google-auth-oauthlib==1.0.0 - grpcio==1.63.0 - h5py==3.11.0 - hf-xet==1.1.7 - huggingface-hub==0.34.4 - imageio==2.34.1 - importlib-metadata==7.1.0 - iopath==0.1.10 - ipdb==0.13.13 - ipython==8.26.0 - jedi==0.19.1 - jmespath==0.10.0 - kiwisolver==1.4.5 - lazy-loader==0.4 - lmdb==1.7.2 - markdown==3.6 - markdown-it-py==3.0.0 - markupsafe==2.1.5 - matplotlib==3.9.0 - matplotlib-inline==0.1.7 - mdurl==0.1.2 - mmcv==2.0.0 - mmdet==3.3.0 - mmengine==0.10.4 - mmsegmentation==1.2.2 - model-index==0.1.11 - modelscope==1.30.0 - multidict==6.6.4 - multiprocess==0.70.16 - networkx==3.3 - oauthlib==3.2.2 - omegaconf==2.4.0.dev3 - opencv-python==4.9.0.80 - opendatalab==0.0.10 - openmim==0.3.9 - openxlab==0.0.38 - ordered-set==4.1.0 - oss2==2.17.0 - packaging==24.0 - pandas==2.2.2 - parso==0.8.4 - pexpect==4.9.0 - platformdirs==4.2.2 - portalocker==3.2.0 - prettytable==3.10.0 - prompt-toolkit==3.0.47 - propcache==0.3.2 - protobuf==3.20.3 - psutil==6.0.0 - ptyprocess==0.7.0 - pure-eval==0.2.2 - pyarrow==21.0.0 - pyasn1==0.6.0 - pyasn1-modules==0.4.0 - pycocotools==2.0.7 - pycryptodome==3.20.0 - pygments==2.18.0 - pyparsing==3.1.2 - python-dateutil==2.9.0.post0 - pytz==2023.4 - pyyaml==6.0.1 - regex==2024.5.15 - requests==2.32.4 - requests-oauthlib==2.0.0 - rich==13.4.2 - rsa==4.9 - safetensors==0.4.3 - scikit-image==0.23.2 - scipy==1.13.0 - seaborn==0.13.2 - setuptools==60.2.0 - shapely==2.0.4 - six==1.16.0 - smmap==5.0.1 - soupsieve==2.6 - stack-data==0.6.3 - tabulate==0.9.0 - tb-nightly==2.21.0a20250719 - tensorboard==2.13.0 - tensorboard-data-server==0.7.0 - tensorboardx==2.6 - termcolor==2.3.0 - terminaltables==3.1.10 - thop==0.1.1-2209072238 - threadpoolctl==3.1.0 - tifffile==2024.5.10 - timm==1.0.3 - tomli==2.0.1 - tqdm==4.67.1 - traitlets==5.14.3 - tzdata==2024.1 - wcwidth==0.2.13 - werkzeug==3.0.3 - wheel==0.26.0 - xxhash==3.5.0 - yacs==0.1.8 - yapf==0.40.2 - yarl==1.20.1 - zipp==3.18.2prefix: /home/suyuejiao/anaconda3/envs/mmseg123456789101112131415161718192021222324252627282930# Copyright (c) OpenMMLab. All rights reserved.from .formatting import PackSegInputsfrom .loading import (LoadAnnotations, LoadBiomedicalAnnotation, LoadBiomedicalData, LoadBiomedicalImageFromFile, LoadDepthAnnotation, LoadImageFromNDArray, LoadMultipleRSImageFromFile, LoadSingleRSImageFromFile)# yapf: disablefrom .transforms import (CLAHE, AdjustGamma, Albu, BioMedical3DPad, BioMedical3DRandomCrop, BioMedical3DRandomFlip, BioMedicalGaussianBlur, BioMedicalGaussianNoise, BioMedicalRandomGamma, ConcatCDInput, GenerateEdge, PhotoMetricDistortion, RandomCrop, RandomCutOut, RandomDepthMix, RandomFlip, RandomMosaic, RandomRotate, RandomRotFlip, Rerange, Resize, ResizeShortestEdge, ResizeToMultiple, RGB2Gray, SegRescale)
# yapf: enable__all__ = [ 'LoadAnnotations', 'RandomCrop', 'BioMedical3DRandomCrop', 'SegRescale', 'PhotoMetricDistortion', 'RandomRotate', 'AdjustGamma', 'CLAHE', 'Rerange', 'RGB2Gray', 'RandomCutOut', 'RandomMosaic', 'PackSegInputs', 'ResizeToMultiple', 'LoadImageFromNDArray', 'LoadBiomedicalImageFromFile', 'LoadBiomedicalAnnotation', 'LoadBiomedicalData', 'GenerateEdge', 'ResizeShortestEdge', 'BioMedicalGaussianNoise', 'BioMedicalGaussianBlur', 'BioMedical3DRandomFlip', 'BioMedicalRandomGamma', 'BioMedical3DPad', 'RandomRotFlip', 'Albu', 'LoadSingleRSImageFromFile', 'ConcatCDInput', 'LoadMultipleRSImageFromFile', 'LoadDepthAnnotation', 'RandomDepthMix', 'RandomFlip', 'Resize']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112# Copyright (c) OpenMMLab. All rights reserved.import warnings
import numpy as npfrom mmcv.transforms import to_tensorfrom mmcv.transforms.base import BaseTransformfrom mmengine.structures import PixelData
from mmseg.registry import TRANSFORMSfrom mmseg.structures import SegDataSample
@TRANSFORMS.register_module()class PackSegInputs(BaseTransform): """Pack the inputs data for the semantic segmentation.
The ``img_meta`` item is always populated. The contents of the ``img_meta`` dictionary depends on ``meta_keys``. By default this includes:
- ``img_path``: filename of the image
- ``ori_shape``: original shape of the image as a tuple (h, w, c)
- ``img_shape``: shape of the image input to the network as a tuple \ (h, w, c). Note that images may be zero padded on the \ bottom/right if the batch tensor is larger than this shape.
- ``pad_shape``: shape of padded images
- ``scale_factor``: a float indicating the preprocessing scale
- ``flip``: a boolean indicating if image flip transform was used
- ``flip_direction``: the flipping direction
Args: meta_keys (Sequence[str], optional): Meta keys to be packed from ``SegDataSample`` and collected in ``data[img_metas]``. Default: ``('img_path', 'ori_shape', 'img_shape', 'pad_shape', 'scale_factor', 'flip', 'flip_direction')`` """
def __init__(self, meta_keys=('img_path', 'seg_map_path', 'ori_shape', 'img_shape', 'pad_shape', 'scale_factor', 'flip', 'flip_direction', 'reduce_zero_label')): self.meta_keys = meta_keys
def transform(self, results: dict) -> dict: """Method to pack the input data.
Args: results (dict): Result dict from the data pipeline.
Returns: dict:
- 'inputs' (obj:`torch.Tensor`): The forward data of models. - 'data_sample' (obj:`SegDataSample`): The annotation info of the sample. """ packed_results = dict() if 'img' in results: img = results['img'] if len(img.shape) < 3: img = np.expand_dims(img, -1) if not img.flags.c_contiguous: img = to_tensor(np.ascontiguousarray(img.transpose(2, 0, 1))) else: img = img.transpose(2, 0, 1) img = to_tensor(img).contiguous() packed_results['inputs'] = img
data_sample = SegDataSample() if 'gt_seg_map' in results: if len(results['gt_seg_map'].shape) == 2: data = to_tensor(results['gt_seg_map'][None, ...].astype(np.int64)) else: warnings.warn('Please pay attention your ground truth ' 'segmentation map, usually the segmentation ' 'map is 2D, but got ' f'{results["gt_seg_map"].shape}') data = to_tensor(results['gt_seg_map'].astype(np.int64)) gt_sem_seg_data = dict(data=data) data_sample.gt_sem_seg = PixelData(**gt_sem_seg_data)
if 'gt_edge_map' in results: gt_edge_data = dict( data=to_tensor(results['gt_edge_map'][None, ...].astype(np.int64))) data_sample.set_data(dict(gt_edge_map=PixelData(**gt_edge_data)))
if 'gt_depth_map' in results: gt_depth_data = dict( data=to_tensor(results['gt_depth_map'][None, ...])) data_sample.set_data(dict(gt_depth_map=PixelData(**gt_depth_data)))
img_meta = {} for key in self.meta_keys: if key in results: img_meta[key] = results[key] data_sample.set_metainfo(img_meta) packed_results['data_samples'] = data_sample
return packed_results
def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(meta_keys={self.meta_keys})' return repr_str123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771# Copyright (c) OpenMMLab. All rights reserved.import warningsfrom pathlib import Pathfrom typing import Dict, Optional, Union
import mmcvimport mmengine.fileio as fileioimport numpy as npfrom mmcv.transforms import BaseTransformfrom mmcv.transforms import LoadAnnotations as MMCV_LoadAnnotationsfrom mmcv.transforms import LoadImageFromFile
from mmseg.registry import TRANSFORMSfrom mmseg.utils import datafrombytes
try: from osgeo import gdalexcept ImportError: gdal = None
@TRANSFORMS.register_module()class LoadAnnotations(MMCV_LoadAnnotations): """Load annotations for semantic segmentation provided by dataset.
The annotation format is as the following:
.. code-block:: python
{ # Filename of semantic segmentation ground truth file. 'seg_map_path': 'a/b/c' }
After this module, the annotation has been changed to the format below:
.. code-block:: python
{ # in str 'seg_fields': List # In uint8 type. 'gt_seg_map': np.ndarray (H, W) }
Required Keys:
- seg_map_path (str): Path of semantic segmentation ground truth file.
Added Keys:
- seg_fields (List) - gt_seg_map (np.uint8)
Args: reduce_zero_label (bool, optional): Whether reduce all label value by 1. Usually used for datasets where 0 is background label. Defaults to None. imdecode_backend (str): The image decoding backend type. The backend argument for :func:``mmcv.imfrombytes``. See :fun:``mmcv.imfrombytes`` for details. Defaults to 'pillow'. backend_args (dict): Arguments to instantiate a file backend. See https://mmengine.readthedocs.io/en/latest/api/fileio.htm for details. Defaults to None. Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. """
def __init__( self, reduce_zero_label=None, backend_args=None, imdecode_backend='pillow', ) -> None: super().__init__( with_bbox=False, with_label=False, with_seg=True, with_keypoints=False, imdecode_backend=imdecode_backend, backend_args=backend_args) self.reduce_zero_label = reduce_zero_label if self.reduce_zero_label is not None: warnings.warn('`reduce_zero_label` will be deprecated, ' 'if you would like to ignore the zero label, please ' 'set `reduce_zero_label=True` when dataset ' 'initialized') self.imdecode_backend = imdecode_backend
def _load_seg_map(self, results: dict) -> None: """Private function to load semantic segmentation annotations.
Args: results (dict): Result dict from :obj:``mmcv.BaseDataset``.
Returns: dict: The dict contains loaded semantic segmentation annotations. """
img_bytes = fileio.get( results['seg_map_path'], backend_args=self.backend_args) gt_semantic_seg = mmcv.imfrombytes( img_bytes, flag='unchanged', backend=self.imdecode_backend).squeeze().astype(np.uint8)
# reduce zero_label if self.reduce_zero_label is None: self.reduce_zero_label = results['reduce_zero_label'] assert self.reduce_zero_label == results['reduce_zero_label'], \ 'Initialize dataset with `reduce_zero_label` as ' \ f'{results["reduce_zero_label"]} but when load annotation ' \ f'the `reduce_zero_label` is {self.reduce_zero_label}' if self.reduce_zero_label: # avoid using underflow conversion gt_semantic_seg[gt_semantic_seg == 0] = 255 gt_semantic_seg = gt_semantic_seg - 1 gt_semantic_seg[gt_semantic_seg == 254] = 255 # modify if custom classes if results.get('label_map', None) is not None: # Add deep copy to solve bug of repeatedly # replace `gt_semantic_seg`, which is reported in # https://github.com/open-mmlab/mmsegmentation/pull/1445/ gt_semantic_seg_copy = gt_semantic_seg.copy() for old_id, new_id in results['label_map'].items(): gt_semantic_seg[gt_semantic_seg_copy == old_id] = new_id results['gt_seg_map'] = gt_semantic_seg results['seg_fields'].append('gt_seg_map')
def __repr__(self) -> str: repr_str = self.__class__.__name__ repr_str += f'(reduce_zero_label={self.reduce_zero_label}, ' repr_str += f"imdecode_backend='{self.imdecode_backend}', " repr_str += f'backend_args={self.backend_args})' return repr_str
@TRANSFORMS.register_module()class LoadImageFromNDArray(LoadImageFromFile): """Load an image from ``results['img']``.
Similar with :obj:`LoadImageFromFile`, but the image has been loaded as :obj:`np.ndarray` in ``results['img']``. Can be used when loading image from webcam.
Required Keys:
- img
Modified Keys:
- img - img_path - img_shape - ori_shape
Args: to_float32 (bool): Whether to convert the loaded image to a float32 numpy array. If set to False, the loaded image is an uint8 array. Defaults to False. """
def transform(self, results: dict) -> dict: """Transform function to add image meta information.
Args: results (dict): Result dict with Webcam read image in ``results['img']``.
Returns: dict: The dict contains loaded image and meta information. """
img = results['img'] if self.to_float32: img = img.astype(np.float32)
results['img_path'] = None results['img'] = img results['img_shape'] = img.shape[:2] results['ori_shape'] = img.shape[:2] return results
@TRANSFORMS.register_module()class LoadBiomedicalImageFromFile(BaseTransform): """Load an biomedical mage from file.
Required Keys:
- img_path
Added Keys:
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X) by default, N is the number of modalities, and data type is float32 if set to_float32 = True, or float64 if decode_backend is 'nifti' and to_float32 is False. - img_shape - ori_shape
Args: decode_backend (str): The data decoding backend type. Options are 'numpy'and 'nifti', and there is a convention that when backend is 'nifti' the axis of data loaded is XYZ, and when backend is 'numpy', the the axis is ZYX. The data will be transposed if the backend is 'nifti'. Defaults to 'nifti'. to_xyz (bool): Whether transpose data from Z, Y, X to X, Y, Z. Defaults to False. to_float32 (bool): Whether to convert the loaded image to a float32 numpy array. If set to False, the loaded image is an float64 array. Defaults to True. backend_args (dict, Optional): Arguments to instantiate a file backend. See https://mmengine.readthedocs.io/en/latest/api/fileio.htm for details. Defaults to None. Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. """
def __init__(self, decode_backend: str = 'nifti', to_xyz: bool = False, to_float32: bool = True, backend_args: Optional[dict] = None) -> None: self.decode_backend = decode_backend self.to_xyz = to_xyz self.to_float32 = to_float32 self.backend_args = backend_args.copy() if backend_args else None
def transform(self, results: Dict) -> Dict: """Functions to load image.
Args: results (dict): Result dict from :obj:``mmcv.BaseDataset``.
Returns: dict: The dict contains loaded image and meta information. """
filename = results['img_path']
data_bytes = fileio.get(filename, self.backend_args) img = datafrombytes(data_bytes, backend=self.decode_backend)
if self.to_float32: img = img.astype(np.float32)
if len(img.shape) == 3: img = img[None, ...]
if self.decode_backend == 'nifti': img = img.transpose(0, 3, 2, 1)
if self.to_xyz: img = img.transpose(0, 3, 2, 1)
results['img'] = img results['img_shape'] = img.shape[1:] results['ori_shape'] = img.shape[1:] return results
def __repr__(self): repr_str = (f'{self.__class__.__name__}(' f"decode_backend='{self.decode_backend}', " f'to_xyz={self.to_xyz}, ' f'to_float32={self.to_float32}, ' f'backend_args={self.backend_args})') return repr_str
@TRANSFORMS.register_module()class LoadBiomedicalAnnotation(BaseTransform): """Load ``seg_map`` annotation provided by biomedical dataset.
The annotation format is as the following:
.. code-block:: python
{ 'gt_seg_map': np.ndarray (X, Y, Z) or (Z, Y, X) }
Required Keys:
- seg_map_path
Added Keys:
- gt_seg_map (np.ndarray): Biomedical seg map with shape (Z, Y, X) by default, and data type is float32 if set to_float32 = True, or float64 if decode_backend is 'nifti' and to_float32 is False.
Args: decode_backend (str): The data decoding backend type. Options are 'numpy'and 'nifti', and there is a convention that when backend is 'nifti' the axis of data loaded is XYZ, and when backend is 'numpy', the the axis is ZYX. The data will be transposed if the backend is 'nifti'. Defaults to 'nifti'. to_xyz (bool): Whether transpose data from Z, Y, X to X, Y, Z. Defaults to False. to_float32 (bool): Whether to convert the loaded seg map to a float32 numpy array. If set to False, the loaded image is an float64 array. Defaults to True. backend_args (dict, Optional): Arguments to instantiate a file backend. See :class:`mmengine.fileio` for details. Defaults to None. Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. """
def __init__(self, decode_backend: str = 'nifti', to_xyz: bool = False, to_float32: bool = True, backend_args: Optional[dict] = None) -> None: super().__init__() self.decode_backend = decode_backend self.to_xyz = to_xyz self.to_float32 = to_float32 self.backend_args = backend_args.copy() if backend_args else None
def transform(self, results: Dict) -> Dict: """Functions to load image.
Args: results (dict): Result dict from :obj:``mmcv.BaseDataset``.
Returns: dict: The dict contains loaded image and meta information. """ data_bytes = fileio.get(results['seg_map_path'], self.backend_args) gt_seg_map = datafrombytes(data_bytes, backend=self.decode_backend)
if self.to_float32: gt_seg_map = gt_seg_map.astype(np.float32)
if self.decode_backend == 'nifti': gt_seg_map = gt_seg_map.transpose(2, 1, 0)
if self.to_xyz: gt_seg_map = gt_seg_map.transpose(2, 1, 0)
results['gt_seg_map'] = gt_seg_map return results
def __repr__(self): repr_str = (f'{self.__class__.__name__}(' f"decode_backend='{self.decode_backend}', " f'to_xyz={self.to_xyz}, ' f'to_float32={self.to_float32}, ' f'backend_args={self.backend_args})') return repr_str
@TRANSFORMS.register_module()class LoadBiomedicalData(BaseTransform): """Load an biomedical image and annotation from file.
The loading data format is as the following:
.. code-block:: python
{ 'img': np.ndarray data[:-1, X, Y, Z] 'seg_map': np.ndarray data[-1, X, Y, Z] }
Required Keys:
- img_path
Added Keys:
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X) by default, N is the number of modalities. - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape (Z, Y, X) by default. - img_shape - ori_shape
Args: with_seg (bool): Whether to parse and load the semantic segmentation annotation. Defaults to False. decode_backend (str): The data decoding backend type. Options are 'numpy'and 'nifti', and there is a convention that when backend is 'nifti' the axis of data loaded is XYZ, and when backend is 'numpy', the the axis is ZYX. The data will be transposed if the backend is 'nifti'. Defaults to 'nifti'. to_xyz (bool): Whether transpose data from Z, Y, X to X, Y, Z. Defaults to False. backend_args (dict, Optional): Arguments to instantiate a file backend. See https://mmengine.readthedocs.io/en/latest/api/fileio.htm for details. Defaults to None. Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. """
def __init__(self, with_seg=False, decode_backend: str = 'numpy', to_xyz: bool = False, backend_args: Optional[dict] = None) -> None: # noqa self.with_seg = with_seg self.decode_backend = decode_backend self.to_xyz = to_xyz self.backend_args = backend_args.copy() if backend_args else None
def transform(self, results: Dict) -> Dict: """Functions to load image.
Args: results (dict): Result dict from :obj:``mmcv.BaseDataset``.
Returns: dict: The dict contains loaded image and meta information. """ data_bytes = fileio.get(results['img_path'], self.backend_args) data = datafrombytes(data_bytes, backend=self.decode_backend) # img is 4D data (N, X, Y, Z), N is the number of protocol img = data[:-1, :]
if self.decode_backend == 'nifti': img = img.transpose(0, 3, 2, 1)
if self.to_xyz: img = img.transpose(0, 3, 2, 1)
results['img'] = img results['img_shape'] = img.shape[1:] results['ori_shape'] = img.shape[1:]
if self.with_seg: gt_seg_map = data[-1, :] if self.decode_backend == 'nifti': gt_seg_map = gt_seg_map.transpose(2, 1, 0)
if self.to_xyz: gt_seg_map = gt_seg_map.transpose(2, 1, 0) results['gt_seg_map'] = gt_seg_map return results
def __repr__(self) -> str: repr_str = (f'{self.__class__.__name__}(' f'with_seg={self.with_seg}, ' f"decode_backend='{self.decode_backend}', " f'to_xyz={self.to_xyz}, ' f'backend_args={self.backend_args})') return repr_str
@TRANSFORMS.register_module()class InferencerLoader(BaseTransform): """Load an image from ``results['img']``.
Similar with :obj:`LoadImageFromFile`, but the image has been loaded as :obj:`np.ndarray` in ``results['img']``. Can be used when loading image from webcam.
Required Keys:
- img
Modified Keys:
- img - img_path - img_shape - ori_shape
Args: to_float32 (bool): Whether to convert the loaded image to a float32 numpy array. If set to False, the loaded image is an uint8 array. Defaults to False. """
def __init__(self, **kwargs) -> None: super().__init__() self.from_file = TRANSFORMS.build( dict(type='LoadImageFromFile', **kwargs)) self.from_ndarray = TRANSFORMS.build( dict(type='LoadImageFromNDArray', **kwargs))
def transform(self, single_input: Union[str, np.ndarray, dict]) -> dict: """Transform function to add image meta information.
Args: results (dict): Result dict with Webcam read image in ``results['img']``.
Returns: dict: The dict contains loaded image and meta information. """ if isinstance(single_input, str): inputs = dict(img_path=single_input) elif isinstance(single_input, np.ndarray): inputs = dict(img=single_input) elif isinstance(single_input, dict): inputs = single_input else: raise NotImplementedError
if 'img' in inputs: return self.from_ndarray(inputs) return self.from_file(inputs)
@TRANSFORMS.register_module()class LoadSingleRSImageFromFile(BaseTransform): """Load a Remote Sensing mage from file.
Required Keys:
- img_path
Modified Keys:
- img - img_shape - ori_shape
Args: to_float32 (bool): Whether to convert the loaded image to a float32 numpy array. If set to False, the loaded image is a float64 array. Defaults to True. """
def __init__(self, to_float32: bool = True): self.to_float32 = to_float32
if gdal is None: raise RuntimeError('gdal is not installed')
def transform(self, results: Dict) -> Dict: """Functions to load image.
Args: results (dict): Result dict from :obj:``mmcv.BaseDataset``.
Returns: dict: The dict contains loaded image and meta information. """
filename = results['img_path'] ds = gdal.Open(filename) if ds is None: raise Exception(f'Unable to open file: {filename}') img = np.einsum('ijk->jki', ds.ReadAsArray())
if self.to_float32: img = img.astype(np.float32)
results['img'] = img results['img_shape'] = img.shape[:2] results['ori_shape'] = img.shape[:2] return results
def __repr__(self): repr_str = (f'{self.__class__.__name__}(' f'to_float32={self.to_float32})') return repr_str
@TRANSFORMS.register_module()class LoadMultipleRSImageFromFile(BaseTransform): """Load two Remote Sensing mage from file.
Required Keys:
- img_path - img_path2
Modified Keys:
- img - img2 - img_shape - ori_shape
Args: to_float32 (bool): Whether to convert the loaded image to a float32 numpy array. If set to False, the loaded image is a float64 array. Defaults to True. """
def __init__(self, to_float32: bool = True): if gdal is None: raise RuntimeError('gdal is not installed') self.to_float32 = to_float32
def transform(self, results: Dict) -> Dict: """Functions to load image.
Args: results (dict): Result dict from :obj:``mmcv.BaseDataset``.
Returns: dict: The dict contains loaded image and meta information. """
filename = results['img_path'] filename2 = results['img_path2']
ds = gdal.Open(filename) ds2 = gdal.Open(filename2)
if ds is None: raise Exception(f'Unable to open file: {filename}') if ds2 is None: raise Exception(f'Unable to open file: {filename2}')
img = np.einsum('ijk->jki', ds.ReadAsArray()) img2 = np.einsum('ijk->jki', ds2.ReadAsArray())
if self.to_float32: img = img.astype(np.float32) img2 = img2.astype(np.float32)
if img.shape != img2.shape: raise Exception(f'Image shapes do not match:' f' {img.shape} vs {img2.shape}')
results['img'] = img results['img2'] = img2 results['img_shape'] = img.shape[:2] results['ori_shape'] = img.shape[:2] return results
def __repr__(self): repr_str = (f'{self.__class__.__name__}(' f'to_float32={self.to_float32})') return repr_str
@TRANSFORMS.register_module()class LoadDepthAnnotation(BaseTransform): """Load ``depth_map`` annotation provided by depth estimation dataset.
The annotation format is as the following:
.. code-block:: python
{ 'gt_depth_map': np.ndarray [Y, X] }
Required Keys:
- seg_depth_path
Added Keys:
- gt_depth_map (np.ndarray): Depth map with shape (Y, X) by default, and data type is float32 if set to_float32 = True. - depth_rescale_factor (float): The rescale factor of depth map, which can be used to recover the original value of depth map.
Args: decode_backend (str): The data decoding backend type. Options are 'numpy', 'nifti', and 'cv2'. Defaults to 'cv2'. to_float32 (bool): Whether to convert the loaded depth map to a float32 numpy array. If set to False, the loaded image is an uint16 array. Defaults to True. depth_rescale_factor (float): Factor to rescale the depth value to limit the range. Defaults to 1.0. backend_args (dict, Optional): Arguments to instantiate a file backend. See :class:`mmengine.fileio` for details. Defaults to None. Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. """
def __init__(self, decode_backend: str = 'cv2', to_float32: bool = True, depth_rescale_factor: float = 1.0, backend_args: Optional[dict] = None) -> None: super().__init__() self.decode_backend = decode_backend self.to_float32 = to_float32 self.depth_rescale_factor = depth_rescale_factor self.backend_args = backend_args.copy() if backend_args else None
def transform(self, results: Dict) -> Dict: """Functions to load depth map.
Args: results (dict): Result dict from :obj:``mmcv.BaseDataset``.
Returns: dict: The dict contains loaded depth map. """ data_bytes = fileio.get(results['depth_map_path'], self.backend_args) gt_depth_map = datafrombytes(data_bytes, backend=self.decode_backend)
if self.to_float32: gt_depth_map = gt_depth_map.astype(np.float32)
gt_depth_map *= self.depth_rescale_factor results['gt_depth_map'] = gt_depth_map results['seg_fields'].append('gt_depth_map') results['depth_rescale_factor'] = self.depth_rescale_factor return results
def __repr__(self): repr_str = (f'{self.__class__.__name__}(' f"decode_backend='{self.decode_backend}', " f'to_float32={self.to_float32}, ' f'backend_args={self.backend_args})') return repr_str
@TRANSFORMS.register_module()class LoadImageFromNpyFile(LoadImageFromFile): """Load an image from ``results['img_path']``.
Required Keys:
- img_path
Modified Keys:
- img - img_shape - ori_shape
Args: to_float32 (bool): Whether to convert the loaded image to a float32 numpy array. If set to False, the loaded image is an uint8 array. Defaults to False. """
def transform(self, results: dict) -> Optional[dict]: """Functions to load image.
Args: results (dict): Result dict from :class:`mmengine.dataset.BaseDataset`.
Returns: dict: The dict contains loaded image and meta information. """
filename = results['img_path']
try: if Path(filename).suffix in ['.npy', '.npz']: img = np.load(filename) else: if self.file_client_args is not None: file_client = fileio.FileClient.infer_client( self.file_client_args, filename) img_bytes = file_client.get(filename) else: img_bytes = fileio.get( filename, backend_args=self.backend_args) img = mmcv.imfrombytes( img_bytes, flag=self.color_type, backend=self.imdecode_backend) except Exception as e: if self.ignore_empty: return None else: raise e
# in some cases, images are not read successfully, the img would be # `None`, refer to https://github.com/open-mmlab/mmpretrain/issues/1427 assert img is not None, f'failed to load image: {filename}' if self.to_float32: img = img.astype(np.float32)
results['img'] = img results['img_shape'] = img.shape[:2] results['ori_shape'] = img.shape[:2] return results12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537# Copyright (c) OpenMMLab. All rights reserved.import copyimport inspectimport warningsfrom typing import Dict, List, Optional, Sequence, Tuple, Union
import cv2import mmcvimport mmengineimport numpy as npfrom mmcv.transforms import RandomFlip as MMCV_RandomFlipfrom mmcv.transforms import Resize as MMCV_Resizefrom mmcv.transforms.base import BaseTransformfrom mmcv.transforms.utils import cache_randomnessfrom mmengine.utils import is_tuple_offrom numpy import randomfrom scipy.ndimage import gaussian_filter
from mmseg.datasets.dataset_wrappers import MultiImageMixDatasetfrom mmseg.registry import TRANSFORMS
try: import albumentations from albumentations import Compose ALBU_INSTALLED = Trueexcept ImportError: albumentations = None Compose = None ALBU_INSTALLED = False
@TRANSFORMS.register_module()class ResizeToMultiple(BaseTransform): """Resize images & seg to multiple of divisor.
Required Keys:
- img - gt_seg_map
Modified Keys:
- img - img_shape - pad_shape
Args: size_divisor (int): images and gt seg maps need to resize to multiple of size_divisor. Default: 32. interpolation (str, optional): The interpolation mode of image resize. Default: None """
def __init__(self, size_divisor=32, interpolation=None): self.size_divisor = size_divisor self.interpolation = interpolation
def transform(self, results: dict) -> dict: """Call function to resize images, semantic segmentation map to multiple of size divisor.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Resized results, 'img_shape', 'pad_shape' keys are updated. """ # Align image to multiple of size divisor. img = results['img'] img = mmcv.imresize_to_multiple( img, self.size_divisor, scale_factor=1, interpolation=self.interpolation if self.interpolation else 'bilinear')
results['img'] = img results['img_shape'] = img.shape[:2] results['pad_shape'] = img.shape[:2]
# Align segmentation map to multiple of size divisor. for key in results.get('seg_fields', []): gt_seg = results[key] gt_seg = mmcv.imresize_to_multiple( gt_seg, self.size_divisor, scale_factor=1, interpolation='nearest') results[key] = gt_seg
return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += (f'(size_divisor={self.size_divisor}, ' f'interpolation={self.interpolation})') return repr_str
@TRANSFORMS.register_module()class Rerange(BaseTransform): """Rerange the image pixel value.
Required Keys:
- img
Modified Keys:
- img
Args: min_value (float or int): Minimum value of the reranged image. Default: 0. max_value (float or int): Maximum value of the reranged image. Default: 255. """
def __init__(self, min_value=0, max_value=255): assert isinstance(min_value, float) or isinstance(min_value, int) assert isinstance(max_value, float) or isinstance(max_value, int) assert min_value < max_value self.min_value = min_value self.max_value = max_value
def transform(self, results: dict) -> dict: """Call function to rerange images.
Args: results (dict): Result dict from loading pipeline. Returns: dict: Reranged results. """
img = results['img'] img_min_value = np.min(img) img_max_value = np.max(img)
assert img_min_value < img_max_value # rerange to [0, 1] img = (img - img_min_value) / (img_max_value - img_min_value) # rerange to [min_value, max_value] img = img * (self.max_value - self.min_value) + self.min_value results['img'] = img
return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(min_value={self.min_value}, max_value={self.max_value})' return repr_str
@TRANSFORMS.register_module()class CLAHE(BaseTransform): """Use CLAHE method to process the image.
See `ZUIDERVELD,K. Contrast Limited Adaptive Histogram Equalization[J]. Graphics Gems, 1994:474-485.` for more information.
Required Keys:
- img
Modified Keys:
- img
Args: clip_limit (float): Threshold for contrast limiting. Default: 40.0. tile_grid_size (tuple[int]): Size of grid for histogram equalization. Input image will be divided into equally sized rectangular tiles. It defines the number of tiles in row and column. Default: (8, 8). """
def __init__(self, clip_limit=40.0, tile_grid_size=(8, 8)): assert isinstance(clip_limit, (float, int)) self.clip_limit = clip_limit assert is_tuple_of(tile_grid_size, int) assert len(tile_grid_size) == 2 self.tile_grid_size = tile_grid_size
def transform(self, results: dict) -> dict: """Call function to Use CLAHE method process images.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Processed results. """
for i in range(results['img'].shape[2]): results['img'][:, :, i] = mmcv.clahe( np.array(results['img'][:, :, i], dtype=np.uint8), self.clip_limit, self.tile_grid_size)
return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(clip_limit={self.clip_limit}, ' \ f'tile_grid_size={self.tile_grid_size})' return repr_str
@TRANSFORMS.register_module()class RandomCrop(BaseTransform): """Random crop the image & seg.
Required Keys:
- img - gt_seg_map
Modified Keys:
- img - img_shape - gt_seg_map
Args: crop_size (Union[int, Tuple[int, int]]): Expected size after cropping with the format of (h, w). If set to an integer, then cropping width and height are equal to this integer. cat_max_ratio (float): The maximum ratio that single category could occupy. ignore_index (int): The label index to be ignored. Default: 255 """
def __init__(self, crop_size: Union[int, Tuple[int, int]], cat_max_ratio: float = 1., ignore_index: int = 255): super().__init__() assert isinstance(crop_size, int) or ( isinstance(crop_size, tuple) and len(crop_size) == 2 ), 'The expected crop_size is an integer, or a tuple containing two ' 'intergers'
if isinstance(crop_size, int): crop_size = (crop_size, crop_size) assert crop_size[0] > 0 and crop_size[1] > 0 self.crop_size = crop_size self.cat_max_ratio = cat_max_ratio self.ignore_index = ignore_index
@cache_randomness def crop_bbox(self, results: dict) -> tuple: """get a crop bounding box.
Args: results (dict): Result dict from loading pipeline.
Returns: tuple: Coordinates of the cropped image. """
def generate_crop_bbox(img: np.ndarray) -> tuple: """Randomly get a crop bounding box.
Args: img (np.ndarray): Original input image.
Returns: tuple: Coordinates of the cropped image. """
margin_h = max(img.shape[0] - self.crop_size[0], 0) margin_w = max(img.shape[1] - self.crop_size[1], 0) offset_h = np.random.randint(0, margin_h + 1) offset_w = np.random.randint(0, margin_w + 1) crop_y1, crop_y2 = offset_h, offset_h + self.crop_size[0] crop_x1, crop_x2 = offset_w, offset_w + self.crop_size[1]
return crop_y1, crop_y2, crop_x1, crop_x2
img = results['img'] crop_bbox = generate_crop_bbox(img) if self.cat_max_ratio < 1.: # Repeat 10 times for _ in range(10): seg_temp = self.crop(results['gt_seg_map'], crop_bbox) labels, cnt = np.unique(seg_temp, return_counts=True) cnt = cnt[labels != self.ignore_index] if len(cnt) > 1 and np.max(cnt) / np.sum( cnt) < self.cat_max_ratio: break crop_bbox = generate_crop_bbox(img)
return crop_bbox
def crop(self, img: np.ndarray, crop_bbox: tuple) -> np.ndarray: """Crop from ``img``
Args: img (np.ndarray): Original input image. crop_bbox (tuple): Coordinates of the cropped image.
Returns: np.ndarray: The cropped image. """
crop_y1, crop_y2, crop_x1, crop_x2 = crop_bbox img = img[crop_y1:crop_y2, crop_x1:crop_x2, ...] return img
def transform(self, results: dict) -> dict: """Transform function to randomly crop images, semantic segmentation maps.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Randomly cropped results, 'img_shape' key in result dict is updated according to crop size. """
img = results['img'] crop_bbox = self.crop_bbox(results)
# crop the image img = self.crop(img, crop_bbox)
# crop semantic seg for key in results.get('seg_fields', []): results[key] = self.crop(results[key], crop_bbox)
results['img'] = img results['img_shape'] = img.shape[:2] return results
def __repr__(self): return self.__class__.__name__ + f'(crop_size={self.crop_size})'
@TRANSFORMS.register_module()class RandomRotate(BaseTransform): """Rotate the image & seg.
Required Keys:
- img - gt_seg_map
Modified Keys:
- img - gt_seg_map
Args: prob (float): The rotation probability. degree (float, tuple[float]): Range of degrees to select from. If degree is a number instead of tuple like (min, max), the range of degree will be (``-degree``, ``+degree``) pad_val (float, optional): Padding value of image. Default: 0. seg_pad_val (float, optional): Padding value of segmentation map. Default: 255. center (tuple[float], optional): Center point (w, h) of the rotation in the source image. If not specified, the center of the image will be used. Default: None. auto_bound (bool): Whether to adjust the image size to cover the whole rotated image. Default: False """
def __init__(self, prob, degree, pad_val=0, seg_pad_val=255, center=None, auto_bound=False): self.prob = prob assert prob >= 0 and prob <= 1 if isinstance(degree, (float, int)): assert degree > 0, f'degree {degree} should be positive' self.degree = (-degree, degree) else: self.degree = degree assert len(self.degree) == 2, f'degree {self.degree} should be a ' \ f'tuple of (min, max)' self.pal_val = pad_val self.seg_pad_val = seg_pad_val self.center = center self.auto_bound = auto_bound
@cache_randomness def generate_degree(self): return np.random.rand() < self.prob, np.random.uniform( min(*self.degree), max(*self.degree))
def transform(self, results: dict) -> dict: """Call function to rotate image, semantic segmentation maps.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Rotated results. """
rotate, degree = self.generate_degree() if rotate: # rotate image results['img'] = mmcv.imrotate( results['img'], angle=degree, border_value=self.pal_val, center=self.center, auto_bound=self.auto_bound)
# rotate segs for key in results.get('seg_fields', []): results[key] = mmcv.imrotate( results[key], angle=degree, border_value=self.seg_pad_val, center=self.center, auto_bound=self.auto_bound, interpolation='nearest') return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(prob={self.prob}, ' \ f'degree={self.degree}, ' \ f'pad_val={self.pal_val}, ' \ f'seg_pad_val={self.seg_pad_val}, ' \ f'center={self.center}, ' \ f'auto_bound={self.auto_bound})' return repr_str
@TRANSFORMS.register_module()class RGB2Gray(BaseTransform): """Convert RGB image to grayscale image.
Required Keys:
- img
Modified Keys:
- img - img_shape
This transform calculate the weighted mean of input image channels with ``weights`` and then expand the channels to ``out_channels``. When ``out_channels`` is None, the number of output channels is the same as input channels.
Args: out_channels (int): Expected number of output channels after transforming. Default: None. weights (tuple[float]): The weights to calculate the weighted mean. Default: (0.299, 0.587, 0.114). """
def __init__(self, out_channels=None, weights=(0.299, 0.587, 0.114)): assert out_channels is None or out_channels > 0 self.out_channels = out_channels assert isinstance(weights, tuple) for item in weights: assert isinstance(item, (float, int)) self.weights = weights
def transform(self, results: dict) -> dict: """Call function to convert RGB image to grayscale image.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Result dict with grayscale image. """ img = results['img'] assert len(img.shape) == 3 assert img.shape[2] == len(self.weights) weights = np.array(self.weights).reshape((1, 1, -1)) img = (img * weights).sum(2, keepdims=True) if self.out_channels is None: img = img.repeat(weights.shape[2], axis=2) else: img = img.repeat(self.out_channels, axis=2)
results['img'] = img results['img_shape'] = img.shape
return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(out_channels={self.out_channels}, ' \ f'weights={self.weights})' return repr_str
@TRANSFORMS.register_module()class AdjustGamma(BaseTransform): """Using gamma correction to process the image.
Required Keys:
- img
Modified Keys:
- img
Args: gamma (float or int): Gamma value used in gamma correction. Default: 1.0. """
def __init__(self, gamma=1.0): assert isinstance(gamma, float) or isinstance(gamma, int) assert gamma > 0 self.gamma = gamma inv_gamma = 1.0 / gamma self.table = np.array([(i / 255.0)**inv_gamma * 255 for i in np.arange(256)]).astype('uint8')
def transform(self, results: dict) -> dict: """Call function to process the image with gamma correction.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Processed results. """
results['img'] = mmcv.lut_transform( np.array(results['img'], dtype=np.uint8), self.table)
return results
def __repr__(self): return self.__class__.__name__ + f'(gamma={self.gamma})'
@TRANSFORMS.register_module()class SegRescale(BaseTransform): """Rescale semantic segmentation maps.
Required Keys:
- gt_seg_map
Modified Keys:
- gt_seg_map
Args: scale_factor (float): The scale factor of the final output. """
def __init__(self, scale_factor=1): self.scale_factor = scale_factor
def transform(self, results: dict) -> dict: """Call function to scale the semantic segmentation map.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Result dict with semantic segmentation map scaled. """ for key in results.get('seg_fields', []): if self.scale_factor != 1: results[key] = mmcv.imrescale( results[key], self.scale_factor, interpolation='nearest') return results
def __repr__(self): return self.__class__.__name__ + f'(scale_factor={self.scale_factor})'
@TRANSFORMS.register_module()class PhotoMetricDistortion(BaseTransform): """Apply photometric distortion to image sequentially, every transformation is applied with a probability of 0.5. The position of random contrast is in second or second to last.
1. random brightness 2. random contrast (mode 0) 3. convert color from BGR to HSV 4. random saturation 5. random hue 6. convert color from HSV to BGR 7. random contrast (mode 1)
Required Keys:
- img
Modified Keys:
- img
Args: brightness_delta (int): delta of brightness. contrast_range (tuple): range of contrast. saturation_range (tuple): range of saturation. hue_delta (int): delta of hue. """
def __init__(self, brightness_delta: int = 32, contrast_range: Sequence[float] = (0.5, 1.5), saturation_range: Sequence[float] = (0.5, 1.5), hue_delta: int = 18): self.brightness_delta = brightness_delta self.contrast_lower, self.contrast_upper = contrast_range self.saturation_lower, self.saturation_upper = saturation_range self.hue_delta = hue_delta
def convert(self, img: np.ndarray, alpha: int = 1, beta: int = 0) -> np.ndarray: """Multiple with alpha and add beat with clip.
Args: img (np.ndarray): The input image. alpha (int): Image weights, change the contrast/saturation of the image. Default: 1 beta (int): Image bias, change the brightness of the image. Default: 0
Returns: np.ndarray: The transformed image. """
img = img.astype(np.float32) * alpha + beta img = np.clip(img, 0, 255) return img.astype(np.uint8)
def brightness(self, img: np.ndarray) -> np.ndarray: """Brightness distortion.
Args: img (np.ndarray): The input image. Returns: np.ndarray: Image after brightness change. """
if random.randint(2): return self.convert( img, beta=random.uniform(-self.brightness_delta, self.brightness_delta)) return img
def contrast(self, img: np.ndarray) -> np.ndarray: """Contrast distortion.
Args: img (np.ndarray): The input image. Returns: np.ndarray: Image after contrast change. """
if random.randint(2): return self.convert( img, alpha=random.uniform(self.contrast_lower, self.contrast_upper)) return img
def saturation(self, img: np.ndarray) -> np.ndarray: """Saturation distortion.
Args: img (np.ndarray): The input image. Returns: np.ndarray: Image after saturation change. """
if random.randint(2): img = mmcv.bgr2hsv(img) img[:, :, 1] = self.convert( img[:, :, 1], alpha=random.uniform(self.saturation_lower, self.saturation_upper)) img = mmcv.hsv2bgr(img) return img
def hue(self, img: np.ndarray) -> np.ndarray: """Hue distortion.
Args: img (np.ndarray): The input image. Returns: np.ndarray: Image after hue change. """
if random.randint(2): img = mmcv.bgr2hsv(img) img[:, :, 0] = (img[:, :, 0].astype(int) + random.randint(-self.hue_delta, self.hue_delta)) % 180 img = mmcv.hsv2bgr(img) return img
def transform(self, results: dict) -> dict: """Transform function to perform photometric distortion on images.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Result dict with images distorted. """
img = results['img'] # random brightness img = self.brightness(img)
# mode == 0 --> do random contrast first # mode == 1 --> do random contrast last mode = random.randint(2) if mode == 1: img = self.contrast(img)
# random saturation img = self.saturation(img)
# random hue img = self.hue(img)
# random contrast if mode == 0: img = self.contrast(img)
results['img'] = img return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += (f'(brightness_delta={self.brightness_delta}, ' f'contrast_range=({self.contrast_lower}, ' f'{self.contrast_upper}), ' f'saturation_range=({self.saturation_lower}, ' f'{self.saturation_upper}), ' f'hue_delta={self.hue_delta})') return repr_str
@TRANSFORMS.register_module()class RandomCutOut(BaseTransform): """CutOut operation.
Randomly drop some regions of image used in `Cutout <https://arxiv.org/abs/1708.04552>`_.
Required Keys:
- img - gt_seg_map
Modified Keys:
- img - gt_seg_map
Args: prob (float): cutout probability. n_holes (int | tuple[int, int]): Number of regions to be dropped. If it is given as a list, number of holes will be randomly selected from the closed interval [`n_holes[0]`, `n_holes[1]`]. cutout_shape (tuple[int, int] | list[tuple[int, int]]): The candidate shape of dropped regions. It can be `tuple[int, int]` to use a fixed cutout shape, or `list[tuple[int, int]]` to randomly choose shape from the list. cutout_ratio (tuple[float, float] | list[tuple[float, float]]): The candidate ratio of dropped regions. It can be `tuple[float, float]` to use a fixed ratio or `list[tuple[float, float]]` to randomly choose ratio from the list. Please note that `cutout_shape` and `cutout_ratio` cannot be both given at the same time. fill_in (tuple[float, float, float] | tuple[int, int, int]): The value of pixel to fill in the dropped regions. Default: (0, 0, 0). seg_fill_in (int): The labels of pixel to fill in the dropped regions. If seg_fill_in is None, skip. Default: None. """
def __init__(self, prob, n_holes, cutout_shape=None, cutout_ratio=None, fill_in=(0, 0, 0), seg_fill_in=None):
assert 0 <= prob and prob <= 1 assert (cutout_shape is None) ^ (cutout_ratio is None), \ 'Either cutout_shape or cutout_ratio should be specified.' assert (isinstance(cutout_shape, (list, tuple)) or isinstance(cutout_ratio, (list, tuple))) if isinstance(n_holes, tuple): assert len(n_holes) == 2 and 0 <= n_holes[0] < n_holes[1] else: n_holes = (n_holes, n_holes) if seg_fill_in is not None: assert (isinstance(seg_fill_in, int) and 0 <= seg_fill_in and seg_fill_in <= 255) self.prob = prob self.n_holes = n_holes self.fill_in = fill_in self.seg_fill_in = seg_fill_in self.with_ratio = cutout_ratio is not None self.candidates = cutout_ratio if self.with_ratio else cutout_shape if not isinstance(self.candidates, list): self.candidates = [self.candidates]
@cache_randomness def do_cutout(self): return np.random.rand() < self.prob
@cache_randomness def generate_patches(self, results): cutout = self.do_cutout()
h, w, _ = results['img'].shape if cutout: n_holes = np.random.randint(self.n_holes[0], self.n_holes[1] + 1) else: n_holes = 0 x1_lst = [] y1_lst = [] index_lst = [] for _ in range(n_holes): x1_lst.append(np.random.randint(0, w)) y1_lst.append(np.random.randint(0, h)) index_lst.append(np.random.randint(0, len(self.candidates))) return cutout, n_holes, x1_lst, y1_lst, index_lst
def transform(self, results: dict) -> dict: """Call function to drop some regions of image.""" cutout, n_holes, x1_lst, y1_lst, index_lst = self.generate_patches( results) if cutout: h, w, c = results['img'].shape for i in range(n_holes): x1 = x1_lst[i] y1 = y1_lst[i] index = index_lst[i] if not self.with_ratio: cutout_w, cutout_h = self.candidates[index] else: cutout_w = int(self.candidates[index][0] * w) cutout_h = int(self.candidates[index][1] * h)
x2 = np.clip(x1 + cutout_w, 0, w) y2 = np.clip(y1 + cutout_h, 0, h) results['img'][y1:y2, x1:x2, :] = self.fill_in
if self.seg_fill_in is not None: for key in results.get('seg_fields', []): results[key][y1:y2, x1:x2] = self.seg_fill_in
return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(prob={self.prob}, ' repr_str += f'n_holes={self.n_holes}, ' repr_str += (f'cutout_ratio={self.candidates}, ' if self.with_ratio else f'cutout_shape={self.candidates}, ') repr_str += f'fill_in={self.fill_in}, ' repr_str += f'seg_fill_in={self.seg_fill_in})' return repr_str
@TRANSFORMS.register_module()class RandomRotFlip(BaseTransform): """Rotate and flip the image & seg or just rotate the image & seg.
Required Keys:
- img - gt_seg_map
Modified Keys:
- img - gt_seg_map
Args: rotate_prob (float): The probability of rotate image. flip_prob (float): The probability of rotate&flip image. degree (float, tuple[float]): Range of degrees to select from. If degree is a number instead of tuple like (min, max), the range of degree will be (``-degree``, ``+degree``) """
def __init__(self, rotate_prob=0.5, flip_prob=0.5, degree=(-20, 20)): self.rotate_prob = rotate_prob self.flip_prob = flip_prob assert 0 <= rotate_prob <= 1 and 0 <= flip_prob <= 1 if isinstance(degree, (float, int)): assert degree > 0, f'degree {degree} should be positive' self.degree = (-degree, degree) else: self.degree = degree assert len(self.degree) == 2, f'degree {self.degree} should be a ' \ f'tuple of (min, max)'
def random_rot_flip(self, results: dict) -> dict: k = np.random.randint(0, 4) results['img'] = np.rot90(results['img'], k) for key in results.get('seg_fields', []): results[key] = np.rot90(results[key], k) axis = np.random.randint(0, 2) results['img'] = np.flip(results['img'], axis=axis).copy() for key in results.get('seg_fields', []): results[key] = np.flip(results[key], axis=axis).copy() return results
def random_rotate(self, results: dict) -> dict: angle = np.random.uniform(min(*self.degree), max(*self.degree)) results['img'] = mmcv.imrotate(results['img'], angle=angle) for key in results.get('seg_fields', []): results[key] = mmcv.imrotate(results[key], angle=angle) return results
def transform(self, results: dict) -> dict: """Call function to rotate or rotate & flip image, semantic segmentation maps.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Rotated or rotated & flipped results. """ rotate_flag = 0 if random.random() < self.rotate_prob: results = self.random_rotate(results) rotate_flag = 1 if random.random() < self.flip_prob and rotate_flag == 0: results = self.random_rot_flip(results) return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(rotate_prob={self.rotate_prob}, ' \ f'flip_prob={self.flip_prob}, ' \ f'degree={self.degree})' return repr_str
@TRANSFORMS.register_module()class RandomFlip(MMCV_RandomFlip): """Flip the image & bbox & segmentation map. Added or Updated keys: flip, flip_direction, img, gt_bboxes, gt_seg_map, and gt_depth_map. There are 3 flip modes:
- ``prob`` is float, ``direction`` is string: the image will be ``direction``ly flipped with probability of ``prob`` . E.g., ``prob=0.5``, ``direction='horizontal'``, then image will be horizontally flipped with probability of 0.5.
- ``prob`` is float, ``direction`` is list of string: the image will be ``direction[i]``ly flipped with probability of ``prob/len(direction)``. E.g., ``prob=0.5``, ``direction=['horizontal', 'vertical']``, then image will be horizontally flipped with probability of 0.25, vertically with probability of 0.25.
- ``prob`` is list of float, ``direction`` is list of string: given ``len(prob) == len(direction)``, the image will be ``direction[i]``ly flipped with probability of ``prob[i]``. E.g., ``prob=[0.3, 0.5]``, ``direction=['horizontal', 'vertical']``, then image will be horizontally flipped with probability of 0.3, vertically with probability of 0.5.
Required Keys:
- img - gt_bboxes (optional) - gt_seg_map (optional) - gt_depth_map (optional)
Modified Keys:
- img - gt_bboxes (optional) - gt_seg_map (optional) - gt_depth_map (optional)
Added Keys:
- flip - flip_direction - swap_seg_labels (optional)
Args: prob (float | list[float], optional): The flipping probability. Defaults to None. direction(str | list[str]): The flipping direction. Options If input is a list, the length must equal ``prob``. Each element in ``prob`` indicates the flip probability of corresponding direction. Defaults to 'horizontal'. swap_seg_labels (list, optional): The label pair need to be swapped for ground truth, like 'left arm' and 'right arm' need to be swapped after horizontal flipping. For example, ``[(1, 5)]``, where 1/5 is the label of the left/right arm. Defaults to None. """
def _flip(self, results: dict) -> None: """Flip images, bounding boxes and semantic segmentation map.""" # flip image results['img'] = mmcv.imflip( results['img'], direction=results['flip_direction'])
img_shape = results['img'].shape[:2]
# flip bboxes if results.get('gt_bboxes', None) is not None: results['gt_bboxes'] = self._flip_bbox(results['gt_bboxes'], img_shape, results['flip_direction'])
# flip seg map for key in results.get('seg_fields', []): if results.get(key, None) is not None: results[key] = self._flip_seg_map( results[key], direction=results['flip_direction']).copy() results['swap_seg_labels'] = self.swap_seg_labels
@TRANSFORMS.register_module()class Resize(MMCV_Resize): """Resize images & seg & depth map.
This transform resizes the input image according to ``scale`` or ``scale_factor``. Seg map, depth map and other relative annotations are then resized with the same scale factor. if ``scale`` and ``scale_factor`` are both set, it will use ``scale`` to resize.
Required Keys:
- img - gt_seg_map (optional) - gt_depth_map (optional)
Modified Keys:
- img - gt_seg_map - gt_depth_map
Added Keys:
- scale - scale_factor - keep_ratio
Args: scale (int or tuple): Images scales for resizing. Defaults to None scale_factor (float or tuple[float]): Scale factors for resizing. Defaults to None. keep_ratio (bool): Whether to keep the aspect ratio when resizing the image. Defaults to False. clip_object_border (bool): Whether to clip the objects outside the border of the image. In some dataset like MOT17, the gt bboxes are allowed to cross the border of images. Therefore, we don't need to clip the gt bboxes in these cases. Defaults to True. backend (str): Image resize backend, choices are 'cv2' and 'pillow'. These two backends generates slightly different results. Defaults to 'cv2'. interpolation (str): Interpolation method, accepted values are "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' backend, "nearest", "bilinear" for 'pillow' backend. Defaults to 'bilinear'. """
def _resize_seg(self, results: dict) -> None: """Resize semantic segmentation map with ``results['scale']``.""" for seg_key in results.get('seg_fields', []): if results.get(seg_key, None) is not None: if self.keep_ratio: gt_seg = mmcv.imrescale( results[seg_key], results['scale'], interpolation='nearest', backend=self.backend) else: gt_seg = mmcv.imresize( results[seg_key], results['scale'], interpolation='nearest', backend=self.backend) results[seg_key] = gt_seg
@TRANSFORMS.register_module()class RandomMosaic(BaseTransform): """Mosaic augmentation. Given 4 images, mosaic transform combines them into one output image. The output image is composed of the parts from each sub- image.
.. code:: text
mosaic transform center_x +------------------------------+ | pad | pad | | +-----------+ | | | | | | | image1 |--------+ | | | | | | | | | image2 | | center_y |----+-------------+-----------| | | cropped | | |pad | image3 | image4 | | | | | +----|-------------+-----------+ | | +-------------+
The mosaic transform steps are as follows: 1. Choose the mosaic center as the intersections of 4 images 2. Get the left top image according to the index, and randomly sample another 3 images from the custom dataset. 3. Sub image will be cropped if image is larger than mosaic patch
Required Keys:
- img - gt_seg_map - mix_results
Modified Keys:
- img - img_shape - ori_shape - gt_seg_map
Args: prob (float): mosaic probability. img_scale (Sequence[int]): Image size after mosaic pipeline of a single image. The size of the output image is four times that of a single image. The output image comprises 4 single images. Default: (640, 640). center_ratio_range (Sequence[float]): Center ratio range of mosaic output. Default: (0.5, 1.5). pad_val (int): Pad value. Default: 0. seg_pad_val (int): Pad value of segmentation map. Default: 255. """
def __init__(self, prob, img_scale=(640, 640), center_ratio_range=(0.5, 1.5), pad_val=0, seg_pad_val=255): assert 0 <= prob and prob <= 1 assert isinstance(img_scale, tuple) self.prob = prob self.img_scale = img_scale self.center_ratio_range = center_ratio_range self.pad_val = pad_val self.seg_pad_val = seg_pad_val
@cache_randomness def do_mosaic(self): return np.random.rand() < self.prob
def transform(self, results: dict) -> dict: """Call function to make a mosaic of image.
Args: results (dict): Result dict.
Returns: dict: Result dict with mosaic transformed. """ mosaic = self.do_mosaic() if mosaic: results = self._mosaic_transform_img(results) results = self._mosaic_transform_seg(results) return results
def get_indices(self, dataset: MultiImageMixDataset) -> list: """Call function to collect indices.
Args: dataset (:obj:`MultiImageMixDataset`): The dataset.
Returns: list: indices. """
indices = [random.randint(0, len(dataset)) for _ in range(3)] return indices
@cache_randomness def generate_mosaic_center(self): # mosaic center x, y center_x = int( random.uniform(*self.center_ratio_range) * self.img_scale[1]) center_y = int( random.uniform(*self.center_ratio_range) * self.img_scale[0]) return center_x, center_y
def _mosaic_transform_img(self, results: dict) -> dict: """Mosaic transform function.
Args: results (dict): Result dict.
Returns: dict: Updated result dict. """
assert 'mix_results' in results if len(results['img'].shape) == 3: c = results['img'].shape[2] mosaic_img = np.full( (int(self.img_scale[0] * 2), int(self.img_scale[1] * 2), c), self.pad_val, dtype=results['img'].dtype) else: mosaic_img = np.full( (int(self.img_scale[0] * 2), int(self.img_scale[1] * 2)), self.pad_val, dtype=results['img'].dtype)
# mosaic center x, y self.center_x, self.center_y = self.generate_mosaic_center() center_position = (self.center_x, self.center_y)
loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right') for i, loc in enumerate(loc_strs): if loc == 'top_left': result_patch = copy.deepcopy(results) else: result_patch = copy.deepcopy(results['mix_results'][i - 1])
img_i = result_patch['img'] h_i, w_i = img_i.shape[:2] # keep_ratio resize scale_ratio_i = min(self.img_scale[0] / h_i, self.img_scale[1] / w_i) img_i = mmcv.imresize( img_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i)))
# compute the combine parameters paste_coord, crop_coord = self._mosaic_combine( loc, center_position, img_i.shape[:2][::-1]) x1_p, y1_p, x2_p, y2_p = paste_coord x1_c, y1_c, x2_c, y2_c = crop_coord
# crop and paste image mosaic_img[y1_p:y2_p, x1_p:x2_p] = img_i[y1_c:y2_c, x1_c:x2_c]
results['img'] = mosaic_img results['img_shape'] = mosaic_img.shape results['ori_shape'] = mosaic_img.shape
return results
def _mosaic_transform_seg(self, results: dict) -> dict: """Mosaic transform function for label annotations.
Args: results (dict): Result dict.
Returns: dict: Updated result dict. """
assert 'mix_results' in results for key in results.get('seg_fields', []): mosaic_seg = np.full( (int(self.img_scale[0] * 2), int(self.img_scale[1] * 2)), self.seg_pad_val, dtype=results[key].dtype)
# mosaic center x, y center_position = (self.center_x, self.center_y)
loc_strs = ('top_left', 'top_right', 'bottom_left', 'bottom_right') for i, loc in enumerate(loc_strs): if loc == 'top_left': result_patch = copy.deepcopy(results) else: result_patch = copy.deepcopy(results['mix_results'][i - 1])
gt_seg_i = result_patch[key] h_i, w_i = gt_seg_i.shape[:2] # keep_ratio resize scale_ratio_i = min(self.img_scale[0] / h_i, self.img_scale[1] / w_i) gt_seg_i = mmcv.imresize( gt_seg_i, (int(w_i * scale_ratio_i), int(h_i * scale_ratio_i)), interpolation='nearest')
# compute the combine parameters paste_coord, crop_coord = self._mosaic_combine( loc, center_position, gt_seg_i.shape[:2][::-1]) x1_p, y1_p, x2_p, y2_p = paste_coord x1_c, y1_c, x2_c, y2_c = crop_coord
# crop and paste image mosaic_seg[y1_p:y2_p, x1_p:x2_p] = \ gt_seg_i[y1_c:y2_c, x1_c:x2_c]
results[key] = mosaic_seg
return results
def _mosaic_combine(self, loc: str, center_position_xy: Sequence[float], img_shape_wh: Sequence[int]) -> tuple: """Calculate global coordinate of mosaic image and local coordinate of cropped sub-image.
Args: loc (str): Index for the sub-image, loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right'). center_position_xy (Sequence[float]): Mixing center for 4 images, (x, y). img_shape_wh (Sequence[int]): Width and height of sub-image
Returns: tuple[tuple[float]]: Corresponding coordinate of pasting and cropping - paste_coord (tuple): paste corner coordinate in mosaic image. - crop_coord (tuple): crop corner coordinate in mosaic image. """
assert loc in ('top_left', 'top_right', 'bottom_left', 'bottom_right') if loc == 'top_left': # index0 to top left part of image x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ max(center_position_xy[1] - img_shape_wh[1], 0), \ center_position_xy[0], \ center_position_xy[1] crop_coord = img_shape_wh[0] - (x2 - x1), img_shape_wh[1] - ( y2 - y1), img_shape_wh[0], img_shape_wh[1]
elif loc == 'top_right': # index1 to top right part of image x1, y1, x2, y2 = center_position_xy[0], \ max(center_position_xy[1] - img_shape_wh[1], 0), \ min(center_position_xy[0] + img_shape_wh[0], self.img_scale[1] * 2), \ center_position_xy[1] crop_coord = 0, img_shape_wh[1] - (y2 - y1), min( img_shape_wh[0], x2 - x1), img_shape_wh[1]
elif loc == 'bottom_left': # index2 to bottom left part of image x1, y1, x2, y2 = max(center_position_xy[0] - img_shape_wh[0], 0), \ center_position_xy[1], \ center_position_xy[0], \ min(self.img_scale[0] * 2, center_position_xy[1] + img_shape_wh[1]) crop_coord = img_shape_wh[0] - (x2 - x1), 0, img_shape_wh[0], min( y2 - y1, img_shape_wh[1])
else: # index3 to bottom right part of image x1, y1, x2, y2 = center_position_xy[0], \ center_position_xy[1], \ min(center_position_xy[0] + img_shape_wh[0], self.img_scale[1] * 2), \ min(self.img_scale[0] * 2, center_position_xy[1] + img_shape_wh[1]) crop_coord = 0, 0, min(img_shape_wh[0], x2 - x1), min(y2 - y1, img_shape_wh[1])
paste_coord = x1, y1, x2, y2 return paste_coord, crop_coord
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(prob={self.prob}, ' repr_str += f'img_scale={self.img_scale}, ' repr_str += f'center_ratio_range={self.center_ratio_range}, ' repr_str += f'pad_val={self.pad_val}, ' repr_str += f'seg_pad_val={self.pad_val})' return repr_str
@TRANSFORMS.register_module()class GenerateEdge(BaseTransform): """Generate Edge for CE2P approach.
Edge will be used to calculate loss of `CE2P <https://arxiv.org/abs/1809.05996>`_.
Modified from https://github.com/liutinglt/CE2P/blob/master/dataset/target_generation.py # noqa:E501
Required Keys:
- img_shape - gt_seg_map
Added Keys: - gt_edge_map (np.ndarray, uint8): The edge annotation generated from the seg map by extracting border between different semantics.
Args: edge_width (int): The width of edge. Default to 3. ignore_index (int): Index that will be ignored. Default to 255. """
def __init__(self, edge_width: int = 3, ignore_index: int = 255) -> None: super().__init__() self.edge_width = edge_width self.ignore_index = ignore_index
def transform(self, results: Dict) -> Dict: """Call function to generate edge from segmentation map.
Args: results (dict): Result dict.
Returns: dict: Result dict with edge mask. """ h, w = results['img_shape'] edge = np.zeros((h, w), dtype=np.uint8) seg_map = results['gt_seg_map']
# down edge_down = edge[1:h, :] edge_down[(seg_map[1:h, :] != seg_map[:h - 1, :]) & (seg_map[1:h, :] != self.ignore_index) & (seg_map[:h - 1, :] != self.ignore_index)] = 1 # left edge_left = edge[:, :w - 1] edge_left[(seg_map[:, :w - 1] != seg_map[:, 1:w]) & (seg_map[:, :w - 1] != self.ignore_index) & (seg_map[:, 1:w] != self.ignore_index)] = 1 # up_left edge_upleft = edge[:h - 1, :w - 1] edge_upleft[(seg_map[:h - 1, :w - 1] != seg_map[1:h, 1:w]) & (seg_map[:h - 1, :w - 1] != self.ignore_index) & (seg_map[1:h, 1:w] != self.ignore_index)] = 1 # up_right edge_upright = edge[:h - 1, 1:w] edge_upright[(seg_map[:h - 1, 1:w] != seg_map[1:h, :w - 1]) & (seg_map[:h - 1, 1:w] != self.ignore_index) & (seg_map[1:h, :w - 1] != self.ignore_index)] = 1
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (self.edge_width, self.edge_width)) edge = cv2.dilate(edge, kernel)
results['gt_edge_map'] = edge results['edge_width'] = self.edge_width
return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'edge_width={self.edge_width}, ' repr_str += f'ignore_index={self.ignore_index})' return repr_str
@TRANSFORMS.register_module()class ResizeShortestEdge(BaseTransform): """Resize the image and mask while keeping the aspect ratio unchanged.
Modified from https://github.com/facebookresearch/detectron2/blob/main/detectron2/data/transforms/augmentation_impl.py#L130 # noqa:E501 Copyright (c) Facebook, Inc. and its affiliates. Licensed under the Apache-2.0 License
This transform attempts to scale the shorter edge to the given `scale`, as long as the longer edge does not exceed `max_size`. If `max_size` is reached, then downscale so that the longer edge does not exceed `max_size`.
Required Keys:
- img - gt_seg_map (optional)
Modified Keys:
- img - img_shape - gt_seg_map (optional))
Added Keys:
- scale - scale_factor - keep_ratio
Args: scale (Union[int, Tuple[int, int]]): The target short edge length. If it's tuple, will select the min value as the short edge length. max_size (int): The maximum allowed longest edge length. """
def __init__(self, scale: Union[int, Tuple[int, int]], max_size: int) -> None: super().__init__() self.scale = scale self.max_size = max_size
# Create a empty Resize object self.resize = TRANSFORMS.build({ 'type': 'Resize', 'scale': 0, 'keep_ratio': True })
def _get_output_shape(self, img, short_edge_length) -> Tuple[int, int]: """Compute the target image shape with the given `short_edge_length`.
Args: img (np.ndarray): The input image. short_edge_length (Union[int, Tuple[int, int]]): The target short edge length. If it's tuple, will select the min value as the short edge length. """ h, w = img.shape[:2] if isinstance(short_edge_length, int): size = short_edge_length * 1.0 elif isinstance(short_edge_length, tuple): size = min(short_edge_length) * 1.0 scale = size / min(h, w) if h < w: new_h, new_w = size, scale * w else: new_h, new_w = scale * h, size
if max(new_h, new_w) > self.max_size: scale = self.max_size * 1.0 / max(new_h, new_w) new_h *= scale new_w *= scale
new_h = int(new_h + 0.5) new_w = int(new_w + 0.5) return (new_w, new_h)
def transform(self, results: Dict) -> Dict: self.resize.scale = self._get_output_shape(results['img'], self.scale) return self.resize(results)
@TRANSFORMS.register_module()class BioMedical3DRandomCrop(BaseTransform): """Crop the input patch for medical image & segmentation mask.
Required Keys:
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X), N is the number of modalities, and data type is float32. - gt_seg_map (np.ndarray, optional): Biomedical semantic segmentation mask with shape (Z, Y, X).
Modified Keys:
- img - img_shape - gt_seg_map (optional)
Args: crop_shape (Union[int, Tuple[int, int, int]]): Expected size after cropping with the format of (z, y, x). If set to an integer, then cropping width and height are equal to this integer. keep_foreground (bool): If keep_foreground is True, it will sample a voxel of foreground classes randomly, and will take it as the center of the crop bounding-box. Default to True. """
def __init__(self, crop_shape: Union[int, Tuple[int, int, int]], keep_foreground: bool = True): super().__init__() assert isinstance(crop_shape, int) or ( isinstance(crop_shape, tuple) and len(crop_shape) == 3 ), 'The expected crop_shape is an integer, or a tuple containing ' 'three integers'
if isinstance(crop_shape, int): crop_shape = (crop_shape, crop_shape, crop_shape) assert crop_shape[0] > 0 and crop_shape[1] > 0 and crop_shape[2] > 0 self.crop_shape = crop_shape self.keep_foreground = keep_foreground
def random_sample_location(self, seg_map: np.ndarray) -> dict: """sample foreground voxel when keep_foreground is True.
Args: seg_map (np.ndarray): gt seg map.
Returns: dict: Coordinates of selected foreground voxel. """ num_samples = 10000 # at least 1% of the class voxels need to be selected, # otherwise it may be too sparse min_percent_coverage = 0.01 class_locs = {} foreground_classes = [] all_classes = np.unique(seg_map) for c in all_classes: if c == 0: # to avoid the segmentation mask full of background 0 # and the class_locs is just void dictionary {} when it return # there add a void list for background 0. class_locs[c] = [] else: all_locs = np.argwhere(seg_map == c) target_num_samples = min(num_samples, len(all_locs)) target_num_samples = max( target_num_samples, int(np.ceil(len(all_locs) * min_percent_coverage)))
selected = all_locs[np.random.choice( len(all_locs), target_num_samples, replace=False)] class_locs[c] = selected foreground_classes.append(c)
selected_voxel = None if len(foreground_classes) > 0: selected_class = np.random.choice(foreground_classes) voxels_of_that_class = class_locs[selected_class] selected_voxel = voxels_of_that_class[np.random.choice( len(voxels_of_that_class))]
return selected_voxel
def random_generate_crop_bbox(self, margin_z: int, margin_y: int, margin_x: int) -> tuple: """Randomly get a crop bounding box.
Args: seg_map (np.ndarray): Ground truth segmentation map.
Returns: tuple: Coordinates of the cropped image. """ offset_z = np.random.randint(0, margin_z + 1) offset_y = np.random.randint(0, margin_y + 1) offset_x = np.random.randint(0, margin_x + 1) crop_z1, crop_z2 = offset_z, offset_z + self.crop_shape[0] crop_y1, crop_y2 = offset_y, offset_y + self.crop_shape[1] crop_x1, crop_x2 = offset_x, offset_x + self.crop_shape[2]
return crop_z1, crop_z2, crop_y1, crop_y2, crop_x1, crop_x2
def generate_margin(self, results: dict) -> tuple: """Generate margin of crop bounding-box.
If keep_foreground is True, it will sample a voxel of foreground classes randomly, and will take it as the center of the bounding-box, and return the margin between of the bounding-box and image. If keep_foreground is False, it will return the difference from crop shape and image shape.
Args: results (dict): Result dict from loading pipeline.
Returns: tuple: The margin for 3 dimensions of crop bounding-box and image. """
seg_map = results['gt_seg_map'] if self.keep_foreground: selected_voxel = self.random_sample_location(seg_map) if selected_voxel is None: # this only happens if some image does not contain # foreground voxels at all warnings.warn(f'case does not contain any foreground classes' f': {results["img_path"]}') margin_z = max(seg_map.shape[0] - self.crop_shape[0], 0) margin_y = max(seg_map.shape[1] - self.crop_shape[1], 0) margin_x = max(seg_map.shape[2] - self.crop_shape[2], 0) else: margin_z = max(0, selected_voxel[0] - self.crop_shape[0] // 2) margin_y = max(0, selected_voxel[1] - self.crop_shape[1] // 2) margin_x = max(0, selected_voxel[2] - self.crop_shape[2] // 2) margin_z = max( 0, min(seg_map.shape[0] - self.crop_shape[0], margin_z)) margin_y = max( 0, min(seg_map.shape[1] - self.crop_shape[1], margin_y)) margin_x = max( 0, min(seg_map.shape[2] - self.crop_shape[2], margin_x)) else: margin_z = max(seg_map.shape[0] - self.crop_shape[0], 0) margin_y = max(seg_map.shape[1] - self.crop_shape[1], 0) margin_x = max(seg_map.shape[2] - self.crop_shape[2], 0)
return margin_z, margin_y, margin_x
def crop(self, img: np.ndarray, crop_bbox: tuple) -> np.ndarray: """Crop from ``img``
Args: img (np.ndarray): Original input image. crop_bbox (tuple): Coordinates of the cropped image.
Returns: np.ndarray: The cropped image. """ crop_z1, crop_z2, crop_y1, crop_y2, crop_x1, crop_x2 = crop_bbox if len(img.shape) == 3: # crop seg map img = img[crop_z1:crop_z2, crop_y1:crop_y2, crop_x1:crop_x2] else: # crop image assert len(img.shape) == 4 img = img[:, crop_z1:crop_z2, crop_y1:crop_y2, crop_x1:crop_x2] return img
def transform(self, results: dict) -> dict: """Transform function to randomly crop images, semantic segmentation maps.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Randomly cropped results, 'img_shape' key in result dict is updated according to crop size. """ margin = self.generate_margin(results) crop_bbox = self.random_generate_crop_bbox(*margin)
# crop the image img = results['img'] results['img'] = self.crop(img, crop_bbox) results['img_shape'] = results['img'].shape[1:]
# crop semantic seg seg_map = results['gt_seg_map'] results['gt_seg_map'] = self.crop(seg_map, crop_bbox)
return results
def __repr__(self): return self.__class__.__name__ + f'(crop_shape={self.crop_shape})'
@TRANSFORMS.register_module()class BioMedicalGaussianNoise(BaseTransform): """Add random Gaussian noise to image.
Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/transforms/noise_transforms.py#L53 # noqa:E501
Copyright (c) German Cancer Research Center (DKFZ) Licensed under the Apache License, Version 2.0
Required Keys:
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X), N is the number of modalities, and data type is float32.
Modified Keys:
- img
Args: prob (float): Probability to add Gaussian noise for each sample. Default to 0.1. mean (float): Mean or “centre” of the distribution. Default to 0.0. std (float): Standard deviation of distribution. Default to 0.1. """
def __init__(self, prob: float = 0.1, mean: float = 0.0, std: float = 0.1) -> None: super().__init__() assert 0.0 <= prob <= 1.0 and std >= 0.0 self.prob = prob self.mean = mean self.std = std
def transform(self, results: Dict) -> Dict: """Call function to add random Gaussian noise to image.
Args: results (dict): Result dict.
Returns: dict: Result dict with random Gaussian noise. """ if np.random.rand() < self.prob: rand_std = np.random.uniform(0, self.std) noise = np.random.normal( self.mean, rand_std, size=results['img'].shape) # noise is float64 array, convert to the results['img'].dtype noise = noise.astype(results['img'].dtype) results['img'] = results['img'] + noise return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(prob={self.prob}, ' repr_str += f'mean={self.mean}, ' repr_str += f'std={self.std})' return repr_str
@TRANSFORMS.register_module()class BioMedicalGaussianBlur(BaseTransform): """Add Gaussian blur with random sigma to image.
Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/transforms/noise_transforms.py#L81 # noqa:E501
Copyright (c) German Cancer Research Center (DKFZ) Licensed under the Apache License, Version 2.0
Required Keys:
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X), N is the number of modalities, and data type is float32.
Modified Keys:
- img
Args: sigma_range (Tuple[float, float]|float): range to randomly select sigma value. Default to (0.5, 1.0). prob (float): Probability to apply Gaussian blur for each sample. Default to 0.2. prob_per_channel (float): Probability to apply Gaussian blur for each channel (axis N of the image). Default to 0.5. different_sigma_per_channel (bool): whether to use different sigma for each channel (axis N of the image). Default to True. different_sigma_per_axis (bool): whether to use different sigma for axis Z, X and Y of the image. Default to True. """
def __init__(self, sigma_range: Tuple[float, float] = (0.5, 1.0), prob: float = 0.2, prob_per_channel: float = 0.5, different_sigma_per_channel: bool = True, different_sigma_per_axis: bool = True) -> None: super().__init__() assert 0.0 <= prob <= 1.0 assert 0.0 <= prob_per_channel <= 1.0 assert isinstance(sigma_range, Sequence) and len(sigma_range) == 2 self.sigma_range = sigma_range self.prob = prob self.prob_per_channel = prob_per_channel self.different_sigma_per_channel = different_sigma_per_channel self.different_sigma_per_axis = different_sigma_per_axis
def _get_valid_sigma(self, value_range) -> Tuple[float, ...]: """Ensure the `value_range` to be either a single value or a sequence of two values. If the `value_range` is a sequence, generate a random value with `[value_range[0], value_range[1]]` based on uniform sampling.
Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/7651ece69faf55263dd582a9f5cbd149ed9c3ad0/batchgenerators/augmentations/utils.py#L625 # noqa:E501
Args: value_range (tuple|list|float|int): the input value range """ if (isinstance(value_range, (list, tuple))): if (value_range[0] == value_range[1]): value = value_range[0] else: orig_type = type(value_range[0]) value = np.random.uniform(value_range[0], value_range[1]) value = orig_type(value) return value
def _gaussian_blur(self, data_sample: np.ndarray) -> np.ndarray: """Random generate sigma and apply Gaussian Blur to the data Args: data_sample (np.ndarray): data sample with multiple modalities, the data shape is (N, Z, Y, X) """ sigma = None for c in range(data_sample.shape[0]): if np.random.rand() < self.prob_per_channel: # if no `sigma` is generated, generate one # if `self.different_sigma_per_channel` is True, # re-generate random sigma for each channel if (sigma is None or self.different_sigma_per_channel): if (not self.different_sigma_per_axis): sigma = self._get_valid_sigma(self.sigma_range) else: sigma = [ self._get_valid_sigma(self.sigma_range) for _ in data_sample.shape[1:] ] # apply gaussian filter with `sigma` data_sample[c] = gaussian_filter( data_sample[c], sigma, order=0) return data_sample
def transform(self, results: Dict) -> Dict: """Call function to add random Gaussian blur to image.
Args: results (dict): Result dict.
Returns: dict: Result dict with random Gaussian noise. """ if np.random.rand() < self.prob: results['img'] = self._gaussian_blur(results['img']) return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(prob={self.prob}, ' repr_str += f'prob_per_channel={self.prob_per_channel}, ' repr_str += f'sigma_range={self.sigma_range}, ' repr_str += 'different_sigma_per_channel=' \ f'{self.different_sigma_per_channel}, ' repr_str += 'different_sigma_per_axis=' \ f'{self.different_sigma_per_axis})' return repr_str
@TRANSFORMS.register_module()class BioMedicalRandomGamma(BaseTransform): """Using random gamma correction to process the biomedical image.
Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/master/batchgenerators/transforms/color_transforms.py#L132 # noqa:E501 With licence: Apache 2.0
Required Keys:
- img (np.ndarray): Biomedical image with shape (N, Z, Y, X), N is the number of modalities, and data type is float32.
Modified Keys: - img
Args: prob (float): The probability to perform this transform. Default: 0.5. gamma_range (Tuple[float]): Range of gamma values. Default: (0.5, 2). invert_image (bool): Whether invert the image before applying gamma augmentation. Default: False. per_channel (bool): Whether perform the transform each channel individually. Default: False retain_stats (bool): Gamma transformation will alter the mean and std of the data in the patch. If retain_stats=True, the data will be transformed to match the mean and standard deviation before gamma augmentation. Default: False. """
def __init__(self, prob: float = 0.5, gamma_range: Tuple[float] = (0.5, 2), invert_image: bool = False, per_channel: bool = False, retain_stats: bool = False): assert 0 <= prob and prob <= 1 assert isinstance(gamma_range, tuple) and len(gamma_range) == 2 assert isinstance(invert_image, bool) assert isinstance(per_channel, bool) assert isinstance(retain_stats, bool) self.prob = prob self.gamma_range = gamma_range self.invert_image = invert_image self.per_channel = per_channel self.retain_stats = retain_stats
@cache_randomness def _do_gamma(self): """Whether do adjust gamma for image.""" return np.random.rand() < self.prob
def _adjust_gamma(self, img: np.array): """Gamma adjustment for image.
Args: img (np.array): Input image before gamma adjust.
Returns: np.arrays: Image after gamma adjust. """
if self.invert_image: img = -img
def _do_adjust(img): if retain_stats_here: img_mean = img.mean() img_std = img.std() if np.random.random() < 0.5 and self.gamma_range[0] < 1: gamma = np.random.uniform(self.gamma_range[0], 1) else: gamma = np.random.uniform( max(self.gamma_range[0], 1), self.gamma_range[1]) img_min = img.min() img_range = img.max() - img_min # range img = np.power(((img - img_min) / float(img_range + 1e-7)), gamma) * img_range + img_min if retain_stats_here: img = img - img.mean() img = img / (img.std() + 1e-8) * img_std img = img + img_mean return img
if not self.per_channel: retain_stats_here = self.retain_stats img = _do_adjust(img) else: for c in range(img.shape[0]): img[c] = _do_adjust(img[c]) if self.invert_image: img = -img return img
def transform(self, results: dict) -> dict: """Call function to perform random gamma correction Args: results (dict): Result dict from loading pipeline.
Returns: dict: Result dict with random gamma correction performed. """ do_gamma = self._do_gamma()
if do_gamma: results['img'] = self._adjust_gamma(results['img']) else: pass return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(prob={self.prob}, ' repr_str += f'gamma_range={self.gamma_range},' repr_str += f'invert_image={self.invert_image},' repr_str += f'per_channel={self.per_channel},' repr_str += f'retain_stats={self.retain_stats}' return repr_str
@TRANSFORMS.register_module()class BioMedical3DPad(BaseTransform): """Pad the biomedical 3d image & biomedical 3d semantic segmentation maps.
Required Keys:
- img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default, N is the number of modalities. - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape (Z, Y, X) by default.
Modified Keys:
- img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default, N is the number of modalities. - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape (Z, Y, X) by default.
Added Keys:
- pad_shape (Tuple[int, int, int]): The padded shape.
Args: pad_shape (Tuple[int, int, int]): Fixed padding size. Expected padding shape (Z, Y, X). pad_val (float): Padding value for biomedical image. The padding mode is set to "constant". The value to be filled in padding area. Default: 0. seg_pad_val (int): Padding value for biomedical 3d semantic segmentation maps. The padding mode is set to "constant". The value to be filled in padding area. Default: 0. """
def __init__(self, pad_shape: Tuple[int, int, int], pad_val: float = 0., seg_pad_val: int = 0) -> None:
# check pad_shape assert pad_shape is not None if not isinstance(pad_shape, tuple): assert len(pad_shape) == 3
self.pad_shape = pad_shape self.pad_val = pad_val self.seg_pad_val = seg_pad_val
def _pad_img(self, results: dict) -> None: """Pad images according to ``self.pad_shape``
Args: results (dict): Result dict from loading pipeline.
Returns: dict: The dict contains the padded image and shape information. """ padded_img = self._to_pad( results['img'], pad_shape=self.pad_shape, pad_val=self.pad_val)
results['img'] = padded_img results['pad_shape'] = padded_img.shape[1:]
def _pad_seg(self, results: dict) -> None: """Pad semantic segmentation map according to ``self.pad_shape`` if ``gt_seg_map`` is not None in results dict.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Update the padded gt seg map in dict. """ if results.get('gt_seg_map', None) is not None: pad_gt_seg = self._to_pad( results['gt_seg_map'][None, ...], pad_shape=results['pad_shape'], pad_val=self.seg_pad_val) results['gt_seg_map'] = pad_gt_seg[1:]
@staticmethod def _to_pad(img: np.ndarray, pad_shape: Tuple[int, int, int], pad_val: Union[int, float] = 0) -> np.ndarray: """Pad the given 3d image to a certain shape with specified padding value.
Args: img (ndarray): Biomedical image with shape (N, Z, Y, X) to be padded. N is the number of modalities. pad_shape (Tuple[int,int,int]): Expected padding shape (Z, Y, X). pad_val (float, int): Values to be filled in padding areas and the padding_mode is set to 'constant'. Default: 0.
Returns: ndarray: The padded image. """ # compute pad width d = max(pad_shape[0] - img.shape[1], 0) pad_d = (d // 2, d - d // 2) h = max(pad_shape[1] - img.shape[2], 0) pad_h = (h // 2, h - h // 2) w = max(pad_shape[2] - img.shape[2], 0) pad_w = (w // 2, w - w // 2)
pad_list = [(0, 0), pad_d, pad_h, pad_w]
img = np.pad(img, pad_list, mode='constant', constant_values=pad_val) return img
def transform(self, results: dict) -> dict: """Call function to pad images, semantic segmentation maps.
Args: results (dict): Result dict from loading pipeline.
Returns: dict: Updated result dict. """ self._pad_img(results) self._pad_seg(results)
return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'pad_shape={self.pad_shape}, ' repr_str += f'pad_val={self.pad_val}), ' repr_str += f'seg_pad_val={self.seg_pad_val})' return repr_str
@TRANSFORMS.register_module()class BioMedical3DRandomFlip(BaseTransform): """Flip biomedical 3D images and segmentations.
Modified from https://github.com/MIC-DKFZ/batchgenerators/blob/master/batchgenerators/transforms/spatial_transforms.py # noqa:E501
Copyright 2021 Division of Medical Image Computing, German Cancer Research Center (DKFZ) and Applied Computer Vision Lab, Helmholtz Imaging Platform. Licensed under the Apache-2.0 License.
Required Keys:
- img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default, N is the number of modalities. - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape (Z, Y, X) by default.
Modified Keys:
- img (np.ndarry): Biomedical image with shape (N, Z, Y, X) by default, N is the number of modalities. - gt_seg_map (np.ndarray, optional): Biomedical seg map with shape (Z, Y, X) by default.
Added Keys:
- do_flip - flip_axes
Args: prob (float): Flipping probability. axes (Tuple[int, ...]): Flipping axes with order 'ZXY'. swap_label_pairs (Optional[List[Tuple[int, int]]]): The segmentation label pairs that are swapped when flipping. """
def __init__(self, prob: float, axes: Tuple[int, ...], swap_label_pairs: Optional[List[Tuple[int, int]]] = None): self.prob = prob self.axes = axes self.swap_label_pairs = swap_label_pairs assert prob >= 0 and prob <= 1 if axes is not None: assert max(axes) <= 2
@staticmethod def _flip(img, direction: Tuple[bool, bool, bool]) -> np.ndarray: if direction[0]: img[:, :] = img[:, ::-1] if direction[1]: img[:, :, :] = img[:, :, ::-1] if direction[2]: img[:, :, :, :] = img[:, :, :, ::-1] return img
def _do_flip(self, img: np.ndarray) -> Tuple[bool, bool, bool]: """Call function to determine which axis to flip.
Args: img (np.ndarry): Image or segmentation map array. Returns: tuple: Flip action, whether to flip on the z, x, and y axes. """ flip_c, flip_x, flip_y = False, False, False if self.axes is not None: flip_c = 0 in self.axes and np.random.rand() < self.prob flip_x = 1 in self.axes and np.random.rand() < self.prob if len(img.shape) == 4: flip_y = 2 in self.axes and np.random.rand() < self.prob return flip_c, flip_x, flip_y
def _swap_label(self, seg: np.ndarray) -> np.ndarray: out = seg.copy() for first, second in self.swap_label_pairs: first_area = (seg == first) second_area = (seg == second) out[first_area] = second out[second_area] = first return out
def transform(self, results: Dict) -> Dict: """Call function to flip and swap pair labels.
Args: results (dict): Result dict. Returns: dict: Flipped results, 'do_flip', 'flip_axes' keys are added into result dict. """ # get actual flipped axis if 'do_flip' not in results: results['do_flip'] = self._do_flip(results['img']) if 'flip_axes' not in results: results['flip_axes'] = self.axes # flip image results['img'] = self._flip( results['img'], direction=results['do_flip']) # flip seg if results['gt_seg_map'] is not None: if results['gt_seg_map'].shape != results['img'].shape: results['gt_seg_map'] = results['gt_seg_map'][None, :] results['gt_seg_map'] = self._flip( results['gt_seg_map'], direction=results['do_flip']) results['gt_seg_map'] = results['gt_seg_map'].squeeze() # swap label pairs if self.swap_label_pairs is not None: results['gt_seg_map'] = self._swap_label(results['gt_seg_map']) return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(prob={self.prob}, axes={self.axes}, ' \ f'swap_label_pairs={self.swap_label_pairs})' return repr_str
@TRANSFORMS.register_module()class Albu(BaseTransform): """Albumentation augmentation. Adds custom transformations from Albumentations library. Please, visit `https://albumentations.readthedocs.io` to get more information. An example of ``transforms`` is as followed:
.. code-block:: [ dict( type='ShiftScaleRotate', shift_limit=0.0625, scale_limit=0.0, rotate_limit=0, interpolation=1, p=0.5), dict( type='RandomBrightnessContrast', brightness_limit=[0.1, 0.3], contrast_limit=[0.1, 0.3], p=0.2), dict(type='ChannelShuffle', p=0.1), dict( type='OneOf', transforms=[ dict(type='Blur', blur_limit=3, p=1.0), dict(type='MedianBlur', blur_limit=3, p=1.0) ], p=0.1), ] Args: transforms (list[dict]): A list of albu transformations keymap (dict): Contains {'input key':'albumentation-style key'} additional_targets(dict): Allows applying same augmentations to \ multiple objects of same type. update_pad_shape (bool): Whether to update padding shape according to \ the output shape of the last transform bgr_to_rgb (bool): Whether to convert the band order to RGB """
def __init__(self, transforms: List[dict], keymap: Optional[dict] = None, additional_targets: Optional[dict] = None, update_pad_shape: bool = False, bgr_to_rgb: bool = True): if not ALBU_INSTALLED: raise ImportError( 'albumentations is not installed, ' 'we suggest install albumentation by ' '"pip install albumentations>=0.3.2 --no-binary qudida,albumentations"' # noqa )
# Args will be modified later, copying it will be safer transforms = copy.deepcopy(transforms)
self.transforms = transforms self.keymap = keymap self.additional_targets = additional_targets self.update_pad_shape = update_pad_shape self.bgr_to_rgb = bgr_to_rgb
self.aug = Compose([self.albu_builder(t) for t in self.transforms], additional_targets=self.additional_targets)
if not keymap: self.keymap_to_albu = {'img': 'image', 'gt_seg_map': 'mask'} else: self.keymap_to_albu = copy.deepcopy(keymap) self.keymap_back = {v: k for k, v in self.keymap_to_albu.items()}
def albu_builder(self, cfg: dict) -> object: """Build a callable object from a dict containing albu arguments.
Args: cfg (dict): Config dict. It should at least contain the key "type".
Returns: Callable: A callable object. """
assert isinstance(cfg, dict) and 'type' in cfg args = cfg.copy()
obj_type = args.pop('type') if mmengine.is_str(obj_type): if not ALBU_INSTALLED: raise ImportError( 'albumentations is not installed, ' 'we suggest install albumentation by ' '"pip install albumentations>=0.3.2 --no-binary qudida,albumentations"' # noqa ) obj_cls = getattr(albumentations, obj_type) elif inspect.isclass(obj_type): obj_cls = obj_type else: raise TypeError( f'type must be a valid type or str, but got {type(obj_type)}')
if 'transforms' in args: args['transforms'] = [ self.albu_builder(t) for t in args['transforms'] ]
return obj_cls(**args)
@staticmethod def mapper(d: dict, keymap: dict): """Dictionary mapper.
Renames keys according to keymap provided. Args: d (dict): old dict keymap (dict): {'old_key':'new_key'} Returns: dict: new dict. """
updated_dict = {} for k, _ in zip(d.keys(), d.values()): new_k = keymap.get(k, k) updated_dict[new_k] = d[k] return updated_dict
def transform(self, results): # dict to albumentations format results = self.mapper(results, self.keymap_to_albu)
# Convert to RGB since Albumentations works with RGB images if self.bgr_to_rgb: results['image'] = cv2.cvtColor(results['image'], cv2.COLOR_BGR2RGB) if self.additional_targets: for key, value in self.additional_targets.items(): if value == 'image': results[key] = cv2.cvtColor(results[key], cv2.COLOR_BGR2RGB)
# Apply Transform results = self.aug(**results)
# Convert back to BGR if self.bgr_to_rgb: results['image'] = cv2.cvtColor(results['image'], cv2.COLOR_RGB2BGR) if self.additional_targets: for key, value in self.additional_targets.items(): if value == 'image': results[key] = cv2.cvtColor(results['image2'], cv2.COLOR_RGB2BGR)
# back to the original format results = self.mapper(results, self.keymap_back)
# update final shape if self.update_pad_shape: results['pad_shape'] = results['img'].shape
return results
def __repr__(self): repr_str = self.__class__.__name__ + f'(transforms={self.transforms})' return repr_str
@TRANSFORMS.register_module()class ConcatCDInput(BaseTransform): """Concat images for change detection.
Required Keys:
- img - img2
Args: input_keys (tuple): Input image keys for change detection. Default: ('img', 'img2'). """
def __init__(self, input_keys=('img', 'img2')): self.input_keys = input_keys
def transform(self, results: dict) -> dict: img = [] for input_key in self.input_keys: img.append(results.pop(input_key)) results['img'] = np.concatenate(img, axis=2) return results
def __repr__(self): repr_str = self.__class__.__name__ repr_str += f'(input_keys={self.input_keys}, ' return repr_str
@TRANSFORMS.register_module()class RandomDepthMix(BaseTransform): """This class implements the RandomDepthMix transform.
Args: prob (float): Probability of applying the transformation. Defaults to 0.25. mix_scale_ratio (float): Ratio to scale the mix width. Defaults to 0.75. """
def __init__( self, prob: float = 0.25, mix_scale_ratio: float = 0.75, ): super().__init__()
self.prob = prob self.mix_scale_ratio = mix_scale_ratio
def transform(self, results: dict) -> dict: if random.random() > self.prob: return results
h, w = results['img_shape'][:2] left = int(w * random.random()) width_ratio = self.mix_scale_ratio * random.random() width = int(max(1, (w - left) * width_ratio))
img = results['img'] depth_rescale_factor = results.get('depth_rescale_factor', 1) depth_map = results['gt_depth_map'] / depth_rescale_factor
if img.ndim == 3: for c in range(img.shape[-1]): img[:, left:left + width, c] = depth_map[:, left:left + width] elif img.ndim == 2: img[:, left:left + width] = depth_map[:, left:left + width] else: raise ValueError(f'Invalid image shape ({img.shape})')
results['img'] = img return results12345678910111213141516171819202122232425262728293031323334353637383940# Copyright (c) OpenMMLab. All rights reserved.import os.path as osp
import mmengine.fileio as fileio
from mmseg.registry import DATASETSfrom .basesegdataset import BaseSegDataset
@DATASETS.register_module()class PascalVOCDataset(BaseSegDataset): """Pascal VOC dataset.
Args: split (str): Split txt file for Pascal VOC. """ METAINFO = dict( classes=('background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'), palette=[[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64, 128]])
def __init__(self, ann_file, img_suffix='.jpg', seg_map_suffix='.png', **kwargs) -> None: super().__init__( img_suffix=img_suffix, seg_map_suffix=seg_map_suffix, ann_file=ann_file, **kwargs) assert fileio.exists(self.data_prefix['img_path'], self.backend_args) and osp.isfile(self.ann_file)123456789101112# Copyright (c) OpenMMLab. All rights reserved.from .hooks import SegVisualizationHookfrom .optimizers import (ForceDefaultOptimWrapperConstructor, LayerDecayOptimizerConstructor, LearningRateDecayOptimizerConstructor)from .schedulers import PolyLRRatio
__all__ = [ 'LearningRateDecayOptimizerConstructor', 'LayerDecayOptimizerConstructor', 'SegVisualizationHook', 'PolyLRRatio', 'ForceDefaultOptimWrapperConstructor']1234# Copyright (c) OpenMMLab. All rights reserved.from .visualization_hook import SegVisualizationHook
__all__ = ['SegVisualizationHook']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129# Copyright (c) OpenMMLab. All rights reserved.import os.path as ospimport warningsfrom typing import Optional, Sequence
import mmcvfrom mmengine.fileio import getfrom mmengine.hooks import Hookfrom mmengine.runner import Runnerfrom mmengine.visualization import Visualizer
from mmseg.registry import HOOKSfrom mmseg.structures import SegDataSample
@HOOKS.register_module()class SegVisualizationHook(Hook): """Segmentation Visualization Hook. Used to visualize validation and testing process prediction results.
In the testing phase:
1. If ``show`` is True, it means that only the prediction results are visualized without storing data, so ``vis_backends`` needs to be excluded.
Args: draw (bool): whether to draw prediction results. If it is False, it means that no drawing will be done. Defaults to False. interval (int): The interval of visualization. Defaults to 50. show (bool): Whether to display the drawn image. Default to False. wait_time (float): The interval of show (s). Defaults to 0. backend_args (dict, Optional): Arguments to instantiate a file backend. See https://mmengine.readthedocs.io/en/latest/api/fileio.htm for details. Defaults to None. Notes: mmcv>=2.0.0rc4, mmengine>=0.2.0 required. """
def __init__(self, draw: bool = False, interval: int = 50, show: bool = False, wait_time: float = 0., backend_args: Optional[dict] = None): self._visualizer: Visualizer = Visualizer.get_current_instance() self.interval = interval self.show = show if self.show: # No need to think about vis backends. self._visualizer._vis_backends = {} warnings.warn('The show is True, it means that only ' 'the prediction results are visualized ' 'without storing data, so vis_backends ' 'needs to be excluded.')
self.wait_time = wait_time self.backend_args = backend_args.copy() if backend_args else None self.draw = draw if not self.draw: warnings.warn('The draw is False, it means that the ' 'hook for visualization will not take ' 'effect. The results will NOT be ' 'visualized or stored.') self._test_index = 0
def after_val_iter(self, runner: Runner, batch_idx: int, data_batch: dict, outputs: Sequence[SegDataSample]) -> None: """Run after every ``self.interval`` validation iterations.
Args: runner (:obj:`Runner`): The runner of the validation process. batch_idx (int): The index of the current batch in the val loop. data_batch (dict): Data from dataloader. outputs (Sequence[:obj:`SegDataSample`]]): A batch of data samples that contain annotations and predictions. """ if self.draw is False: return
# There is no guarantee that the same batch of images # is visualized for each evaluation. total_curr_iter = runner.iter + batch_idx
# Visualize only the first data img_path = outputs[0].img_path img_bytes = get(img_path, backend_args=self.backend_args) img = mmcv.imfrombytes(img_bytes, channel_order='rgb') window_name = f'val_{osp.basename(img_path)}'
if total_curr_iter % self.interval == 0: self._visualizer.add_datasample( window_name, img, data_sample=outputs[0], show=self.show, wait_time=self.wait_time, step=total_curr_iter)
def after_test_iter(self, runner: Runner, batch_idx: int, data_batch: dict, outputs: Sequence[SegDataSample]) -> None: """Run after every testing iterations.
Args: runner (:obj:`Runner`): The runner of the testing process. batch_idx (int): The index of the current batch in the val loop. data_batch (dict): Data from dataloader. outputs (Sequence[:obj:`SegDataSample`]): A batch of data samples that contain annotations and predictions. """ if self.draw is False: return
for data_sample in outputs: self._test_index += 1
img_path = data_sample.img_path window_name = f'test_{osp.basename(img_path)}'
img_path = data_sample.img_path img_bytes = get(img_path, backend_args=self.backend_args) img = mmcv.imfrombytes(img_bytes, channel_order='rgb')
self._visualizer.add_datasample( window_name, img, data_sample=data_sample, show=self.show, wait_time=self.wait_time, step=self._test_index)123456789# Copyright (c) OpenMMLab. All rights reserved.from .force_default_constructor import ForceDefaultOptimWrapperConstructorfrom .layer_decay_optimizer_constructor import ( LayerDecayOptimizerConstructor, LearningRateDecayOptimizerConstructor)
__all__ = [ 'LearningRateDecayOptimizerConstructor', 'LayerDecayOptimizerConstructor', 'ForceDefaultOptimWrapperConstructor']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255# Copyright (c) OpenMMLab. All rights reserved.import loggingfrom typing import List, Optional, Union
import torchimport torch.nn as nnfrom mmengine.logging import print_logfrom mmengine.optim import DefaultOptimWrapperConstructorfrom mmengine.utils.dl_utils import mmcv_full_availablefrom mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm, _InstanceNormfrom torch.nn import GroupNorm, LayerNorm
from mmseg.registry import OPTIM_WRAPPER_CONSTRUCTORS
@OPTIM_WRAPPER_CONSTRUCTORS.register_module()class ForceDefaultOptimWrapperConstructor(DefaultOptimWrapperConstructor): """Default constructor with forced optimizer settings.
This constructor extends the default constructor to add an option for forcing default optimizer settings. This is useful for ensuring that certain parameters or layers strictly adhere to pre-defined default settings, regardless of any custom settings specified.
By default, each parameter share the same optimizer settings, and we provide an argument ``paramwise_cfg`` to specify parameter-wise settings. It is a dict and may contain various fields like 'custom_keys', 'bias_lr_mult', etc., as well as the additional field `force_default_settings` which allows for enforcing default settings on optimizer parameters.
- ``custom_keys`` (dict): Specified parameters-wise settings by keys. If one of the keys in ``custom_keys`` is a substring of the name of one parameter, then the setting of the parameter will be specified by ``custom_keys[key]`` and other setting like ``bias_lr_mult`` etc. will be ignored. It should be noted that the aforementioned ``key`` is the longest key that is a substring of the name of the parameter. If there are multiple matched keys with the same length, then the key with lower alphabet order will be chosen. ``custom_keys[key]`` should be a dict and may contain fields ``lr_mult`` and ``decay_mult``. See Example 2 below. - ``bias_lr_mult`` (float): It will be multiplied to the learning rate for all bias parameters (except for those in normalization layers and offset layers of DCN). - ``bias_decay_mult`` (float): It will be multiplied to the weight decay for all bias parameters (except for those in normalization layers, depthwise conv layers, offset layers of DCN). - ``norm_decay_mult`` (float): It will be multiplied to the weight decay for all weight and bias parameters of normalization layers. - ``flat_decay_mult`` (float): It will be multiplied to the weight decay for all one-dimensional parameters - ``dwconv_decay_mult`` (float): It will be multiplied to the weight decay for all weight and bias parameters of depthwise conv layers. - ``dcn_offset_lr_mult`` (float): It will be multiplied to the learning rate for parameters of offset layer in the deformable convs of a model. - ``bypass_duplicate`` (bool): If true, the duplicate parameters would not be added into optimizer. Defaults to False. - ``force_default_settings`` (bool): If true, this will override any custom settings defined by ``custom_keys`` and enforce the use of default settings for optimizer parameters like ``bias_lr_mult``. This is particularly useful when you want to ensure that certain layers or parameters adhere strictly to the pre-defined default settings.
Note:
1. If the option ``dcn_offset_lr_mult`` is used, the constructor will override the effect of ``bias_lr_mult`` in the bias of offset layer. So be careful when using both ``bias_lr_mult`` and ``dcn_offset_lr_mult``. If you wish to apply both of them to the offset layer in deformable convs, set ``dcn_offset_lr_mult`` to the original ``dcn_offset_lr_mult`` * ``bias_lr_mult``.
2. If the option ``dcn_offset_lr_mult`` is used, the constructor will apply it to all the DCN layers in the model. So be careful when the model contains multiple DCN layers in places other than backbone.
3. When the option ``force_default_settings`` is true, it will override any custom settings provided in ``custom_keys``. This ensures that the default settings for the optimizer parameters are used.
Args: optim_wrapper_cfg (dict): The config dict of the optimizer wrapper.
Required fields of ``optim_wrapper_cfg`` are
- ``type``: class name of the OptimizerWrapper - ``optimizer``: The configuration of optimizer.
Optional fields of ``optim_wrapper_cfg`` are
- any arguments of the corresponding optimizer wrapper type, e.g., accumulative_counts, clip_grad, etc.
Required fields of ``optimizer`` are
- `type`: class name of the optimizer.
Optional fields of ``optimizer`` are
- any arguments of the corresponding optimizer type, e.g., lr, weight_decay, momentum, etc.
paramwise_cfg (dict, optional): Parameter-wise options.
Example 1: >>> model = torch.nn.modules.Conv1d(1, 1, 1) >>> optim_wrapper_cfg = dict( >>> dict(type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01, >>> momentum=0.9, weight_decay=0.0001)) >>> paramwise_cfg = dict(norm_decay_mult=0.) >>> optim_wrapper_builder = DefaultOptimWrapperConstructor( >>> optim_wrapper_cfg, paramwise_cfg) >>> optim_wrapper = optim_wrapper_builder(model)
Example 2: >>> # assume model have attribute model.backbone and model.cls_head >>> optim_wrapper_cfg = dict(type='OptimWrapper', optimizer=dict( >>> type='SGD', lr=0.01, weight_decay=0.95)) >>> paramwise_cfg = dict(custom_keys={ >>> 'backbone': dict(lr_mult=0.1, decay_mult=0.9)}) >>> optim_wrapper_builder = DefaultOptimWrapperConstructor( >>> optim_wrapper_cfg, paramwise_cfg) >>> optim_wrapper = optim_wrapper_builder(model) >>> # Then the `lr` and `weight_decay` for model.backbone is >>> # (0.01 * 0.1, 0.95 * 0.9). `lr` and `weight_decay` for >>> # model.cls_head is (0.01, 0.95). """
def add_params(self, params: List[dict], module: nn.Module, prefix: str = '', is_dcn_module: Optional[Union[int, float]] = None) -> None: """Add all parameters of module to the params list.
The parameters of the given module will be added to the list of param groups, with specific rules defined by paramwise_cfg.
Args: params (list[dict]): A list of param groups, it will be modified in place. module (nn.Module): The module to be added. prefix (str): The prefix of the module is_dcn_module (int|float|None): If the current module is a submodule of DCN, `is_dcn_module` will be passed to control conv_offset layer's learning rate. Defaults to None. """ # get param-wise options custom_keys = self.paramwise_cfg.get('custom_keys', {}) # first sort with alphabet order and then sort with reversed len of str sorted_keys = sorted(sorted(custom_keys.keys()), key=len, reverse=True)
bias_lr_mult = self.paramwise_cfg.get('bias_lr_mult', None) bias_decay_mult = self.paramwise_cfg.get('bias_decay_mult', None) norm_decay_mult = self.paramwise_cfg.get('norm_decay_mult', None) dwconv_decay_mult = self.paramwise_cfg.get('dwconv_decay_mult', None) flat_decay_mult = self.paramwise_cfg.get('flat_decay_mult', None) bypass_duplicate = self.paramwise_cfg.get('bypass_duplicate', False) dcn_offset_lr_mult = self.paramwise_cfg.get('dcn_offset_lr_mult', None) force_default_settings = self.paramwise_cfg.get( 'force_default_settings', False)
# special rules for norm layers and depth-wise conv layers is_norm = isinstance(module, (_BatchNorm, _InstanceNorm, GroupNorm, LayerNorm)) is_dwconv = ( isinstance(module, torch.nn.Conv2d) and module.in_channels == module.groups)
for name, param in module.named_parameters(recurse=False): param_group = {'params': [param]} if bypass_duplicate and self._is_in(param_group, params): print_log( f'{prefix} is duplicate. It is skipped since ' f'bypass_duplicate={bypass_duplicate}', logger='current', level=logging.WARNING) continue if not param.requires_grad: params.append(param_group) continue
# if the parameter match one of the custom keys, ignore other rules is_custom = False for key in sorted_keys: if key in f'{prefix}.{name}': is_custom = True lr_mult = custom_keys[key].get('lr_mult', 1.) param_group['lr'] = self.base_lr * lr_mult if self.base_wd is not None: decay_mult = custom_keys[key].get('decay_mult', 1.) param_group['weight_decay'] = self.base_wd * decay_mult # add custom settings to param_group for k, v in custom_keys[key].items(): param_group[k] = v break
if not is_custom or force_default_settings: # bias_lr_mult affects all bias parameters # except for norm.bias dcn.conv_offset.bias if name == 'bias' and not ( is_norm or is_dcn_module) and bias_lr_mult is not None: param_group['lr'] = self.base_lr * bias_lr_mult
if (prefix.find('conv_offset') != -1 and is_dcn_module and dcn_offset_lr_mult is not None and isinstance(module, torch.nn.Conv2d)): # deal with both dcn_offset's bias & weight param_group['lr'] = self.base_lr * dcn_offset_lr_mult
# apply weight decay policies if self.base_wd is not None: # norm decay if is_norm and norm_decay_mult is not None: param_group[ 'weight_decay'] = self.base_wd * norm_decay_mult # bias lr and decay elif (name == 'bias' and not is_dcn_module and bias_decay_mult is not None): param_group[ 'weight_decay'] = self.base_wd * bias_decay_mult # depth-wise conv elif is_dwconv and dwconv_decay_mult is not None: param_group[ 'weight_decay'] = self.base_wd * dwconv_decay_mult # flatten parameters except dcn offset elif (param.ndim == 1 and not is_dcn_module and flat_decay_mult is not None): param_group[ 'weight_decay'] = self.base_wd * flat_decay_mult params.append(param_group) for key, value in param_group.items(): if key == 'params': continue full_name = f'{prefix}.{name}' if prefix else name print_log( f'paramwise_options -- {full_name}:{key}={value}', logger='current')
if mmcv_full_available(): from mmcv.ops import DeformConv2d, ModulatedDeformConv2d is_dcn_module = isinstance(module, (DeformConv2d, ModulatedDeformConv2d)) else: is_dcn_module = False for child_name, child_mod in module.named_children(): child_prefix = f'{prefix}.{child_name}' if prefix else child_name self.add_params( params, child_mod, prefix=child_prefix, is_dcn_module=is_dcn_module)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207# Copyright (c) OpenMMLab. All rights reserved.import jsonimport warnings
from mmengine.dist import get_dist_infofrom mmengine.logging import print_logfrom mmengine.optim import DefaultOptimWrapperConstructor
from mmseg.registry import OPTIM_WRAPPER_CONSTRUCTORS
def get_layer_id_for_convnext(var_name, max_layer_id): """Get the layer id to set the different learning rates in ``layer_wise`` decay_type.
Args: var_name (str): The key of the model. max_layer_id (int): Maximum number of backbone layers.
Returns: int: The id number corresponding to different learning rate in ``LearningRateDecayOptimizerConstructor``. """
if var_name in ('backbone.cls_token', 'backbone.mask_token', 'backbone.pos_embed'): return 0 elif var_name.startswith('backbone.downsample_layers'): stage_id = int(var_name.split('.')[2]) if stage_id == 0: layer_id = 0 elif stage_id == 1: layer_id = 2 elif stage_id == 2: layer_id = 3 elif stage_id == 3: layer_id = max_layer_id return layer_id elif var_name.startswith('backbone.stages'): stage_id = int(var_name.split('.')[2]) block_id = int(var_name.split('.')[3]) if stage_id == 0: layer_id = 1 elif stage_id == 1: layer_id = 2 elif stage_id == 2: layer_id = 3 + block_id // 3 elif stage_id == 3: layer_id = max_layer_id return layer_id else: return max_layer_id + 1
def get_stage_id_for_convnext(var_name, max_stage_id): """Get the stage id to set the different learning rates in ``stage_wise`` decay_type.
Args: var_name (str): The key of the model. max_stage_id (int): Maximum number of backbone layers.
Returns: int: The id number corresponding to different learning rate in ``LearningRateDecayOptimizerConstructor``. """
if var_name in ('backbone.cls_token', 'backbone.mask_token', 'backbone.pos_embed'): return 0 elif var_name.startswith('backbone.downsample_layers'): return 0 elif var_name.startswith('backbone.stages'): stage_id = int(var_name.split('.')[2]) return stage_id + 1 else: return max_stage_id - 1
def get_layer_id_for_vit(var_name, max_layer_id): """Get the layer id to set the different learning rates.
Args: var_name (str): The key of the model. num_max_layer (int): Maximum number of backbone layers.
Returns: int: Returns the layer id of the key. """
if var_name in ('backbone.cls_token', 'backbone.mask_token', 'backbone.pos_embed'): return 0 elif var_name.startswith('backbone.patch_embed'): return 0 elif var_name.startswith('backbone.layers'): layer_id = int(var_name.split('.')[2]) return layer_id + 1 else: return max_layer_id - 1
@OPTIM_WRAPPER_CONSTRUCTORS.register_module()class LearningRateDecayOptimizerConstructor(DefaultOptimWrapperConstructor): """Different learning rates are set for different layers of backbone.
Note: Currently, this optimizer constructor is built for ConvNeXt, BEiT and MAE. """
def add_params(self, params, module, **kwargs): """Add all parameters of module to the params list.
The parameters of the given module will be added to the list of param groups, with specific rules defined by paramwise_cfg.
Args: params (list[dict]): A list of param groups, it will be modified in place. module (nn.Module): The module to be added. """
parameter_groups = {} print_log(f'self.paramwise_cfg is {self.paramwise_cfg}') num_layers = self.paramwise_cfg.get('num_layers') + 2 decay_rate = self.paramwise_cfg.get('decay_rate') decay_type = self.paramwise_cfg.get('decay_type', 'layer_wise') print_log('Build LearningRateDecayOptimizerConstructor ' f'{decay_type} {decay_rate} - {num_layers}') weight_decay = self.base_wd for name, param in module.named_parameters(): if not param.requires_grad: continue # frozen weights if len(param.shape) == 1 or name.endswith('.bias') or name in ( 'pos_embed', 'cls_token'): group_name = 'no_decay' this_weight_decay = 0. else: group_name = 'decay' this_weight_decay = weight_decay if 'layer_wise' in decay_type: if 'ConvNeXt' in module.backbone.__class__.__name__: layer_id = get_layer_id_for_convnext( name, self.paramwise_cfg.get('num_layers')) print_log(f'set param {name} as id {layer_id}') elif 'BEiT' in module.backbone.__class__.__name__ or \ 'MAE' in module.backbone.__class__.__name__: layer_id = get_layer_id_for_vit(name, num_layers) print_log(f'set param {name} as id {layer_id}') else: raise NotImplementedError() elif decay_type == 'stage_wise': if 'ConvNeXt' in module.backbone.__class__.__name__: layer_id = get_stage_id_for_convnext(name, num_layers) print_log(f'set param {name} as id {layer_id}') else: raise NotImplementedError() group_name = f'layer_{layer_id}_{group_name}'
if group_name not in parameter_groups: scale = decay_rate**(num_layers - layer_id - 1)
parameter_groups[group_name] = { 'weight_decay': this_weight_decay, 'params': [], 'param_names': [], 'lr_scale': scale, 'group_name': group_name, 'lr': scale * self.base_lr, }
parameter_groups[group_name]['params'].append(param) parameter_groups[group_name]['param_names'].append(name) rank, _ = get_dist_info() if rank == 0: to_display = {} for key in parameter_groups: to_display[key] = { 'param_names': parameter_groups[key]['param_names'], 'lr_scale': parameter_groups[key]['lr_scale'], 'lr': parameter_groups[key]['lr'], 'weight_decay': parameter_groups[key]['weight_decay'], } print_log(f'Param groups = {json.dumps(to_display, indent=2)}') params.extend(parameter_groups.values())
@OPTIM_WRAPPER_CONSTRUCTORS.register_module()class LayerDecayOptimizerConstructor(LearningRateDecayOptimizerConstructor): """Different learning rates are set for different layers of backbone.
Note: Currently, this optimizer constructor is built for BEiT, and it will be deprecated. Please use ``LearningRateDecayOptimizerConstructor`` instead. """
def __init__(self, optim_wrapper_cfg, paramwise_cfg): warnings.warn('DeprecationWarning: Original ' 'LayerDecayOptimizerConstructor of BEiT ' 'will be deprecated. Please use ' 'LearningRateDecayOptimizerConstructor instead, ' 'and set decay_type = layer_wise_vit in paramwise_cfg.') paramwise_cfg.update({'decay_type': 'layer_wise_vit'}) warnings.warn('DeprecationWarning: Layer_decay_rate will ' 'be deleted, please use decay_rate instead.') paramwise_cfg['decay_rate'] = paramwise_cfg.pop('layer_decay_rate') super().__init__(optim_wrapper_cfg, paramwise_cfg)1234# Copyright (c) OpenMMLab. All rights reserved.from .poly_ratio_scheduler import PolyLRRatio
__all__ = ['PolyLRRatio']1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# Copyright (c) OpenMMLab. All rights reserved.from typing import Optional
from mmengine.optim.scheduler import PolyLR
from mmseg.registry import PARAM_SCHEDULERS
@PARAM_SCHEDULERS.register_module()class PolyLRRatio(PolyLR): """Implements polynomial learning rate decay with ratio.
This scheduler adjusts the learning rate of each parameter group following a polynomial decay equation. The decay can occur in conjunction with external parameter adjustments made outside this scheduler.
Args: optimizer (Optimizer or OptimWrapper): Wrapped optimizer. eta_min (float): Minimum learning rate at the end of scheduling. Defaults to 0. eta_min_ratio (float, optional): The ratio of the minimum parameter value to the base parameter value. Either `eta_min` or `eta_min_ratio` should be specified. Defaults to None. power (float): The power of the polynomial. Defaults to 1.0. begin (int): Step at which to start updating the parameters. Defaults to 0. end (int): Step at which to stop updating the parameters. Defaults to INF. last_step (int): The index of last step. Used for resume without state dict. Defaults to -1. by_epoch (bool): Whether the scheduled parameters are updated by epochs. Defaults to True. verbose (bool): Whether to print the value for each update. Defaults to False. """
def __init__(self, eta_min_ratio: Optional[int] = None, *args, **kwargs): super().__init__(*args, **kwargs)
self.eta_min_ratio = eta_min_ratio
def _get_value(self): """Compute value using chainable form of the scheduler."""
if self.last_step == 0: return [ group[self.param_name] for group in self.optimizer.param_groups ]
param_groups_value = [] for base_value, param_group in zip(self.base_values, self.optimizer.param_groups): eta_min = self.eta_min if self.eta_min_ratio is None else \ base_value * self.eta_min_ratio step_ratio = (1 - 1 / (self.total_iters - self.last_step + 1))**self.power step_value = (param_group[self.param_name] - eta_min) * step_ratio + eta_min param_groups_value.append(step_value)
return param_groups_value1234# Copyright (c) OpenMMLab. All rights reserved.from .metrics import CityscapesMetric, DepthMetric, IoUMetric
__all__ = ['IoUMetric', 'CityscapesMetric', 'DepthMetric']123456# Copyright (c) OpenMMLab. All rights reserved.from .citys_metric import CityscapesMetricfrom .depth_metric import DepthMetricfrom .iou_metric import IoUMetric
__all__ = ['IoUMetric', 'CityscapesMetric', 'DepthMetric']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158# Copyright (c) OpenMMLab. All rights reserved.import os.path as ospimport shutilfrom collections import OrderedDictfrom typing import Dict, Optional, Sequence
try:
import cityscapesscripts.evaluation.evalPixelLevelSemanticLabeling as CSEval # noqa import cityscapesscripts.helpers.labels as CSLabelsexcept ImportError: CSLabels = None CSEval = None
import numpy as npfrom mmengine.dist import is_main_process, master_onlyfrom mmengine.evaluator import BaseMetricfrom mmengine.logging import MMLogger, print_logfrom mmengine.utils import mkdir_or_existfrom PIL import Image
from mmseg.registry import METRICS
@METRICS.register_module()class CityscapesMetric(BaseMetric): """Cityscapes evaluation metric.
Args: output_dir (str): The directory for output prediction ignore_index (int): Index that will be ignored in evaluation. Default: 255. format_only (bool): Only format result for results commit without perform evaluation. It is useful when you want to format the result to a specific format and submit it to the test server. Defaults to False. keep_results (bool): Whether to keep the results. When ``format_only`` is True, ``keep_results`` must be True. Defaults to False. collect_device (str): Device name used for collecting results from different ranks during distributed training. Must be 'cpu' or 'gpu'. Defaults to 'cpu'. prefix (str, optional): The prefix that will be added in the metric names to disambiguate homonymous metrics of different evaluators. If prefix is not provided in the argument, self.default_prefix will be used instead. Defaults to None. """
def __init__(self, output_dir: str, ignore_index: int = 255, format_only: bool = False, keep_results: bool = False, collect_device: str = 'cpu', prefix: Optional[str] = None, **kwargs) -> None: super().__init__(collect_device=collect_device, prefix=prefix) if CSEval is None: raise ImportError('Please run "pip install cityscapesscripts" to ' 'install cityscapesscripts first.') self.output_dir = output_dir self.ignore_index = ignore_index
self.format_only = format_only if format_only: assert keep_results, ( 'When format_only is True, the results must be keep, please ' f'set keep_results as True, but got {keep_results}') self.keep_results = keep_results self.prefix = prefix if is_main_process(): mkdir_or_exist(self.output_dir)
@master_only def __del__(self) -> None: """Clean up.""" if not self.keep_results: shutil.rmtree(self.output_dir)
def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None: """Process one batch of data and data_samples.
The processed results should be stored in ``self.results``, which will be used to computed the metrics when all batches have been processed.
Args: data_batch (dict): A batch of data from the dataloader. data_samples (Sequence[dict]): A batch of outputs from the model. """ mkdir_or_exist(self.output_dir)
for data_sample in data_samples: pred_label = data_sample['pred_sem_seg']['data'][0].cpu().numpy() # when evaluating with official cityscapesscripts, # labelIds should be used pred_label = self._convert_to_label_id(pred_label) basename = osp.splitext(osp.basename(data_sample['img_path']))[0] png_filename = osp.abspath( osp.join(self.output_dir, f'{basename}.png')) output = Image.fromarray(pred_label.astype(np.uint8)).convert('P') output.save(png_filename) if self.format_only: # format_only always for test dataset without ground truth gt_filename = '' else: # when evaluating with official cityscapesscripts, # **_gtFine_labelIds.png is used gt_filename = data_sample['seg_map_path'].replace( 'labelTrainIds.png', 'labelIds.png') self.results.append((png_filename, gt_filename))
def compute_metrics(self, results: list) -> Dict[str, float]: """Compute the metrics from processed results.
Args: results (list): Testing results of the dataset.
Returns: dict[str: float]: Cityscapes evaluation results. """ logger: MMLogger = MMLogger.get_current_instance() if self.format_only: logger.info(f'results are saved to {osp.dirname(self.output_dir)}') return OrderedDict()
msg = 'Evaluating in Cityscapes style' if logger is None: msg = '\n' + msg print_log(msg, logger=logger)
eval_results = dict() print_log( f'Evaluating results under {self.output_dir} ...', logger=logger)
CSEval.args.evalInstLevelScore = True CSEval.args.predictionPath = osp.abspath(self.output_dir) CSEval.args.evalPixelAccuracy = True CSEval.args.JSONOutput = False
pred_list, gt_list = zip(*results) metric = dict() eval_results.update( CSEval.evaluateImgLists(pred_list, gt_list, CSEval.args)) metric['averageScoreCategories'] = eval_results[ 'averageScoreCategories'] metric['averageScoreInstCategories'] = eval_results[ 'averageScoreInstCategories'] return metric
@staticmethod def _convert_to_label_id(result): """Convert trainId to id for cityscapes.""" if isinstance(result, str): result = np.load(result) result_copy = result.copy() for trainId, label in CSLabels.trainId2label.items(): result_copy[result == trainId] = label.id
return result_copy123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212# Copyright (c) OpenMMLab. All rights reserved.import os.path as ospfrom collections import OrderedDict, defaultdictfrom typing import Dict, List, Optional, Sequence
import cv2import numpy as npimport torchfrom mmengine.dist import is_main_processfrom mmengine.evaluator import BaseMetricfrom mmengine.logging import MMLogger, print_logfrom mmengine.utils import mkdir_or_existfrom prettytable import PrettyTablefrom torch import Tensor
from mmseg.registry import METRICS
@METRICS.register_module()class DepthMetric(BaseMetric): """Depth estimation evaluation metric.
Args: depth_metrics (List[str], optional): List of metrics to compute. If not specified, defaults to all metrics in self.METRICS. min_depth_eval (float): Minimum depth value for evaluation. Defaults to 0.0. max_depth_eval (float): Maximum depth value for evaluation. Defaults to infinity. crop_type (str, optional): Specifies the type of cropping to be used during evaluation. This option can affect how the evaluation mask is generated. Currently, 'nyu_crop' is supported, but other types can be added in future. Defaults to None if no cropping should be applied. depth_scale_factor (float): Factor to scale the depth values. Defaults to 1.0. collect_device (str): Device name used for collecting results from different ranks during distributed training. Must be 'cpu' or 'gpu'. Defaults to 'cpu'. output_dir (str): The directory for output prediction. Defaults to None. format_only (bool): Only format result for results commit without perform evaluation. It is useful when you want to save the result to a specific format and submit it to the test server. Defaults to False. prefix (str, optional): The prefix that will be added in the metric names to disambiguate homonymous metrics of different evaluators. If prefix is not provided in the argument, self.default_prefix will be used instead. Defaults to None. """ METRICS = ('d1', 'd2', 'd3', 'abs_rel', 'sq_rel', 'rmse', 'rmse_log', 'log10', 'silog')
def __init__(self, depth_metrics: Optional[List[str]] = None, min_depth_eval: float = 0.0, max_depth_eval: float = float('inf'), crop_type: Optional[str] = None, depth_scale_factor: float = 1.0, collect_device: str = 'cpu', output_dir: Optional[str] = None, format_only: bool = False, prefix: Optional[str] = None, **kwargs) -> None: super().__init__(collect_device=collect_device, prefix=prefix)
if depth_metrics is None: self.metrics = self.METRICS elif isinstance(depth_metrics, [tuple, list]): for metric in depth_metrics: assert metric in self.METRICS, f'the metric {metric} is not ' \ f'supported. Please use metrics in {self.METRICS}' self.metrics = depth_metrics
# Validate crop_type, if provided assert crop_type in [ None, 'nyu_crop' ], (f'Invalid value for crop_type: {crop_type}. Supported values are ' 'None or \'nyu_crop\'.') self.crop_type = crop_type self.min_depth_eval = min_depth_eval self.max_depth_eval = max_depth_eval self.output_dir = output_dir if self.output_dir and is_main_process(): mkdir_or_exist(self.output_dir) self.format_only = format_only self.depth_scale_factor = depth_scale_factor
def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None: """Process one batch of data and data_samples.
The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been processed.
Args: data_batch (dict): A batch of data from the dataloader. data_samples (Sequence[dict]): A batch of outputs from the model. """ for data_sample in data_samples: pred_label = data_sample['pred_depth_map']['data'].squeeze() # format_only always for test dataset without ground truth if not self.format_only: gt_depth = data_sample['gt_depth_map']['data'].squeeze().to( pred_label)
eval_mask = self._get_eval_mask(gt_depth) self.results.append( (gt_depth[eval_mask], pred_label[eval_mask])) # format_result if self.output_dir is not None: basename = osp.splitext(osp.basename( data_sample['img_path']))[0] png_filename = osp.abspath( osp.join(self.output_dir, f'{basename}.png')) output_mask = pred_label.cpu().numpy( ) * self.depth_scale_factor
cv2.imwrite(png_filename, output_mask.astype(np.uint16), [cv2.IMWRITE_PNG_COMPRESSION, 0])
def _get_eval_mask(self, gt_depth: Tensor): """Generates an evaluation mask based on ground truth depth and cropping.
Args: gt_depth (Tensor): Ground truth depth map.
Returns: Tensor: Boolean mask where evaluation should be performed. """ valid_mask = torch.logical_and(gt_depth > self.min_depth_eval, gt_depth < self.max_depth_eval)
if self.crop_type == 'nyu_crop': # this implementation is adapted from # https://github.com/zhyever/Monocular-Depth-Estimation-Toolbox/blob/main/depth/datasets/nyu.py # noqa crop_mask = torch.zeros_like(valid_mask) crop_mask[45:471, 41:601] = 1 else: crop_mask = torch.ones_like(valid_mask)
eval_mask = torch.logical_and(valid_mask, crop_mask) return eval_mask
@staticmethod def _calc_all_metrics(gt_depth, pred_depth): """Computes final evaluation metrics based on accumulated results.""" assert gt_depth.shape == pred_depth.shape
thresh = torch.max((gt_depth / pred_depth), (pred_depth / gt_depth)) diff = pred_depth - gt_depth diff_log = torch.log(pred_depth) - torch.log(gt_depth)
d1 = torch.sum(thresh < 1.25).float() / len(thresh) d2 = torch.sum(thresh < 1.25**2).float() / len(thresh) d3 = torch.sum(thresh < 1.25**3).float() / len(thresh)
abs_rel = torch.mean(torch.abs(diff) / gt_depth) sq_rel = torch.mean(torch.pow(diff, 2) / gt_depth)
rmse = torch.sqrt(torch.mean(torch.pow(diff, 2))) rmse_log = torch.sqrt(torch.mean(torch.pow(diff_log, 2)))
log10 = torch.mean( torch.abs(torch.log10(pred_depth) - torch.log10(gt_depth))) silog = torch.sqrt( torch.pow(diff_log, 2).mean() - 0.5 * torch.pow(diff_log.mean(), 2))
return { 'd1': d1.item(), 'd2': d2.item(), 'd3': d3.item(), 'abs_rel': abs_rel.item(), 'sq_rel': sq_rel.item(), 'rmse': rmse.item(), 'rmse_log': rmse_log.item(), 'log10': log10.item(), 'silog': silog.item() }
def compute_metrics(self, results: list) -> Dict[str, float]: """Compute the metrics from processed results.
Args: results (list): The processed results of each batch.
Returns: Dict[str, float]: The computed metrics. The keys are the names of the metrics, and the values are corresponding results. The keys are identical with self.metrics. """ logger: MMLogger = MMLogger.get_current_instance() if self.format_only: logger.info(f'results are saved to {osp.dirname(self.output_dir)}') return OrderedDict()
metrics = defaultdict(list) for gt_depth, pred_depth in results: for key, value in self._calc_all_metrics(gt_depth, pred_depth).items(): metrics[key].append(value) metrics = {k: sum(metrics[k]) / len(metrics[k]) for k in self.metrics}
table_data = PrettyTable() for key, val in metrics.items(): table_data.add_column(key, [round(val, 5)])
print_log('results:', logger) print_log('\n' + table_data.get_string(), logger=logger)
return metrics123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286# Copyright (c) OpenMMLab. All rights reserved.import os.path as ospfrom collections import OrderedDictfrom typing import Dict, List, Optional, Sequence
import numpy as npimport torchfrom mmengine.dist import is_main_processfrom mmengine.evaluator import BaseMetricfrom mmengine.logging import MMLogger, print_logfrom mmengine.utils import mkdir_or_existfrom PIL import Imagefrom prettytable import PrettyTable
from mmseg.registry import METRICS
@METRICS.register_module()class IoUMetric(BaseMetric): """IoU evaluation metric.
Args: ignore_index (int): Index that will be ignored in evaluation. Default: 255. iou_metrics (list[str] | str): Metrics to be calculated, the options includes 'mIoU', 'mDice' and 'mFscore'. nan_to_num (int, optional): If specified, NaN values will be replaced by the numbers defined by the user. Default: None. beta (int): Determines the weight of recall in the combined score. Default: 1. collect_device (str): Device name used for collecting results from different ranks during distributed training. Must be 'cpu' or 'gpu'. Defaults to 'cpu'. output_dir (str): The directory for output prediction. Defaults to None. format_only (bool): Only format result for results commit without perform evaluation. It is useful when you want to save the result to a specific format and submit it to the test server. Defaults to False. prefix (str, optional): The prefix that will be added in the metric names to disambiguate homonymous metrics of different evaluators. If prefix is not provided in the argument, self.default_prefix will be used instead. Defaults to None. """
def __init__(self, ignore_index: int = 255, iou_metrics: List[str] = ['mIoU'], nan_to_num: Optional[int] = None, beta: int = 1, collect_device: str = 'cpu', output_dir: Optional[str] = None, format_only: bool = False, prefix: Optional[str] = None, **kwargs) -> None: super().__init__(collect_device=collect_device, prefix=prefix)
self.ignore_index = ignore_index self.metrics = iou_metrics self.nan_to_num = nan_to_num self.beta = beta self.output_dir = output_dir if self.output_dir and is_main_process(): mkdir_or_exist(self.output_dir) self.format_only = format_only
def process(self, data_batch: dict, data_samples: Sequence[dict]) -> None: """Process one batch of data and data_samples.
The processed results should be stored in ``self.results``, which will be used to compute the metrics when all batches have been processed.
Args: data_batch (dict): A batch of data from the dataloader. data_samples (Sequence[dict]): A batch of outputs from the model. """ num_classes = len(self.dataset_meta['classes']) for data_sample in data_samples: pred_label = data_sample['pred_sem_seg']['data'].squeeze() # format_only always for test dataset without ground truth if not self.format_only: label = data_sample['gt_sem_seg']['data'].squeeze().to( pred_label) self.results.append( self.intersect_and_union(pred_label, label, num_classes, self.ignore_index)) # format_result if self.output_dir is not None: basename = osp.splitext(osp.basename( data_sample['img_path']))[0] png_filename = osp.abspath( osp.join(self.output_dir, f'{basename}.png')) output_mask = pred_label.cpu().numpy() # The index range of official ADE20k dataset is from 0 to 150. # But the index range of output is from 0 to 149. # That is because we set reduce_zero_label=True. if data_sample.get('reduce_zero_label', False): output_mask = output_mask + 1 output = Image.fromarray(output_mask.astype(np.uint8)) output.save(png_filename)
def compute_metrics(self, results: list) -> Dict[str, float]: """Compute the metrics from processed results.
Args: results (list): The processed results of each batch.
Returns: Dict[str, float]: The computed metrics. The keys are the names of the metrics, and the values are corresponding results. The key mainly includes aAcc, mIoU, mAcc, mDice, mFscore, mPrecision, mRecall. """ logger: MMLogger = MMLogger.get_current_instance() if self.format_only: logger.info(f'results are saved to {osp.dirname(self.output_dir)}') return OrderedDict() # convert list of tuples to tuple of lists, e.g. # [(A_1, B_1, C_1, D_1), ..., (A_n, B_n, C_n, D_n)] to # ([A_1, ..., A_n], ..., [D_1, ..., D_n]) results = tuple(zip(*results)) assert len(results) == 4
total_area_intersect = sum(results[0]) total_area_union = sum(results[1]) total_area_pred_label = sum(results[2]) total_area_label = sum(results[3]) ret_metrics = self.total_area_to_metrics( total_area_intersect, total_area_union, total_area_pred_label, total_area_label, self.metrics, self.nan_to_num, self.beta)
class_names = self.dataset_meta['classes']
# summary table ret_metrics_summary = OrderedDict({ ret_metric: np.round(np.nanmean(ret_metric_value) * 100, 2) for ret_metric, ret_metric_value in ret_metrics.items() }) metrics = dict() for key, val in ret_metrics_summary.items(): if key == 'aAcc': metrics[key] = val else: metrics['m' + key] = val
# each class table ret_metrics.pop('aAcc', None) ret_metrics_class = OrderedDict({ ret_metric: np.round(ret_metric_value * 100, 2) for ret_metric, ret_metric_value in ret_metrics.items() }) ret_metrics_class.update({'Class': class_names}) ret_metrics_class.move_to_end('Class', last=False) class_table_data = PrettyTable() for key, val in ret_metrics_class.items(): class_table_data.add_column(key, val)
print_log('per class results:', logger) print_log('\n' + class_table_data.get_string(), logger=logger)
return metrics
@staticmethod def intersect_and_union(pred_label: torch.tensor, label: torch.tensor, num_classes: int, ignore_index: int): """Calculate Intersection and Union.
Args: pred_label (torch.tensor): Prediction segmentation map or predict result filename. The shape is (H, W). label (torch.tensor): Ground truth segmentation map or label filename. The shape is (H, W). num_classes (int): Number of categories. ignore_index (int): Index that will be ignored in evaluation.
Returns: torch.Tensor: The intersection of prediction and ground truth histogram on all classes. torch.Tensor: The union of prediction and ground truth histogram on all classes. torch.Tensor: The prediction histogram on all classes. torch.Tensor: The ground truth histogram on all classes. """
mask = (label != ignore_index) pred_label = pred_label[mask] label = label[mask]
intersect = pred_label[pred_label == label] area_intersect = torch.histc( intersect.float(), bins=(num_classes), min=0, max=num_classes - 1).cpu() area_pred_label = torch.histc( pred_label.float(), bins=(num_classes), min=0, max=num_classes - 1).cpu() area_label = torch.histc( label.float(), bins=(num_classes), min=0, max=num_classes - 1).cpu() area_union = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label
@staticmethod def total_area_to_metrics(total_area_intersect: np.ndarray, total_area_union: np.ndarray, total_area_pred_label: np.ndarray, total_area_label: np.ndarray, metrics: List[str] = ['mIoU'], nan_to_num: Optional[int] = None, beta: int = 1): """Calculate evaluation metrics Args: total_area_intersect (np.ndarray): The intersection of prediction and ground truth histogram on all classes. total_area_union (np.ndarray): The union of prediction and ground truth histogram on all classes. total_area_pred_label (np.ndarray): The prediction histogram on all classes. total_area_label (np.ndarray): The ground truth histogram on all classes. metrics (List[str] | str): Metrics to be evaluated, 'mIoU' and 'mDice'. nan_to_num (int, optional): If specified, NaN values will be replaced by the numbers defined by the user. Default: None. beta (int): Determines the weight of recall in the combined score. Default: 1. Returns: Dict[str, np.ndarray]: per category evaluation metrics, shape (num_classes, ). """
def f_score(precision, recall, beta=1): """calculate the f-score value.
Args: precision (float | torch.Tensor): The precision value. recall (float | torch.Tensor): The recall value. beta (int): Determines the weight of recall in the combined score. Default: 1.
Returns: [torch.tensor]: The f-score value. """ score = (1 + beta**2) * (precision * recall) / ( (beta**2 * precision) + recall) return score
if isinstance(metrics, str): metrics = [metrics] allowed_metrics = ['mIoU', 'mDice', 'mFscore'] if not set(metrics).issubset(set(allowed_metrics)): raise KeyError(f'metrics {metrics} is not supported')
all_acc = total_area_intersect.sum() / total_area_label.sum() ret_metrics = OrderedDict({'aAcc': all_acc}) for metric in metrics: if metric == 'mIoU': iou = total_area_intersect / total_area_union acc = total_area_intersect / total_area_label ret_metrics['IoU'] = iou ret_metrics['Acc'] = acc elif metric == 'mDice': dice = 2 * total_area_intersect / ( total_area_pred_label + total_area_label) acc = total_area_intersect / total_area_label ret_metrics['Dice'] = dice ret_metrics['Acc'] = acc elif metric == 'mFscore': precision = total_area_intersect / total_area_pred_label recall = total_area_intersect / total_area_label f_value = torch.tensor([ f_score(x[0], x[1], beta) for x in zip(precision, recall) ]) ret_metrics['Fscore'] = f_value ret_metrics['Precision'] = precision ret_metrics['Recall'] = recall
ret_metrics = { metric: value.numpy() for metric, value in ret_metrics.items() } if nan_to_num is not None: ret_metrics = OrderedDict({ metric: np.nan_to_num(metric_value, nan=nan_to_num) for metric, metric_value in ret_metrics.items() }) return ret_metrics12345678910111213141516# Copyright (c) OpenMMLab. All rights reserved.from .assigners import * # noqa: F401,F403from .backbones import * # noqa: F401,F403from .builder import (BACKBONES, HEADS, LOSSES, SEGMENTORS, build_backbone, build_head, build_loss, build_segmentor)from .data_preprocessor import SegDataPreProcessorfrom .decode_heads import * # noqa: F401,F403from .losses import * # noqa: F401,F403from .necks import * # noqa: F401,F403from .segmentors import * # noqa: F401,F403from .text_encoder import * # noqa: F401,F403
__all__ = [ 'BACKBONES', 'HEADS', 'LOSSES', 'SEGMENTORS', 'build_backbone', 'build_head', 'build_loss', 'build_segmentor', 'SegDataPreProcessor']123456789101112# Copyright (c) OpenMMLab. All rights reserved.from .base_assigner import BaseAssignerfrom .hungarian_assigner import HungarianAssignerfrom .match_cost import ClassificationCost, CrossEntropyLossCost, DiceCost
__all__ = [ 'BaseAssigner', 'HungarianAssigner', 'ClassificationCost', 'CrossEntropyLossCost', 'DiceCost',]123456789101112131415161718# Copyright (c) OpenMMLab. All rights reserved.from abc import ABCMeta, abstractmethodfrom typing import Optional
from mmengine.structures import InstanceData
class BaseAssigner(metaclass=ABCMeta): """Base assigner that assigns masks to ground truth class labels."""
@abstractmethod def assign(self, pred_instances: InstanceData, gt_instances: InstanceData, gt_instances_ignore: Optional[InstanceData] = None, **kwargs): """Assign masks to either a ground truth class label or a negative label."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# Copyright (c) OpenMMLab. All rights reserved.from typing import List, Union
import torchfrom mmengine import ConfigDictfrom mmengine.structures import InstanceDatafrom scipy.optimize import linear_sum_assignmentfrom torch.cuda.amp import autocast
from mmseg.registry import TASK_UTILSfrom .base_assigner import BaseAssigner
@TASK_UTILS.register_module()class HungarianAssigner(BaseAssigner): """Computes one-to-one matching between prediction masks and ground truth.
This class uses bipartite matching-based assignment to computes an assignment between the prediction masks and the ground truth. The assignment result is based on the weighted sum of match costs. The Hungarian algorithm is used to calculate the best matching with the minimum cost. The prediction masks that are not matched are classified as background.
Args: match_costs (ConfigDict|List[ConfigDict]): Match cost configs. """
def __init__( self, match_costs: Union[List[Union[dict, ConfigDict]], dict, ConfigDict] ) -> None:
if isinstance(match_costs, dict): match_costs = [match_costs] elif isinstance(match_costs, list): assert len(match_costs) > 0, \ 'match_costs must not be a empty list.'
self.match_costs = [ TASK_UTILS.build(match_cost) for match_cost in match_costs ]
def assign(self, pred_instances: InstanceData, gt_instances: InstanceData, **kwargs): """Computes one-to-one matching based on the weighted costs.
This method assign each query prediction to a ground truth or background. The assignment first calculates the cost for each category assigned to each query mask, and then uses the Hungarian algorithm to calculate the minimum cost as the best match.
Args: pred_instances (InstanceData): Instances of model predictions. It includes "masks", with shape (n, h, w) or (n, l), and "cls", with shape (n, num_classes+1) gt_instances (InstanceData): Ground truth of instance annotations. It includes "labels", with shape (k, ), and "masks", with shape (k, h, w) or (k, l).
Returns: matched_quiery_inds (Tensor): The indexes of matched quieres. matched_label_inds (Tensor): The indexes of matched labels. """ # compute weighted cost cost_list = [] with autocast(enabled=False): for match_cost in self.match_costs: cost = match_cost( pred_instances=pred_instances, gt_instances=gt_instances) cost_list.append(cost) cost = torch.stack(cost_list).sum(dim=0)
device = cost.device # do Hungarian matching on CPU using linear_sum_assignment cost = cost.detach().cpu() if linear_sum_assignment is None: raise ImportError('Please run "pip install scipy" ' 'to install scipy first.')
matched_quiery_inds, matched_label_inds = linear_sum_assignment(cost) matched_quiery_inds = torch.from_numpy(matched_quiery_inds).to(device) matched_label_inds = torch.from_numpy(matched_label_inds).to(device)
return matched_quiery_inds, matched_label_inds123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231# Copyright (c) OpenMMLab. All rights reserved.from abc import abstractmethodfrom typing import Union
import torchimport torch.nn.functional as Ffrom mmengine.structures import InstanceDatafrom torch import Tensor
from mmseg.registry import TASK_UTILS
class BaseMatchCost: """Base match cost class.
Args: weight (Union[float, int]): Cost weight. Defaults to 1. """
def __init__(self, weight: Union[float, int] = 1.) -> None: self.weight = weight
@abstractmethod def __call__(self, pred_instances: InstanceData, gt_instances: InstanceData, **kwargs) -> Tensor: """Compute match cost.
Args: pred_instances (InstanceData): Instances of model predictions. It often includes "labels" and "scores". gt_instances (InstanceData): Ground truth of instance annotations. It usually includes "labels".
Returns: Tensor: Match Cost matrix of shape (num_preds, num_gts). """ pass
@TASK_UTILS.register_module()class ClassificationCost(BaseMatchCost): """ClsSoftmaxCost.
Args: weight (Union[float, int]): Cost weight. Defaults to 1.
Examples: >>> from mmseg.models.assigners import ClassificationCost >>> import torch >>> self = ClassificationCost() >>> cls_pred = torch.rand(4, 3) >>> gt_labels = torch.tensor([0, 1, 2]) >>> factor = torch.tensor([10, 8, 10, 8]) >>> self(cls_pred, gt_labels) tensor([[-0.3430, -0.3525, -0.3045], [-0.3077, -0.2931, -0.3992], [-0.3664, -0.3455, -0.2881], [-0.3343, -0.2701, -0.3956]]) """
def __init__(self, weight: Union[float, int] = 1) -> None: super().__init__(weight=weight)
def __call__(self, pred_instances: InstanceData, gt_instances: InstanceData, **kwargs) -> Tensor: """Compute match cost.
Args: pred_instances (InstanceData): "scores" inside is predicted classification logits, of shape (num_queries, num_class). gt_instances (InstanceData): "labels" inside should have shape (num_gt, ).
Returns: Tensor: Match Cost matrix of shape (num_preds, num_gts). """ assert hasattr(pred_instances, 'scores'), \ "pred_instances must contain 'scores'" assert hasattr(gt_instances, 'labels'), \ "gt_instances must contain 'labels'" pred_scores = pred_instances.scores gt_labels = gt_instances.labels
pred_scores = pred_scores.softmax(-1) cls_cost = -pred_scores[:, gt_labels]
return cls_cost * self.weight
@TASK_UTILS.register_module()class DiceCost(BaseMatchCost): """Cost of mask assignments based on dice losses.
Args: pred_act (bool): Whether to apply sigmoid to mask_pred. Defaults to False. eps (float): Defaults to 1e-3. naive_dice (bool): If True, use the naive dice loss in which the power of the number in the denominator is the first power. If False, use the second power that is adopted by K-Net and SOLO. Defaults to True. weight (Union[float, int]): Cost weight. Defaults to 1. """
def __init__(self, pred_act: bool = False, eps: float = 1e-3, naive_dice: bool = True, weight: Union[float, int] = 1.) -> None: super().__init__(weight=weight) self.pred_act = pred_act self.eps = eps self.naive_dice = naive_dice
def _binary_mask_dice_loss(self, mask_preds: Tensor, gt_masks: Tensor) -> Tensor: """ Args: mask_preds (Tensor): Mask prediction in shape (num_queries, *). gt_masks (Tensor): Ground truth in shape (num_gt, *) store 0 or 1, 0 for negative class and 1 for positive class.
Returns: Tensor: Dice cost matrix in shape (num_queries, num_gt). """ mask_preds = mask_preds.flatten(1) gt_masks = gt_masks.flatten(1).float() numerator = 2 * torch.einsum('nc,mc->nm', mask_preds, gt_masks) if self.naive_dice: denominator = mask_preds.sum(-1)[:, None] + \ gt_masks.sum(-1)[None, :] else: denominator = mask_preds.pow(2).sum(1)[:, None] + \ gt_masks.pow(2).sum(1)[None, :] loss = 1 - (numerator + self.eps) / (denominator + self.eps) return loss
def __call__(self, pred_instances: InstanceData, gt_instances: InstanceData, **kwargs) -> Tensor: """Compute match cost.
Args: pred_instances (InstanceData): Predicted instances which must contain "masks". gt_instances (InstanceData): Ground truth which must contain "mask".
Returns: Tensor: Match Cost matrix of shape (num_preds, num_gts). """ assert hasattr(pred_instances, 'masks'), \ "pred_instances must contain 'masks'" assert hasattr(gt_instances, 'masks'), \ "gt_instances must contain 'masks'" pred_masks = pred_instances.masks gt_masks = gt_instances.masks
if self.pred_act: pred_masks = pred_masks.sigmoid() dice_cost = self._binary_mask_dice_loss(pred_masks, gt_masks) return dice_cost * self.weight
@TASK_UTILS.register_module()class CrossEntropyLossCost(BaseMatchCost): """CrossEntropyLossCost.
Args: use_sigmoid (bool): Whether the prediction uses sigmoid of softmax. Defaults to True. weight (Union[float, int]): Cost weight. Defaults to 1. """
def __init__(self, use_sigmoid: bool = True, weight: Union[float, int] = 1.) -> None: super().__init__(weight=weight) self.use_sigmoid = use_sigmoid
def _binary_cross_entropy(self, cls_pred: Tensor, gt_labels: Tensor) -> Tensor: """ Args: cls_pred (Tensor): The prediction with shape (num_queries, 1, *) or (num_queries, *). gt_labels (Tensor): The learning label of prediction with shape (num_gt, *).
Returns: Tensor: Cross entropy cost matrix in shape (num_queries, num_gt). """ cls_pred = cls_pred.flatten(1).float() gt_labels = gt_labels.flatten(1).float() n = cls_pred.shape[1] pos = F.binary_cross_entropy_with_logits( cls_pred, torch.ones_like(cls_pred), reduction='none') neg = F.binary_cross_entropy_with_logits( cls_pred, torch.zeros_like(cls_pred), reduction='none') cls_cost = torch.einsum('nc,mc->nm', pos, gt_labels) + \ torch.einsum('nc,mc->nm', neg, 1 - gt_labels) cls_cost = cls_cost / n
return cls_cost
def __call__(self, pred_instances: InstanceData, gt_instances: InstanceData, **kwargs) -> Tensor: """Compute match cost.
Args: pred_instances (:obj:`InstanceData`): Predicted instances which must contain ``masks``. gt_instances (:obj:`InstanceData`): Ground truth which must contain ``masks``.
Returns: Tensor: Match Cost matrix of shape (num_preds, num_gts). """ assert hasattr(pred_instances, 'masks'), \ "pred_instances must contain 'masks'" assert hasattr(gt_instances, 'masks'), \ "gt_instances must contain 'masks'" pred_masks = pred_instances.masks gt_masks = gt_instances.masks if self.use_sigmoid: cls_cost = self._binary_cross_entropy(pred_masks, gt_masks) else: raise NotImplementedError
return cls_cost * self.weight1234567891011121314151617181920212223242526272829303132333435# Copyright (c) OpenMMLab. All rights reserved.from .beit import BEiTfrom .bisenetv1 import BiSeNetV1from .bisenetv2 import BiSeNetV2from .cgnet import CGNetfrom .ddrnet import DDRNetfrom .erfnet import ERFNetfrom .fast_scnn import FastSCNNfrom .hrnet import HRNetfrom .icnet import ICNetfrom .mae import MAEfrom .mit import MixVisionTransformerfrom .mobilenet_v2 import MobileNetV2from .mobilenet_v3 import MobileNetV3from .mscan import MSCANfrom .pidnet import PIDNetfrom .resnest import ResNeStfrom .resnet import ResNet, ResNetV1c, ResNetV1dfrom .resnext import ResNeXtfrom .stdc import STDCContextPathNet, STDCNetfrom .swin import SwinTransformerfrom .timm_backbone import TIMMBackbonefrom .twins import PCPVT, SVTfrom .unet import UNetfrom .vit import VisionTransformerfrom .vpd import VPD
__all__ = [ 'ResNet', 'ResNetV1c', 'ResNetV1d', 'ResNeXt', 'HRNet', 'FastSCNN', 'ResNeSt', 'MobileNetV2', 'UNet', 'CGNet', 'MobileNetV3', 'VisionTransformer', 'SwinTransformer', 'MixVisionTransformer', 'BiSeNetV1', 'BiSeNetV2', 'ICNet', 'TIMMBackbone', 'ERFNet', 'PCPVT', 'SVT', 'STDCNet', 'STDCContextPathNet', 'BEiT', 'MAE', 'PIDNet', 'MSCAN', 'DDRNet', 'VPD']third-party/InterFormer/mmseg.yamlAdded+257
third-party/InterFormer/mmseg/datasets/transforms/__init__.pyAdded+30
third-party/InterFormer/mmseg/datasets/transforms/__pycache__/__init__.cpython-38.pycAdded
third-party/InterFormer/mmseg/datasets/transforms/__pycache__/formatting.cpython-38.pycAdded
third-party/InterFormer/mmseg/datasets/transforms/__pycache__/loading.cpython-38.pycAdded
third-party/InterFormer/mmseg/datasets/transforms/__pycache__/transforms.cpython-38.pycAdded
third-party/InterFormer/mmseg/datasets/transforms/formatting.pyAdded+112
third-party/InterFormer/mmseg/datasets/transforms/loading.pyAdded+771
third-party/InterFormer/mmseg/datasets/transforms/transforms.pyAdded+2537
third-party/InterFormer/mmseg/datasets/voc.pyAdded+40
third-party/InterFormer/mmseg/engine/__init__.pyAdded+12
third-party/InterFormer/mmseg/engine/__pycache__/__init__.cpython-38.pycAdded
third-party/InterFormer/mmseg/engine/hooks/__init__.pyAdded+4
third-party/InterFormer/mmseg/engine/hooks/__pycache__/__init__.cpython-38.pycAdded
third-party/InterFormer/mmseg/engine/hooks/__pycache__/visualization_hook.cpython-38.pycAdded
third-party/InterFormer/mmseg/engine/hooks/visualization_hook.pyAdded+129
third-party/InterFormer/mmseg/engine/optimizers/__init__.pyAdded+9
third-party/InterFormer/mmseg/engine/optimizers/__pycache__/__init__.cpython-38.pycAdded
third-party/InterFormer/mmseg/engine/optimizers/__pycache__/force_default_constructor.cpython-38.pycAdded
third-party/InterFormer/mmseg/engine/optimizers/__pycache__/layer_decay_optimizer_constructor.cpython-38.pycAdded
third-party/InterFormer/mmseg/engine/optimizers/force_default_constructor.pyAdded+255
third-party/InterFormer/mmseg/engine/optimizers/layer_decay_optimizer_constructor.pyAdded+207
third-party/InterFormer/mmseg/engine/schedulers/__init__.pyAdded+4
third-party/InterFormer/mmseg/engine/schedulers/__pycache__/__init__.cpython-38.pycAdded
third-party/InterFormer/mmseg/engine/schedulers/__pycache__/poly_ratio_scheduler.cpython-38.pycAdded
third-party/InterFormer/mmseg/engine/schedulers/poly_ratio_scheduler.pyAdded+62
third-party/InterFormer/mmseg/evaluation/__init__.pyAdded+4
third-party/InterFormer/mmseg/evaluation/__pycache__/__init__.cpython-38.pycAdded
third-party/InterFormer/mmseg/evaluation/metrics/__init__.pyAdded+6
third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/__init__.cpython-38.pycAdded
third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/citys_metric.cpython-38.pycAdded
third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/depth_metric.cpython-38.pycAdded
third-party/InterFormer/mmseg/evaluation/metrics/__pycache__/iou_metric.cpython-38.pycAdded
third-party/InterFormer/mmseg/evaluation/metrics/citys_metric.pyAdded+158
third-party/InterFormer/mmseg/evaluation/metrics/depth_metric.pyAdded+212
third-party/InterFormer/mmseg/evaluation/metrics/iou_metric.pyAdded+286
third-party/InterFormer/mmseg/models/__init__.pyAdded+16
third-party/InterFormer/mmseg/models/__pycache__/__init__.cpython-38.pycAdded
third-party/InterFormer/mmseg/models/__pycache__/builder.cpython-38.pycAdded
third-party/InterFormer/mmseg/models/__pycache__/data_preprocessor.cpython-38.pycAdded
third-party/InterFormer/mmseg/models/assigners/__init__.pyAdded+12
third-party/InterFormer/mmseg/models/assigners/__pycache__/__init__.cpython-38.pycAdded
third-party/InterFormer/mmseg/models/assigners/__pycache__/base_assigner.cpython-38.pycAdded
third-party/InterFormer/mmseg/models/assigners/__pycache__/hungarian_assigner.cpython-38.pycAdded
third-party/InterFormer/mmseg/models/assigners/__pycache__/match_cost.cpython-38.pycAdded
third-party/InterFormer/mmseg/models/assigners/base_assigner.pyAdded+18
third-party/InterFormer/mmseg/models/assigners/hungarian_assigner.pyAdded+86
third-party/InterFormer/mmseg/models/assigners/match_cost.pyAdded+231
third-party/InterFormer/mmseg/models/backbones/__init__.pyAdded+35
third-party/InterFormer/mmseg/models/backbones/__pycache__/__init__.cpython-38.pycAdded