mmseg.apis — MMSegmentation 1.2.2 documentation (original) (raw)

mmseg.datasets

datasets

transforms

mmseg.engine

hooks

class mmseg.engine.hooks.SegVisualizationHook(draw: bool = False, interval: int = 50, show: bool = False, wait_time: float = 0.0, backend_args: Optional[dict] = None)[source]

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.

Parameters

after_test_iter(runner: mmengine.runner.runner.Runner, batch_idx: int, data_batch: dict, outputs: Sequence[mmseg.structures.seg_data_sample.SegDataSample]) → None[source]

Run after every testing iterations.

Parameters

after_val_iter(runner: mmengine.runner.runner.Runner, batch_idx: int, data_batch: dict, outputs: Sequence[mmseg.structures.seg_data_sample.SegDataSample]) → None[source]

Run after every self.interval validation iterations.

Parameters

optimizers

class mmseg.engine.optimizers.ForceDefaultOptimWrapperConstructor(optim_wrapper_cfg: dict, paramwise_cfg: Optional[dict] = None)[source]

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 fieldforce_default_settings which allows for enforcing default settings on optimizer parameters.

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 anddcn_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 originaldcn_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.

Parameters

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).

add_params(params: List[dict], module: torch.nn.modules.module.Module, prefix: str = '', is_dcn_module: Optional[Union[int, float]] = None) → None[source]

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.

Parameters

class mmseg.engine.optimizers.LayerDecayOptimizerConstructor(optim_wrapper_cfg, paramwise_cfg)[source]

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.

class mmseg.engine.optimizers.LearningRateDecayOptimizerConstructor(optim_wrapper_cfg: dict, paramwise_cfg: Optional[dict] = None)[source]

Different learning rates are set for different layers of backbone.

Note: Currently, this optimizer constructor is built for ConvNeXt, BEiT and MAE.

add_params(params, module, **kwargs)[source]

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.

Parameters

mmseg.evaluation

metrics

class mmseg.evaluation.metrics.CityscapesMetric(output_dir: str, ignore_index: int = 255, format_only: bool = False, keep_results: bool = False, collect_device: str = 'cpu', prefix: Optional[str] = None, **kwargs)[source]

Cityscapes evaluation metric.

Parameters

compute_metrics(results: list) → Dict[str, float][source]

Compute the metrics from processed results.

Parameters

results (list) – Testing results of the dataset.

Returns

float]: Cityscapes evaluation results.

Return type

dict[str

process(data_batch: dict, data_samples: Sequence[dict]) → None[source]

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.

Parameters

class mmseg.evaluation.metrics.DepthMetric(depth_metrics: Optional[List[str]] = None, min_depth_eval: float = 0.0, max_depth_eval: 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)[source]

Depth estimation evaluation metric.

Parameters

compute_metrics(results: list) → Dict[str, float][source]

Compute the metrics from processed results.

Parameters

results (list) – The processed results of each batch.

Returns

The computed metrics. The keys are the names of

the metrics, and the values are corresponding results. The keys are identical with self.metrics.

Return type

Dict[str, float]

process(data_batch: dict, data_samples: Sequence[dict]) → None[source]

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.

Parameters

class mmseg.evaluation.metrics.IoUMetric(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)[source]

IoU evaluation metric.

Parameters

compute_metrics(results: list) → Dict[str, float][source]

Compute the metrics from processed results.

Parameters

results (list) – The processed results of each batch.

Returns

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.

Return type

Dict[str, float]

static intersect_and_union(pred_label: torch._VariableFunctionsClass.tensor, label: torch._VariableFunctionsClass.tensor, num_classes: int, ignore_index: int)[source]

Calculate Intersection and Union.

Parameters

Returns

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.

Return type

torch.Tensor

process(data_batch: dict, data_samples: Sequence[dict]) → None[source]

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.

Parameters

static total_area_to_metrics(total_area_intersect: numpy.ndarray, total_area_union: numpy.ndarray, total_area_pred_label: numpy.ndarray, total_area_label: numpy.ndarray, metrics: List[str] = ['mIoU'], nan_to_num: Optional[int] = None, beta: int = 1)[source]

Calculate evaluation metrics :param total_area_intersect: The intersection of prediction

and ground truth histogram on all classes.

Parameters

Returns

per category evaluation metrics,

shape (num_classes, ).

Return type

Dict[str, np.ndarray]

mmseg.models

backbones

decode_heads

segmentors

losses

necks

utils

mmseg.structures

structures

class mmseg.structures.BasePixelSampler(**kwargs)[source]

Base class of pixel sampler.

abstract sample(seg_logit, seg_label)[source]

Placeholder for sample function.

class mmseg.structures.OHEMPixelSampler(context, thresh=None, min_kept=100000)[source]

Online Hard Example Mining Sampler for segmentation.

Parameters

sample(seg_logit, seg_label)[source]

Sample pixels that have high loss or with low prediction confidence.

Parameters

Returns

segmentation weight, shape (N, H, W)

Return type

torch.Tensor

class mmseg.structures.SegDataSample(*, metainfo: Optional[dict] = None, **kwargs)[source]

A data structure interface of MMSegmentation. They are used as interfaces between different components.

The attributes in SegDataSample are divided into several parts:

Examples

import torch import numpy as np from mmengine.structures import PixelData from mmseg.structures import SegDataSample

data_sample = SegDataSample() img_meta = dict(img_shape=(4, 4, 3), ... pad_shape=(4, 4, 3)) gt_segmentations = PixelData(metainfo=img_meta) gt_segmentations.data = torch.randint(0, 2, (1, 4, 4)) data_sample.gt_sem_seg = gt_segmentations assert 'img_shape' in data_sample.gt_sem_seg.metainfo_keys() data_sample.gt_sem_seg.shape (4, 4) print(data_sample)

<SegDataSample(

META INFORMATION

DATA FIELDS gt_sem_seg: <PixelData(

META INFORMATION img_shape: (4, 4, 3) pad_shape: (4, 4, 3)

DATA FIELDS data: tensor([[[1, 1, 1, 0],

[1, 0, 1, 1], [1, 1, 1, 1], [0, 1, 0, 1]]])

) at 0x1c2b4156460>

) at 0x1c2aae44d60>

data_sample = SegDataSample() gt_sem_seg_data = dict(sem_seg=torch.rand(1, 4, 4)) gt_sem_seg = PixelData(**gt_sem_seg_data) data_sample.gt_sem_seg = gt_sem_seg assert 'gt_sem_seg' in data_sample assert 'sem_seg' in data_sample.gt_sem_seg

mmseg.structures.build_pixel_sampler(cfg, **default_args)[source]

Build pixel sampler for segmentation map.

sampler

class mmseg.structures.sampler.BasePixelSampler(**kwargs)[source]

Base class of pixel sampler.

abstract sample(seg_logit, seg_label)[source]

Placeholder for sample function.

class mmseg.structures.sampler.OHEMPixelSampler(context, thresh=None, min_kept=100000)[source]

Online Hard Example Mining Sampler for segmentation.

Parameters

sample(seg_logit, seg_label)[source]

Sample pixels that have high loss or with low prediction confidence.

Parameters

Returns

segmentation weight, shape (N, H, W)

Return type

torch.Tensor

mmseg.structures.sampler.build_pixel_sampler(cfg, **default_args)[source]

Build pixel sampler for segmentation map.

mmseg.visualization

mmseg.utils