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
- classComposeTransformNotFoundError
- classBaseCompose
- classCompose
- classOneOf
- classSomeOf
- classRandomOrder
- classOneOrOther
- classSelectiveChannelTransform
- classReplayCompose
- classSequential
ComposeTransformNotFoundErrorclass
ComposeTransformNotFoundError()Raised when compose subtraction cannot find a requested transform class, preserving ValueError compatibility while satisfying operator semantics.
BaseComposeclass
BaseCompose(
transforms: TransformsSeqType,
p: float,
mask_interpolation: int | None,
seed: int | None,
save_applied_params: bool = False,
**kwargs: Any
)Base class for composing multiple transforms. Supports +, __radd__, - for pipeline modification; serialization; add_targets, set_deterministic. 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. The class supports dynamic pipeline modification after initialization using mathematical operators: - Addition (`+`): Add transforms to the end of the pipeline - Right addition (`__radd__`): Add transforms to the beginning of the pipeline - Subtraction (`-`): Remove transforms by class from the pipeline Attributes: transforms (List[TransformType]): A list of transforms to be applied. p (float): Probability of applying the compose. Should be in the range [0, 1]. replay_mode (bool): If True, the compose is in replay mode. _additional_targets (Dict[str, str]): Additional targets for transforms. _available_keys (Set[str]): Set of available keys for data. processors (Dict[str, Union[BboxProcessor, KeypointsProcessor]]): Processors for specific data types. Args: transforms (TransformsSeqType): A sequence of transforms to compose. p (float): Probability of applying the compose. Raises: ValueError: If an invalid additional target is specified. Note: - 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. - All compose classes support pipeline modification operators: - `compose + transform` adds individual transform(s) to the end - `transform + compose` adds individual transform(s) to the beginning - `compose - TransformClass` removes transforms by class type - Only BasicTransform instances (not BaseCompose) can be added - All operator operations return new instances without modifying the original. Examples: >>> import albumentations as A >>> # Create base pipeline >>> compose = A.Compose([A.HorizontalFlip(p=1.0)]) >>> >>> # Add transforms using operators >>> extended = compose + A.VerticalFlip(p=1.0) # Append >>> extended = compose + [A.Blur(), A.Rotate()] # Append multiple >>> extended = A.RandomCrop(256, 256) + compose # Prepend >>> >>> # Remove transforms by class >>> compose = A.Compose([A.HorizontalFlip(p=0.5), A.VerticalFlip(p=1.0)]) >>> reduced = compose - A.HorizontalFlip # Remove by class
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| transforms | TransformsSeqType | - | - |
| p | float | - | - |
| mask_interpolation | One of:
| - | - |
| seed | One of:
| - | - |
| save_applied_params | bool | False | - |
| **kwargs | Any | - | - |
Composeclass
Compose(
transforms: TransformsSeqType,
bbox_params: dict[str, Any] | BboxParams | None,
keypoint_params: dict[str, Any] | KeypointParams | None,
additional_targets: dict[str, str] | None,
p: float = 1.0,
is_check_shapes: bool = True,
strict: bool = False,
mask_interpolation: int | None,
seed: int | None,
save_applied_params: bool = False,
telemetry: bool = True,
instance_binding: Sequence[str] | None,
strict_instance_invariant: bool = True,
semantic_mask_label_mappings: dict[str, dict[int, int]] | None
)Compose multiple transforms sequentially. Supports bbox_params, keypoint_params, additional_targets, strict, seed; supports +, -, __radd__. 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. The configured child order is frozen after construction. Mathematical operators create a new Compose with the requested child sequence while preserving bbox, keypoint, and additional-target policy. Args: transforms (Sequence[BasicTransform | BaseCompose]): Ordered transforms to apply. Compose stores an immutable tuple of this configuration. bbox_params (dict[str, Any] | BboxParams | None): Parameters for bounding box transforms. Can be a dict of params or a BboxParams object. Default is None. keypoint_params (dict[str, Any] | KeypointParams | None): Parameters for keypoint transforms. Can be a dict of params or a KeypointParams object. Default is None. additional_targets (dict[str, str] | None): A dictionary mapping additional target names to their types. For example, {'image2': 'image'}. Passing a spatial alias also requires passing its canonical target (`image` in this example). Default is None. semantic_mask_label_mappings (dict[str, dict[int, int]] | None): Label replacements applied to spatial mask targets when a realized transform emits a label-mapping event. The outer key is the emitted event name; `D4` and `SquareSymmetry` emit the corresponding base reflection event (`HorizontalFlip`, `VerticalFlip`, or `Transpose`) rather than their class name. Other transforms may emit their own events, such as `Flip3D`. The inner dictionary maps source class IDs to target class IDs. `Flip3D` emits its event for a realized reflection across an odd number of axes and remaps `mask3d` and its aliases, not 2D `mask` or `masks` targets. Default: None. p (float): Probability of applying all transforms. Should be in range [0, 1]. Default is 1.0. is_check_shapes (bool): 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): 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 (int | None): Interpolation method for mask transforms. When defined, it overrides the interpolation method specified in individual transforms. Default is None. seed (int | 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): 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. telemetry (bool): If True, enables telemetry collection to help improve AlbumentationsX. This collects anonymous usage data including pipeline configuration, environment info, and common parameter patterns. No image data or personal information is collected. Telemetry can be disabled globally via settings.telemetry_enabled = False or by setting the environment variable ALBUMENTATIONS_NO_TELEMETRY=1. Default is True. instance_binding (Sequence[str] | None): Targets that describe the same object in each `instances` item. Supported targets are `mask` or `masks`, `bboxes`, and `keypoints`. Compose transforms these targets together and removes all fields for an instance when its bbox fails bbox filtering. When masks and bboxes are bound, Compose also removes the instance if its transformed mask contains no non-zero pixels. Default is None. Examples: >>> # Basic usage: >>> 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) >>> # Swap left/right semantic-mask class IDs after a realized horizontal flip: >>> transform = A.Compose( ... [A.HorizontalFlip(p=1.0)], ... semantic_mask_label_mappings={"HorizontalFlip": {2: 3, 3: 2}}, ... ) >>> transformed = transform(image=image, mask=mask) >>> # Pipeline modification after initialization: >>> # Create initial pipeline with bbox support >>> base_transform = A.Compose([ ... A.HorizontalFlip(p=0.5), ... A.RandomCrop(width=512, height=512) ... ], bbox_params=A.BboxParams(coord_format='pascal_voc', label_fields=['labels'])) >>> >>> # Add transforms using operators (bbox_params preserved) >>> extended = base_transform + A.RandomBrightnessContrast(p=0.3) >>> extended = base_transform + [A.Blur(), A.GaussNoise()] >>> extended = A.Resize(height=1024, width=1024) + base_transform >>> >>> # Remove transforms by class >>> pipeline = A.Compose([A.HorizontalFlip(p=0.5), A.VerticalFlip(), A.Rotate()]) >>> without_flip = pipeline - A.HorizontalFlip # Remove by class Note: - 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. - Semantic-mask mappings replace class IDs simultaneously, so paired swaps do not overwrite one another. Unmapped labels stay unchanged. For D4/SquareSymmetry, configure the realized reflection name: `HorizontalFlip`, `VerticalFlip`, or `Transpose`; identity and rotations do not remap labels. `Flip3D` emits its mapping event only when the realized reflection includes an odd number of axes. - Configure semantic-mask mappings only when the transformed and relabeled sample remains valid for your domain. Compose applies the declared mapping but cannot verify its semantic truth. - When strict mode is enabled, it performs additional validation to ensure data and transform configuration correctness. - Pipeline modification operators (+, -, __radd__) preserve all Compose parameters including bbox_params, keypoint_params, additional_targets, and other configuration settings. - All operators return new Compose instances without modifying the original pipeline. - Concurrent calls to one Compose instance, including `run_with_trace()`, keep all mutable execution state in separate invocations. A short root-only seed reservation establishes each caller's private random streams; pass `invocation_seed` when a sample must be independent of reservation order.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| transforms | TransformsSeqType | - | - |
| bbox_params | One of:
| - | - |
| keypoint_params | One of:
| - | - |
| additional_targets | One of:
| - | - |
| p | float | 1.0 | - |
| is_check_shapes | bool | True | - |
| strict | bool | False | - |
| mask_interpolation | One of:
| - | - |
| seed | One of:
| - | - |
| save_applied_params | bool | False | - |
| telemetry | bool | True | - |
| instance_binding | One of:
| - | - |
| strict_instance_invariant | bool | True | - |
| semantic_mask_label_mappings | One of:
| - | - |
OneOfclass
OneOf(
transforms: TransformsSeqType,
p: float = 0.5
)Apply one of the child transforms at random; probabilities normalized as weights. Selected transform runs with force_apply=True. Args: transforms (Sequence[BasicTransform | BaseCompose]): Ordered transforms to choose from; stored immutably. p (float): probability of applying selected transform. Default: 0.5.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| transforms | TransformsSeqType | - | - |
| p | float | 0.5 | - |
SomeOfclass
SomeOf(
transforms: TransformsSeqType,
n: int = 1,
replace: bool = False,
p: float = 1
)Select exactly n transforms from the list and apply them. Selection uniform; each runs with its own p. Use replace=True for sampling with replacement. 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`. Args: transforms (Sequence[BasicTransform | BaseCompose]): Ordered transforms to choose from; stored immutably. n (int): 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): 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): 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. Note: - 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. - When using pipeline modification operators (+, -, __radd__), the `n` parameter is preserved while the pool of available transforms changes: - `SomeOf([A, B], n=2) + C` → `SomeOf([A, B, C], n=2)` (selects 2 from 3 transforms) - This allows for dynamic adjustment of the transform pool without changing selection count. Examples: >>> 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) >>> # Pipeline modification example: >>> # Add more transforms to the pool while keeping n=2 >>> extended = transform + [A.Blur(p=1.0), A.RandomBrightnessContrast(p=0.7)] >>> # Now selects 2 transforms from 5 available transforms uniformly
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| transforms | TransformsSeqType | - | - |
| n | int | 1 | - |
| replace | bool | False | - |
| p | float | 1 | - |
RandomOrderclass
RandomOrder(
transforms: TransformsSeqType,
n: int = 1,
replace: bool = False,
p: float = 1
)Apply a random subset of transforms in random order. Subclass of SomeOf; selection uniform, order random. Use n, replace, p. 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`. Attributes: transforms (TransformsSeqType): Ordered transformations to choose from; stored immutably. n (int): The number of transforms to apply. If `n` is greater than the number of available transforms and `replace` is False, `n` will be set to the number of available transforms. replace (bool): Whether to sample transforms with replacement. If True, the same transform can be selected multiple times. Default is False. p (float): Probability of applying the selected transforms. Should be in the range [0, 1]. Default is 1.0. Examples: >>> 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). Note: - Inherits from SomeOf, but overrides `get_indices` to ensure random order without sorting. - Selection is uniform; application depends on individual transform probabilities.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| transforms | TransformsSeqType | - | - |
| n | int | 1 | - |
| replace | bool | False | - |
| p | float | 1 | - |
OneOrOtherclass
OneOrOther(
first: TransformType | None,
second: TransformType | None,
transforms: TransformsSeqType | None,
p: float = 0.5
)Select one or the other transform. Selected runs with force_apply=True. Exactly two transforms; p chooses first vs second. Like OneOf n=2 but binary choice.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| first | One of:
| - | - |
| second | One of:
| - | - |
| transforms | One of:
| - | - |
| p | float | 0.5 | - |
SelectiveChannelTransformclass
SelectiveChannelTransform(
transforms: TransformsSeqType,
channels: Sequence[int] = (0, 1, 2),
p: float = 1.0
)Apply transforms to selected image channels. Extracts channels, runs compose, writes back. Use channels=(0,1,2) for RGB. Supports +, -, __radd__. 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. Args: transforms (TransformsSeqType): A sequence of transformations (from Albumentations) to be applied to the specified channels. channels (Sequence[int]): A sequence of integers specifying the indices of the channels to which the transforms should be applied. p (float): 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. Note: - When using pipeline modification operators (+, -, __radd__), the `channels` parameter is preserved in the resulting SelectiveChannelTransform instance. - Only the transform list is modified while maintaining the same channel selection behavior.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| transforms | TransformsSeqType | - | - |
| channels | Sequence[int] | (0, 1, 2) | - |
| p | float | 1.0 | - |
ReplayComposeclass
ReplayCompose(
transforms: TransformsSeqType,
bbox_params: dict[str, Any] | BboxParams | None,
keypoint_params: dict[str, Any] | KeypointParams | None,
additional_targets: dict[str, str] | None,
p: float = 1.0,
is_check_shapes: bool = True,
save_key: str = replay,
seed: int | None,
instance_binding: Sequence[str] | None,
semantic_mask_label_mappings: dict[str, dict[int, int]] | None,
strict: bool = False,
mask_interpolation: int | None,
save_applied_params: bool = False,
telemetry: bool = True,
strict_instance_invariant: bool = True
)Compose with replay: records params per call in save_key; use replay() to reapply same augmentations. Set save_key, deterministic=True. 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. Args: transforms (TransformsSeqType): Ordered transformations to compose; stored immutably. bbox_params (dict[str, Any] | BboxParams | None): Parameters for bounding box transforms. keypoint_params (dict[str, Any] | KeypointParams | None): Parameters for keypoint transforms. additional_targets (dict[str, str] | None): Dictionary of additional targets. semantic_mask_label_mappings (dict[str, dict[int, int]] | None): Transform-aware semantic-mask class-ID replacements. p (float): Probability of applying the compose. is_check_shapes (bool): Whether to check shapes of different targets. save_key (str): Key for storing the applied transformations. seed (int | None): Controls reproducibility of random augmentations. See superclass documentation for further information.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| transforms | TransformsSeqType | - | - |
| bbox_params | One of:
| - | - |
| keypoint_params | One of:
| - | - |
| additional_targets | One of:
| - | - |
| p | float | 1.0 | - |
| is_check_shapes | bool | True | - |
| save_key | str | replay | - |
| seed | One of:
| - | - |
| instance_binding | One of:
| - | - |
| semantic_mask_label_mappings | One of:
| - | - |
| strict | bool | False | - |
| mask_interpolation | One of:
| - | - |
| save_applied_params | bool | False | - |
| telemetry | bool | True | - |
| strict_instance_invariant | bool | True | - |
Sequentialclass
Sequential(
transforms: TransformsSeqType,
p: float = 0.5
)Apply all transforms to targets in order. Use inside Compose with OneOf (e.g. OneOf([Sequential([A,B]), Sequential([C,D])])). Each runs with its own p. 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). Examples: >>> 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) >>> ])
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| transforms | TransformsSeqType | - | - |
| p | float | 0.5 | - |