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,920 @@
"""Utilities for handling bounding box operations during image augmentation.
This module provides tools for processing bounding boxes in various formats (COCO, Pascal VOC, YOLO),
converting between coordinate systems, normalizing and denormalizing coordinates, filtering
boxes based on visibility and size criteria, and performing transformations on boxes to match
image augmentations. It forms the core functionality for all bounding box-related operations
in the albumentations library.
"""
from __future__ import annotations
from collections.abc import Sequence
from typing import Any, Literal
import numpy as np
from albumentations.augmentations.utils import handle_empty_array
from albumentations.core.type_definitions import MONO_CHANNEL_DIMENSIONS, NUM_BBOXES_COLUMNS_IN_ALBUMENTATIONS
from .utils import DataProcessor, Params, ShapeType
__all__ = [
"BboxParams",
"BboxProcessor",
"check_bboxes",
"convert_bboxes_from_albumentations",
"convert_bboxes_to_albumentations",
"denormalize_bboxes",
"filter_bboxes",
"normalize_bboxes",
"union_of_bboxes",
]
BBOX_WITH_LABEL_SHAPE = 5
class BboxParams(Params):
"""Parameters for bounding box transforms.
Args:
format (Literal["coco", "pascal_voc", "albumentations", "yolo"]): Format of bounding boxes.
Should be one of:
- 'coco': [x_min, y_min, width, height], e.g. [97, 12, 150, 200].
- 'pascal_voc': [x_min, y_min, x_max, y_max], e.g. [97, 12, 247, 212].
- 'albumentations': like pascal_voc but normalized in [0, 1] range, e.g. [0.2, 0.3, 0.4, 0.5].
- 'yolo': [x_center, y_center, width, height] normalized in [0, 1] range, e.g. [0.1, 0.2, 0.3, 0.4].
label_fields (Sequence[str] | None): List of fields that are joined with boxes,
e.g., ['class_labels', 'scores']. Default: None.
min_area (float): Minimum area of a bounding box. All bounding boxes whose visible area in pixels is less than
this value will be removed. Default: 0.0.
min_visibility (float): Minimum fraction of area for a bounding box to remain this box in the result.
Should be in [0.0, 1.0] range. Default: 0.0.
min_width (float): Minimum width of a bounding box in pixels or normalized units. Bounding boxes with width
less than this value will be removed. Default: 0.0.
min_height (float): Minimum height of a bounding box in pixels or normalized units. Bounding boxes with height
less than this value will be removed. Default: 0.0.
check_each_transform (bool): If True, performs checks for each dual transform. Default: True.
clip (bool): If True, clips bounding boxes to image boundaries before applying any transform. Default: False.
filter_invalid_bboxes (bool): If True, filters out invalid bounding boxes (e.g., boxes with negative dimensions
or boxes where x_max < x_min or y_max < y_min) at the beginning of the pipeline. If clip=True, filtering
is applied after clipping. Default: False.
max_accept_ratio (float | None): Maximum allowed aspect ratio for bounding boxes. The aspect ratio is calculated
as max(width/height, height/width), so it's always >= 1. Boxes with aspect ratio greater than this value
will be filtered out. For example, if max_accept_ratio=3.0, boxes with width:height or height:width ratios
greater than 3:1 will be removed. Set to None to disable aspect ratio filtering. Default: None.
Note:
The processing order for bounding boxes is:
1. Convert to albumentations format (normalized pascal_voc)
2. Clip boxes to image boundaries (if clip=True)
3. Filter invalid boxes (if filter_invalid_bboxes=True)
4. Apply transformations
5. Filter boxes based on min_area, min_visibility, min_width, min_height
6. Convert back to the original format
Examples:
>>> # Create BboxParams for COCO format with class labels
>>> bbox_params = BboxParams(
... format='coco',
... label_fields=['class_labels'],
... min_area=1024,
... min_visibility=0.1
... )
>>> # Create BboxParams that clips and filters invalid boxes
>>> bbox_params = BboxParams(
... format='pascal_voc',
... clip=True,
... filter_invalid_bboxes=True
... )
>>> # Create BboxParams that filters extremely elongated boxes
>>> bbox_params = BboxParams(
... format='yolo',
... max_accept_ratio=5.0, # Filter boxes with aspect ratio > 5:1
... clip=True
... )
"""
def __init__(
self,
format: Literal["coco", "pascal_voc", "albumentations", "yolo"], # noqa: A002
label_fields: Sequence[Any] | None = None,
min_area: float = 0.0,
min_visibility: float = 0.0,
min_width: float = 0.0,
min_height: float = 0.0,
check_each_transform: bool = True,
clip: bool = False,
filter_invalid_bboxes: bool = False,
max_accept_ratio: float | None = None,
):
super().__init__(format, label_fields)
self.min_area = min_area
self.min_visibility = min_visibility
self.min_width = min_width
self.min_height = min_height
self.check_each_transform = check_each_transform
self.clip = clip
self.filter_invalid_bboxes = filter_invalid_bboxes
if max_accept_ratio is not None and max_accept_ratio < 1.0:
raise ValueError(
"max_accept_ratio must be >= 1.0 when provided, as aspect ratio is calculated as max(w/h, h/w)",
)
self.max_accept_ratio = max_accept_ratio # e.g., 5.0
def to_dict_private(self) -> dict[str, Any]:
"""Get the private dictionary representation of bounding box parameters.
Returns:
dict[str, Any]: Dictionary containing the bounding box parameters.
"""
data = super().to_dict_private()
data.update(
{
"min_area": self.min_area,
"min_visibility": self.min_visibility,
"min_width": self.min_width,
"min_height": self.min_height,
"check_each_transform": self.check_each_transform,
"clip": self.clip,
"max_accept_ratio": self.max_accept_ratio,
},
)
return data
@classmethod
def is_serializable(cls) -> bool:
"""Check if the bounding box parameters are serializable.
Returns:
bool: Always returns True as BboxParams is serializable.
"""
return True
@classmethod
def get_class_fullname(cls) -> str:
"""Get the full name of the class.
Returns:
str: The string "BboxParams".
"""
return "BboxParams"
def __repr__(self) -> str:
return (
f"BboxParams(format={self.format}, label_fields={self.label_fields}, min_area={self.min_area},"
f" min_visibility={self.min_visibility}, min_width={self.min_width}, min_height={self.min_height},"
f" check_each_transform={self.check_each_transform}, clip={self.clip})"
)
class BboxProcessor(DataProcessor):
"""Processor for bounding box transformations.
This class handles the preprocessing and postprocessing of bounding boxes during augmentation pipeline,
including format conversion, validation, clipping, and filtering.
Args:
params (BboxParams): Parameters that control bounding box processing.
See BboxParams class for details.
additional_targets (dict[str, str] | None): Dictionary with additional targets to process.
Keys are names of additional targets, values are their types.
For example: {'bbox2': 'bboxes'} will handle 'bbox2' as another bounding box target.
Default: None.
Note:
The processing order for bounding boxes is:
1. Convert to albumentations format (normalized pascal_voc)
2. Clip boxes to image boundaries (if params.clip=True)
3. Filter invalid boxes (if params.filter_invalid_bboxes=True)
4. Apply transformations
5. Filter boxes based on min_area, min_visibility, min_width, min_height
6. Convert back to the original format
Examples:
>>> import albumentations as A
>>> # Process COCO format bboxes with class labels
>>> params = A.BboxParams(
... format='coco',
... label_fields=['class_labels'],
... min_area=1024,
... min_visibility=0.1
... )
>>> processor = BboxProcessor(params)
>>>
>>> # Process multiple bbox fields
>>> params = A.BboxParams('pascal_voc')
>>> processor = BboxProcessor(
... params,
... additional_targets={'bbox2': 'bboxes'}
... )
"""
def __init__(self, params: BboxParams, additional_targets: dict[str, str] | None = None):
super().__init__(params, additional_targets)
@property
def default_data_name(self) -> str:
"""Returns the default key for bounding box data in transformations.
Returns:
str: The string 'bboxes'.
"""
return "bboxes"
def ensure_data_valid(self, data: dict[str, Any]) -> None:
"""Validates the input bounding box data.
Checks that:
- Bounding boxes have labels (either in the bbox array or in label_fields)
- All specified label_fields exist in the data
Args:
data (dict[str, Any]): Dict with bounding boxes and optional label fields.
Raises:
ValueError: If bounding boxes don't have labels or if label_fields are invalid.
"""
if self.params.label_fields and not all(i in data for i in self.params.label_fields):
msg = "Your 'label_fields' are not valid - them must have same names as params in dict"
raise ValueError(msg)
def filter(self, data: np.ndarray, shape: ShapeType) -> np.ndarray:
"""Filter bounding boxes based on size and visibility criteria.
Args:
data (np.ndarray): Array of bounding boxes in Albumentations format.
shape (ShapeType): Shape information for validation.
Returns:
np.ndarray: Filtered bounding boxes that meet the criteria.
"""
self.params: BboxParams
return filter_bboxes(
data,
shape,
min_area=self.params.min_area,
min_visibility=self.params.min_visibility,
min_width=self.params.min_width,
min_height=self.params.min_height,
max_accept_ratio=self.params.max_accept_ratio,
)
def check_and_convert(
self,
data: np.ndarray,
shape: ShapeType,
direction: Literal["to", "from"] = "to",
) -> np.ndarray:
"""Converts bounding boxes between formats and applies preprocessing/postprocessing.
Args:
data (np.ndarray): Array of bounding boxes to process.
shape (ShapeType): Image shape as dict with height and width keys.
direction (Literal["to", "from"]): Direction of conversion:
- "to": Convert from original format to albumentations format
- "from": Convert from albumentations format to original format
Default: "to".
Returns:
np.ndarray: Processed bounding boxes.
Note:
When direction="to":
1. Converts to albumentations format
2. Clips boxes if params.clip=True
3. Filters invalid boxes if params.filter_invalid_bboxes=True
4. Validates remaining boxes
When direction="from":
1. Validates boxes
2. Converts back to original format
"""
if direction == "to":
# First convert to albumentations format
if self.params.format == "albumentations":
converted_data = data
else:
converted_data = convert_bboxes_to_albumentations(
data,
self.params.format,
shape,
check_validity=False, # Don't check validity yet
)
if self.params.clip and converted_data.size > 0:
converted_data[:, :4] = np.clip(converted_data[:, :4], 0, 1)
# Then filter invalid boxes if requested
if self.params.filter_invalid_bboxes:
converted_data = filter_bboxes(
converted_data,
shape,
min_area=0,
min_visibility=0,
min_width=0,
min_height=0,
)
# Finally check the remaining boxes
self.check(converted_data, shape)
return converted_data
self.check(data, shape)
if self.params.format == "albumentations":
return data
return convert_bboxes_from_albumentations(data, self.params.format, shape)
def check(self, data: np.ndarray, shape: ShapeType) -> None:
"""Check if bounding boxes are valid.
Args:
data (np.ndarray): Array of bounding boxes to validate.
shape (ShapeType): Shape to check against.
"""
check_bboxes(data)
def convert_from_albumentations(self, data: np.ndarray, shape: ShapeType) -> np.ndarray:
"""Convert bounding boxes from internal Albumentations format to the specified format.
Args:
data (np.ndarray): Bounding boxes in Albumentations format.
shape (ShapeType): Shape information for validation.
Returns:
np.ndarray: Converted bounding boxes in the target format.
"""
return np.array(
convert_bboxes_from_albumentations(data, self.params.format, shape, check_validity=True),
dtype=data.dtype,
)
def convert_to_albumentations(self, data: np.ndarray, shape: ShapeType) -> np.ndarray:
"""Convert bounding boxes from the specified format to internal Albumentations format.
Args:
data (np.ndarray): Bounding boxes in source format.
shape (ShapeType): Shape information for validation.
Returns:
np.ndarray: Converted bounding boxes in Albumentations format.
"""
if self.params.clip:
data_np = convert_bboxes_to_albumentations(data, self.params.format, shape, check_validity=False)
data_np = filter_bboxes(data_np, shape, min_area=0, min_visibility=0, min_width=0, min_height=0)
check_bboxes(data_np)
return data_np
return convert_bboxes_to_albumentations(data, self.params.format, shape, check_validity=True)
@handle_empty_array("bboxes")
def normalize_bboxes(bboxes: np.ndarray, shape: ShapeType | tuple[int, int]) -> np.ndarray:
"""Normalize array of bounding boxes.
Args:
bboxes (np.ndarray): Denormalized bounding boxes `[(x_min, y_min, x_max, y_max, ...)]`.
shape (ShapeType | tuple[int, int]): Image shape `(height, width)`.
Returns:
np.ndarray: Normalized bounding boxes `[(x_min, y_min, x_max, y_max, ...)]`.
"""
if isinstance(shape, tuple):
rows, cols = shape[:2]
else:
rows, cols = shape["height"], shape["width"]
normalized = bboxes.copy().astype(float)
normalized[:, [0, 2]] /= cols
normalized[:, [1, 3]] /= rows
return normalized
@handle_empty_array("bboxes")
def denormalize_bboxes(
bboxes: np.ndarray,
shape: ShapeType | tuple[int, int],
) -> np.ndarray:
"""Denormalize array of bounding boxes.
Args:
bboxes (np.ndarray): Normalized bounding boxes `[(x_min, y_min, x_max, y_max, ...)]`.
shape (ShapeType | tuple[int, int]): Image shape `(height, width)`.
Returns:
np.ndarray: Denormalized bounding boxes `[(x_min, y_min, x_max, y_max, ...)]`.
"""
scale_factors = (shape[1], shape[0]) if isinstance(shape, tuple) else (shape["width"], shape["height"])
# Vectorized scaling of bbox coordinates
return bboxes * np.array([*scale_factors, *scale_factors, *[1] * (bboxes.shape[1] - 4)], dtype=float)
def calculate_bbox_areas_in_pixels(bboxes: np.ndarray, shape: ShapeType) -> np.ndarray:
"""Calculate areas for multiple bounding boxes.
This function computes the areas of bounding boxes given their normalized coordinates
and the dimensions of the image they belong to. The bounding boxes are expected to be
in the format [x_min, y_min, x_max, y_max] with normalized coordinates (0 to 1).
Args:
bboxes (np.ndarray): A numpy array of shape (N, 4+) where N is the number of bounding boxes.
Each row contains [x_min, y_min, x_max, y_max] in normalized coordinates.
Additional columns beyond the first 4 are ignored.
shape (ShapeType): A tuple containing the height and width of the image (height, width).
Returns:
np.ndarray: A 1D numpy array of shape (N,) containing the areas of the bounding boxes in pixels.
Returns an empty array if the input `bboxes` is empty.
Note:
- The function assumes that the input bounding boxes are valid (i.e., x_max > x_min and y_max > y_min).
Invalid bounding boxes may result in negative areas.
- The function preserves the input array and creates a copy for internal calculations.
- The returned areas are in pixel units, not normalized.
Example:
>>> bboxes = np.array([[0.1, 0.1, 0.5, 0.5], [0.2, 0.2, 0.8, 0.8]])
>>> image_shape = (100, 100)
>>> areas = calculate_bbox_areas(bboxes, image_shape)
>>> print(areas)
[1600. 3600.]
"""
if len(bboxes) == 0:
return np.array([], dtype=np.float32)
# Unpack shape to variables
height, width = shape["height"], shape["width"]
# Directly compute denormalized bbox dimensions and areas
widths = (bboxes[:, 2] - bboxes[:, 0]) * width
heights = (bboxes[:, 3] - bboxes[:, 1]) * height
return widths * heights
@handle_empty_array("bboxes")
def convert_bboxes_to_albumentations(
bboxes: np.ndarray,
source_format: Literal["coco", "pascal_voc", "yolo"],
shape: ShapeType,
check_validity: bool = False,
) -> np.ndarray:
"""Convert bounding boxes from a specified format to the format used by albumentations:
normalized coordinates of top-left and bottom-right corners of the bounding box in the form of
`(x_min, y_min, x_max, y_max)` e.g. `(0.15, 0.27, 0.67, 0.5)`.
Args:
bboxes (np.ndarray): A numpy array of bounding boxes with shape (num_bboxes, 4+).
source_format (Literal["coco", "pascal_voc", "yolo"]): Format of the input bounding boxes.
shape (ShapeType): Image shape (height, width).
check_validity (bool): Check if all boxes are valid boxes.
Returns:
np.ndarray: An array of bounding boxes in albumentations format with shape (num_bboxes, 4+).
Raises:
ValueError: If `source_format` is not 'coco', 'pascal_voc', or 'yolo'.
ValueError: If in YOLO format, any coordinates are not in the range (0, 1].
"""
if source_format not in {"coco", "pascal_voc", "yolo"}:
raise ValueError(
f"Unknown source_format {source_format}. Supported formats are: 'coco', 'pascal_voc' and 'yolo'",
)
bboxes = bboxes.copy().astype(np.float32)
converted_bboxes = np.zeros_like(bboxes)
converted_bboxes[:, 4:] = bboxes[:, 4:] # Preserve additional columns
if source_format == "coco":
converted_bboxes[:, 0] = bboxes[:, 0] # x_min
converted_bboxes[:, 1] = bboxes[:, 1] # y_min
converted_bboxes[:, 2] = bboxes[:, 0] + bboxes[:, 2] # x_max
converted_bboxes[:, 3] = bboxes[:, 1] + bboxes[:, 3] # y_max
elif source_format == "yolo":
if check_validity and np.any((bboxes[:, :4] <= 0) | (bboxes[:, :4] > 1)):
raise ValueError(f"In YOLO format all coordinates must be float and in range (0, 1], got {bboxes}")
w_half, h_half = bboxes[:, 2] / 2, bboxes[:, 3] / 2
converted_bboxes[:, 0] = bboxes[:, 0] - w_half # x_min
converted_bboxes[:, 1] = bboxes[:, 1] - h_half # y_min
converted_bboxes[:, 2] = bboxes[:, 0] + w_half # x_max
converted_bboxes[:, 3] = bboxes[:, 1] + h_half # y_max
else: # pascal_voc
converted_bboxes[:, :4] = bboxes[:, :4]
if source_format != "yolo":
converted_bboxes[:, :4] = normalize_bboxes(converted_bboxes[:, :4], shape)
if check_validity:
check_bboxes(converted_bboxes)
return converted_bboxes
@handle_empty_array("bboxes")
def convert_bboxes_from_albumentations(
bboxes: np.ndarray,
target_format: Literal["coco", "pascal_voc", "yolo"],
shape: ShapeType,
check_validity: bool = False,
) -> np.ndarray:
"""Convert bounding boxes from the format used by albumentations to a specified format.
Args:
bboxes (np.ndarray): A numpy array of albumentations bounding boxes with shape (num_bboxes, 4+).
The first 4 columns are [x_min, y_min, x_max, y_max].
target_format (Literal["coco", "pascal_voc", "yolo"]): Required format of the output bounding boxes.
shape (ShapeType): Image shape (height, width).
check_validity (bool): Check if all boxes are valid boxes.
Returns:
np.ndarray: An array of bounding boxes in the target format with shape (num_bboxes, 4+).
Raises:
ValueError: If `target_format` is not 'coco', 'pascal_voc' or 'yolo'.
"""
if target_format not in {"coco", "pascal_voc", "yolo"}:
raise ValueError(
f"Unknown target_format {target_format}. Supported formats are: 'coco', 'pascal_voc' and 'yolo'",
)
if check_validity:
check_bboxes(bboxes)
converted_bboxes = np.zeros_like(bboxes)
converted_bboxes[:, 4:] = bboxes[:, 4:] # Preserve additional columns
denormalized_bboxes = denormalize_bboxes(bboxes[:, :4], shape) if target_format != "yolo" else bboxes[:, :4]
if target_format == "coco":
converted_bboxes[:, 0] = denormalized_bboxes[:, 0] # x_min
converted_bboxes[:, 1] = denormalized_bboxes[:, 1] # y_min
converted_bboxes[:, 2] = denormalized_bboxes[:, 2] - denormalized_bboxes[:, 0] # width
converted_bboxes[:, 3] = denormalized_bboxes[:, 3] - denormalized_bboxes[:, 1] # height
elif target_format == "yolo":
converted_bboxes[:, 0] = (denormalized_bboxes[:, 0] + denormalized_bboxes[:, 2]) / 2 # x_center
converted_bboxes[:, 1] = (denormalized_bboxes[:, 1] + denormalized_bboxes[:, 3]) / 2 # y_center
converted_bboxes[:, 2] = denormalized_bboxes[:, 2] - denormalized_bboxes[:, 0] # width
converted_bboxes[:, 3] = denormalized_bboxes[:, 3] - denormalized_bboxes[:, 1] # height
else: # pascal_voc
converted_bboxes[:, :4] = denormalized_bboxes
return converted_bboxes
@handle_empty_array("bboxes")
def check_bboxes(bboxes: np.ndarray) -> None:
"""Check if bounding boxes are valid.
Args:
bboxes (np.ndarray): A numpy array of bounding boxes with shape (num_bboxes, 4+).
Raises:
ValueError: If any bounding box is invalid.
"""
# Check if all values are in range [0, 1]
in_range = (bboxes[:, :4] >= 0) & (bboxes[:, :4] <= 1)
close_to_zero = np.isclose(bboxes[:, :4], 0)
close_to_one = np.isclose(bboxes[:, :4], 1)
valid_range = in_range | close_to_zero | close_to_one
if not np.all(valid_range):
invalid_idx = np.where(~np.all(valid_range, axis=1))[0][0]
invalid_bbox = bboxes[invalid_idx]
invalid_coord = ["x_min", "y_min", "x_max", "y_max"][np.where(~valid_range[invalid_idx])[0][0]]
invalid_value = invalid_bbox[np.where(~valid_range[invalid_idx])[0][0]]
raise ValueError(
f"Expected {invalid_coord} for bbox {invalid_bbox} to be in the range [0.0, 1.0], got {invalid_value}.",
)
# Check if x_max > x_min and y_max > y_min
valid_order = (bboxes[:, 2] > bboxes[:, 0]) & (bboxes[:, 3] > bboxes[:, 1])
if not np.all(valid_order):
invalid_idx = np.where(~valid_order)[0][0]
invalid_bbox = bboxes[invalid_idx]
if invalid_bbox[2] <= invalid_bbox[0]:
raise ValueError(f"x_max is less than or equal to x_min for bbox {invalid_bbox}.")
raise ValueError(f"y_max is less than or equal to y_min for bbox {invalid_bbox}.")
@handle_empty_array("bboxes")
def clip_bboxes(bboxes: np.ndarray, shape: ShapeType) -> np.ndarray:
"""Clip bounding boxes to the image shape.
Args:
bboxes (np.ndarray): A numpy array of bounding boxes with shape (num_bboxes, 4+).
shape (ShapeType): The shape of the image/volume:
- For 2D: {'height': int, 'width': int}
- For 3D: {'height': int, 'width': int, 'depth': int}
Returns:
np.ndarray: A numpy array of bounding boxes with shape (num_bboxes, 4+).
"""
height, width = shape["height"], shape["width"]
# Denormalize bboxes
denorm_bboxes = denormalize_bboxes(bboxes, shape)
## Note:
# It could be tempting to use cols - 1 and rows - 1 as the upper bounds for the clipping
# But this would cause the bounding box to be clipped to the image dimensions - 1 which is not what we want.
# Bounding box lives not in the middle of pixels but between them.
# Example: for image with height 100, width 100, the pixel values are in the range [0, 99]
# but if we want bounding box to be 1 pixel width and height and lie on the boundary of the image
# it will be described as [99, 99, 100, 100] => clip by image_size - 1 will lead to [99, 99, 99, 99]
# which is incorrect
# It could be also tempting to clip `x_min`` to `cols - 1`` and `y_min` to `rows - 1`, but this also leads
# to another error. If image fully lies outside of the visible area and min_area is set to 0, then
# the bounding box will be clipped to the image size - 1 and will be 1 pixel in size and fully visible,
# but it should be completely removed.
# Clip coordinates
denorm_bboxes[:, [0, 2]] = np.clip(denorm_bboxes[:, [0, 2]], 0, width, out=denorm_bboxes[:, [0, 2]])
denorm_bboxes[:, [1, 3]] = np.clip(denorm_bboxes[:, [1, 3]], 0, height, out=denorm_bboxes[:, [1, 3]])
# Normalize clipped bboxes
return normalize_bboxes(denorm_bboxes, shape)
def filter_bboxes(
bboxes: np.ndarray,
shape: ShapeType,
min_area: float = 0.0,
min_visibility: float = 0.0,
min_width: float = 1.0,
min_height: float = 1.0,
max_accept_ratio: float | None = None,
) -> np.ndarray:
"""Remove bounding boxes that either lie outside of the visible area by more than min_visibility
or whose area in pixels is under the threshold set by `min_area`. Also crops boxes to final image size.
Args:
bboxes (np.ndarray): A numpy array of bounding boxes with shape (num_bboxes, 4+).
shape (ShapeType): The shape of the image/volume:
- For 2D: {'height': int, 'width': int}
- For 3D: {'height': int, 'width': int, 'depth': int}
min_area (float): Minimum area of a bounding box in pixels. Default: 0.0.
min_visibility (float): Minimum fraction of area for a bounding box to remain. Default: 0.0.
min_width (float): Minimum width of a bounding box in pixels. Default: 0.0.
min_height (float): Minimum height of a bounding box in pixels. Default: 0.0.
max_accept_ratio (float | None): Maximum allowed aspect ratio, calculated as max(width/height, height/width).
Boxes with higher ratios will be filtered out. Default: None.
Returns:
np.ndarray: Filtered bounding boxes.
"""
epsilon = 1e-7
if len(bboxes) == 0:
return np.array([], dtype=np.float32).reshape(0, 4)
# Calculate areas of bounding boxes before clipping in pixels
denormalized_box_areas = calculate_bbox_areas_in_pixels(bboxes, shape)
# Clip bounding boxes in ratio
clipped_bboxes = clip_bboxes(bboxes, shape)
# Calculate areas of clipped bounding boxes in pixels
clipped_box_areas = calculate_bbox_areas_in_pixels(clipped_bboxes, shape)
# Calculate width and height of the clipped bounding boxes
denormalized_bboxes = denormalize_bboxes(clipped_bboxes[:, :4], shape)
clipped_widths = denormalized_bboxes[:, 2] - denormalized_bboxes[:, 0]
clipped_heights = denormalized_bboxes[:, 3] - denormalized_bboxes[:, 1]
# Calculate aspect ratios if needed
if max_accept_ratio is not None:
aspect_ratios = np.maximum(
clipped_widths / (clipped_heights + epsilon),
clipped_heights / (clipped_widths + epsilon),
)
valid_ratios = aspect_ratios <= max_accept_ratio
else:
valid_ratios = np.ones_like(denormalized_box_areas, dtype=bool)
# Create a mask for bboxes that meet all criteria
mask = (
(denormalized_box_areas >= epsilon)
& (clipped_box_areas >= min_area - epsilon)
& (clipped_box_areas / (denormalized_box_areas + epsilon) >= min_visibility)
& (clipped_widths >= min_width - epsilon)
& (clipped_heights >= min_height - epsilon)
& valid_ratios
)
# Apply the mask to get the filtered bboxes
filtered_bboxes = clipped_bboxes[mask]
return np.array([], dtype=np.float32).reshape(0, 4) if len(filtered_bboxes) == 0 else filtered_bboxes
def union_of_bboxes(bboxes: np.ndarray, erosion_rate: float) -> np.ndarray | None:
"""Calculate union of bounding boxes. Boxes could be in albumentations or Pascal Voc format.
Args:
bboxes (np.ndarray): List of bounding boxes
erosion_rate (float): How much each bounding box can be shrunk, useful for erosive cropping.
Set this in range [0, 1]. 0 will not be erosive at all, 1.0 can make any bbox lose its volume.
Returns:
np.ndarray | None: A bounding box `(x_min, y_min, x_max, y_max)` or None if no bboxes are given or if
the bounding boxes become invalid after erosion.
"""
if not bboxes.size:
return None
if erosion_rate == 1:
return None
if bboxes.shape[0] == 1:
return bboxes[0][:4]
epsilon = 1e-6
x_min, y_min = np.min(bboxes[:, :2], axis=0)
x_max, y_max = np.max(bboxes[:, 2:4], axis=0)
width = x_max - x_min
height = y_max - y_min
erosion_x = width * erosion_rate * 0.5
erosion_y = height * erosion_rate * 0.5
x_min += erosion_x
y_min += erosion_y
x_max -= erosion_x
y_max -= erosion_y
if abs(x_max - x_min) < epsilon or abs(y_max - y_min) < epsilon:
return None
return np.array([x_min, y_min, x_max, y_max], dtype=np.float32)
def bboxes_from_masks(masks: np.ndarray) -> np.ndarray:
"""Create bounding boxes from binary masks (fast version)
Args:
masks (np.ndarray): Binary masks of shape (H, W) or (N, H, W) where N is the number of masks,
and H, W are the height and width of each mask.
Returns:
np.ndarray: An array of bounding boxes with shape (N, 4), where each row is
(x_min, y_min, x_max, y_max).
"""
# Handle single mask case by adding batch dimension
if len(masks.shape) == MONO_CHANNEL_DIMENSIONS:
masks = masks[np.newaxis, ...]
rows = np.any(masks, axis=2)
cols = np.any(masks, axis=1)
bboxes = np.zeros((masks.shape[0], 4), dtype=np.int32)
for i, (row, col) in enumerate(zip(rows, cols)):
if not np.any(row) or not np.any(col):
bboxes[i] = [-1, -1, -1, -1]
else:
y_min, y_max = np.where(row)[0][[0, -1]]
x_min, x_max = np.where(col)[0][[0, -1]]
bboxes[i] = [x_min, y_min, x_max + 1, y_max + 1]
return bboxes
def masks_from_bboxes(bboxes: np.ndarray, shape: ShapeType | tuple[int, int]) -> np.ndarray:
"""Convert bounding boxes to masks.
Args:
bboxes (np.ndarray): A numpy array of bounding boxes with shape (num_bboxes, 4+).
shape (ShapeType | tuple[int, int]): Image shape (height, width).
Returns:
np.ndarray: A numpy array of masks with shape (num_bboxes, height, width).
"""
if isinstance(shape, dict):
height, width = shape["height"], shape["width"]
else:
height, width = shape[:2]
masks = np.zeros((len(bboxes), height, width), dtype=np.uint8)
y, x = np.ogrid[:height, :width]
for i, (x_min, y_min, x_max, y_max) in enumerate(bboxes[:, :4].astype(int)):
masks[i] = (x_min <= x) & (x < x_max) & (y_min <= y) & (y < y_max)
return masks
def bboxes_to_mask(
bboxes: np.ndarray,
image_shape: tuple[int, int],
) -> np.ndarray:
"""Convert bounding boxes to a single mask.
Args:
bboxes (np.ndarray): A numpy array of bounding boxes with shape (num_bboxes, 4+).
image_shape (tuple[int, int]): Image shape (height, width).
Returns:
np.ndarray: A numpy array of shape (height, width) with 1s where any bounding box is present.
"""
height, width = image_shape[:2]
num_boxes = len(bboxes)
# Create multi-channel mask where each channel represents one bbox
bbox_masks = np.zeros((height, width, num_boxes), dtype=np.uint8)
# Fill each bbox in its channel
for idx, box in enumerate(bboxes):
x_min, y_min, x_max, y_max = map(round, box[:4])
x_min = max(0, min(width - 1, x_min))
x_max = max(0, min(width - 1, x_max))
y_min = max(0, min(height - 1, y_min))
y_max = max(0, min(height - 1, y_max))
bbox_masks[y_min : y_max + 1, x_min : x_max + 1, idx] = 1
return bbox_masks
def mask_to_bboxes(
masks: np.ndarray,
original_bboxes: np.ndarray,
) -> np.ndarray:
"""Convert masks back to bounding boxes.
Args:
masks (np.ndarray): A numpy array of masks with shape (num_masks, height, width).
original_bboxes (np.ndarray): Original bounding boxes with shape (num_bboxes, 4+).
Returns:
np.ndarray: A numpy array of bounding boxes with shape (num_masks, 4+).
"""
num_boxes = masks.shape[-1]
new_bboxes = []
num_boxes = masks.shape[-1]
if num_boxes == 0:
# Return empty array with correct shape
return np.zeros((0, original_bboxes.shape[1]), dtype=original_bboxes.dtype)
for idx in range(num_boxes):
mask = masks[..., idx]
if np.any(mask):
y_coords, x_coords = np.where(mask)
x_min, x_max = x_coords.min(), x_coords.max()
y_min, y_max = y_coords.min(), y_coords.max()
new_bboxes.append([x_min, y_min, x_max, y_max])
else:
# If bbox disappeared, use original coords
new_bboxes.append(original_bboxes[idx, :4])
new_bboxes = np.array(new_bboxes)
return (
np.column_stack([new_bboxes, original_bboxes[:, 4:]])
if original_bboxes.shape[1] > NUM_BBOXES_COLUMNS_IN_ALBUMENTATIONS
else new_bboxes
)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,299 @@
"""This module provides mixin functionality for the Albumentations library.
It includes utility functions and classes to enhance the core capabilities.
"""
from __future__ import annotations
import functools
import logging
from pathlib import Path
from typing import Any, Callable
from albumentations.core.serialization import load as load_transform
from albumentations.core.serialization import save as save_transform
try:
from huggingface_hub import HfApi, hf_hub_download
from huggingface_hub.utils import HfHubHTTPError, SoftTemporaryDirectory
is_huggingface_hub_available = True
except ImportError:
is_huggingface_hub_available = False
logger = logging.getLogger(__name__)
def require_huggingface_hub(func: Callable[..., Any]) -> Callable[..., Any]:
"""Decorator to require huggingface_hub.
This decorator ensures that the `huggingface_hub` package is installed before
executing the decorated function. If the package is not installed, it raises
an ImportError with instructions on how to install it.
Args:
func (Callable[..., Any]): The function to decorate.
Returns:
Callable[..., Any]: The decorated function.
"""
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
if not is_huggingface_hub_available:
raise ImportError(
f"You need to install `huggingface_hub` to use {func.__name__}. "
"Run `pip install huggingface_hub`, or `pip install albumentations[hub]`.",
)
return func(*args, **kwargs)
return wrapper
class HubMixin:
"""Mixin class for Hugging Face Hub integration.
This class provides functionality for saving and loading transforms to/from
the Hugging Face Hub. It enables serialization, deserialization, and sharing
of transform configurations.
Args:
_CONFIG_KEYS (tuple[str, ...]): Keys used for configuration files.
_CONFIG_FILE_NAME_TEMPLATE (str): Template for configuration filenames.
"""
_CONFIG_KEYS = ("train", "eval")
_CONFIG_FILE_NAME_TEMPLATE = "albumentations_config_{}.json"
def _save_pretrained(self, save_directory: str | Path, filename: str) -> Path:
"""Save the transform to a specified directory.
Args:
save_directory (Union[str, Path]):
Directory where the transform will be saved.
filename (str):
Name of the file to save the transform.
Returns:
Path: Path to the saved transform file.
"""
# create save directory and path
save_directory = Path(save_directory)
save_directory.mkdir(parents=True, exist_ok=True)
save_path = save_directory / filename
# save transforms
save_transform(self, save_path, data_format="json") # type: ignore[arg-type]
return save_path
@classmethod
def _from_pretrained(cls, save_directory: str | Path, filename: str) -> object:
"""Load a transform from a specified directory.
Args:
save_directory (Union[str, Path]):
Directory from where the transform will be loaded.
filename (str):
Name of the file to load the transform from.
Returns:
A.Compose: Loaded transform.
"""
save_path = Path(save_directory) / filename
return load_transform(save_path, data_format="json")
def save_pretrained(
self,
save_directory: str | Path,
*,
key: str = "eval",
allow_custom_keys: bool = False,
repo_id: str | None = None,
push_to_hub: bool = False,
**push_to_hub_kwargs: Any,
) -> str | None:
"""Save the transform and optionally push it to the Huggingface Hub.
Args:
save_directory (`str` or `Path`):
Path to directory in which the transform configuration will be saved.
key (`str`, *optional*):
Key to identify the configuration type, one of ["train", "eval"]. Defaults to "eval".
allow_custom_keys (`bool`, *optional*):
Allow custom keys for the configuration. Defaults to False.
push_to_hub (`bool`, *optional*, defaults to `False`):
Whether or not to push your transform to the Huggingface Hub after saving it.
repo_id (`str`, *optional*):
ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if
not provided.
push_to_hub_kwargs (`dict`, *optional*):
Additional key word arguments passed along to the [`push_to_hub`] method.
Returns:
`str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise.
"""
if not allow_custom_keys and key not in self._CONFIG_KEYS:
raise ValueError(
f"Invalid key: `{key}`. Please use key from {self._CONFIG_KEYS} keys for upload. "
"If you want to use a custom key, set `allow_custom_keys=True`.",
)
# save model transforms
filename = self._CONFIG_FILE_NAME_TEMPLATE.format(key)
self._save_pretrained(save_directory, filename)
# push to the Hub if required
if push_to_hub:
kwargs = push_to_hub_kwargs.copy() # soft-copy to avoid mutating input
if repo_id is None:
repo_id = Path(save_directory).name # Defaults to `save_directory` name
return self.push_to_hub(repo_id=repo_id, key=key, **kwargs)
return None
@classmethod
def from_pretrained(
cls: Any,
directory_or_repo_id: str | Path,
*,
key: str = "eval",
force_download: bool = False,
proxies: dict[str, str] | None = None,
token: str | bool | None = None,
cache_dir: str | Path | None = None,
local_files_only: bool = False,
revision: str | None = None,
) -> object:
"""Load a transform from the Huggingface Hub or a local directory.
Args:
directory_or_repo_id (`str`, `Path`):
- Either the `repo_id` (string) of a repo with hosted transform on the Hub, e.g. `qubvel-hf/albu`.
- Or a path to a `directory` containing transform config saved using
[`~albumentations.Compose.save_pretrained`], e.g., `../path/to/my_directory/`.
key (`str`, *optional*):
Key to identify the configuration type, one of ["train", "eval"]. Defaults to "eval".
revision (`str`, *optional*):
Revision of the repo on the Hub. Can be a branch name, a git tag or any commit id.
Defaults to the latest commit on `main` branch.
force_download (`bool`, *optional*, defaults to `False`):
Whether to force (re-)downloading the transform configuration files from the Hub, overriding
the existing cache.
proxies (`dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}`. The proxies are used on every request.
token (`str` or `bool`, *optional*):
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
cached when running `huggingface-cli login`.
cache_dir (`str`, `Path`, *optional*):
Path to the folder where cached files are stored.
local_files_only (`bool`, *optional*, defaults to `False`):
If `True`, avoid downloading the file and return the path to the local cached file if it exists.
"""
filename = cls._CONFIG_FILE_NAME_TEMPLATE.format(key)
directory_or_repo_id = Path(directory_or_repo_id)
transform = None
# check if the file is already present locally
if directory_or_repo_id.is_dir():
if filename in [f.name for f in directory_or_repo_id.iterdir()]:
transform = cls._from_pretrained(save_directory=directory_or_repo_id, filename=filename)
elif is_huggingface_hub_available:
logger.info(
f"{filename} not found in {Path(directory_or_repo_id).resolve()}, trying to load from the Hub.",
)
else:
raise FileNotFoundError(
f"{filename} not found in {Path(directory_or_repo_id).resolve()}."
" Please install `huggingface_hub` to load from the Hub.",
)
if transform is not None:
return transform
# download the file from the Hub
try:
config_file = hf_hub_download(
repo_id=str(directory_or_repo_id).replace("\\", "/"),
filename=filename,
revision=revision,
cache_dir=cache_dir,
force_download=force_download,
proxies=proxies,
token=token,
local_files_only=local_files_only,
)
directory, filename = Path(config_file).parent, Path(config_file).name
return cls._from_pretrained(save_directory=directory, filename=filename)
except HfHubHTTPError as e:
raise HfHubHTTPError(f"{filename} not found on the HuggingFace Hub") from e
@require_huggingface_hub
def push_to_hub(
self,
repo_id: str,
*,
key: str = "eval",
allow_custom_keys: bool = False,
commit_message: str = "Push transform using huggingface_hub.",
private: bool = False,
token: str | None = None,
branch: str | None = None,
create_pr: bool | None = None,
) -> str:
"""Push the transform to the Huggingface Hub.
Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
`delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
details.
Args:
repo_id (`str`):
ID of the repository to push to (example: `"username/my-model"`).
key (`str`, *optional*):
Key to identify the configuration type, one of ["train", "eval"]. Defaults to "eval".
allow_custom_keys (`bool`, *optional*):
Allow custom keys for the configuration. Defaults to False.
commit_message (`str`, *optional*):
Message to commit while pushing.
private (`bool`, *optional*, defaults to `False`):
Whether the repository created should be private.
token (`str`, *optional*):
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
cached when running `huggingface-cli login`.
branch (`str`, *optional*):
The git branch on which to push the transform. This defaults to `"main"`.
create_pr (`boolean`, *optional*):
Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`.
Returns:
str: The url of the commit of your transform in the given repository.
"""
if not allow_custom_keys and key not in self._CONFIG_KEYS:
raise ValueError(
f"Invalid key: `{key}`. Please use key from {self._CONFIG_KEYS} keys for upload. "
"If you still want to use a custom key, set `allow_custom_keys=True`.",
)
api = HfApi(token=token)
repo_id = api.create_repo(repo_id=repo_id, private=private, exist_ok=True).repo_id
# Push the files to the repo in a single commit
with SoftTemporaryDirectory() as tmp:
save_directory = Path(tmp) / repo_id
filename = self._CONFIG_FILE_NAME_TEMPLATE.format(key)
save_path = self._save_pretrained(save_directory, filename=filename)
return api.upload_file(
path_or_fileobj=save_path,
path_in_repo=filename,
repo_id=repo_id,
commit_message=commit_message,
revision=branch,
create_pr=create_pr,
)
@@ -0,0 +1,521 @@
"""Module for handling keypoint operations during augmentation.
This module provides utilities for working with keypoints in various formats during
the augmentation process. It includes functions for converting between coordinate systems,
filtering keypoints based on visibility, validating keypoint data, and applying
transformations to keypoints. The module supports different keypoint formats including
xy, yx, and those with additional angle or size information.
"""
from __future__ import annotations
import math
from collections.abc import Sequence
from typing import Any, Literal
import numpy as np
from albumentations.core.type_definitions import NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS
from .utils import DataProcessor, Params, ShapeType
__all__ = [
"KeypointParams",
"KeypointsProcessor",
"angle_to_2pi_range",
"check_keypoints",
"convert_keypoints_from_albumentations",
"convert_keypoints_to_albumentations",
"filter_keypoints",
]
keypoint_formats = {"xy", "yx", "xya", "xys", "xyas", "xysa", "xyz"}
def angle_to_2pi_range(angles: np.ndarray) -> np.ndarray:
"""Convert angles to the range [0, 2π).
This function takes an array of angles and ensures they are all within
the range of 0 to 2π (exclusive) by applying modulo 2π.
Args:
angles (np.ndarray): Array of angle values in radians.
Returns:
np.ndarray: Array of the same shape as input with angles normalized to [0, 2π).
"""
return np.mod(angles, 2 * np.pi)
class KeypointParams(Params):
"""Parameters of keypoints
Args:
format (str): format of keypoints. Should be 'xy', 'yx', 'xya', 'xys', 'xyas', 'xysa', 'xyz'.
x - X coordinate,
y - Y coordinate
z - Z coordinate (for 3D keypoints)
s - Keypoint scale
a - Keypoint orientation in radians or degrees (depending on KeypointParams.angle_in_degrees)
label_fields (list[str]): list of fields that are joined with keypoints, e.g labels.
Should be same type as keypoints.
remove_invisible (bool): to remove invisible points after transform or not
angle_in_degrees (bool): angle in degrees or radians in 'xya', 'xyas', 'xysa' keypoints
check_each_transform (bool): if `True`, then keypoints will be checked after each dual transform.
Default: `True`
Note:
The internal Albumentations format is [x, y, z, angle, scale]. For 2D formats (xy, yx, xya, xys, xyas, xysa),
z coordinate is set to 0. For formats without angle or scale, these values are set to 0.
"""
def __init__(
self,
format: str, # noqa: A002
label_fields: Sequence[str] | None = None,
remove_invisible: bool = True,
angle_in_degrees: bool = True,
check_each_transform: bool = True,
):
super().__init__(format, label_fields)
self.remove_invisible = remove_invisible
self.angle_in_degrees = angle_in_degrees
self.check_each_transform = check_each_transform
def to_dict_private(self) -> dict[str, Any]:
"""Get the private dictionary representation of keypoint parameters.
Returns:
dict[str, Any]: Dictionary containing the keypoint parameters.
"""
data = super().to_dict_private()
data.update(
{
"remove_invisible": self.remove_invisible,
"angle_in_degrees": self.angle_in_degrees,
"check_each_transform": self.check_each_transform,
},
)
return data
@classmethod
def is_serializable(cls) -> bool:
"""Check if the keypoint parameters are serializable.
Returns:
bool: Always returns True as KeypointParams is serializable.
"""
return True
@classmethod
def get_class_fullname(cls) -> str:
"""Get the full name of the class.
Returns:
str: The string "KeypointParams".
"""
return "KeypointParams"
def __repr__(self) -> str:
return (
f"KeypointParams(format={self.format}, label_fields={self.label_fields},"
f" remove_invisible={self.remove_invisible}, angle_in_degrees={self.angle_in_degrees},"
f" check_each_transform={self.check_each_transform})"
)
class KeypointsProcessor(DataProcessor):
"""Processor for keypoint data transformation.
This class handles the conversion, validation, and filtering of keypoints
during transformations. It ensures keypoints are correctly formatted and
processed according to the specified keypoint parameters.
Args:
params (KeypointParams): Parameters for keypoint processing.
additional_targets (dict[str, str] | None): Dictionary mapping additional target names to their types.
"""
def __init__(self, params: KeypointParams, additional_targets: dict[str, str] | None = None):
super().__init__(params, additional_targets)
@property
def default_data_name(self) -> str:
"""Get the default name for keypoint data.
Returns:
str: The string "keypoints".
"""
return "keypoints"
def ensure_data_valid(self, data: dict[str, Any]) -> None:
"""Ensure the provided data dictionary contains all required label fields.
Args:
data (dict[str, Any]): The data dictionary to validate.
Raises:
ValueError: If any label field specified in params is missing from the data.
"""
if self.params.label_fields and not all(i in data for i in self.params.label_fields):
msg = "Your 'label_fields' are not valid - them must have same names as params in 'keypoint_params' dict"
raise ValueError(msg)
def filter(
self,
data: np.ndarray,
shape: ShapeType,
) -> np.ndarray:
"""Filter keypoints based on visibility within given shape.
Args:
data (np.ndarray): Keypoints in [x, y, z, angle, scale] format
shape (ShapeType): Shape to check against as {'height': height, 'width': width, 'depth': depth}
Returns:
np.ndarray: Filtered keypoints
"""
self.params: KeypointParams
return filter_keypoints(data, shape, remove_invisible=self.params.remove_invisible)
def check(self, data: np.ndarray, shape: ShapeType) -> None:
"""Check if keypoints are valid within the given shape.
Args:
data (np.ndarray): Keypoints to validate.
shape (ShapeType): Shape to check against.
"""
check_keypoints(data, shape)
def convert_from_albumentations(
self,
data: np.ndarray,
shape: ShapeType,
) -> np.ndarray:
"""Convert keypoints from internal Albumentations format to the specified format.
Args:
data (np.ndarray): Keypoints in Albumentations format.
shape (ShapeType): Shape information for validation.
Returns:
np.ndarray: Converted keypoints in the target format.
"""
if not data.size:
return data
params = self.params
return convert_keypoints_from_albumentations(
data,
params.format,
shape,
check_validity=params.remove_invisible,
angle_in_degrees=params.angle_in_degrees,
)
def convert_to_albumentations(
self,
data: np.ndarray,
shape: ShapeType,
) -> np.ndarray:
"""Convert keypoints from the specified format to internal Albumentations format.
Args:
data (np.ndarray): Keypoints in source format.
shape (ShapeType): Shape information for validation.
Returns:
np.ndarray: Converted keypoints in Albumentations format.
"""
if not data.size:
return data
params = self.params
return convert_keypoints_to_albumentations(
data,
params.format,
shape,
check_validity=params.remove_invisible,
angle_in_degrees=params.angle_in_degrees,
)
def check_keypoints(keypoints: np.ndarray, shape: ShapeType) -> None:
"""Check if keypoint coordinates are within valid ranges for the given shape.
This function validates that:
1. All x-coordinates are within [0, width)
2. All y-coordinates are within [0, height)
3. If depth is provided in shape, z-coordinates are within [0, depth)
4. Angles are within the range [0, 2π)
Args:
keypoints (np.ndarray): Array of keypoints with shape (N, 5+), where N is the number of keypoints.
- First 2 columns are always x, y
- Column 3 (if present) is z
- Column 4 (if present) is angle
- Column 5+ (if present) are additional attributes
shape (ShapeType): The shape of the image/volume:
- For 2D: {'height': int, 'width': int}
- For 3D: {'height': int, 'width': int, 'depth': int}
Raises:
ValueError: If any keypoint coordinate is outside the valid range, or if angles are invalid.
The error message will detail which keypoints are invalid and why.
Note:
- The function assumes that keypoint coordinates are in absolute pixel values, not normalized
- Angles are in radians
- Z-coordinates are only checked if 'depth' is present in shape
"""
height, width = shape["height"], shape["width"]
has_depth = "depth" in shape
# Check x and y coordinates (always present)
x, y = keypoints[:, 0], keypoints[:, 1]
invalid_x = np.where((x < 0) | (x >= width))[0]
invalid_y = np.where((y < 0) | (y >= height))[0]
error_messages = []
# Handle x, y errors
for idx in sorted(set(invalid_x) | set(invalid_y)):
if idx in invalid_x:
error_messages.append(
f"Expected x for keypoint {keypoints[idx]} to be in range [0, {width}), got {x[idx]}",
)
if idx in invalid_y:
error_messages.append(
f"Expected y for keypoint {keypoints[idx]} to be in range [0, {height}), got {y[idx]}",
)
# Check z coordinates if depth is provided and keypoints have z
if has_depth and keypoints.shape[1] > 2:
z = keypoints[:, 2]
depth = shape["depth"]
invalid_z = np.where((z < 0) | (z >= depth))[0]
error_messages.extend(
f"Expected z for keypoint {keypoints[idx]} to be in range [0, {depth}), got {z[idx]}" for idx in invalid_z
)
# Check angles only if keypoints have angle column
if keypoints.shape[1] > 3:
angles = keypoints[:, 3]
invalid_angles = np.where((angles < 0) | (angles >= 2 * math.pi))[0]
error_messages.extend(
f"Expected angle for keypoint {keypoints[idx]} to be in range [0, 2π), got {angles[idx]}"
for idx in invalid_angles
)
if error_messages:
raise ValueError("\n".join(error_messages))
def filter_keypoints(
keypoints: np.ndarray,
shape: ShapeType,
remove_invisible: bool,
) -> np.ndarray:
"""Filter keypoints to remove those outside the boundaries.
Args:
keypoints (np.ndarray): A numpy array of shape (N, 5+) where N is the number of keypoints.
Each row represents a keypoint (x, y, z, angle, scale, ...).
shape (ShapeType): Shape to check against as {'height': height, 'width': width, 'depth': depth}.
remove_invisible (bool): If True, remove keypoints outside the boundaries.
Returns:
np.ndarray: Filtered keypoints.
"""
if not remove_invisible:
return keypoints
if not keypoints.size:
return keypoints
height, width, depth = shape["height"], shape["width"], shape.get("depth", None)
# Create boolean mask for visible keypoints
x, y, z = keypoints[:, 0], keypoints[:, 1], keypoints[:, 2]
visible = (x >= 0) & (x < width) & (y >= 0) & (y < height)
if depth is not None:
visible &= (z >= 0) & (z < depth)
# Apply the mask to filter keypoints
return keypoints[visible]
def convert_keypoints_to_albumentations(
keypoints: np.ndarray,
source_format: Literal["xy", "yx", "xya", "xys", "xyas", "xysa", "xyz"],
shape: ShapeType,
check_validity: bool = False,
angle_in_degrees: bool = True,
) -> np.ndarray:
"""Convert keypoints from various formats to the Albumentations format.
This function takes keypoints in different formats and converts them to the standard
Albumentations format: [x, y, z, angle, scale]. For 2D formats, z is set to 0.
For formats without angle or scale, these values are set to 0.
Args:
keypoints (np.ndarray): Array of keypoints with shape (N, 2+), where N is the number of keypoints.
The number of columns depends on the source_format.
source_format (Literal["xy", "yx", "xya", "xys", "xyas", "xysa", "xyz"]): The format of the input keypoints.
- "xy": [x, y]
- "yx": [y, x]
- "xya": [x, y, angle]
- "xys": [x, y, scale]
- "xyas": [x, y, angle, scale]
- "xysa": [x, y, scale, angle]
- "xyz": [x, y, z]
shape (ShapeType): The shape of the image {'height': height, 'width': width, 'depth': depth}.
check_validity (bool, optional): If True, check if the converted keypoints are within the image boundaries.
Defaults to False.
angle_in_degrees (bool, optional): If True, convert input angles from degrees to radians.
Defaults to True.
Returns:
np.ndarray: Array of keypoints in Albumentations format [x, y, z, angle, scale] with shape (N, 5+).
Any additional columns from the input keypoints are preserved and appended after the
first 5 columns.
Raises:
ValueError: If the source_format is not one of the supported formats.
Note:
- For 2D formats (xy, yx, xya, xys, xyas, xysa), z coordinate is set to 0
- Angles are converted to the range [0, 2π) radians
- If the input keypoints have additional columns beyond what's specified in the source_format,
these columns are preserved in the output
"""
if source_format not in keypoint_formats:
raise ValueError(f"Unknown source_format {source_format}. Supported formats are: {keypoint_formats}")
format_to_indices: dict[str, list[int | None]] = {
"xy": [0, 1, None, None, None],
"yx": [1, 0, None, None, None],
"xya": [0, 1, None, 2, None],
"xys": [0, 1, None, None, 2],
"xyas": [0, 1, None, 2, 3],
"xysa": [0, 1, None, 3, 2],
"xyz": [0, 1, 2, None, None],
}
indices: list[int | None] = format_to_indices[source_format]
processed_keypoints = np.zeros((keypoints.shape[0], NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS), dtype=np.float32)
for i, idx in enumerate(indices):
if idx is not None:
processed_keypoints[:, i] = keypoints[:, idx]
if angle_in_degrees and indices[3] is not None: # angle is now at index 3
processed_keypoints[:, 3] = np.radians(processed_keypoints[:, 3])
processed_keypoints[:, 3] = angle_to_2pi_range(processed_keypoints[:, 3]) # angle is now at index 3
if keypoints.shape[1] > len(source_format):
processed_keypoints = np.column_stack((processed_keypoints, keypoints[:, len(source_format) :]))
if check_validity:
check_keypoints(processed_keypoints, shape)
return processed_keypoints
def convert_keypoints_from_albumentations(
keypoints: np.ndarray,
target_format: Literal["xy", "yx", "xya", "xys", "xyas", "xysa", "xyz"],
shape: ShapeType,
check_validity: bool = False,
angle_in_degrees: bool = True,
) -> np.ndarray:
"""Convert keypoints from Albumentations format to various other formats.
This function takes keypoints in the standard Albumentations format [x, y, z, angle, scale]
and converts them to the specified target format.
Args:
keypoints (np.ndarray): Array of keypoints in Albumentations format with shape (N, 5+),
where N is the number of keypoints. Each row represents a keypoint
[x, y, z, angle, scale, ...].
target_format (Literal["xy", "yx", "xya", "xys", "xyas", "xysa", "xyz"]): The desired output format.
- "xy": [x, y]
- "yx": [y, x]
- "xya": [x, y, angle]
- "xys": [x, y, scale]
- "xyas": [x, y, angle, scale]
- "xysa": [x, y, scale, angle]
- "xyz": [x, y, z]
shape (ShapeType): The shape of the image {'height': height, 'width': width, 'depth': depth}.
check_validity (bool, optional): If True, check if the keypoints are within the image boundaries.
Defaults to False.
angle_in_degrees (bool, optional): If True, convert output angles to degrees.
If False, angles remain in radians.
Defaults to True.
Returns:
np.ndarray: Array of keypoints in the specified target format with shape (N, 2+).
Any additional columns from the input keypoints beyond the first 5
are preserved and appended after the converted columns.
Raises:
ValueError: If the target_format is not one of the supported formats.
Note:
- Input angles are assumed to be in the range [0, 2π) radians
- If the input keypoints have additional columns beyond the first 5,
these columns are preserved in the output
"""
if target_format not in keypoint_formats:
raise ValueError(f"Unknown target_format {target_format}. Supported formats are: {keypoint_formats}")
x, y, z, angle, scale = keypoints[:, 0], keypoints[:, 1], keypoints[:, 2], keypoints[:, 3], keypoints[:, 4]
angle = angle_to_2pi_range(angle)
if check_validity:
check_keypoints(np.column_stack((x, y, z, angle, scale)), shape)
if angle_in_degrees:
angle = np.degrees(angle)
format_to_columns = {
"xy": [x, y],
"yx": [y, x],
"xya": [x, y, angle],
"xys": [x, y, scale],
"xyas": [x, y, angle, scale],
"xysa": [x, y, scale, angle],
"xyz": [x, y, z],
}
result = np.column_stack(format_to_columns[target_format])
# Add any additional columns from the original keypoints
if keypoints.shape[1] > NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS:
return np.column_stack((result, keypoints[:, NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS:]))
return result
@@ -0,0 +1,339 @@
"""Module for managing and transforming label data during augmentation.
This module provides utilities for encoding, decoding, and tracking metadata for labels
during the augmentation process. It includes classes for managing label transformations,
preserving data types, and ensuring consistent handling of categorical, numerical, and
mixed label types. The module supports automatic encoding of string labels to numerical
values and restoration of original data types after processing.
"""
from __future__ import annotations
from collections import defaultdict
from collections.abc import Sequence
from dataclasses import dataclass
from numbers import Real
from typing import Any
import numpy as np
def custom_sort(item: Any) -> tuple[int, Real | str]:
"""Sort items by type then value for consistent label ordering.
This function is used to sort labels in a consistent order, prioritizing numerical
values before string values. All numerical values are given priority 0, while
string values are given priority 1, ensuring numerical values are sorted first.
Args:
item (Any): Item to be sorted, can be either a numeric value or any other type.
Returns:
tuple[int, Real | str]: A tuple with sort priority (0 for numbers, 1 for others)
and the value itself (or string representation for non-numeric values).
"""
return (0, item) if isinstance(item, Real) else (1, str(item))
def _categorize_labels(labels: set[Any]) -> tuple[list[Real], list[str]]:
numeric_labels: list[Real] = []
string_labels: list[str] = []
for label in labels:
(numeric_labels if isinstance(label, Real) else string_labels).append(label)
return numeric_labels, string_labels
class LabelEncoder:
"""Encodes labels into integer indices.
This class handles the conversion between original label values and their
numerical representations. It supports both numerical and categorical labels.
Args:
classes_ (dict[str | Real, int]): Mapping from original labels to encoded indices.
inverse_classes_ (dict[int, str | Real]): Mapping from encoded indices to original labels.
num_classes (int): Number of unique classes.
is_numerical (bool): Whether the original labels are numerical.
"""
def __init__(self) -> None:
self.classes_: dict[str | Real, int] = {}
self.inverse_classes_: dict[int, str | Real] = {}
self.num_classes: int = 0
self.is_numerical: bool = True
def fit(self, y: Sequence[Any] | np.ndarray) -> LabelEncoder:
"""Fit the encoder to the input labels.
Args:
y (Sequence[Any] | np.ndarray): Input labels to fit the encoder.
Returns:
LabelEncoder: The fitted encoder instance.
"""
if isinstance(y, np.ndarray):
y = y.flatten().tolist()
# If input is empty, default to non-numerical to allow potential updates later
if not y:
self.is_numerical = False
return self
self.is_numerical = all(isinstance(label, Real) for label in y)
if self.is_numerical:
return self
unique_labels = sorted(set(y), key=custom_sort)
for label in unique_labels:
if label not in self.classes_:
self.classes_[label] = self.num_classes
self.inverse_classes_[self.num_classes] = label
self.num_classes += 1
return self
def transform(self, y: Sequence[Any] | np.ndarray) -> np.ndarray:
"""Transform labels to encoded integer indices.
Args:
y (Sequence[Any] | np.ndarray): Input labels to transform.
Returns:
np.ndarray: Encoded integer indices.
"""
if isinstance(y, np.ndarray):
y = y.flatten().tolist()
if self.is_numerical:
return np.array(y)
return np.array([self.classes_[label] for label in y])
def fit_transform(self, y: Sequence[Any] | np.ndarray) -> np.ndarray:
"""Fit the encoder and transform the input labels in one step.
Args:
y (Sequence[Any] | np.ndarray): Input labels to fit and transform.
Returns:
np.ndarray: Encoded integer indices.
"""
self.fit(y)
return self.transform(y)
def inverse_transform(self, y: Sequence[Any] | np.ndarray) -> np.ndarray:
"""Transform encoded indices back to original labels.
Args:
y (Sequence[Any] | np.ndarray): Encoded integer indices.
Returns:
np.ndarray: Original labels.
"""
if isinstance(y, np.ndarray):
y = y.flatten().tolist()
if self.is_numerical:
return np.array(y)
return np.array([self.inverse_classes_[label] for label in y])
def update(self, y: Sequence[Any] | np.ndarray) -> LabelEncoder:
"""Update the encoder with new labels encountered after initial fitting.
This method identifies labels in the input sequence that are not already
known to the encoder and adds them to the internal mapping. It does not
change the encoding of previously seen labels.
Args:
y (Sequence[Any] | np.ndarray): A sequence or array of potentially new labels.
Returns:
LabelEncoder: The updated encoder instance.
"""
if self.is_numerical:
# Do not update if the original data was purely numerical
return self
# Standardize input type to list for easier processing
if isinstance(y, np.ndarray):
input_labels = y.flatten().tolist()
elif isinstance(y, Sequence) and not isinstance(y, str):
input_labels = list(y)
elif y is None:
# Handle cases where a label field might be None or empty
return self
else:
# Handle single item case or string (treat string as single label)
input_labels = [y]
# Find labels not already in the encoder efficiently using sets
current_labels_set = set(self.classes_.keys())
new_unique_labels = set(input_labels) - current_labels_set
if not new_unique_labels:
# No new labels to add
return self
# Separate and sort new labels for deterministic encoding order
numeric_labels, string_labels = _categorize_labels(new_unique_labels)
sorted_new_labels = sorted(numeric_labels) + sorted(string_labels, key=str)
for label in sorted_new_labels:
new_id = self.num_classes
self.classes_[label] = new_id
self.inverse_classes_[new_id] = label
self.num_classes += 1
return self
@dataclass
class LabelMetadata:
"""Stores metadata about a label field."""
input_type: type
is_numerical: bool
dtype: np.dtype | None = None
encoder: LabelEncoder | None = None
class LabelManager:
"""Manages label encoding and decoding across multiple data fields.
This class handles the encoding, decoding, and type management for label fields.
It maintains metadata about each field to ensure proper conversion between
original and encoded representations.
Args:
metadata (dict[str, dict[str, LabelMetadata]]): Dictionary mapping data types
and label fields to their metadata.
"""
def __init__(self) -> None:
self.metadata: dict[str, dict[str, LabelMetadata]] = defaultdict(dict)
def process_field(self, data_name: str, label_field: str, field_data: Any) -> np.ndarray:
"""Process a label field, store metadata, and encode.
If the field has been processed before (metadata exists), this will update
the existing LabelEncoder with any new labels found in `field_data` before encoding.
Otherwise, it analyzes the input, creates metadata, and fits the encoder.
Args:
data_name (str): The name of the main data type (e.g., 'bboxes', 'keypoints').
label_field (str): The specific label field being processed (e.g., 'class_labels').
field_data (Any): The actual label data for this field.
Returns:
np.ndarray: The encoded label data as a numpy array.
"""
if data_name in self.metadata and label_field in self.metadata[data_name]:
# Metadata exists, potentially update encoder
metadata = self.metadata[data_name][label_field]
if not metadata.is_numerical and metadata.encoder:
metadata.encoder.update(field_data)
else:
# First time seeing this field, analyze and create metadata
metadata = self._analyze_input(field_data)
self.metadata[data_name][label_field] = metadata
# Encode data using the (potentially updated) metadata/encoder
return self._encode_data(field_data, metadata)
def restore_field(self, data_name: str, label_field: str, encoded_data: np.ndarray) -> Any:
"""Restore a label field to its original format."""
metadata = self.metadata[data_name][label_field]
decoded_data = self._decode_data(encoded_data, metadata)
return self._restore_type(decoded_data, metadata)
def _analyze_input(self, field_data: Any) -> LabelMetadata:
"""Analyze input data and create metadata."""
input_type = type(field_data)
dtype = field_data.dtype if isinstance(field_data, np.ndarray) else None
# Determine if input is numerical. Handle empty case explicitly.
if isinstance(field_data, np.ndarray) and field_data.size > 0:
is_numerical = np.issubdtype(field_data.dtype, np.number)
elif isinstance(field_data, Sequence) and not isinstance(field_data, str) and field_data:
is_numerical = all(isinstance(label, (int, float)) for label in field_data)
elif isinstance(field_data, (int, float)):
is_numerical = True # Handle single numeric item
else:
# Default to non-numerical for empty sequences, single strings, or other types
is_numerical = False
metadata = LabelMetadata(
input_type=input_type,
is_numerical=is_numerical,
dtype=dtype,
)
if not is_numerical:
metadata.encoder = LabelEncoder()
return metadata
def _encode_data(self, field_data: Any, metadata: LabelMetadata) -> np.ndarray:
"""Encode field data for processing."""
if metadata.is_numerical:
# For numerical values, convert to float32 for processing
if isinstance(field_data, np.ndarray):
return field_data.reshape(-1, 1).astype(np.float32)
return np.array(field_data, dtype=np.float32).reshape(-1, 1)
# For non-numerical values, use LabelEncoder
if metadata.encoder is None:
raise ValueError("Encoder not initialized for non-numerical data")
return metadata.encoder.fit_transform(field_data).reshape(-1, 1)
def _decode_data(self, encoded_data: np.ndarray, metadata: LabelMetadata) -> np.ndarray:
"""Decode processed data."""
if metadata.is_numerical:
if metadata.dtype is not None:
return encoded_data.astype(metadata.dtype)
return encoded_data.flatten() # Flatten for list conversion
if metadata.encoder is None:
raise ValueError("Encoder not found for non-numerical data")
decoded = metadata.encoder.inverse_transform(encoded_data.astype(int))
return decoded.reshape(-1) # Ensure 1D array
def _restore_type(self, decoded_data: np.ndarray, metadata: LabelMetadata) -> Any:
"""Restore data to its original type."""
# If original input was a list or sequence, convert back to list
if isinstance(metadata.input_type, type) and issubclass(metadata.input_type, (list, Sequence)):
return decoded_data.tolist()
# If original input was a numpy array, restore original dtype
if isinstance(metadata.input_type, type) and issubclass(metadata.input_type, np.ndarray):
if metadata.dtype is not None:
return decoded_data.astype(metadata.dtype)
return decoded_data
# For any other type, convert to list by default
return decoded_data.tolist()
def handle_empty_data(self) -> list[Any]:
"""Handle empty data case."""
return []
def get_encoder(self, data_name: str, label_field: str) -> LabelEncoder | None:
"""Retrieves the fitted LabelEncoder for a specific data and label field."""
if data_name in self.metadata and label_field in self.metadata[data_name]:
encoder = self.metadata[data_name][label_field].encoder
# Ensure encoder is LabelEncoder or None, handle potential type issues
if isinstance(encoder, LabelEncoder):
return encoder
return None
@@ -0,0 +1,239 @@
"""Module containing Pydantic validation utilities for Albumentations.
This module provides a collection of validators and utility functions used for validating
parameters in the Pydantic models throughout the Albumentations library. It includes
functions for ensuring numeric ranges are valid, handling type conversions, and creating
standardized validation patterns that are reused across the codebase.
"""
from __future__ import annotations
from collections.abc import Callable
from typing import Annotated, TypeVar, Union, overload
from pydantic.functional_validators import AfterValidator
from albumentations.core.type_definitions import Number
from albumentations.core.utils import to_tuple
def nondecreasing(value: tuple[Number, Number]) -> tuple[Number, Number]:
"""Ensure a tuple of two numbers is in non-decreasing order.
Args:
value (tuple[Number, Number]): Tuple of two numeric values to validate.
Returns:
tuple[Number, Number]: The original tuple if valid.
Raises:
ValueError: If the first value is greater than the second value.
"""
if not value[0] <= value[1]:
raise ValueError(f"First value should be less than the second value, got {value} instead")
return value
def process_non_negative_range(value: tuple[float, float] | float | None) -> tuple[float, float]:
"""Process and validate a non-negative range.
Args:
value (tuple[float, float] | float | None): Value to process. Can be:
- A tuple of two floats
- A single float (converted to symmetric range)
- None (defaults to 0)
Returns:
tuple[float, float]: Validated non-negative range.
Raises:
ValueError: If any values in the range are negative.
"""
result = to_tuple(value if value is not None else 0, 0)
if not all(x >= 0 for x in result):
msg = "All values in the non negative range should be non negative"
raise ValueError(msg)
return result
def float2int(value: tuple[float, float]) -> tuple[int, int]:
"""Convert a tuple of floats to a tuple of integers.
Args:
value (tuple[float, float]): Tuple of two float values.
Returns:
tuple[int, int]: Tuple of two integer values.
"""
return int(value[0]), int(value[1])
NonNegativeFloatRangeType = Annotated[
Union[tuple[float, float], float],
AfterValidator(process_non_negative_range),
AfterValidator(nondecreasing),
]
NonNegativeIntRangeType = Annotated[
Union[tuple[int, int], int],
AfterValidator(process_non_negative_range),
AfterValidator(nondecreasing),
AfterValidator(float2int),
]
@overload
def create_symmetric_range(value: tuple[int, int] | int) -> tuple[int, int]: ...
@overload
def create_symmetric_range(value: tuple[float, float] | float) -> tuple[float, float]: ...
def create_symmetric_range(value: tuple[float, float] | float) -> tuple[float, float]:
"""Create a symmetric range around zero or use provided range.
Args:
value (tuple[float, float] | float): Input value, either:
- A tuple of two floats (used directly)
- A single float (converted to (-value, value))
Returns:
tuple[float, float]: Symmetric range.
"""
return to_tuple(value)
SymmetricRangeType = Annotated[Union[tuple[float, float], float], AfterValidator(create_symmetric_range)]
def convert_to_1plus_range(value: tuple[float, float] | float) -> tuple[float, float]:
"""Convert value to a range with lower bound of 1.
Args:
value (tuple[float, float] | float): Input value.
Returns:
tuple[float, float]: Range with minimum value of at least 1.
"""
return to_tuple(value, low=1)
def convert_to_0plus_range(value: tuple[float, float] | float) -> tuple[float, float]:
"""Convert value to a range with lower bound of 0.
Args:
value (tuple[float, float] | float): Input value.
Returns:
tuple[float, float]: Range with minimum value of at least 0.
"""
return to_tuple(value, low=0)
def repeat_if_scalar(value: tuple[float, float] | float) -> tuple[float, float]:
"""Convert a scalar value to a tuple by repeating it, or return the tuple as is.
Args:
value (tuple[float, float] | float): Input value, either a scalar or tuple.
Returns:
tuple[float, float]: If input is scalar, returns (value, value), otherwise returns input unchanged.
"""
return (value, value) if isinstance(value, (int, float)) else value
T = TypeVar("T", int, float)
def check_range_bounds(
min_val: Number,
max_val: Number | None = None,
min_inclusive: bool = True,
max_inclusive: bool = True,
) -> Callable[[tuple[T, ...] | None], tuple[T, ...] | None]:
"""Validates that all values in a tuple are within specified bounds.
Args:
min_val (int | float):
Minimum allowed value.
max_val (int | float | None):
Maximum allowed value. If None, only lower bound is checked.
min_inclusive (bool):
If True, min_val is inclusive (>=). If False, exclusive (>).
max_inclusive (bool):
If True, max_val is inclusive (<=). If False, exclusive (<).
Returns:
Callable[[tuple[T, ...] | None], tuple[T, ...] | None]: Validator function that
checks if all values in tuple are within bounds. Returns None if input is None.
Raises:
ValueError: If any value in tuple is outside the allowed range
Examples:
>>> validator = check_range_bounds(0, 1) # For [0, 1] range
>>> validator((0.1, 0.5)) # Valid 2D
(0.1, 0.5)
>>> validator((0.1, 0.5, 0.7)) # Valid 3D
(0.1, 0.5, 0.7)
>>> validator((1.1, 0.5)) # Raises ValueError - outside range
>>> validator = check_range_bounds(0, 1, max_inclusive=False) # For [0, 1) range
>>> validator((0, 1)) # Raises ValueError - 1 not included
"""
def validator(value: tuple[T, ...] | None) -> tuple[T, ...] | None:
if value is None:
return None
min_op = (lambda x, y: x >= y) if min_inclusive else (lambda x, y: x > y)
max_op = (lambda x, y: x <= y) if max_inclusive else (lambda x, y: x < y)
if max_val is None:
if not all(min_op(x, min_val) for x in value):
op_symbol = ">=" if min_inclusive else ">"
raise ValueError(f"All values in {value} must be {op_symbol} {min_val}")
else:
min_symbol = ">=" if min_inclusive else ">"
max_symbol = "<=" if max_inclusive else "<"
if not all(min_op(x, min_val) and max_op(x, max_val) for x in value):
raise ValueError(f"All values in {value} must be {min_symbol} {min_val} and {max_symbol} {max_val}")
return value
return validator
ZeroOneRangeType = Annotated[
Union[tuple[float, float], float],
AfterValidator(convert_to_0plus_range),
AfterValidator(check_range_bounds(0, 1)),
AfterValidator(nondecreasing),
]
OnePlusFloatRangeType = Annotated[
Union[tuple[float, float], float],
AfterValidator(convert_to_1plus_range),
AfterValidator(check_range_bounds(1, None)),
]
OnePlusIntRangeType = Annotated[
Union[tuple[float, float], float],
AfterValidator(convert_to_1plus_range),
AfterValidator(check_range_bounds(1, None)),
AfterValidator(float2int),
]
OnePlusIntNonDecreasingRangeType = Annotated[
tuple[int, int],
AfterValidator(check_range_bounds(1, None)),
AfterValidator(nondecreasing),
AfterValidator(float2int),
]
@@ -0,0 +1,325 @@
"""Module for serialization and deserialization of Albumentations transforms.
This module provides functionality to serialize transforms to JSON or YAML format and
deserialize them back. It implements the Serializable interface that allows transforms
to be converted to and from dictionaries, which can then be saved to disk or transmitted
over a network. This is particularly useful for saving augmentation pipelines and
restoring them later with the exact same configuration.
"""
from __future__ import annotations
import importlib.util
import json
import warnings
from abc import ABC, ABCMeta, abstractmethod
from collections.abc import Mapping, Sequence
from enum import Enum
from pathlib import Path
from typing import Any, Literal, TextIO
from warnings import warn
try:
import yaml
yaml_available = True
except ImportError:
yaml_available = False
from albumentations import __version__
__all__ = ["from_dict", "load", "save", "to_dict"]
SERIALIZABLE_REGISTRY: dict[str, SerializableMeta] = {}
NON_SERIALIZABLE_REGISTRY: dict[str, SerializableMeta] = {}
def shorten_class_name(class_fullname: str) -> str:
# Split the class_fullname once at the last '.' to separate the class name
split_index = class_fullname.rfind(".")
# If there's no '.' or the top module is not 'albumentations', return the full name
if split_index == -1 or not class_fullname.startswith("albumentations."):
return class_fullname
# Extract the class name after the last '.'
return class_fullname[split_index + 1 :]
class SerializableMeta(ABCMeta):
"""A metaclass that is used to register classes in `SERIALIZABLE_REGISTRY` or `NON_SERIALIZABLE_REGISTRY`
so they can be found later while deserializing transformation pipeline using classes full names.
"""
def __new__(cls, name: str, bases: tuple[type, ...], *args: Any, **kwargs: Any) -> SerializableMeta:
cls_obj = super().__new__(cls, name, bases, *args, **kwargs)
if name != "Serializable" and ABC not in bases:
if cls_obj.is_serializable():
SERIALIZABLE_REGISTRY[cls_obj.get_class_fullname()] = cls_obj
else:
NON_SERIALIZABLE_REGISTRY[cls_obj.get_class_fullname()] = cls_obj
return cls_obj
@classmethod
def is_serializable(cls) -> bool:
return False
@classmethod
def get_class_fullname(cls) -> str:
return get_shortest_class_fullname(cls)
@classmethod
def _to_dict(cls) -> dict[str, Any]:
return {}
class Serializable(metaclass=SerializableMeta):
@classmethod
@abstractmethod
def is_serializable(cls) -> bool:
raise NotImplementedError
@classmethod
@abstractmethod
def get_class_fullname(cls) -> str:
raise NotImplementedError
@abstractmethod
def to_dict_private(self) -> dict[str, Any]:
raise NotImplementedError
def to_dict(self, on_not_implemented_error: str = "raise") -> dict[str, Any]:
"""Take a transform pipeline and convert it to a serializable representation that uses only standard
python data types: dictionaries, lists, strings, integers, and floats.
Args:
self (Serializable): A transform that should be serialized. If the transform doesn't implement the `to_dict`
method and `on_not_implemented_error` equals to 'raise' then `NotImplementedError` is raised.
If `on_not_implemented_error` equals to 'warn' then `NotImplementedError` will be ignored
but no transform parameters will be serialized.
on_not_implemented_error (str): `raise` or `warn`.
"""
if on_not_implemented_error not in {"raise", "warn"}:
msg = f"Unknown on_not_implemented_error value: {on_not_implemented_error}. Supported values are: 'raise' "
"and 'warn'"
raise ValueError(msg)
try:
transform_dict = self.to_dict_private()
except NotImplementedError:
if on_not_implemented_error == "raise":
raise
transform_dict = {}
warnings.warn(
f"Got NotImplementedError while trying to serialize {self}. Object arguments are not preserved. "
f"The transform class '{self.__class__.__name__}' needs to implement 'to_dict_private' or inherit from "
f"BasicTransform to be properly serialized.",
stacklevel=2,
)
return {"__version__": __version__, "transform": transform_dict}
def to_dict(transform: Serializable, on_not_implemented_error: str = "raise") -> dict[str, Any]:
"""Take a transform pipeline and convert it to a serializable representation that uses only standard
python data types: dictionaries, lists, strings, integers, and floats.
Args:
transform (Serializable): A transform that should be serialized. If the transform doesn't implement
the `to_dict` method and `on_not_implemented_error` equals to 'raise' then `NotImplementedError` is raised.
If `on_not_implemented_error` equals to 'warn' then `NotImplementedError` will be ignored
but no transform parameters will be serialized.
on_not_implemented_error (str): `raise` or `warn`.
"""
return transform.to_dict(on_not_implemented_error)
def instantiate_nonserializable(
transform: dict[str, Any],
nonserializable: dict[str, Any] | None = None,
) -> Serializable | None:
if transform.get("__class_fullname__") in NON_SERIALIZABLE_REGISTRY:
name = transform["__name__"]
if nonserializable is None:
msg = f"To deserialize a non-serializable transform with name {name} you need to pass a dict with"
"this transform as the `lambda_transforms` argument"
raise ValueError(msg)
result_transform = nonserializable.get(name)
if transform is None:
raise ValueError(f"Non-serializable transform with {name} was not found in `nonserializable`")
return result_transform
return None
def from_dict(
transform_dict: dict[str, Any],
nonserializable: dict[str, Any] | None = None,
) -> Serializable | None:
"""Args:
transform_dict: A dictionary with serialized transform pipeline.
nonserializable (dict): A dictionary that contains non-serializable transforms.
This dictionary is required when you are restoring a pipeline that contains non-serializable transforms.
Keys in that dictionary should be named same as `name` arguments in respective transforms from
a serialized pipeline.
"""
register_additional_transforms()
transform = transform_dict["transform"]
lmbd = instantiate_nonserializable(transform, nonserializable)
if lmbd:
return lmbd
name = transform["__class_fullname__"]
args = {k: v for k, v in transform.items() if k != "__class_fullname__"}
# Ensure 'p' is included, default to 0.5 if missing for backward compatibility
if "p" not in args and name not in ("Compose", "Sequential"):
warn(f"Transform {name} has no 'p' parameter in serialized data, defaulting to 0.5", stacklevel=2)
args["p"] = 0.5
cls = SERIALIZABLE_REGISTRY[shorten_class_name(name)]
if "transforms" in args:
args["transforms"] = [from_dict({"transform": t}, nonserializable=nonserializable) for t in args["transforms"]]
return cls(**args)
def check_data_format(data_format: Literal["json", "yaml"]) -> None:
if data_format not in {"json", "yaml"}:
raise ValueError(f"Unknown data_format {data_format}. Supported formats are: 'json' and 'yaml'")
def serialize_enum(obj: Any) -> Any:
"""Recursively search for Enum objects and convert them to their value.
Also handle any Mapping or Sequence types.
"""
if isinstance(obj, Mapping):
return {k: serialize_enum(v) for k, v in obj.items()}
if isinstance(obj, Sequence) and not isinstance(obj, str): # exclude strings since they're also sequences
return [serialize_enum(v) for v in obj]
return obj.value if isinstance(obj, Enum) else obj
def save(
transform: Serializable,
filepath_or_buffer: str | Path | TextIO,
data_format: Literal["json", "yaml"] = "json",
on_not_implemented_error: Literal["raise", "warn"] = "raise",
) -> None:
"""Serialize a transform pipeline and save it to either a file specified by a path or a file-like object
in either JSON or YAML format.
Args:
transform (Serializable): The transform pipeline to serialize.
filepath_or_buffer (Union[str, Path, TextIO]): The file path or file-like object to write the serialized
data to.
If a string is provided, it is interpreted as a path to a file. If a file-like object is provided,
the serialized data will be written to it directly.
data_format (str): The format to serialize the data in. Valid options are 'json' and 'yaml'.
Defaults to 'json'.
on_not_implemented_error (str): Determines the behavior if a transform does not implement the `to_dict` method.
If set to 'raise', a `NotImplementedError` is raised. If set to 'warn', the exception is ignored, and
no transform arguments are saved. Defaults to 'raise'.
Raises:
ValueError: If `data_format` is 'yaml' but PyYAML is not installed.
"""
check_data_format(data_format)
transform_dict = transform.to_dict(on_not_implemented_error=on_not_implemented_error)
transform_dict = serialize_enum(transform_dict)
# Determine whether to write to a file or a file-like object
if isinstance(filepath_or_buffer, (str, Path)): # It's a filepath
with Path(filepath_or_buffer).open("w") as f:
if data_format == "yaml":
if not yaml_available:
msg = "You need to install PyYAML to save a pipeline in YAML format"
raise ValueError(msg)
yaml.safe_dump(transform_dict, f, default_flow_style=False)
elif data_format == "json":
json.dump(transform_dict, f)
elif data_format == "yaml":
if not yaml_available:
msg = "You need to install PyYAML to save a pipeline in YAML format"
raise ValueError(msg)
yaml.safe_dump(transform_dict, filepath_or_buffer, default_flow_style=False)
elif data_format == "json":
json.dump(transform_dict, filepath_or_buffer, indent=2)
def load(
filepath_or_buffer: str | Path | TextIO,
data_format: Literal["json", "yaml"] = "json",
nonserializable: dict[str, Any] | None = None,
) -> object:
"""Load a serialized pipeline from a file or file-like object and construct a transform pipeline.
Args:
filepath_or_buffer (Union[str, Path, TextIO]): The file path or file-like object to read the serialized
data from.
If a string is provided, it is interpreted as a path to a file. If a file-like object is provided,
the serialized data will be read from it directly.
data_format (Literal["json", "yaml"]): The format of the serialized data.
Defaults to 'json'.
nonserializable (Optional[dict[str, Any]]): A dictionary that contains non-serializable transforms.
This dictionary is required when restoring a pipeline that contains non-serializable transforms.
Keys in the dictionary should be named the same as the `name` arguments in respective transforms
from the serialized pipeline. Defaults to None.
Returns:
object: The deserialized transform pipeline.
Raises:
ValueError: If `data_format` is 'yaml' but PyYAML is not installed.
"""
check_data_format(data_format)
if isinstance(filepath_or_buffer, (str, Path)): # Assume it's a filepath
with Path(filepath_or_buffer).open() as f:
if data_format == "json":
transform_dict = json.load(f)
else:
if not yaml_available:
msg = "You need to install PyYAML to load a pipeline in yaml format"
raise ValueError(msg)
transform_dict = yaml.safe_load(f)
elif data_format == "json":
transform_dict = json.load(filepath_or_buffer)
else:
if not yaml_available:
msg = "You need to install PyYAML to load a pipeline in yaml format"
raise ValueError(msg)
transform_dict = yaml.safe_load(filepath_or_buffer)
return from_dict(transform_dict, nonserializable=nonserializable)
def register_additional_transforms() -> None:
"""Register transforms that are not imported directly into the `albumentations` module by checking
the availability of optional dependencies.
"""
if importlib.util.find_spec("torch") is not None:
try:
# Import `albumentations.pytorch` only if `torch` is installed.
import albumentations.pytorch
# Use a dummy operation to acknowledge the use of the imported module and avoid linting errors.
_ = albumentations.pytorch.ToTensorV2
except ImportError:
pass
def get_shortest_class_fullname(cls: type[Any]) -> str:
"""The function `get_shortest_class_fullname` takes a class object as input and returns its shortened
full name.
:param cls: The parameter `cls` is of type `Type[BasicCompose]`, which means it expects a class that
is a subclass of `BasicCompose`
:type cls: Type[BasicCompose]
:return: a string, which is the shortened version of the full class name.
"""
class_fullname = f"{cls.__module__}.{cls.__name__}"
return shorten_class_name(class_fullname)
@@ -0,0 +1,976 @@
"""Module containing base interfaces for all transform implementations.
This module defines the fundamental transform interfaces that form the base hierarchy for
all transformation classes in Albumentations. It provides abstract classes and mixins that
define common behavior for image, keypoint, bounding box, and volumetric transformations.
The interfaces handle parameter validation, random state management, target type checking,
and serialization capabilities that are inherited by concrete transform implementations.
"""
from __future__ import annotations
import random
from copy import deepcopy
from typing import Any, Callable
from warnings import warn
import cv2
import numpy as np
from albucore import batch_transform
from pydantic import BaseModel, ConfigDict, Field
from albumentations.core.bbox_utils import BboxProcessor
from albumentations.core.keypoints_utils import KeypointsProcessor
from albumentations.core.validation import ValidatedTransformMeta
from .serialization import Serializable, SerializableMeta, get_shortest_class_fullname
from .type_definitions import ALL_TARGETS, Targets
from .utils import ensure_contiguous_output, format_args
__all__ = ["BasicTransform", "DualTransform", "ImageOnlyTransform", "NoOp", "Transform3D"]
class Interpolation:
def __init__(self, downscale: int = cv2.INTER_NEAREST, upscale: int = cv2.INTER_NEAREST):
self.downscale = downscale
self.upscale = upscale
class BaseTransformInitSchema(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
p: float = Field(ge=0, le=1)
strict: bool
class CombinedMeta(SerializableMeta, ValidatedTransformMeta):
pass
class BasicTransform(Serializable, metaclass=CombinedMeta):
"""Base class for all transforms in Albumentations.
This class provides core functionality for transform application, serialization,
and parameter handling. It defines the interface that all transforms must follow
and implements common methods used across different transform types.
Class Attributes:
_targets (tuple[Targets, ...] | Targets): Target types this transform can work with.
_available_keys (set[str]): String representations of valid target keys.
_key2func (dict[str, Callable[..., Any]]): Mapping between target keys and their processing functions.
Args:
interpolation (int): Interpolation method for image transforms.
fill (int | float | list[int] | list[float]): Fill value for image padding.
fill_mask (int | float | list[int] | list[float]): Fill value for mask padding.
deterministic (bool, optional): Whether the transform is deterministic.
save_key (str, optional): Key for saving transform parameters.
replay_mode (bool, optional): Whether the transform is in replay mode.
applied_in_replay (bool, optional): Whether the transform was applied in replay.
p (float): Probability of applying the transform.
"""
_targets: tuple[Targets, ...] | Targets # targets that this transform can work on
_available_keys: set[str] # targets that this transform, as string, lower-cased
_key2func: dict[
str,
Callable[..., Any],
] # mapping for targets (plus additional targets) and methods for which they depend
call_backup = None
interpolation: int
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float | None
# replay mode params
deterministic: bool = False
save_key = "replay"
replay_mode = False
applied_in_replay = False
class InitSchema(BaseTransformInitSchema):
pass
def __init__(self, p: float = 0.5):
self.p = p
self._additional_targets: dict[str, str] = {}
self.params: dict[Any, Any] = {}
self._key2func = {}
self._set_keys()
self.processors: dict[str, BboxProcessor | KeypointsProcessor] = {}
self.seed: int | None = None
self.set_random_seed(self.seed)
self._strict = False # Use private attribute
self.invalid_args: list[str] = [] # Store invalid args found during init
@property
def strict(self) -> bool:
"""Get the current strict mode setting.
Returns:
bool: True if strict mode is enabled, False otherwise.
"""
return self._strict
@strict.setter
def strict(self, value: bool) -> None:
"""Set strict mode and validate for invalid arguments if enabled."""
if value == self._strict:
return # No change needed
# Only validate if strict is being set to True and we have stored init args
if value and hasattr(self, "_init_args"):
# Get the list of valid arguments for this transform
valid_args = {"p", "strict"} # Base valid args
if hasattr(self, "InitSchema"):
valid_args.update(self.InitSchema.model_fields.keys())
# Check for invalid arguments
invalid_args = [name_arg for name_arg in self._init_args if name_arg not in valid_args]
if invalid_args:
message = (
f"Argument(s) '{', '.join(invalid_args)}' are not valid for transform {self.__class__.__name__}"
)
if value: # In strict mode
raise ValueError(message)
warn(message, stacklevel=2)
self._strict = value
def set_random_state(
self,
random_generator: np.random.Generator,
py_random: random.Random,
) -> None:
"""Set random state directly from generators.
Args:
random_generator (np.random.Generator): numpy random generator to use
py_random (random.Random): python random generator to use
"""
self.random_generator = random_generator
self.py_random = py_random
def set_random_seed(self, seed: int | None) -> None:
"""Set random state from seed.
Args:
seed (int | None): Random seed to use
"""
self.seed = seed
self.random_generator = np.random.default_rng(seed)
self.py_random = random.Random(seed)
def get_dict_with_id(self) -> dict[str, Any]:
"""Return a dictionary representation of the transform with its ID.
Returns:
dict[str, Any]: Dictionary containing transform parameters and ID.
"""
d = self.to_dict_private()
d.update({"id": id(self)})
return d
def get_transform_init_args_names(self) -> tuple[str, ...]:
"""Returns names of arguments that are used in __init__ method of the transform.
This method introspects the entire Method Resolution Order (MRO) to gather the names
of parameters accepted by the __init__ methods of all parent classes,
to collect all possible parameters, excluding 'self' and 'strict'
which are handled separately.
"""
import inspect
all_param_names = set()
for cls in self.__class__.__mro__:
# Skip the class if it's the base object or doesn't define __init__
if cls is object or "__init__" not in cls.__dict__:
continue
try:
# Access the class's __init__ method through __dict__ to avoid mypy errors
init_method = cls.__dict__["__init__"]
signature = inspect.signature(init_method)
for name, param in signature.parameters.items():
if param.kind in {inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY}:
all_param_names.add(name)
except (ValueError, TypeError):
continue
# Exclude 'self' and 'strict'
return tuple(sorted(all_param_names - {"self", "strict"}))
def set_processors(self, processors: dict[str, BboxProcessor | KeypointsProcessor]) -> None:
"""Set the processors dictionary used for processing bbox and keypoint transformations.
Args:
processors (dict[str, BboxProcessor | KeypointsProcessor]): Dictionary mapping processor
names to processor instances.
"""
self.processors = processors
def get_processor(self, key: str) -> BboxProcessor | KeypointsProcessor | None:
"""Get the processor for a specific key.
Args:
key (str): The processor key to retrieve.
Returns:
BboxProcessor | KeypointsProcessor | None: The processor instance if found, None otherwise.
"""
return self.processors.get(key)
def __call__(self, *args: Any, force_apply: bool = False, **kwargs: Any) -> Any:
"""Apply the transform to the input data.
Args:
*args (Any): Positional arguments are not supported and will raise an error.
force_apply (bool, optional): If True, the transform will be applied regardless of probability.
**kwargs (Any): Input data to transform as named arguments.
Returns:
dict[str, Any]: Transformed data.
Raises:
KeyError: If positional arguments are provided.
"""
if args:
msg = "You have to pass data to augmentations as named arguments, for example: aug(image=image)"
raise KeyError(msg)
if self.replay_mode:
if self.applied_in_replay:
return self.apply_with_params(self.params, **kwargs)
return kwargs
# Reset params at the start of each call
self.params = {}
if self.should_apply(force_apply=force_apply):
params = self.get_params()
params = self.update_transform_params(params=params, data=kwargs)
if self.targets_as_params: # check if all required targets are in kwargs.
missing_keys = set(self.targets_as_params).difference(kwargs.keys())
if missing_keys and not (missing_keys == {"image"} and "images" in kwargs):
msg = f"{self.__class__.__name__} requires {self.targets_as_params} missing keys: {missing_keys}"
raise ValueError(msg)
params_dependent_on_data = self.get_params_dependent_on_data(params=params, data=kwargs)
params.update(params_dependent_on_data)
# Store the final params
self.params = params
if self.deterministic:
kwargs[self.save_key][id(self)] = deepcopy(params)
return self.apply_with_params(params, **kwargs)
return kwargs
def get_applied_params(self) -> dict[str, Any]:
"""Returns the parameters that were used in the last transform application.
Returns empty dict if transform was not applied.
"""
return self.params
def should_apply(self, force_apply: bool = False) -> bool:
"""Determine whether to apply the transform based on probability and force flag.
Args:
force_apply (bool, optional): If True, always apply the transform regardless of probability.
Returns:
bool: True if the transform should be applied, False otherwise.
"""
if self.p <= 0.0:
return False
if self.p >= 1.0 or force_apply:
return True
return self.py_random.random() < self.p
def apply_with_params(self, params: dict[str, Any], *args: Any, **kwargs: Any) -> dict[str, Any]:
"""Apply transforms with parameters."""
res = {}
for key, arg in kwargs.items():
if key in self._key2func and arg is not None:
# Handle empty lists for mask-like keys
if key in {"masks", "masks3d"} and isinstance(arg, (list, tuple)) and not arg:
res[key] = arg # Keep empty list as is
else:
target_function = self._key2func[key]
res[key] = ensure_contiguous_output(
target_function(ensure_contiguous_output(arg), **params),
)
else:
res[key] = arg
return res
def set_deterministic(self, flag: bool, save_key: str = "replay") -> BasicTransform:
"""Set transform to be deterministic."""
if save_key == "params":
msg = "params save_key is reserved"
raise KeyError(msg)
self.deterministic = flag
if self.deterministic and self.targets_as_params:
warn(
self.get_class_fullname() + " could work incorrectly in ReplayMode for other input data"
" because its' params depend on targets.",
stacklevel=2,
)
self.save_key = save_key
return self
def __repr__(self) -> str:
state = self.get_base_init_args()
state.update(self.get_transform_init_args())
return f"{self.__class__.__name__}({format_args(state)})"
def apply(self, img: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform on image."""
raise NotImplementedError
def apply_to_images(self, images: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform on images.
Args:
images (np.ndarray): Input images as numpy array of shape:
- (num_images, height, width, channels)
- (num_images, height, width) for grayscale
*args (Any): Additional positional arguments
**params (Any): Additional parameters specific to the transform
Returns:
np.ndarray: Transformed images as numpy array in the same format as input
"""
# Handle batched numpy array input
transformed = np.stack([self.apply(image, **params) for image in images])
return np.require(transformed, requirements=["C_CONTIGUOUS"])
def apply_to_volume(self, volume: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform slice by slice to a volume.
Args:
volume (np.ndarray): Input volume of shape (depth, height, width) or (depth, height, width, channels)
*args (Any): Additional positional arguments
**params (Any): Additional parameters specific to the transform
Returns:
np.ndarray: Transformed volume as numpy array in the same format as input
"""
return self.apply_to_images(volume, *args, **params)
def apply_to_volumes(self, volumes: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to multiple volumes."""
return np.stack([self.apply_to_volume(vol, *args, **params) for vol in volumes])
def get_params(self) -> dict[str, Any]:
"""Returns parameters independent of input."""
return {}
def update_transform_params(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Updates parameters with input shape and transform-specific params.
Args:
params (dict[str, Any]): Parameters to be updated
data (dict[str, Any]): Input data dictionary containing images/volumes
Returns:
dict[str, Any]: Updated parameters dictionary with shape and transform-specific params
"""
# Extract shape from volume, volumes, image, or images
if "volume" in data:
shape = data["volume"][0].shape # Take first slice of volume
elif "volumes" in data:
shape = data["volumes"][0][0].shape # Take first slice of first volume
elif "image" in data:
shape = data["image"].shape
else:
shape = data["images"][0].shape
# For volumes/images, shape will be either (H, W) or (H, W, C)
params["shape"] = shape
# Add transform-specific params
if hasattr(self, "interpolation"):
params["interpolation"] = self.interpolation
if hasattr(self, "fill"):
params["fill"] = self.fill
if hasattr(self, "fill_mask"):
params["fill_mask"] = self.fill_mask
return params
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Returns parameters dependent on input."""
return params
@property
def targets(self) -> dict[str, Callable[..., Any]]:
"""Get mapping of target keys to their corresponding processing functions.
Returns:
dict[str, Callable[..., Any]]: Dictionary mapping target keys to their processing functions.
"""
# mapping for targets and methods for which they depend
# for example:
# >> {"image": self.apply}
# >> {"masks": self.apply_to_masks}
raise NotImplementedError
def _set_keys(self) -> None:
"""Set _available_keys."""
if not hasattr(self, "_targets"):
self._available_keys = set()
else:
self._available_keys = {
target.value.lower()
for target in (self._targets if isinstance(self._targets, tuple) else [self._targets])
}
self._available_keys.update(self.targets.keys())
self._key2func = {key: self.targets[key] for key in self._available_keys if key in self.targets}
@property
def available_keys(self) -> set[str]:
"""Returns set of available keys."""
return self._available_keys
def add_targets(self, additional_targets: dict[str, str]) -> None:
"""Add targets to transform them the same way as one of existing targets.
ex: {'target_image': 'image'}
ex: {'obj1_mask': 'mask', 'obj2_mask': 'mask'}
by the way you must have at least one object with key 'image'
Args:
additional_targets (dict[str, str]): keys - new target name, values
- old target name. ex: {'image2': 'image'}
"""
for k, v in additional_targets.items():
if k in self._additional_targets and v != self._additional_targets[k]:
raise ValueError(
f"Trying to overwrite existed additional targets. "
f"Key={k} Exists={self._additional_targets[k]} New value: {v}",
)
if v in self._available_keys:
self._additional_targets[k] = v
self._key2func[k] = self.targets[v]
self._available_keys.add(k)
@property
def targets_as_params(self) -> list[str]:
"""Targets used to get params dependent on targets.
This is used to check input has all required targets.
"""
return []
@classmethod
def get_class_fullname(cls) -> str:
"""Get the full qualified name of the class.
Returns:
str: The shortest class fullname.
"""
return get_shortest_class_fullname(cls)
@classmethod
def is_serializable(cls) -> bool:
"""Check if the transform class is serializable.
Returns:
bool: True if the class is serializable, False otherwise.
"""
return True
def get_base_init_args(self) -> dict[str, Any]:
"""Returns base init args - p"""
return {"p": self.p}
def get_transform_init_args(self) -> dict[str, Any]:
"""Get transform initialization arguments for serialization.
Returns a dictionary of parameter names and their values, excluding parameters
that are not actually set on the instance or that shouldn't be serialized.
"""
# Get the parameter names
arg_names = self.get_transform_init_args_names()
# Create a dictionary of parameter values
args = {}
for name in arg_names:
# Only include parameters that are actually set as instance attributes
# and have non-default values
if hasattr(self, name):
value = getattr(self, name)
# Skip attributes that are basic containers with no content
if not (isinstance(value, (list, dict, tuple, set)) and len(value) == 0):
args[name] = value
# Remove seed explicitly (it's not meant to be serialized)
args.pop("seed", None)
return args
def to_dict_private(self) -> dict[str, Any]:
"""Returns a dictionary representation of the transform, excluding internal parameters."""
state = {"__class_fullname__": self.get_class_fullname()}
state.update(self.get_base_init_args())
# Get transform init args (our improved method handles all types of transforms)
transform_args = self.get_transform_init_args()
# Add transform args to state
state.update(transform_args)
# Remove strict from serialization
state.pop("strict", None)
return state
class DualTransform(BasicTransform):
"""A base class for transformations that should be applied both to an image and its corresponding properties
such as masks, bounding boxes, and keypoints. This class ensures that when a transform is applied to an image,
all associated entities are transformed accordingly to maintain consistency between the image and its annotations.
Methods:
apply(img: np.ndarray, **params: Any) -> np.ndarray:
Apply the transform to the image.
img: Input image of shape (H, W, C) or (H, W) for grayscale.
**params: Additional parameters specific to the transform.
Returns Transformed image of the same shape as input.
apply_to_images(images: np.ndarray, **params: Any) -> np.ndarray:
Apply the transform to multiple images.
images: Input images of shape (N, H, W, C) or (N, H, W) for grayscale.
**params: Additional parameters specific to the transform.
Returns Transformed images in the same format as input.
apply_to_mask(mask: np.ndarray, **params: Any) -> np.ndarray:
Apply the transform to a mask.
mask: Input mask of shape (H, W), (H, W, C) for multi-channel masks
**params: Additional parameters specific to the transform.
Returns Transformed mask in the same format as input.
apply_to_masks(masks: np.ndarray, **params: Any) -> np.ndarray | list[np.ndarray]:
Apply the transform to multiple masks.
masks: Array of shape (N, H, W) or (N, H, W, C) where N is number of masks
**params: Additional parameters specific to the transform.
Returns Transformed masks in the same format as input.
apply_to_keypoints(keypoints: np.ndarray, **params: Any) -> np.ndarray:
Apply the transform to keypoints.
keypoints: Array of shape (N, 2+) where N is the number of keypoints.
**params: Additional parameters specific to the transform.
Returns Transformed keypoints array of shape (N, 2+).
apply_to_bboxes(bboxes: np.ndarray, **params: Any) -> np.ndarray:
Apply the transform to bounding boxes.
bboxes: Array of shape (N, 4+) where N is the number of bounding boxes,
and each row is in the format [x_min, y_min, x_max, y_max].
**params: Additional parameters specific to the transform.
Returns Transformed bounding boxes array of shape (N, 4+).
apply_to_volume(volume: np.ndarray, **params: Any) -> np.ndarray:
Apply the transform to a volume.
volume: Input volume of shape (D, H, W) or (D, H, W, C).
**params: Additional parameters specific to the transform.
Returns Transformed volume of the same shape as input.
apply_to_volumes(volumes: np.ndarray, **params: Any) -> np.ndarray:
Apply the transform to multiple volumes.
volumes: Input volumes of shape (N, D, H, W) or (N, D, H, W, C).
**params: Additional parameters specific to the transform.
Returns Transformed volumes in the same format as input.
apply_to_mask3d(mask: np.ndarray, **params: Any) -> np.ndarray:
Apply the transform to a 3D mask.
mask: Input 3D mask of shape (D, H, W) or (D, H, W, C)
**params: Additional parameters specific to the transform.
Returns Transformed 3D mask in the same format as input.
apply_to_masks3d(masks: np.ndarray, **params: Any) -> np.ndarray:
Apply the transform to multiple 3D masks.
masks: Input 3D masks of shape (N, D, H, W) or (N, D, H, W, C)
**params: Additional parameters specific to the transform.
Returns Transformed 3D masks in the same format as input.
Note:
- All `apply_*` methods should maintain the input shape and format of the data.
- When applying transforms to masks, ensure that discrete values (e.g., class labels) are preserved.
- For keypoints and bounding boxes, the transformation should maintain their relative positions
with respect to the transformed image.
- The difference between `apply_to_mask` and `apply_to_masks` is mainly in how they handle 3D arrays:
`apply_to_mask` treats a 3D array as a multi-channel mask, while `apply_to_masks` treats it as
multiple single-channel masks.
"""
@property
def targets(self) -> dict[str, Callable[..., Any]]:
"""Get mapping of target keys to their corresponding processing functions for DualTransform.
Returns:
dict[str, Callable[..., Any]]: Dictionary mapping target keys to their processing functions.
"""
return {
"image": self.apply,
"images": self.apply_to_images,
"mask": self.apply_to_mask,
"masks": self.apply_to_masks,
"mask3d": self.apply_to_mask3d,
"masks3d": self.apply_to_masks3d,
"bboxes": self.apply_to_bboxes,
"keypoints": self.apply_to_keypoints,
"volume": self.apply_to_volume,
"volumes": self.apply_to_volumes,
}
def apply_to_keypoints(self, keypoints: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to keypoints.
Args:
keypoints (np.ndarray): Array of keypoints of shape (N, 2+).
*args (Any): Additional positional arguments.
**params (Any): Additional parameters.
Raises:
NotImplementedError: This method must be implemented by subclass.
Returns:
np.ndarray: Transformed keypoints.
"""
msg = f"Method apply_to_keypoints is not implemented in class {self.__class__.__name__}"
raise NotImplementedError(msg)
def apply_to_bboxes(self, bboxes: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to bounding boxes.
Args:
bboxes (np.ndarray): Array of bounding boxes of shape (N, 4+).
*args (Any): Additional positional arguments.
**params (Any): Additional parameters.
Raises:
NotImplementedError: This method must be implemented by subclass.
Returns:
np.ndarray: Transformed bounding boxes.
"""
raise NotImplementedError(f"BBoxes not implemented for {self.__class__.__name__}")
def apply_to_mask(self, mask: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to mask.
Args:
mask (np.ndarray): Input mask.
*args (Any): Additional positional arguments.
**params (Any): Additional parameters.
Returns:
np.ndarray: Transformed mask.
"""
return self.apply(mask, *args, **params)
def apply_to_masks(self, masks: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to multiple masks.
Args:
masks (np.ndarray): Input masks as numpy array
*args (Any): Additional positional arguments
**params (Any): Additional parameters specific to the transform
Returns:
np.ndarray: Transformed masks as numpy array
"""
return np.stack([self.apply_to_mask(mask, **params) for mask in masks])
@batch_transform("spatial", has_batch_dim=False, has_depth_dim=True)
def apply_to_mask3d(self, mask3d: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to a 3D mask.
Args:
mask3d (np.ndarray): Input 3D mask as numpy array
*args (Any): Additional positional arguments
**params (Any): Additional parameters specific to the transform
Returns:
np.ndarray: Transformed 3D mask as numpy array
"""
return self.apply_to_mask(mask3d, **params)
@batch_transform("spatial", has_batch_dim=True, has_depth_dim=True)
def apply_to_masks3d(self, masks3d: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to multiple 3D masks.
Args:
masks3d (np.ndarray): Input 3D masks as numpy array
*args (Any): Additional positional arguments
**params (Any): Additional parameters specific to the transform
Returns:
np.ndarray: Transformed 3D masks as numpy array
"""
return np.stack([self.apply_to_mask3d(mask3d, **params) for mask3d in masks3d])
class ImageOnlyTransform(BasicTransform):
"""Transform applied to image only."""
_targets = (Targets.IMAGE, Targets.VOLUME)
@property
def targets(self) -> dict[str, Callable[..., Any]]:
"""Get mapping of target keys to their corresponding processing functions for ImageOnlyTransform.
Returns:
dict[str, Callable[..., Any]]: Dictionary mapping target keys to their processing functions.
"""
return {
"image": self.apply,
"images": self.apply_to_images,
"volume": self.apply_to_volume,
"volumes": self.apply_to_volumes,
}
class NoOp(DualTransform):
"""Identity transform (does nothing).
Targets:
image, mask, bboxes, keypoints, volume, mask3d
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.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[10, 10, 50, 50], [40, 40, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Create transform pipeline with NoOp
>>> transform = A.Compose([
... A.NoOp(p=1.0), # Always applied, but does nothing
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Verify nothing has changed
>>> np.array_equal(image, transformed['image']) # True
>>> np.array_equal(mask, transformed['mask']) # True
>>> np.array_equal(bboxes, transformed['bboxes']) # True
>>> np.array_equal(keypoints, transformed['keypoints']) # True
>>> bbox_labels == transformed['bbox_labels'] # True
>>> keypoint_labels == transformed['keypoint_labels'] # True
>>>
>>> # NoOp is often used as a placeholder or for testing
>>> # For example, in conditional transforms:
>>> condition = False # Some condition
>>> transform = A.Compose([
... A.HorizontalFlip(p=1.0) if condition else A.NoOp(p=1.0)
... ])
"""
_targets = ALL_TARGETS
def apply_to_keypoints(self, keypoints: np.ndarray, **params: Any) -> np.ndarray:
"""Apply transform to keypoints (identity operation).
Args:
keypoints (np.ndarray): Array of keypoints.
**params (Any): Additional parameters.
Returns:
np.ndarray: Unchanged keypoints array.
"""
return keypoints
def apply_to_bboxes(self, bboxes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply transform to bounding boxes (identity operation).
Args:
bboxes (np.ndarray): Array of bounding boxes.
**params (Any): Additional parameters.
Returns:
np.ndarray: Unchanged bounding boxes array.
"""
return bboxes
def apply(self, img: np.ndarray, **params: Any) -> np.ndarray:
"""Apply transform to image (identity operation).
Args:
img (np.ndarray): Input image.
**params (Any): Additional parameters.
Returns:
np.ndarray: Unchanged image.
"""
return img
def apply_to_mask(self, mask: np.ndarray, **params: Any) -> np.ndarray:
"""Apply transform to mask (identity operation).
Args:
mask (np.ndarray): Input mask.
**params (Any): Additional parameters.
Returns:
np.ndarray: Unchanged mask.
"""
return mask
def apply_to_volume(self, volume: np.ndarray, **params: Any) -> np.ndarray:
"""Apply transform to volume (identity operation).
Args:
volume (np.ndarray): Input volume.
**params (Any): Additional parameters.
Returns:
np.ndarray: Unchanged volume.
"""
return volume
def apply_to_volumes(self, volumes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply transform to multiple volumes (identity operation).
Args:
volumes (np.ndarray): Input volumes.
**params (Any): Additional parameters.
Returns:
np.ndarray: Unchanged volumes.
"""
return volumes
def apply_to_mask3d(self, mask3d: np.ndarray, **params: Any) -> np.ndarray:
"""Apply transform to 3D mask (identity operation).
Args:
mask3d (np.ndarray): Input 3D mask.
**params (Any): Additional parameters.
Returns:
np.ndarray: Unchanged 3D mask.
"""
return mask3d
def apply_to_masks3d(self, masks3d: np.ndarray, **params: Any) -> np.ndarray:
"""Apply transform to multiple 3D masks (identity operation).
Args:
masks3d (np.ndarray): Input 3D masks.
**params (Any): Additional parameters.
Returns:
np.ndarray: Unchanged 3D masks.
"""
return masks3d
class Transform3D(DualTransform):
"""Base class for all 3D transforms.
Transform3D inherits from DualTransform because 3D transforms can be applied to both
volumes and masks, similar to how 2D DualTransforms work with images and masks.
Targets:
volume: 3D numpy array of shape (D, H, W) or (D, H, W, C)
volumes: Batch of 3D arrays of shape (N, D, H, W) or (N, D, H, W, C)
mask: 3D numpy array of shape (D, H, W)
masks: Batch of 3D arrays of shape (N, D, H, W)
keypoints: 3D numpy array of shape (N, 3)
"""
def apply_to_volume(self, volume: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to single 3D volume."""
raise NotImplementedError
@batch_transform("spatial", keep_depth_dim=True, has_batch_dim=True, has_depth_dim=True)
def apply_to_volumes(self, volumes: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to batch of 3D volumes."""
return self.apply_to_volume(volumes, *args, **params)
def apply_to_mask3d(self, mask3d: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to single 3D mask."""
return self.apply_to_volume(mask3d, *args, **params)
@batch_transform("spatial", keep_depth_dim=True, has_batch_dim=True, has_depth_dim=True)
def apply_to_masks3d(self, masks3d: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
"""Apply transform to batch of 3D masks."""
return self.apply_to_mask3d(masks3d, *args, **params)
@property
def targets(self) -> dict[str, Callable[..., Any]]:
"""Define valid targets for 3D transforms."""
return {
"volume": self.apply_to_volume,
"volumes": self.apply_to_volumes,
"mask3d": self.apply_to_mask3d,
"masks3d": self.apply_to_masks3d,
"keypoints": self.apply_to_keypoints,
}
@@ -0,0 +1,127 @@
"""Module containing type definitions and constants used throughout Albumentations.
This module defines common types, constants, and enumerations that are used across the
Albumentations library. It includes type aliases for numeric types, enumerations for
targets supported by transforms, and constants that define standard dimensions or values
used in image and volumetric data processing. These definitions help ensure type safety
and provide a centralized location for commonly used values.
"""
from __future__ import annotations
from enum import Enum
from typing import TypeVar, Union
import cv2
import numpy as np
from albucore.utils import MAX_VALUES_BY_DTYPE
from numpy.typing import NDArray
from typing_extensions import NotRequired, TypedDict
Number = TypeVar("Number", float, int)
IntNumType = Union[np.integer, NDArray[np.integer]]
FloatNumType = Union[np.floating, NDArray[np.floating]]
d4_group_elements = ["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]
class ReferenceImage(TypedDict):
"""Dictionary-like container for reference image data.
A typed dictionary defining the structure of reference image data used within
Albumentations, including optional components like masks, bounding boxes,
and keypoints.
Args:
image (np.ndarray): The reference image array.
mask (np.ndarray | None): Optional mask array.
bbox (tuple[float, ...] | np.ndarray | None): Optional bounding box coordinates.
keypoints (tuple[float, ...] | np.ndarray | None): Optional keypoint coordinates.
"""
image: np.ndarray
mask: NotRequired[np.ndarray]
bbox: NotRequired[tuple[float, ...] | np.ndarray]
keypoints: NotRequired[tuple[float, ...] | np.ndarray]
class Targets(Enum):
"""Enumeration of supported target types in Albumentations.
This enum defines the different types of data that can be augmented
by Albumentations transforms, including both 2D and 3D targets.
Args:
IMAGE (str): 2D image target.
MASK (str): 2D mask target.
BBOXES (str): Bounding box target.
KEYPOINTS (str): Keypoint coordinates target.
VOLUME (str): 3D volume target.
MASK3D (str): 3D mask target.
"""
IMAGE = "Image"
MASK = "Mask"
BBOXES = "BBoxes"
KEYPOINTS = "Keypoints"
VOLUME = "Volume"
MASK3D = "Mask3D"
ALL_TARGETS = (Targets.IMAGE, Targets.MASK, Targets.BBOXES, Targets.KEYPOINTS, Targets.VOLUME, Targets.MASK3D)
NUM_VOLUME_DIMENSIONS = 4
NUM_MULTI_CHANNEL_DIMENSIONS = 3
MONO_CHANNEL_DIMENSIONS = 2
NUM_RGB_CHANNELS = 3
PAIR = 2
TWO = 2
THREE = 3
FOUR = 4
SEVEN = 7
EIGHT = 8
THREE_SIXTY = 360
BIG_INTEGER = MAX_VALUES_BY_DTYPE[np.uint32]
MAX_RAIN_ANGLE = 45 # Maximum angle for rain augmentation in degrees
LENGTH_RAW_BBOX = 4
PercentType = Union[
float,
tuple[float, float],
tuple[float, float, float, float],
tuple[
Union[float, tuple[float, float], list[float]],
Union[float, tuple[float, float], list[float]],
Union[float, tuple[float, float], list[float]],
Union[float, tuple[float, float], list[float]],
],
]
PxType = Union[
int,
tuple[int, int],
tuple[int, int, int, int],
tuple[
Union[int, tuple[int, int], list[int]],
Union[int, tuple[int, int], list[int]],
Union[int, tuple[int, int], list[int]],
Union[int, tuple[int, int], list[int]],
],
]
REFLECT_BORDER_MODES = {
cv2.BORDER_REFLECT_101,
cv2.BORDER_REFLECT,
}
NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS = 5
NUM_BBOXES_COLUMNS_IN_ALBUMENTATIONS = 4
@@ -0,0 +1,605 @@
"""Module containing utility functions and classes for the core Albumentations framework.
This module provides a collection of helper functions and base classes used throughout
the Albumentations library. It includes utilities for shape handling, parameter processing,
data conversion, and serialization. The module defines abstract base classes for data
processors that implement the conversion logic between different data formats used in
the transformation pipeline.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Sequence
from numbers import Real
from typing import TYPE_CHECKING, Any, Literal, cast, overload
import numpy as np
from albumentations.core.label_manager import LabelManager
from .serialization import Serializable
from .type_definitions import PAIR, Number
if TYPE_CHECKING:
import torch
ShapeType = dict[Literal["depth", "height", "width"], int]
def get_image_shape(img: np.ndarray | torch.Tensor) -> tuple[int, int]:
"""Extract height and width dimensions from an image.
Args:
img (np.ndarray | torch.Tensor): Image as either numpy array (HWC format)
or torch tensor (CHW format).
Returns:
tuple[int, int]: Image dimensions as (height, width).
Raises:
RuntimeError: If the image type is not supported.
"""
if isinstance(img, np.ndarray):
return img.shape[:2] # HWC format
try:
import torch
if torch.is_tensor(img):
return img.shape[-2:] # CHW format
except ImportError:
pass
raise RuntimeError(f"Unsupported image type: {type(img)}")
def get_volume_shape(vol: np.ndarray | torch.Tensor) -> tuple[int, int, int]:
"""Extract depth, height, and width dimensions from a volume.
Args:
vol (np.ndarray | torch.Tensor): Volume as either numpy array (DHWC format)
or torch tensor (CDHW format).
Returns:
tuple[int, int, int]: Volume dimensions as (depth, height, width).
Raises:
RuntimeError: If the volume type is not supported.
"""
if isinstance(vol, np.ndarray):
return vol.shape[:3] # DHWC format
try:
import torch
if torch.is_tensor(vol):
return vol.shape[-3:] # CDHW format
except ImportError:
pass
raise RuntimeError(f"Unsupported volume type: {type(vol)}")
def get_shape(data: dict[str, Any]) -> ShapeType:
"""Extract spatial dimensions from input data dictionary containing image or volume.
Args:
data (dict[str, Any]): Dictionary containing image or volume data with one of:
- 'volume': 3D array of shape (D, H, W, C) [numpy] or (C, D, H, W) [torch]
- 'image': 2D array of shape (H, W, C) [numpy] or (C, H, W) [torch]
- 'images': Batch of arrays of shape (N, H, W, C) [numpy] or (N, C, H, W) [torch]
Returns:
dict[Literal["depth", "height", "width"], int]: Dictionary containing spatial dimensions
"""
if "volume" in data:
depth, height, width = get_volume_shape(data["volume"])
return {"depth": depth, "height": height, "width": width}
if "image" in data:
height, width = get_image_shape(data["image"])
return {"height": height, "width": width}
if "images" in data:
height, width = get_image_shape(data["images"][0])
return {"height": height, "width": width}
raise ValueError("No image or volume found in data", data.keys())
def format_args(args_dict: dict[str, Any]) -> str:
"""Format a dictionary of arguments into a string representation.
Args:
args_dict (dict[str, Any]): Dictionary of argument names and values.
Returns:
str: Formatted string of arguments in the form "key1='value1', key2=value2".
"""
formatted_args = []
for k, v in args_dict.items():
v_formatted = f"'{v}'" if isinstance(v, str) else str(v)
formatted_args.append(f"{k}={v_formatted}")
return ", ".join(formatted_args)
class Params(Serializable, ABC):
"""Base class for parameter handling in transforms.
Args:
format (Any): The format of the data this parameter object will process.
label_fields (Sequence[str] | None): List of fields that are joined with the data, such as labels.
"""
def __init__(self, format: Any, label_fields: Sequence[str] | None): # noqa: A002
self.format = format
self.label_fields = label_fields
def to_dict_private(self) -> dict[str, Any]:
"""Return a dictionary containing the private parameters of this object.
Returns:
dict[str, Any]: Dictionary with format and label_fields parameters.
"""
return {"format": self.format, "label_fields": self.label_fields}
class DataProcessor(ABC):
"""Abstract base class for data processors.
Data processors handle the conversion, validation, and filtering of data
during transformations.
Args:
params (Params): Parameters for data processing.
additional_targets (dict[str, str] | None): Dictionary mapping additional target names to their types.
"""
def __init__(self, params: Params, additional_targets: dict[str, str] | None = None):
self.params = params
self.data_fields = [self.default_data_name]
self.is_sequence_input: dict[str, bool] = {}
self.label_manager = LabelManager()
if additional_targets is not None:
self.add_targets(additional_targets)
@property
@abstractmethod
def default_data_name(self) -> str:
"""Return the default name of the data field.
Returns:
str: Default data field name.
"""
raise NotImplementedError
def add_targets(self, additional_targets: dict[str, str]) -> None:
"""Add targets to transform them the same way as one of existing targets."""
for k, v in additional_targets.items():
if v == self.default_data_name and k not in self.data_fields:
self.data_fields.append(k)
def ensure_data_valid(self, data: dict[str, Any]) -> None:
"""Validate input data before processing.
Args:
data (dict[str, Any]): Input data dictionary to validate.
"""
def ensure_transforms_valid(self, transforms: Sequence[object]) -> None:
"""Validate transforms before applying them.
Args:
transforms (Sequence[object]): Sequence of transforms to validate.
"""
def postprocess(self, data: dict[str, Any]) -> dict[str, Any]:
"""Process data after transformation.
Args:
data (dict[str, Any]): Data dictionary after transformation.
Returns:
dict[str, Any]: Processed data dictionary.
"""
shape = get_shape(data)
data = self._process_data_fields(data, shape)
data = self.remove_label_fields_from_data(data)
return self._convert_sequence_inputs(data)
def _process_data_fields(self, data: dict[str, Any], shape: ShapeType) -> dict[str, Any]:
for data_name in set(self.data_fields) & set(data.keys()):
data[data_name] = self._process_single_field(data_name, data[data_name], shape)
return data
def _process_single_field(self, data_name: str, field_data: Any, shape: ShapeType) -> Any:
field_data = self.filter(field_data, shape)
if data_name == "keypoints" and len(field_data) == 0:
field_data = self._create_empty_keypoints_array()
return self.check_and_convert(field_data, shape, direction="from")
def _create_empty_keypoints_array(self) -> np.ndarray:
return np.array([], dtype=np.float32).reshape(0, len(self.params.format))
def _convert_sequence_inputs(self, data: dict[str, Any]) -> dict[str, Any]:
for data_name in set(self.data_fields) & set(data.keys()):
if self.is_sequence_input.get(data_name, False):
data[data_name] = data[data_name].tolist()
return data
def preprocess(self, data: dict[str, Any]) -> None:
"""Process data before transformation.
Args:
data (dict[str, Any]): Data dictionary to preprocess.
"""
shape = get_shape(data)
for data_name in set(self.data_fields) & set(data.keys()): # Convert list of lists to numpy array if necessary
if isinstance(data[data_name], Sequence):
self.is_sequence_input[data_name] = True
data[data_name] = np.array(data[data_name], dtype=np.float32)
else:
self.is_sequence_input[data_name] = False
data = self.add_label_fields_to_data(data)
for data_name in set(self.data_fields) & set(data.keys()):
data[data_name] = self.check_and_convert(data[data_name], shape, direction="to")
def check_and_convert(
self,
data: np.ndarray,
shape: ShapeType,
direction: Literal["to", "from"] = "to",
) -> np.ndarray:
"""Check and convert data between Albumentations and external formats.
Args:
data (np.ndarray): Input data array.
shape (ShapeType): Shape information containing dimensions.
direction (Literal["to", "from"], optional): Conversion direction.
"to" converts to Albumentations format, "from" converts from it.
Defaults to "to".
Returns:
np.ndarray: Converted data array.
"""
if self.params.format == "albumentations":
self.check(data, shape)
return data
process_func = self.convert_to_albumentations if direction == "to" else self.convert_from_albumentations
return process_func(data, shape)
@abstractmethod
def filter(self, data: np.ndarray, shape: ShapeType) -> np.ndarray:
"""Filter data based on shapes.
Args:
data (np.ndarray): Data to filter.
shape (ShapeType): Shape information containing dimensions.
Returns:
np.ndarray: Filtered data.
"""
@abstractmethod
def check(self, data: np.ndarray, shape: ShapeType) -> None:
"""Validate data structure against shape requirements.
Args:
data (np.ndarray): Data to validate.
shape (ShapeType): Shape information containing dimensions.
"""
@abstractmethod
def convert_to_albumentations(
self,
data: np.ndarray,
shape: ShapeType,
) -> np.ndarray:
"""Convert data from external format to Albumentations internal format.
Args:
data (np.ndarray): Data in external format.
shape (ShapeType): Shape information containing dimensions.
Returns:
np.ndarray: Data in Albumentations format.
"""
@abstractmethod
def convert_from_albumentations(
self,
data: np.ndarray,
shape: ShapeType,
) -> np.ndarray:
"""Convert data from Albumentations internal format to external format.
Args:
data (np.ndarray): Data in Albumentations format.
shape (ShapeType): Shape information containing dimensions.
Returns:
np.ndarray: Data in external format.
"""
def add_label_fields_to_data(self, data: dict[str, Any]) -> dict[str, Any]:
"""Add label fields to data arrays.
This method processes label fields and joins them with the corresponding data arrays.
Args:
data (dict[str, Any]): Input data dictionary.
Returns:
dict[str, Any]: Data with label fields added.
"""
if not self.params.label_fields:
return data
for data_name in set(self.data_fields) & set(data.keys()):
if not data[data_name].size:
continue
data[data_name] = self._process_label_fields(data, data_name)
return data
def _process_label_fields(self, data: dict[str, Any], data_name: str) -> np.ndarray:
data_array = data[data_name]
if self.params.label_fields is not None:
for label_field in self.params.label_fields:
self._validate_label_field_length(data, data_name, label_field)
encoded_labels = self.label_manager.process_field(data_name, label_field, data[label_field])
data_array = np.hstack((data_array, encoded_labels))
del data[label_field]
return data_array
def _validate_label_field_length(self, data: dict[str, Any], data_name: str, label_field: str) -> None:
if len(data[data_name]) != len(data[label_field]):
raise ValueError(
f"The lengths of {data_name} and {label_field} do not match. "
f"Got {len(data[data_name])} and {len(data[label_field])} respectively.",
)
def remove_label_fields_from_data(self, data: dict[str, Any]) -> dict[str, Any]:
"""Remove label fields from data arrays and restore them as separate entries.
Args:
data (dict[str, Any]): Input data dictionary with combined label fields.
Returns:
dict[str, Any]: Data with label fields extracted as separate entries.
"""
if not self.params.label_fields:
return data
for data_name in set(self.data_fields) & set(data.keys()):
if not data[data_name].size:
self._handle_empty_data_array(data)
continue
self._remove_label_fields(data, data_name)
return data
def _handle_empty_data_array(self, data: dict[str, Any]) -> None:
if self.params.label_fields is not None:
for label_field in self.params.label_fields:
data[label_field] = self.label_manager.handle_empty_data()
def _remove_label_fields(self, data: dict[str, Any], data_name: str) -> None:
if self.params.label_fields is None:
return
data_array = data[data_name]
num_label_fields = len(self.params.label_fields)
non_label_columns = data_array.shape[1] - num_label_fields
for idx, label_field in enumerate(self.params.label_fields):
encoded_labels = data_array[:, non_label_columns + idx]
data[label_field] = self.label_manager.restore_field(data_name, label_field, encoded_labels)
data[data_name] = data_array[:, :non_label_columns]
def validate_args(
low: float | Sequence[int] | Sequence[float] | None,
bias: float | None,
) -> None:
"""Validate that 'low' and 'bias' parameters are not used together.
Args:
low (float | Sequence[int] | Sequence[float] | None): Lower bound value.
bias (float | None): Bias value to be added to both min and max values.
Raises:
ValueError: If both 'low' and 'bias' are provided.
"""
if low is not None and bias is not None:
raise ValueError("Arguments 'low' and 'bias' cannot be used together.")
def process_sequence(param: Sequence[Number]) -> tuple[Number, Number]:
"""Process a sequence and return it as a (min, max) tuple.
Args:
param (Sequence[Number]): Sequence of numeric values.
Returns:
tuple[Number, Number]: Tuple containing (min_value, max_value) from the sequence.
Raises:
ValueError: If the sequence doesn't contain exactly 2 elements.
"""
if len(param) != PAIR:
raise ValueError("Sequence must contain exactly 2 elements.")
return min(param), max(param)
def process_scalar(param: Number, low: Number | None) -> tuple[Number, Number]:
"""Process a scalar value and optional low bound into a (min, max) tuple.
Args:
param (Number): Scalar numeric value.
low (Number | None): Optional lower bound.
Returns:
tuple[Number, Number]: Tuple containing (min_value, max_value) where:
- If low is provided: (low, param) if low < param else (param, low)
- If low is None: (-param, param) creating a symmetric range around zero
"""
if isinstance(low, Real):
return (low, param) if low < param else (param, low)
return -param, param
def apply_bias(min_val: Number, max_val: Number, bias: Number) -> tuple[Number, Number]:
"""Apply a bias to both values in a range.
Args:
min_val (Number): Minimum value.
max_val (Number): Maximum value.
bias (Number): Value to add to both min and max.
Returns:
tuple[Number, Number]: Tuple containing (min_val + bias, max_val + bias).
"""
return bias + min_val, bias + max_val
def ensure_int_output(
min_val: Number,
max_val: Number,
param: Number,
) -> tuple[int, int] | tuple[float, float]:
"""Ensure output is of the same type (int or float) as the input parameter.
Args:
min_val (Number): Minimum value.
max_val (Number): Maximum value.
param (Number): Original parameter used to determine the output type.
Returns:
tuple[int, int] | tuple[float, float]: Tuple with values converted to int if param is int,
otherwise values remain as float.
"""
return (int(min_val), int(max_val)) if isinstance(param, int) else (float(min_val), float(max_val))
def ensure_contiguous_output(arg: np.ndarray | Sequence[np.ndarray]) -> np.ndarray | list[np.ndarray]:
"""Ensure that numpy arrays are contiguous in memory.
Args:
arg (np.ndarray | Sequence[np.ndarray]): A numpy array or sequence of numpy arrays.
Returns:
np.ndarray | list[np.ndarray]: Contiguous array(s) with the same data.
"""
if isinstance(arg, np.ndarray):
arg = np.ascontiguousarray(arg)
elif isinstance(arg, Sequence):
arg = list(map(ensure_contiguous_output, arg))
return arg
@overload
def to_tuple(
param: int | tuple[int, int],
low: int | tuple[int, int] | None = None,
bias: float | None = None,
) -> tuple[int, int]: ...
@overload
def to_tuple(
param: float | tuple[float, float],
low: float | tuple[float, float] | None = None,
bias: float | None = None,
) -> tuple[float, float]: ...
def to_tuple(
param: float | tuple[float, float] | tuple[int, int],
low: float | tuple[float, float] | tuple[int, int] | None = None,
bias: float | None = None,
) -> tuple[float, float] | tuple[int, int]:
"""Convert input argument to a min-max tuple.
This function processes various input types and returns a tuple representing a range.
It handles single values, sequences, and can apply optional low bounds or biases.
Args:
param (tuple[float, float] | float | tuple[int, int] | int): The primary input value. Can be:
- A single int or float: Converted to a symmetric range around zero.
- A tuple of two ints or two floats: Used directly as min and max values.
low (tuple[float, float] | float | None, optional): A lower bound value. Used when param is a single value.
If provided, the result will be (low, param) or (param, low), depending on which is smaller.
Cannot be used together with 'bias'. Defaults to None.
bias (float | int | None, optional): A value to be added to both elements of the resulting tuple.
Cannot be used together with 'low'. Defaults to None.
Returns:
tuple[int, int] | tuple[float, float]: A tuple representing the processed range.
- If input is int-based, returns tuple[int, int]
- If input is float-based, returns tuple[float, float]
Raises:
ValueError: If both 'low' and 'bias' are provided.
TypeError: If 'param' is neither a scalar nor a sequence of 2 elements.
Examples:
>>> to_tuple(5)
(-5, 5)
>>> to_tuple(5.0)
(-5.0, 5.0)
>>> to_tuple((1, 10))
(1, 10)
>>> to_tuple(5, low=3)
(3, 5)
>>> to_tuple(5, bias=1)
(-4, 6)
Notes:
- When 'param' is a single value and 'low' is not provided, the function creates a symmetric range around zero.
- The function preserves the type (int or float) of the input in the output.
- If a sequence is provided, it must contain exactly 2 elements.
"""
validate_args(low, bias)
if isinstance(param, Sequence):
min_val, max_val = process_sequence(param)
elif isinstance(param, Real):
min_val, max_val = process_scalar(param, cast("Real", low))
else:
raise TypeError("Argument 'param' must be either a scalar or a sequence of 2 elements.")
if bias is not None:
min_val, max_val = apply_bias(min_val, max_val, bias)
return ensure_int_output(min_val, max_val, param if isinstance(param, (int, float)) else min_val)
@@ -0,0 +1,129 @@
"""Module containing validation mechanisms for transform parameters.
This module provides a metaclass that enables parameter validation for transforms using
Pydantic models. It intercepts the initialization of transform classes to validate their
parameters against schema definitions, raising appropriate errors for invalid values and
providing type conversion capabilities. This validation layer helps prevent runtime errors
by catching configuration issues at initialization time.
"""
from __future__ import annotations
from inspect import Parameter, signature
from typing import Any, Callable
from warnings import warn
from pydantic import BaseModel, ValidationError
class ValidatedTransformMeta(type):
"""Metaclass that validates transform parameters during instantiation.
This metaclass enables automatic validation of transform parameters using Pydantic models,
ensuring proper typing and constraints are enforced before object creation.
Args:
original_init (Callable[..., Any]): Original __init__ method of the class.
args (tuple[Any, ...]): Positional arguments passed to the __init__ method.
kwargs (dict[str, Any]): Keyword arguments passed to the __init__ method.
"""
@staticmethod
def _process_init_parameters(
original_init: Callable[..., Any],
args: tuple[Any, ...],
kwargs: dict[str, Any],
) -> tuple[dict[str, Any], list[str], bool]:
init_params = signature(original_init).parameters
param_names = list(init_params.keys())[1:] # Exclude 'self'
full_kwargs: dict[str, Any] = dict(zip(param_names, args)) | kwargs
# Get strict value before validation
strict = full_kwargs.pop("strict", False)
# Add default values if not provided
for parameter_name, parameter in init_params.items():
if (
parameter_name != "self"
and parameter_name not in full_kwargs
and parameter.default is not Parameter.empty
):
full_kwargs[parameter_name] = parameter.default
return full_kwargs, param_names, strict
@staticmethod
def _validate_parameters(
schema_cls: type[BaseModel],
full_kwargs: dict[str, Any],
param_names: list[str],
strict: bool,
) -> dict[str, Any]:
try:
# Include strict parameter for schema validation
schema_kwargs = {k: v for k, v in full_kwargs.items() if k in param_names}
schema_kwargs["strict"] = strict
config = schema_cls(**schema_kwargs)
validated_kwargs = config.model_dump()
validated_kwargs.pop("strict", None)
except ValidationError as e:
raise ValueError(str(e)) from e
except Exception as e:
if strict:
raise ValueError(str(e)) from e
warn(str(e), stacklevel=2)
return {}
else:
return validated_kwargs
@staticmethod
def _get_default_values(init_params: dict[str, Parameter]) -> dict[str, Any]:
validated_kwargs = {}
for param_name, param in init_params.items():
if param_name in {"self", "strict"}:
continue
if param.default is not Parameter.empty:
validated_kwargs[param_name] = param.default
return validated_kwargs
def __new__(cls: type[Any], name: str, bases: tuple[type, ...], dct: dict[str, Any]) -> type[Any]:
"""This is a custom metaclass that validates the parameters of the class during instantiation.
It is used to ensure that the parameters of the class are valid and that they are of the correct type.
"""
if "InitSchema" in dct and issubclass(dct["InitSchema"], BaseModel):
original_init: Callable[..., Any] | None = dct.get("__init__")
if original_init is None:
msg = "__init__ not found in class definition"
raise ValueError(msg)
original_sig = signature(original_init)
def custom_init(self: Any, *args: Any, **kwargs: Any) -> None:
full_kwargs, param_names, strict = cls._process_init_parameters(original_init, args, kwargs)
validated_kwargs = cls._validate_parameters(
dct["InitSchema"],
full_kwargs,
param_names,
strict,
) or cls._get_default_values(signature(original_init).parameters)
# Store and check invalid args
invalid_args = [name_arg for name_arg in kwargs if name_arg not in param_names and name_arg != "strict"]
original_init(self, **validated_kwargs)
self.invalid_args = invalid_args
if invalid_args:
message = f"Argument(s) '{', '.join(invalid_args)}' are not valid for transform {name}"
if strict:
raise ValueError(message)
warn(message, stacklevel=2)
# Preserve the original signature and docstring
custom_init.__signature__ = original_sig # type: ignore[attr-defined]
custom_init.__doc__ = original_init.__doc__
dct["__init__"] = custom_init
return super().__new__(cls, name, bases, dct)