Initial commit: new baseline

This commit is contained in:
Andre Neto
2025-08-31 19:45:56 +01:00
commit 0dcc994dbe
416 changed files with 522730 additions and 0 deletions
@@ -0,0 +1,134 @@
"""Implementation of the Channel Dropout transform for multi-channel images.
This module provides the ChannelDropout transform, which randomly drops (sets to a fill value)
one or more channels in multi-channel images. This augmentation can help models become more
robust to missing or corrupted channel information and encourage learning from all available
channels rather than relying on a subset.
"""
from __future__ import annotations
from typing import Annotated, Any
import numpy as np
from albucore import get_num_channels
from pydantic import AfterValidator
from albumentations.core.pydantic import check_range_bounds
from albumentations.core.transforms_interface import BaseTransformInitSchema, ImageOnlyTransform
from .functional import channel_dropout
__all__ = ["ChannelDropout"]
MIN_DROPOUT_CHANNEL_LIST_LENGTH = 2
class ChannelDropout(ImageOnlyTransform):
"""Randomly drop channels in the input image.
This transform randomly selects a number of channels to drop from the input image
and replaces them with a specified fill value. This can improve model robustness
to missing or corrupted channels.
The technique is conceptually similar to:
- Dropout layers in neural networks, which randomly set input units to 0 during training.
- CoarseDropout augmentation, which drops out regions in the spatial dimensions of the image.
However, ChannelDropout operates on the channel dimension, effectively "dropping out"
entire color channels or feature maps.
Args:
channel_drop_range (tuple[int, int]): Range from which to choose the number
of channels to drop. The actual number will be randomly selected from
the inclusive range [min, max]. Default: (1, 1).
fill (float): Pixel value used to fill the dropped channels.
Default: 0.
p (float): Probability of applying the transform. Must be in the range
[0, 1]. Default: 0.5.
Raises:
NotImplementedError: If the input image has only one channel.
ValueError: If the upper bound of channel_drop_range is greater than or
equal to the number of channels in the input image.
Targets:
image, volume
Image types:
uint8, float32
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> transform = A.ChannelDropout(channel_drop_range=(1, 2), fill=128, p=1.0)
>>> result = transform(image=image)
>>> dropped_image = result['image']
>>> assert dropped_image.shape == image.shape
>>> assert np.any(dropped_image != image) # Some channels should be different
Note:
- The number of channels to drop is randomly chosen within the specified range.
- Channels are randomly selected for dropping.
- This transform is not applicable to single-channel (grayscale) images.
- The transform will raise an error if it's not possible to drop the specified
number of channels (e.g., trying to drop 3 channels from an RGB image).
- This augmentation can be particularly useful for training models to be robust
against missing or corrupted channel data in multi-spectral or hyperspectral imagery.
"""
class InitSchema(BaseTransformInitSchema):
channel_drop_range: Annotated[tuple[int, int], AfterValidator(check_range_bounds(1, None))]
fill: float
def __init__(
self,
channel_drop_range: tuple[int, int] = (1, 1),
fill: float = 0,
p: float = 0.5,
):
super().__init__(p=p)
self.channel_drop_range = channel_drop_range
self.fill = fill
def apply(self, img: np.ndarray, channels_to_drop: list[int], **params: Any) -> np.ndarray:
"""Apply channel dropout to the image.
Args:
img (np.ndarray): Image to apply channel dropout to.
channels_to_drop (list[int]): List of channel indices to drop.
**params (Any): Additional parameters.
Returns:
np.ndarray: Image with dropped channels.
"""
return channel_dropout(img, channels_to_drop, self.fill)
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, list[int]]:
"""Get parameters that depend on input data.
Args:
params (dict[str, Any]): Parameters.
data (dict[str, Any]): Input data.
Returns:
dict[str, list[int]]: Dictionary with channels to drop.
"""
image = data["image"] if "image" in data else data["images"][0]
num_channels = get_num_channels(image)
if num_channels == 1:
msg = "Images has one channel. ChannelDropout is not defined."
raise NotImplementedError(msg)
if self.channel_drop_range[1] >= num_channels:
msg = "Can not drop all channels in ChannelDropout."
raise ValueError(msg)
num_drop_channels = self.py_random.randint(*self.channel_drop_range)
channels_to_drop = self.py_random.sample(range(num_channels), k=num_drop_channels)
return {"channels_to_drop": channels_to_drop}
@@ -0,0 +1,567 @@
"""Implementation of coarse dropout and random erasing augmentations.
This module provides several variations of coarse dropout augmentations, which drop out
rectangular regions from images. It includes CoarseDropout for randomly placed dropouts,
ConstrainedCoarseDropout for dropping out regions based on masks or bounding boxes,
and Erasing for random erasing augmentation. These techniques help models become more
robust to occlusions and varying object completeness.
"""
from __future__ import annotations
from typing import Annotated, Any, Literal
from warnings import warn
import numpy as np
from pydantic import AfterValidator
import albumentations.augmentations.dropout.functional as fdropout
from albumentations.augmentations.dropout.transforms import BaseDropout
from albumentations.core.bbox_utils import denormalize_bboxes
from albumentations.core.pydantic import check_range_bounds, nondecreasing
__all__ = ["CoarseDropout", "ConstrainedCoarseDropout", "Erasing"]
class CoarseDropout(BaseDropout):
"""CoarseDropout randomly drops out rectangular regions from the image and optionally,
the corresponding regions in an associated mask, to simulate occlusion and
varied object sizes found in real-world settings.
This transformation is an evolution of CutOut and RandomErasing, offering more
flexibility in the size, number of dropout regions, and fill values.
Args:
num_holes_range (tuple[int, int]): Range (min, max) for the number of rectangular
regions to drop out. Default: (1, 1)
hole_height_range (tuple[int, int] | tuple[float, float]): Range (min, max) for the height
of dropout regions. If int, specifies absolute pixel values. If float,
interpreted as a fraction of the image height. Default: (0.1, 0.2)
hole_width_range (tuple[int, int] | tuple[float, float]): Range (min, max) for the width
of dropout regions. If int, specifies absolute pixel values. If float,
interpreted as a fraction of the image width. Default: (0.1, 0.2)
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value for the dropped pixels. Can be:
- int or float: all channels are filled with this value
- tuple: tuple of values for each channel
- 'random': each pixel is filled with random values
- 'random_uniform': each hole is filled with a single random color
- 'inpaint_telea': uses OpenCV Telea inpainting method
- 'inpaint_ns': uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Fill value for dropout regions in the mask.
If None, mask regions corresponding to image dropouts are unchanged. Default: None
p (float): Probability of applying the transform. Default: 0.5
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The actual number and size of dropout regions are randomly chosen within the specified ranges for each
application.
- When using float values for hole_height_range and hole_width_range, ensure they are between 0 and 1.
- This implementation includes deprecation warnings for older parameter names (min_holes, max_holes, etc.).
- Inpainting methods ('inpaint_telea', 'inpaint_ns') work only with grayscale or RGB images.
- For 'random_uniform' fill, each hole gets a single random color, unlike 'random' where each pixel
gets its own random value.
Example:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> # Example with random uniform fill
>>> aug_random = A.CoarseDropout(
... num_holes_range=(3, 6),
... hole_height_range=(10, 20),
... hole_width_range=(10, 20),
... fill="random_uniform",
... p=1.0
... )
>>> # Example with inpainting
>>> aug_inpaint = A.CoarseDropout(
... num_holes_range=(3, 6),
... hole_height_range=(10, 20),
... hole_width_range=(10, 20),
... fill="inpaint_ns",
... p=1.0
... )
>>> transformed = aug_random(image=image, mask=mask)
>>> transformed_image, transformed_mask = transformed["image"], transformed["mask"]
References:
- CutOut: https://arxiv.org/abs/1708.04552
- Random Erasing: https://arxiv.org/abs/1708.04896
- OpenCV Inpainting methods: https://docs.opencv.org/master/df/d3d/tutorial_py_inpainting.html
"""
class InitSchema(BaseDropout.InitSchema):
num_holes_range: Annotated[
tuple[int, int],
AfterValidator(check_range_bounds(1, None)),
AfterValidator(nondecreasing),
]
hole_height_range: Annotated[
tuple[float, float] | tuple[int, int],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, None)),
]
hole_width_range: Annotated[
tuple[float, float] | tuple[int, int],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, None)),
]
def __init__(
self,
num_holes_range: tuple[int, int] = (1, 2),
hole_height_range: tuple[float, float] | tuple[int, int] = (0.1, 0.2),
hole_width_range: tuple[float, float] | tuple[int, int] = (0.1, 0.2),
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(fill=fill, fill_mask=fill_mask, p=p)
self.num_holes_range = num_holes_range
self.hole_height_range = hole_height_range
self.hole_width_range = hole_width_range
def calculate_hole_dimensions(
self,
image_shape: tuple[int, int],
height_range: tuple[float, float] | tuple[int, int],
width_range: tuple[float, float] | tuple[int, int],
size: int,
) -> tuple[np.ndarray, np.ndarray]:
"""Calculate random hole dimensions based on the provided ranges."""
height, width = image_shape[:2]
if height_range[1] >= 1:
min_height = height_range[0]
max_height = min(height_range[1], height)
min_width = width_range[0]
max_width = min(width_range[1], width)
hole_heights = self.random_generator.integers(int(min_height), int(max_height + 1), size=size)
hole_widths = self.random_generator.integers(int(min_width), int(max_width + 1), size=size)
else: # Assume float
hole_heights = (height * self.random_generator.uniform(*height_range, size=size)).astype(int)
hole_widths = (width * self.random_generator.uniform(*width_range, size=size)).astype(int)
return hole_heights, hole_widths
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, Any]: Dictionary with parameters for transformation.
"""
image_shape = params["shape"][:2]
num_holes = self.py_random.randint(*self.num_holes_range)
hole_heights, hole_widths = self.calculate_hole_dimensions(
image_shape,
self.hole_height_range,
self.hole_width_range,
size=num_holes,
)
height, width = image_shape[:2]
y_min = self.random_generator.integers(0, height - hole_heights + 1, size=num_holes)
x_min = self.random_generator.integers(0, width - hole_widths + 1, size=num_holes)
y_max = y_min + hole_heights
x_max = x_min + hole_widths
holes = np.stack([x_min, y_min, x_max, y_max], axis=-1)
return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
class Erasing(BaseDropout):
"""Randomly erases rectangular regions in an image, following the Random Erasing Data Augmentation technique.
This augmentation helps improve model robustness by randomly masking out rectangular regions in the image,
simulating occlusions and encouraging the model to learn from partial information. It's particularly
effective for image classification and person re-identification tasks.
Args:
scale (tuple[float, float]): Range for the proportion of image area to erase.
The actual area will be randomly sampled from (scale[0] * image_area, scale[1] * image_area).
Default: (0.02, 0.33)
ratio (tuple[float, float]): Range for the aspect ratio (width/height) of the erased region.
The actual ratio will be randomly sampled from (ratio[0], ratio[1]).
Default: (0.3, 3.3)
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value used to fill the erased regions. Can be:
- int or float: fills all channels with this value
- tuple: fills each channel with corresponding value
- "random": fills each pixel with random values
- "random_uniform": fills entire erased region with a single random color
- "inpaint_telea": uses OpenCV Telea inpainting method
- "inpaint_ns": uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Value used to fill erased regions in the mask.
If None, mask regions are not modified. Default: None
p (float): Probability of applying the transform. Default: 0.5
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The transform attempts to find valid erasing parameters up to 10 times.
If unsuccessful, no erasing is performed.
- The actual erased area and aspect ratio are randomly sampled within
the specified ranges for each application.
- When using inpainting methods, only grayscale or RGB images are supported.
Example:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> # Basic usage with default parameters
>>> transform = A.Erasing()
>>> transformed = transform(image=image)
>>> # Custom configuration
>>> transform = A.Erasing(
... scale=(0.1, 0.4),
... ratio=(0.5, 2.0),
... fill_value="random_uniform",
... p=1.0
... )
>>> transformed = transform(image=image)
References:
- Paper: https://arxiv.org/abs/1708.04896
- Implementation inspired by torchvision:
https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.RandomErasing
"""
class InitSchema(BaseDropout.InitSchema):
scale: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, None)),
]
ratio: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, None)),
]
def __init__(
self,
scale: tuple[float, float] = (0.02, 0.33),
ratio: tuple[float, float] = (0.3, 3.3),
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(fill=fill, fill_mask=fill_mask, p=p)
self.scale = scale
self.ratio = ratio
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Calculate erasing parameters using direct mathematical derivation.
Given:
- Image dimensions (H, W)
- Target area (A)
- Aspect ratio (r = w/h)
We know:
- h * w = A (area equation)
- w = r * h (aspect ratio equation)
Therefore:
- h * (r * h) = A
- h² = A/r
- h = sqrt(A/r)
- w = r * sqrt(A/r) = sqrt(A*r)
"""
height, width = params["shape"][:2]
total_area = height * width
# Calculate maximum valid area based on dimensions and aspect ratio
max_area = total_area * self.scale[1]
min_area = total_area * self.scale[0]
# For each aspect ratio r, the maximum area is constrained by:
# h = sqrt(A/r) ≤ H and w = sqrt(A*r) ≤ W
# Therefore: A ≤ min(r*H², W²/r)
r_min, r_max = self.ratio
def area_constraint_h(r: float) -> float:
return r * height * height
def area_constraint_w(r: float) -> float:
return width * width / r
# Find maximum valid area considering aspect ratio constraints
max_area_h = min(area_constraint_h(r_min), area_constraint_h(r_max))
max_area_w = min(area_constraint_w(r_min), area_constraint_w(r_max))
max_valid_area = min(max_area, max_area_h, max_area_w)
if max_valid_area < min_area:
return {"holes": np.array([], dtype=np.int32).reshape((0, 4))}
# Sample valid area and aspect ratio
erase_area = self.py_random.uniform(min_area, max_valid_area)
# Calculate valid aspect ratio range for this area
max_r = min(r_max, width * width / erase_area)
min_r = max(r_min, erase_area / (height * height))
if min_r > max_r:
return {"holes": np.array([], dtype=np.int32).reshape((0, 4))}
aspect_ratio = self.py_random.uniform(min_r, max_r)
# Calculate dimensions
h = round(np.sqrt(erase_area / aspect_ratio))
w = round(np.sqrt(erase_area * aspect_ratio))
# Sample position
top = self.py_random.randint(0, height - h)
left = self.py_random.randint(0, width - w)
holes = np.array([[left, top, left + w, top + h]], dtype=np.int32)
return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
class ConstrainedCoarseDropout(BaseDropout):
"""Applies coarse dropout to regions containing specific objects in the image.
This augmentation creates holes (dropout regions) for each target object in the image.
Objects can be specified either by their class indices in a segmentation mask or
by their labels in bounding box annotations.
The hole generation differs between mask and box modes:
Mask mode:
1. For each connected component in the mask matching target indices:
- Samples N points randomly from within the object region (with replacement)
- Creates holes centered at these points
- Hole sizes are proportional to sqrt(component area), not total object area
- Each component's holes are sized based on its own area
Box mode:
1. For each bounding box matching target labels:
- Creates N holes with random positions inside the box
- Hole sizes are proportional to the box dimensions
In both modes:
- N is sampled once from num_holes_range and used for all objects
- For example, if num_holes_range=(2,4) and 3 is sampled:
* With 3 target objects, you'll get exactly 3 holes per object (9 total)
* Holes may overlap within or between objects
* All holes are clipped to image boundaries
Args:
num_holes_range (tuple[int, int]): Range for number of holes per object (min, max)
hole_height_range (tuple[float, float]): Range for hole height as proportion
of object height/size (min, max). E.g., (0.2, 0.4) means:
- For boxes: 20-40% of box height
- For masks: 20-40% of sqrt(component area)
hole_width_range (tuple[float, float]): Range for hole width, similar to height
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value used to fill the erased regions. Can be:
- int or float: fills all channels with this value
- tuple: fills each channel with corresponding value
- "random": fills each pixel with random values
- "random_uniform": fills entire erased region with a single random color
- "inpaint_telea": uses OpenCV Telea inpainting method
- "inpaint_ns": uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Value used to fill erased regions in the mask.
If None, mask regions are not modified. Default: None
p (float): Probability of applying the transform
mask_indices (List[int], optional): List of class indices in segmentation mask to target.
Only objects of these classes will be considered for hole placement.
bbox_labels (List[str | int | float], optional): List of object labels in bbox
annotations to target. String labels will be automatically encoded.
When multiple label fields are specified in BboxParams, only the first
label field is used for filtering.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Requires one of:
- 'mask' key with segmentation mask where:
* 0 represents background
* Non-zero values represent different object instances/classes
* Values must correspond to mask_indices
- 'bboxes' key with bounding boxes in format [x_min, y_min, x_max, y_max, label, ...]
Note:
At least one of mask_indices or bbox_labels must be provided.
If both are provided, mask_indices takes precedence.
Examples:
>>> # Using segmentation mask
>>> transform = ConstrainedCoarseDropout(
... num_holes_range=(2, 4), # 2-4 holes per object
... hole_height_range=(0.2, 0.4), # 20-40% of sqrt(object area)
... hole_width_range=(0.2, 0.4), # 20-40% of sqrt(object area)
... mask_indices=[1, 2], # Target objects of class 1 and 2
... fill=0, # Fill holes with black
... )
>>> # Apply to image and its segmentation mask
>>> transformed = transform(image=image, mask=mask)
>>> # Using bounding boxes with Compose
>>> transform = A.Compose([
... ConstrainedCoarseDropout(
... num_holes_range=(1, 3),
... hole_height_range=(0.3, 0.5), # 30-50% of box height
... hole_width_range=(0.3, 0.5), # 30-50% of box width
... bbox_labels=['person'], # Target people
... fill=127, # Fill holes with gray
... )
... ], bbox_params=A.BboxParams(
... format='pascal_voc', # [x_min, y_min, x_max, y_max]
... label_fields=['labels'] # Specify field containing labels
... ))
>>> # Apply to image and its bounding boxes
>>> transformed = transform(
... image=image,
... bboxes=[[0, 0, 100, 100, 'car'], [150, 150, 300, 300, 'person']],
... labels=['car', 'person']
... )
"""
class InitSchema(BaseDropout.InitSchema):
num_holes_range: Annotated[
tuple[int, int],
AfterValidator(check_range_bounds(1, None)),
AfterValidator(nondecreasing),
]
hole_height_range: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0.0, 1.0)),
]
hole_width_range: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0.0, 1.0)),
]
mask_indices: Annotated[
list[int] | None,
AfterValidator(check_range_bounds(1, None)),
]
bbox_labels: list[str | int | float] | None = None
def __init__(
self,
num_holes_range: tuple[int, int] = (1, 1),
hole_height_range: tuple[float, float] = (0.1, 0.1),
hole_width_range: tuple[float, float] = (0.1, 0.1),
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
mask_indices: list[int] | None = None,
bbox_labels: list[str | int | float] | None = None,
):
super().__init__(fill=fill, fill_mask=fill_mask, p=p)
self.num_holes_range = num_holes_range
self.hole_height_range = hole_height_range
self.hole_width_range = hole_width_range
self.mask_indices = mask_indices
self.bbox_labels = bbox_labels
def get_boxes_from_bboxes(self, bboxes: np.ndarray) -> np.ndarray | None:
"""Get bounding boxes that match specified labels.
Uses BboxProcessor's label encoder if bbox_labels contain strings.
"""
if len(bboxes) == 0 or self.bbox_labels is None:
return None
# Get label encoder from BboxProcessor if needed
bbox_processor = self.get_processor("bboxes")
if bbox_processor is None:
return None
if not all(isinstance(label, (int, float)) for label in self.bbox_labels):
label_fields = bbox_processor.params.label_fields
if label_fields is None:
raise ValueError("BboxParams.label_fields must be specified when using string labels")
first_class_label = label_fields[0]
# Access encoder through label_manager's metadata
metadata = bbox_processor.label_manager.metadata["bboxes"][first_class_label]
if metadata.encoder is None:
raise ValueError(f"No encoder found for label field {first_class_label}")
target_labels = metadata.encoder.transform(self.bbox_labels)
else:
target_labels = np.array(self.bbox_labels)
# Filter boxes by labels (usually in column 4)
mask = np.isin(bboxes[:, 4], target_labels)
filtered_boxes = bboxes[mask, :4]
return filtered_boxes if len(filtered_boxes) > 0 else None
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get hole parameters based on either mask indices or bbox labels."""
num_holes_per_obj = self.py_random.randint(*self.num_holes_range)
if self.mask_indices is not None and "mask" in data:
holes = fdropout.get_holes_from_mask(
data["mask"],
num_holes_per_obj,
self.mask_indices,
self.hole_height_range,
self.hole_width_range,
self.random_generator,
)
elif self.bbox_labels is not None and "bboxes" in data:
target_boxes = self.get_boxes_from_bboxes(data["bboxes"])
if target_boxes is None:
holes = np.array([], dtype=np.int32).reshape((0, 4))
else:
target_boxes = denormalize_bboxes(target_boxes, data["image"].shape[:2])
holes = fdropout.get_holes_from_boxes(
target_boxes,
num_holes_per_obj,
self.hole_height_range,
self.hole_width_range,
self.random_generator,
)
else:
warn("Neither valid mask nor bboxes provided, do not apply Constrained Coarse Dropout", stacklevel=2)
holes = np.array([], dtype=np.int32).reshape((0, 4))
return {
"holes": holes,
"seed": self.random_generator.integers(0, 2**32 - 1),
}
@@ -0,0 +1,166 @@
"""Implementation of grid-based dropout augmentation.
This module provides GridDropout, which creates a regular grid over the image and drops out
rectangular regions according to the specified grid pattern. Unlike random dropout methods,
grid dropout enforces a structured pattern of occlusions that can help models learn spatial
relationships and context across the entire image space.
"""
from __future__ import annotations
from typing import Annotated, Any, Literal
from pydantic import AfterValidator, Field
import albumentations.augmentations.dropout.functional as fdropout
from albumentations.augmentations.dropout.transforms import BaseDropout
from albumentations.core.pydantic import check_range_bounds, nondecreasing
__all__ = ["GridDropout"]
class GridDropout(BaseDropout):
"""Apply GridDropout augmentation to images, masks, bounding boxes, and keypoints.
GridDropout drops out rectangular regions of an image and the corresponding mask in a grid fashion.
This technique can help improve model robustness by forcing the network to rely on a broader context
rather than specific local features.
Args:
ratio (float): The ratio of the mask holes to the unit size (same for horizontal and vertical directions).
Must be between 0 and 1. Default: 0.5.
unit_size_range (tuple[int, int] | None): Range from which to sample grid size. Default: None.
Must be between 2 and the image's shorter edge. If None, grid size is calculated based on image size.
holes_number_xy (tuple[int, int] | None): The number of grid units in x and y directions.
First value should be between 1 and image width//2,
Second value should be between 1 and image height//2.
Default: None. If provided, overrides unit_size_range.
random_offset (bool): Whether to offset the grid randomly between 0 and (grid unit size - hole size).
If True, entered shift_xy is ignored and set randomly. Default: True.
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value for the dropped pixels. Can be:
- int or float: all channels are filled with this value
- tuple: tuple of values for each channel
- 'random': each pixel is filled with random values
- 'random_uniform': each hole is filled with a single random color
- 'inpaint_telea': uses OpenCV Telea inpainting method
- 'inpaint_ns': uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Value for the dropped pixels in mask.
If None, the mask is not modified. Default: None.
shift_xy (tuple[int, int]): Offsets of the grid start in x and y directions from (0,0) coordinate.
Only used when random_offset is False. Default: (0, 0).
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- If both unit_size_range and holes_number_xy are None, the grid size is calculated based on the image size.
- The actual number of dropped regions may differ slightly from holes_number_xy due to rounding.
- Inpainting methods ('inpaint_telea', 'inpaint_ns') work only with grayscale or RGB images.
- For 'random_uniform' fill, each grid cell gets a single random color, unlike 'random' where each pixel
gets its own random value.
Example:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> # Example with standard fill value
>>> aug_basic = A.GridDropout(
... ratio=0.3,
... unit_size_range=(10, 20),
... random_offset=True,
... p=1.0
... )
>>> # Example with random uniform fill
>>> aug_random = A.GridDropout(
... ratio=0.3,
... unit_size_range=(10, 20),
... fill="random_uniform",
... p=1.0
... )
>>> # Example with inpainting
>>> aug_inpaint = A.GridDropout(
... ratio=0.3,
... unit_size_range=(10, 20),
... fill="inpaint_ns",
... p=1.0
... )
>>> transformed = aug_random(image=image, mask=mask)
>>> transformed_image, transformed_mask = transformed["image"], transformed["mask"]
Reference:
- Paper: https://arxiv.org/abs/2001.04086
- OpenCV Inpainting methods: https://docs.opencv.org/master/df/d3d/tutorial_py_inpainting.html
"""
class InitSchema(BaseDropout.InitSchema):
ratio: float = Field(gt=0, le=1)
random_offset: bool
unit_size_range: (
Annotated[tuple[int, int], AfterValidator(check_range_bounds(2, None)), AfterValidator(nondecreasing)]
| None
)
shift_xy: Annotated[tuple[int, int], AfterValidator(check_range_bounds(0, None))]
holes_number_xy: Annotated[tuple[int, int], AfterValidator(check_range_bounds(1, None))] | None
def __init__(
self,
ratio: float = 0.5,
random_offset: bool = True,
unit_size_range: tuple[int, int] | None = None,
holes_number_xy: tuple[int, int] | None = None,
shift_xy: tuple[int, int] = (0, 0),
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(fill=fill, fill_mask=fill_mask, p=p)
self.ratio = ratio
self.unit_size_range = unit_size_range
self.holes_number_xy = holes_number_xy
self.random_offset = random_offset
self.shift_xy = shift_xy
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, Any]: Dictionary with parameters for transformation.
"""
image_shape = params["shape"]
if self.holes_number_xy:
grid = self.holes_number_xy
else:
# Calculate grid based on unit_size_range or default
unit_height, unit_width = fdropout.calculate_grid_dimensions(
image_shape,
self.unit_size_range,
self.holes_number_xy,
self.random_generator,
)
grid = (image_shape[0] // unit_height, image_shape[1] // unit_width)
holes = fdropout.generate_grid_holes(
image_shape,
grid,
self.ratio,
self.random_offset,
self.shift_xy,
self.random_generator,
)
return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
@@ -0,0 +1,274 @@
"""Implementation of mask-based dropout augmentation.
This module provides the MaskDropout transform, which identifies objects in a segmentation mask
and drops out random objects completely. This augmentation is particularly useful for instance
segmentation and object detection tasks, as it simulates occlusions or missing objects in a
semantically meaningful way, rather than dropping out random pixels or regions.
"""
from __future__ import annotations
from typing import Any, Literal, cast
import cv2
import numpy as np
import albumentations.augmentations.dropout.functional as fdropout
from albumentations.core.bbox_utils import BboxProcessor, denormalize_bboxes, normalize_bboxes
from albumentations.core.keypoints_utils import KeypointsProcessor
from albumentations.core.pydantic import OnePlusIntRangeType
from albumentations.core.transforms_interface import BaseTransformInitSchema, DualTransform
from albumentations.core.type_definitions import ALL_TARGETS
__all__ = ["MaskDropout"]
class MaskDropout(DualTransform):
"""Apply dropout to random objects in a mask, zeroing out the corresponding regions in both the image and mask.
This transform identifies objects in the mask (where each unique non-zero value represents a distinct object),
randomly selects a number of these objects, and sets their corresponding regions to zero in both the image and mask.
It can also handle bounding boxes and keypoints, removing or adjusting them based on the dropout regions.
Args:
max_objects (int | tuple[int, int]): Maximum number of objects to dropout. If a single int is provided,
it's treated as the upper bound. If a tuple of two ints is provided, it's treated as a range [min, max].
fill (float | Literal["inpaint_telea", "inpaint_ns"]): Value to fill dropped out regions in the image.
Can be one of:
- float: Constant value to fill the regions (e.g., 0 for black, 255 for white)
- "inpaint_telea": Use Telea inpainting algorithm (for 3-channel images only)
- "inpaint_ns": Use Navier-Stokes inpainting algorithm (for 3-channel images only)
fill_mask (float): Value to fill the dropped out regions in the mask.
min_area (float): Minimum area (in pixels) of a bounding box that must remain visible after dropout to be kept.
Only applicable if bounding box augmentation is enabled. Default: 0.0
min_visibility (float): Minimum visibility ratio (visible area / total area) of a bounding box after dropout
to be kept. Only applicable if bounding box augmentation is enabled. Default: 0.0
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The mask should be a single-channel image where 0 represents the background and non-zero values represent
different object instances.
- For bounding box and keypoint augmentation, make sure to set up the corresponding processors in the pipeline.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.zeros((100, 100), dtype=np.uint8)
>>> mask[20:40, 20:40] = 1 # Object 1
>>> mask[60:80, 60:80] = 2 # Object 2
>>> bboxes = np.array([[20, 20, 40, 40], [60, 60, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[30, 30], [70, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Define the transform with tuple for max_objects
>>> transform = A.Compose(
... transforms=[
... A.MaskDropout(
... max_objects=(1, 2), # Using tuple to specify min and max objects to drop
... fill=0, # Fill value for dropped regions in image
... fill_mask=0, # Fill value for dropped regions in mask
... p=1.0
... ),
... ],
... bbox_params=A.BboxParams(
... format='pascal_voc',
... label_fields=['bbox_labels'],
... min_area=1,
... min_visibility=0.1
... ),
... keypoint_params=A.KeypointParams(
... format='xy',
... label_fields=['keypoint_labels'],
... remove_invisible=True
... )
... )
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # Image with dropped out regions
>>> transformed_mask = transformed['mask'] # Mask with dropped out regions
>>> transformed_bboxes = transformed['bboxes'] # Remaining bboxes after dropout
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels for remaining bboxes
>>> transformed_keypoints = transformed['keypoints'] # Remaining keypoints after dropout
>>> transformed_keypoint_labels = transformed['keypoint_labels'] # Labels for remaining keypoints
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
max_objects: OnePlusIntRangeType
fill: float | Literal["inpaint_telea", "inpaint_ns"]
fill_mask: float
def __init__(
self,
max_objects: tuple[int, int] | int = (1, 1),
fill: float | Literal["inpaint_telea", "inpaint_ns"] = 0,
fill_mask: float = 0,
p: float = 0.5,
):
super().__init__(p=p)
self.max_objects = cast("tuple[int, int]", max_objects)
self.fill = fill # type: ignore[assignment]
self.fill_mask = fill_mask
@property
def targets_as_params(self) -> list[str]:
"""Get targets as parameters.
Returns:
list[str]: List of targets as parameters.
"""
return ["mask"]
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, Any]: Dictionary with parameters for transformation.
"""
mask = data["mask"]
label_image, num_labels = fdropout.label(mask, return_num=True)
if num_labels == 0:
dropout_mask = None
else:
objects_to_drop = self.py_random.randint(*self.max_objects)
objects_to_drop = min(num_labels, objects_to_drop)
if objects_to_drop == num_labels:
dropout_mask = mask > 0
else:
labels_index = self.py_random.sample(range(1, num_labels + 1), objects_to_drop)
dropout_mask = np.zeros(mask.shape[:2], dtype=bool)
for label_index in labels_index:
dropout_mask |= label_image == label_index
return {"dropout_mask": dropout_mask}
def apply(self, img: np.ndarray, dropout_mask: np.ndarray | None, **params: Any) -> np.ndarray:
"""Apply dropout to the image.
Args:
img (np.ndarray): The image to apply the transform to.
dropout_mask (np.ndarray | None): The dropout mask for the image.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed image.
"""
if dropout_mask is None:
return img
if self.fill in {"inpaint_telea", "inpaint_ns"}:
dropout_mask = dropout_mask.astype(np.uint8)
_, _, width, height = cv2.boundingRect(dropout_mask)
radius = min(3, max(width, height) // 2)
return cv2.inpaint(img, dropout_mask, radius, cast("Literal['inpaint_telea', 'inpaint_ns']", self.fill))
img = img.copy()
img[dropout_mask] = self.fill
return img
def apply_to_mask(self, mask: np.ndarray, dropout_mask: np.ndarray | None, **params: Any) -> np.ndarray:
"""Apply dropout to the mask.
Args:
mask (np.ndarray): The mask to apply the transform to.
dropout_mask (np.ndarray | None): The dropout mask for the mask.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed mask.
"""
if dropout_mask is None or self.fill_mask is None:
return mask
mask = mask.copy()
mask[dropout_mask] = self.fill_mask
return mask
def apply_to_bboxes(self, bboxes: np.ndarray, dropout_mask: np.ndarray | None, **params: Any) -> np.ndarray:
"""Apply dropout to bounding boxes.
Args:
bboxes (np.ndarray): The bounding boxes to apply the transform to.
dropout_mask (np.ndarray | None): The dropout mask for the bounding boxes.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed bounding boxes.
"""
if dropout_mask is None:
return bboxes
processor = cast("BboxProcessor", self.get_processor("bboxes"))
if processor is None:
return bboxes
image_shape = params["shape"][:2]
denormalized_bboxes = denormalize_bboxes(bboxes, image_shape)
result = fdropout.mask_dropout_bboxes(
denormalized_bboxes,
dropout_mask,
image_shape,
processor.params.min_area,
processor.params.min_visibility,
)
return normalize_bboxes(result, image_shape)
def apply_to_keypoints(self, keypoints: np.ndarray, dropout_mask: np.ndarray | None, **params: Any) -> np.ndarray:
"""Apply dropout to keypoints.
Args:
keypoints (np.ndarray): The keypoints to apply the transform to.
dropout_mask (np.ndarray | None): The dropout mask for the keypoints.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed keypoints.
"""
if dropout_mask is None:
return keypoints
processor = cast("KeypointsProcessor", self.get_processor("keypoints"))
if processor is None or not processor.params.remove_invisible:
return keypoints
return fdropout.mask_dropout_keypoints(keypoints, dropout_mask)
@@ -0,0 +1,461 @@
"""Transform classes for dropout-based augmentations.
This module contains transform classes for various dropout techniques used in image
augmentation. It provides the base dropout class and specialized implementations like
PixelDropout. These transforms randomly remove or modify pixels, channels, or regions
in images, which can help models become more robust to occlusions and missing information.
"""
from __future__ import annotations
from typing import Any, Literal, cast
import numpy as np
from albucore import get_num_channels
from pydantic import Field
from albumentations.augmentations.dropout import functional as fdropout
from albumentations.augmentations.dropout.functional import (
cutout,
cutout_on_volume,
cutout_on_volumes,
filter_bboxes_by_holes,
filter_keypoints_in_holes,
)
from albumentations.augmentations.pixel import functional as fpixel
from albumentations.core.bbox_utils import BboxProcessor, denormalize_bboxes, normalize_bboxes
from albumentations.core.keypoints_utils import KeypointsProcessor
from albumentations.core.transforms_interface import BaseTransformInitSchema, DualTransform
from albumentations.core.type_definitions import ALL_TARGETS, Targets
__all__ = ["PixelDropout"]
class BaseDropout(DualTransform):
"""Base class for dropout-style transformations.
This class provides common functionality for various dropout techniques,
including applying cutouts to images and masks.
Args:
fill (tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value to fill dropped regions.
fill_mask (tuple[float, ...] | float | None): Value to fill
dropped regions in the mask. If None, the mask is not modified.
p (float): Probability of applying the transform.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Examples:
>>> import numpy as np
>>> import albumentations as A
>>>
>>> # Example of a custom dropout transform inheriting from BaseDropout
>>> class CustomDropout(A.BaseDropout):
... def __init__(self, num_holes_range=(4, 8), hole_size_range=(10, 20), *args, **kwargs):
... super().__init__(*args, **kwargs)
... self.num_holes_range = num_holes_range
... self.hole_size_range = hole_size_range
...
... def get_params_dependent_on_data(self, params, data):
... img = data["image"]
... height, width = img.shape[:2]
...
... # Generate random holes
... num_holes = self.py_random.randint(*self.num_holes_range)
... hole_sizes = self.py_random.randint(*self.hole_size_range, size=num_holes)
...
... holes = []
... for i in range(num_holes):
... # Random position for each hole
... x1 = self.py_random.randint(0, max(1, width - hole_sizes[i]))
... y1 = self.py_random.randint(0, max(1, height - hole_sizes[i]))
... x2 = min(width, x1 + hole_sizes[i])
... y2 = min(height, y1 + hole_sizes[i])
... holes.append([x1, y1, x2, y2])
...
... # Return holes and random seed
... return {
... "holes": np.array(holes) if holes else np.empty((0, 4), dtype=np.int32),
... "seed": self.py_random.integers(0, 100000)
... }
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[0.1, 0.1, 0.4, 0.4], [0.6, 0.6, 0.9, 0.9]])
>>>
>>> # Create a transform with custom dropout
>>> transform = A.Compose([
... CustomDropout(
... num_holes_range=(3, 6), # Generate 3-6 random holes
... hole_size_range=(5, 15), # Holes of size 5-15 pixels
... fill=0, # Fill holes with black
... fill_mask=1, # Fill mask holes with 1
... p=1.0 # Always apply for this example
... )
... ], bbox_params=A.BboxParams(format='yolo', min_visibility=0.3))
>>>
>>> # Apply the transform
>>> transformed = transform(image=image, mask=mask, bboxes=bboxes)
>>>
>>> # Get the transformed data
>>> dropout_image = transformed["image"] # Image with random holes filled with 0
>>> dropout_mask = transformed["mask"] # Mask with same holes filled with 1
>>> dropout_bboxes = transformed["bboxes"] # Bboxes filtered by visibility threshold
"""
_targets: tuple[Targets, ...] | Targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]
fill_mask: tuple[float, ...] | float | None
def __init__(
self,
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"],
fill_mask: tuple[float, ...] | float | None,
p: float,
):
super().__init__(p=p)
self.fill = fill # type: ignore[assignment]
self.fill_mask = fill_mask
def apply(self, img: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if holes.size == 0:
return img
if self.fill in {"inpaint_telea", "inpaint_ns"}:
num_channels = get_num_channels(img)
if num_channels not in {1, 3}:
raise ValueError("Inpainting works only for 1 or 3 channel images")
return cutout(img, holes, self.fill, np.random.default_rng(seed))
def apply_to_images(self, images: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if holes.size == 0:
return images
if self.fill in {"inpaint_telea", "inpaint_ns"}:
num_channels = images.shape[3] if images.ndim == 4 else 1
if num_channels not in {1, 3}:
raise ValueError("Inpainting works only for 1 or 3 channel images")
# Images (N, H, W, C) have the same structure as volumes (D, H, W, C)
return cutout_on_volume(images, holes, self.fill, np.random.default_rng(seed))
def apply_to_volume(self, volume: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
# Volume (D, H, W, C) has the same structure as images (N, H, W, C)
# We can reuse the same logic
return self.apply_to_images(volume, holes, seed, **params)
def apply_to_volumes(self, volumes: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if holes.size == 0:
return volumes
if self.fill in {"inpaint_telea", "inpaint_ns"}:
num_channels = volumes.shape[4] if volumes.ndim == 5 else 1
if num_channels not in {1, 3}:
raise ValueError("Inpainting works only for 1 or 3 channel images")
return cutout_on_volumes(volumes, holes, self.fill, np.random.default_rng(seed))
def apply_to_mask3d(self, mask: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if self.fill_mask is None or holes.size == 0:
return mask
return cutout_on_volume(mask, holes, self.fill_mask, np.random.default_rng(seed))
def apply_to_masks3d(self, mask: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if self.fill_mask is None or holes.size == 0:
return mask
return cutout_on_volumes(mask, holes, self.fill_mask, np.random.default_rng(seed))
def apply_to_mask(self, mask: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if self.fill_mask is None or holes.size == 0:
return mask
return cutout(mask, holes, self.fill_mask, np.random.default_rng(seed))
def apply_to_bboxes(
self,
bboxes: np.ndarray,
holes: np.ndarray,
**params: Any,
) -> np.ndarray:
if holes.size == 0:
return bboxes
processor = cast("BboxProcessor", self.get_processor("bboxes"))
if processor is None:
return bboxes
image_shape = params["shape"][:2]
denormalized_bboxes = denormalize_bboxes(bboxes, image_shape)
return normalize_bboxes(
filter_bboxes_by_holes(
denormalized_bboxes,
holes,
image_shape,
min_area=processor.params.min_area,
min_visibility=processor.params.min_visibility,
),
image_shape,
)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
holes: np.ndarray,
**params: Any,
) -> np.ndarray:
if holes.size == 0:
return keypoints
processor = cast("KeypointsProcessor", self.get_processor("keypoints"))
if processor is None or not processor.params.remove_invisible:
return keypoints
return filter_keypoints_in_holes(keypoints, holes)
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
raise NotImplementedError("Subclasses must implement this method.")
class PixelDropout(DualTransform):
"""Drops random pixels from the image.
This transform randomly sets pixels in the image to a specified value, effectively "dropping out" those pixels.
It can be applied to both the image and its corresponding mask.
Args:
dropout_prob (float): Probability of dropping out each pixel. Should be in the range [0, 1].
Default: 0.01
per_channel (bool): If True, the dropout mask will be generated independently for each channel.
If False, the same dropout mask will be applied to all channels.
Default: False
drop_value (float | tuple[float, ...] | None): Value to assign to the dropped pixels.
If None, the value will be randomly sampled for each application:
- For uint8 images: Random integer in [0, 255]
- For float32 images: Random float in [0, 1]
If a single number, that value will be used for all dropped pixels.
If a sequence, it should contain one value per channel.
Default: 0
mask_drop_value (float | tuple[float, ...] | None): Value to assign to dropped pixels in the mask.
If None, the mask will remain unchanged.
If a single number, that value will be used for all dropped pixels in the mask.
If a sequence, it should contain one value per channel.
Default: None
p (float): Probability of applying the transform. Should be in the range [0, 1].
Default: 0.5
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- When applied to bounding boxes, this transform may cause some boxes to have zero area
if all pixels within the box are dropped. Such boxes will be removed.
- When applied to keypoints, keypoints that fall on dropped pixels will be removed if
the keypoint processor is configured to remove invisible keypoints.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> transform = A.PixelDropout(dropout_prob=0.1, per_channel=True, p=1.0)
>>> result = transform(image=image, mask=mask)
>>> dropped_image, dropped_mask = result['image'], result['mask']
"""
class InitSchema(BaseTransformInitSchema):
dropout_prob: float = Field(ge=0, le=1)
per_channel: bool
drop_value: tuple[float, ...] | float | None
mask_drop_value: tuple[float, ...] | float | None
_targets = ALL_TARGETS
def __init__(
self,
dropout_prob: float = 0.01,
per_channel: bool = False,
drop_value: tuple[float, ...] | float | None = 0,
mask_drop_value: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(p=p)
self.dropout_prob = dropout_prob
self.per_channel = per_channel
self.drop_value = drop_value
self.mask_drop_value = mask_drop_value
def apply(
self,
img: np.ndarray,
drop_mask: np.ndarray,
drop_values: np.ndarray,
**params: Any,
) -> np.ndarray:
"""Apply pixel dropout to the image.
Args:
img (np.ndarray): The image to apply the transform to.
drop_mask (np.ndarray): The dropout mask.
drop_values (np.ndarray): The values to assign to the dropped pixels.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed image.
"""
return fpixel.pixel_dropout(img, drop_mask, drop_values)
def apply_to_mask(
self,
mask: np.ndarray,
mask_drop_mask: np.ndarray,
mask_drop_values: float | np.ndarray,
**params: Any,
) -> np.ndarray:
"""Apply pixel dropout to the mask.
Args:
mask (np.ndarray): The mask to apply the transform to.
mask_drop_mask (np.ndarray): The dropout mask for the mask.
mask_drop_values (float | np.ndarray): The values to assign to the dropped pixels in the mask.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed mask.
"""
if self.mask_drop_value is None:
return mask
return fpixel.pixel_dropout(mask, mask_drop_mask, mask_drop_values)
def apply_to_bboxes(
self,
bboxes: np.ndarray,
drop_mask: np.ndarray | None,
**params: Any,
) -> np.ndarray:
"""Apply pixel dropout to the bounding boxes.
Args:
bboxes (np.ndarray): The bounding boxes to apply the transform to.
drop_mask (np.ndarray | None): The dropout mask for the bounding boxes.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed bounding boxes.
"""
if drop_mask is None or self.per_channel:
return bboxes
processor = cast("BboxProcessor", self.get_processor("bboxes"))
if processor is None:
return bboxes
image_shape = params["shape"][:2]
denormalized_bboxes = denormalize_bboxes(bboxes, image_shape)
# If per_channel is True, we need to create a single channel mask
# by combining the multi-channel mask (considering a pixel dropped if it's dropped in any channel)
if self.per_channel and len(drop_mask.shape) > 2:
# Create a single channel mask where a pixel is considered dropped if it's dropped in any channel
combined_mask = np.any(drop_mask, axis=-1 if drop_mask.shape[-1] <= 4 else 0)
# Ensure the mask has the right shape for the bboxes function
if combined_mask.ndim == 3 and combined_mask.shape[0] == 1:
combined_mask = combined_mask[0]
else:
combined_mask = drop_mask
result = fdropout.mask_dropout_bboxes(
denormalized_bboxes,
combined_mask,
image_shape,
processor.params.min_area,
processor.params.min_visibility,
)
return normalize_bboxes(result, image_shape)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
**params: Any,
) -> np.ndarray:
"""Apply pixel dropout to the keypoints.
Args:
keypoints (np.ndarray): The keypoints to apply the transform to.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed keypoints.
"""
return keypoints
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, Any]:
"""Generate parameters for pixel dropout based on input data.
Args:
params (dict[str, Any]): Transform parameters
data (dict[str, Any]): Input data dictionary
Returns:
dict[str, Any]: Dictionary of parameters for applying the transform
"""
reference_array = data["image"] if "image" in data else data["images"][0]
# Generate drop mask and values for all targets
drop_mask = fpixel.get_drop_mask(
reference_array.shape,
self.per_channel,
self.dropout_prob,
self.random_generator,
)
drop_values = fpixel.prepare_drop_values(
reference_array,
self.drop_value,
self.random_generator,
)
# Handle mask drop values if specified
mask_drop_mask = None
mask_drop_values = None
mask = fpixel.get_mask_array(data)
if self.mask_drop_value is not None and mask is not None:
mask_drop_mask = fpixel.get_drop_mask(
mask.shape,
self.per_channel,
self.dropout_prob,
self.random_generator,
)
mask_drop_values = fpixel.prepare_drop_values(
mask,
self.mask_drop_value,
self.random_generator,
)
return {
"drop_mask": drop_mask,
"drop_values": drop_values,
"mask_drop_mask": mask_drop_mask if mask_drop_mask is not None else None,
"mask_drop_values": mask_drop_values if mask_drop_values is not None else None,
}
@@ -0,0 +1,186 @@
"""Implementation of XY masking for time-frequency domain transformations.
This module provides the XYMasking transform, which applies masking strips along the X and Y axes
of an image. This is particularly useful for audio spectrograms, time-series data visualizations,
and other grid-like data representations where masking in specific directions (time or frequency)
can improve model robustness and generalization.
"""
from __future__ import annotations
from typing import Any, Literal, cast
import numpy as np
from pydantic import model_validator
from typing_extensions import Self
from albumentations.augmentations.dropout.transforms import BaseDropout
from albumentations.core.pydantic import NonNegativeIntRangeType
from albumentations.core.transforms_interface import BaseTransformInitSchema
__all__ = ["XYMasking"]
class XYMasking(BaseDropout):
"""Applies masking strips to an image, either horizontally (X axis) or vertically (Y axis),
simulating occlusions. This transform is useful for training models to recognize images
with varied visibility conditions. It's particularly effective for spectrogram images,
allowing spectral and frequency masking to improve model robustness.
At least one of `max_x_length` or `max_y_length` must be specified, dictating the mask's
maximum size along each axis.
Args:
num_masks_x (int | tuple[int, int]): Number or range of horizontal regions to mask. Defaults to 0.
num_masks_y (int | tuple[int, int]): Number or range of vertical regions to mask. Defaults to 0.
mask_x_length (int | tuple[int, int]): Specifies the length of the masks along
the X (horizontal) axis. If an integer is provided, it sets a fixed mask length.
If a tuple of two integers (min, max) is provided,
the mask length is randomly chosen within this range for each mask.
This allows for variable-length masks in the horizontal direction.
mask_y_length (int | tuple[int, int]): Specifies the height of the masks along
the Y (vertical) axis. Similar to `mask_x_length`, an integer sets a fixed mask height,
while a tuple (min, max) allows for variable-height masks, chosen randomly
within the specified range for each mask. This flexibility facilitates creating masks of various
sizes in the vertical direction.
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value for the dropped pixels. Can be:
- int or float: all channels are filled with this value
- tuple: tuple of values for each channel
- 'random': each pixel is filled with random values
- 'random_uniform': each hole is filled with a single random color
- 'inpaint_telea': uses OpenCV Telea inpainting method
- 'inpaint_ns': uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Fill value for dropout regions in the mask.
If None, mask regions corresponding to image dropouts are unchanged. Default: None
p (float): Probability of applying the transform. Defaults to 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note: Either `max_x_length` or `max_y_length` or both must be defined.
"""
class InitSchema(BaseTransformInitSchema):
num_masks_x: NonNegativeIntRangeType
num_masks_y: NonNegativeIntRangeType
mask_x_length: NonNegativeIntRangeType
mask_y_length: NonNegativeIntRangeType
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]
fill_mask: tuple[float, ...] | float | None
@model_validator(mode="after")
def _check_mask_length(self) -> Self:
if (
isinstance(self.mask_x_length, int)
and self.mask_x_length <= 0
and isinstance(self.mask_y_length, int)
and self.mask_y_length <= 0
):
msg = "At least one of `mask_x_length` or `mask_y_length` Should be a positive number."
raise ValueError(msg)
return self
def __init__(
self,
num_masks_x: tuple[int, int] | int = 0,
num_masks_y: tuple[int, int] | int = 0,
mask_x_length: tuple[int, int] | int = 0,
mask_y_length: tuple[int, int] | int = 0,
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(p=p, fill=fill, fill_mask=fill_mask)
self.num_masks_x = cast("tuple[int, int]", num_masks_x)
self.num_masks_y = cast("tuple[int, int]", num_masks_y)
self.mask_x_length = cast("tuple[int, int]", mask_x_length)
self.mask_y_length = cast("tuple[int, int]", mask_y_length)
def _validate_mask_length(
self,
mask_length: tuple[int, int] | None,
dimension_size: int,
dimension_name: str,
) -> None:
"""Validate the mask length against the corresponding image dimension size."""
if mask_length is not None:
if isinstance(mask_length, (tuple, list)):
if mask_length[0] < 0 or mask_length[1] > dimension_size:
raise ValueError(
f"{dimension_name} range {mask_length} is out of valid range [0, {dimension_size}]",
)
elif mask_length < 0 or mask_length > dimension_size:
raise ValueError(f"{dimension_name} {mask_length} exceeds image {dimension_name} {dimension_size}")
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, np.ndarray]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, np.ndarray]: Dictionary with parameters for transformation.
"""
image_shape = params["shape"][:2]
height, width = image_shape
self._validate_mask_length(self.mask_x_length, width, "mask_x_length")
self._validate_mask_length(self.mask_y_length, height, "mask_y_length")
masks_x = self._generate_masks(self.num_masks_x, image_shape, self.mask_x_length, axis="x")
masks_y = self._generate_masks(self.num_masks_y, image_shape, self.mask_y_length, axis="y")
holes = np.array(masks_x + masks_y)
return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
def _generate_mask_size(self, mask_length: tuple[int, int]) -> int:
return self.py_random.randint(*mask_length)
def _generate_masks(
self,
num_masks: tuple[int, int],
image_shape: tuple[int, int],
max_length: tuple[int, int] | None,
axis: str,
) -> list[tuple[int, int, int, int]]:
if max_length is None or max_length == 0 or (isinstance(num_masks, (int, float)) and num_masks == 0):
return []
masks = []
num_masks_integer = (
num_masks if isinstance(num_masks, int) else self.py_random.randint(num_masks[0], num_masks[1])
)
height, width = image_shape
for _ in range(num_masks_integer):
length = self._generate_mask_size(max_length)
if axis == "x":
x_min = self.py_random.randint(0, width - length)
y_min = 0
x_max, y_max = x_min + length, height
else: # axis == 'y'
y_min = self.py_random.randint(0, height - length)
x_min = 0
x_max, y_max = width, y_min + length
masks.append((x_min, y_min, x_max, y_max))
return masks