albumentations.core.composition
Module for composing multiple transforms into augmentation pipelines. This module provides classes for combining multiple transformations into cohesive augmentation pipelines. It includes various composition strategies such as sequential application, random selection, and conditional application of transforms. These composition classes handle the coordination between different transforms, ensuring proper data flow and maintaining consistent behavior across the augmentation pipeline.
Members
- classBaseCompose
- classCompose
- classOneOf
- classOneOrOther
- classRandomOrder
- classReplayCompose
- classSelectiveChannelTransform
- classSequential
- classSomeOf
BaseComposeclass
BaseCompose(
transforms: TransformsSeqType,
p: float,
mask_interpolation: int | None = None,
seed: int | None = None,
save_applied_params: bool = False
)
Base class for composing multiple transforms together. This class serves as a foundation for creating compositions of transforms in the Albumentations library. It provides basic functionality for managing a sequence of transforms and applying them to data.
Parameters
Name | Type | Default | Description |
---|---|---|---|
transforms | TransformsSeqType | - | A list of transforms to be applied. |
p | float | - | Probability of applying the compose. Should be in the range [0, 1]. |
mask_interpolation | One of:
| None | - |
seed | One of:
| None | - |
save_applied_params | bool | False | - |
Notes
- Subclasses should implement the __call__ method to define how the composition is applied to data. - The class supports serialization and deserialization of transforms. - It provides methods for adding targets, setting deterministic behavior, and checking data validity post-transform.
Composeclass
Compose(
transforms: TransformsSeqType,
bbox_params: dict[str, Any] | BboxParams | None = None,
keypoint_params: dict[str, Any] | KeypointParams | None = None,
additional_targets: dict[str, str] | None = None,
p: float = 1.0,
is_check_shapes: bool = True,
strict: bool = False,
mask_interpolation: int | None = None,
seed: int | None = None,
save_applied_params: bool = False
)
Compose multiple transforms together and apply them sequentially to input data. This class allows you to chain multiple image augmentation transforms and apply them in a specified order. It also handles bounding box and keypoint transformations if the appropriate parameters are provided.
Parameters
Name | Type | Default | Description |
---|---|---|---|
transforms | TransformsSeqType | - | A list of transforms to apply. |
bbox_params | One of:
| None | Parameters for bounding box transforms. Can be a dict of params or a BboxParams object. Default is None. |
keypoint_params | One of:
| None | Parameters for keypoint transforms. Can be a dict of params or a KeypointParams object. Default is None. |
additional_targets | One of:
| None | A dictionary mapping additional target names to their types. For example, {'image2': 'image'}. Default is None. |
p | float | 1.0 | Probability of applying all transforms. Should be in range [0, 1]. Default is 1.0. |
is_check_shapes | bool | True | If True, checks consistency of shapes for image/mask/masks on each call. Disable only if you are sure about your data consistency. Default is True. |
strict | bool | False | If True, enables strict mode which: 1. Validates that all input keys are known/expected 2. Validates that no transforms have invalid arguments 3. Raises ValueError if any validation fails If False, these validations are skipped. Default is False. |
mask_interpolation | One of:
| None | Interpolation method for mask transforms. When defined, it overrides the interpolation method specified in individual transforms. Default is None. |
seed | One of:
| None | Controls reproducibility of random augmentations. Compose uses its own internal random state, completely independent from global random seeds. When seed is set (int): - Creates a fixed internal random state - Two Compose instances with the same seed and transforms will produce identical sequences of augmentations - Each call to the same Compose instance still produces random augmentations, but these sequences are reproducible between different Compose instances - Example: transform1 = A.Compose([...], seed=137) and transform2 = A.Compose([...], seed=137) will produce identical sequences When seed is None (default): - Generates a new internal random state on each Compose creation - Different Compose instances will produce different sequences of augmentations - Example: transform = A.Compose([...]) # random results Important: Setting random seeds outside of Compose (like np.random.seed() or random.seed()) has no effect on augmentations as Compose uses its own internal random state. |
save_applied_params | bool | False | If True, saves the applied parameters of each transform. Default is False. You will need to use the `applied_transforms` key in the output dictionary to access the parameters. |
Example
>>> import albumentations as A
>>> transform = A.Compose([
... A.RandomCrop(width=256, height=256),
... A.HorizontalFlip(p=0.5),
... A.RandomBrightnessContrast(p=0.2),
... ], seed=137)
>>> transformed = transform(image=image)
Notes
- The class checks the validity of input data and shapes if is_check_args and is_check_shapes are True. - When bbox_params or keypoint_params are provided, it sets up the corresponding processors. - The transform can handle additional targets specified in the additional_targets dictionary. - When strict mode is enabled, it performs additional validation to ensure data and transform configuration correctness.
OneOfclass
OneOf(
transforms: TransformsSeqType,
p: float = 0.5
)
Select one of transforms to apply. Selected transform will be called with `force_apply=True`. Transforms probabilities will be normalized to one 1, so in this case transforms probabilities works as weights.
Parameters
Name | Type | Default | Description |
---|---|---|---|
transforms | TransformsSeqType | - | list of transformations to compose. |
p | float | 0.5 | probability of applying selected transform. Default: 0.5. |
OneOrOtherclass
OneOrOther(
first: TransformType | None = None,
second: TransformType | None = None,
transforms: TransformsSeqType | None = None,
p: float = 0.5
)
Select one or another transform to apply. Selected transform will be called with `force_apply=True`.
Parameters
Name | Type | Default | Description |
---|---|---|---|
first | One of:
| None | - |
second | One of:
| None | - |
transforms | One of:
| None | - |
p | float | 0.5 | - |
RandomOrderclass
RandomOrder(
transforms: TransformsSeqType,
n: int = 1,
replace: bool = False,
p: float = 1
)
Apply a random subset of transforms from the given list in a random order. Selects exactly `n` transforms uniformly at random from the list, and then applies the selected transforms in a random order. Each selected transform is applied based on its individual probability `p`.
Parameters
Name | Type | Default | Description |
---|---|---|---|
transforms | TransformsSeqType | - | - |
n | int | 1 | - |
replace | bool | False | - |
p | float | 1 | - |
Example
>>> import albumentations as A
>>> transform = A.RandomOrder([
... A.HorizontalFlip(p=0.5),
... A.VerticalFlip(p=1.0),
... A.RandomBrightnessContrast(p=0.8),
... ], n=2, replace=False, p=1.0)
>>> # This will uniformly select 2 transforms and apply them in a random order,
>>> # respecting their individual probabilities (0.5, 1.0, 0.8).
Notes
- Inherits from SomeOf, but overrides `_get_idx` to ensure random order without sorting. - Selection is uniform; application depends on individual transform probabilities.
ReplayComposeclass
ReplayCompose(
transforms: TransformsSeqType,
bbox_params: dict[str, Any] | BboxParams | None = None,
keypoint_params: dict[str, Any] | KeypointParams | None = None,
additional_targets: dict[str, str] | None = None,
p: float = 1.0,
is_check_shapes: bool = True,
save_key: str = replay
)
Composition class that enables transform replay functionality. This class extends the Compose class with the ability to record and replay transformations. This is useful for applying the same sequence of random transformations to different data.
Parameters
Name | Type | Default | Description |
---|---|---|---|
transforms | TransformsSeqType | - | List of transformations to compose. |
bbox_params | One of:
| None | Parameters for bounding box transforms. |
keypoint_params | One of:
| None | Parameters for keypoint transforms. |
additional_targets | One of:
| None | Dictionary of additional targets. |
p | float | 1.0 | Probability of applying the compose. |
is_check_shapes | bool | True | Whether to check shapes of different targets. |
save_key | str | replay | Key for storing the applied transformations. |
SelectiveChannelTransformclass
SelectiveChannelTransform(
transforms: TransformsSeqType,
channels: Sequence[int] = (0, 1, 2),
p: float = 1.0
)
A transformation class to apply specified transforms to selected channels of an image. This class extends BaseCompose to allow selective application of transformations to specified image channels. It extracts the selected channels, applies the transformations, and then reinserts the transformed channels back into their original positions in the image.
Parameters
Name | Type | Default | Description |
---|---|---|---|
transforms | TransformsSeqType | - | A sequence of transformations (from Albumentations) to be applied to the specified channels. |
channels | Sequence[int] | (0, 1, 2) | A sequence of integers specifying the indices of the channels to which the transforms should be applied. |
p | float | 1.0 | Probability that the transform will be applied; the default is 1.0 (always apply). |
Returns
- dict[str, Any]: The transformed data dictionary, which includes the transformed 'image' key.
Sequentialclass
Sequential(
transforms: TransformsSeqType,
p: float = 0.5
)
Sequentially applies all transforms to targets. Note: This transform is not intended to be a replacement for `Compose`. Instead, it should be used inside `Compose` the same way `OneOf` or `OneOrOther` are used. For instance, you can combine `OneOf` with `Sequential` to create an augmentation pipeline that contains multiple sequences of augmentations and applies one randomly chose sequence to input data (see the `Example` section for an example definition of such pipeline).
Parameters
Name | Type | Default | Description |
---|---|---|---|
transforms | TransformsSeqType | - | - |
p | float | 0.5 | - |
Example
>>> import albumentations as A
>>> transform = A.Compose([
>>> A.OneOf([
>>> A.Sequential([
>>> A.HorizontalFlip(p=0.5),
>>> A.ShiftScaleRotate(p=0.5),
>>> ]),
>>> A.Sequential([
>>> A.VerticalFlip(p=0.5),
>>> A.RandomBrightnessContrast(p=0.5),
>>> ]),
>>> ], p=1)
>>> ])
Notes
This transform is not intended to be a replacement for `Compose`. Instead, it should be used inside `Compose` the same way `OneOf` or `OneOrOther` are used. For instance, you can combine `OneOf` with `Sequential` to create an augmentation pipeline that contains multiple sequences of augmentations and applies one randomly chose sequence to input data (see the `Example` section for an example definition of such pipeline).
SomeOfclass
SomeOf(
transforms: TransformsSeqType,
n: int = 1,
replace: bool = False,
p: float = 1
)
Selects exactly `n` transforms from the given list and applies them. The selection of which `n` transforms to apply is done **uniformly at random** from the provided list. Each transform in the list has an equal chance of being selected. Once the `n` transforms are selected, each one is applied **based on its individual probability** `p`.
Parameters
Name | Type | Default | Description |
---|---|---|---|
transforms | TransformsSeqType | - | A list of transforms to choose from. |
n | int | 1 | The exact number of transforms to select and potentially apply. If `replace=False` and `n` is greater than the number of available transforms, `n` will be capped at the number of transforms. |
replace | bool | False | Whether to sample transforms with replacement. If True, the same transform can be selected multiple times (up to `n` times). Default is False. |
p | float | 1 | The probability that this `SomeOf` composition will be applied. If applied, it will select `n` transforms and attempt to apply them. Default is 1.0. |
Example
>>> import albumentations as A
>>> transform = A.SomeOf([
... A.HorizontalFlip(p=0.5), # 50% chance to apply if selected
... A.VerticalFlip(p=0.8), # 80% chance to apply if selected
... A.RandomRotate90(p=1.0), # 100% chance to apply if selected
... ], n=2, replace=False, p=1.0) # Always select 2 transforms uniformly
# In each call, 2 transforms out of 3 are chosen uniformly.
# For example, if HFlip and VFlip are chosen:
# - HFlip runs if random() < 0.5
# - VFlip runs if random() < 0.8
# If VFlip and Rotate90 are chosen:
# - VFlip runs if random() < 0.8
# - Rotate90 runs if random() < 1.0 (always)
Notes
- The overall probability `p` of the `SomeOf` block determines if *any* selection and application occurs. - The individual probability `p` of each transform inside the list determines if that specific transform runs *if it is selected*. - If `replace` is True, the same transform might be selected multiple times, and its individual probability `p` will be checked each time it's encountered.