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,23 @@
from .blur.transforms import *
from .crops.transforms import *
from .dropout.channel_dropout import *
from .dropout.coarse_dropout import *
from .dropout.grid_dropout import *
from .dropout.mask_dropout import *
from .dropout.transforms import *
from .dropout.xy_masking import *
from .geometric.distortion import *
from .geometric.flip import *
from .geometric.pad import *
from .geometric.resize import *
from .geometric.rotate import *
from .geometric.transforms import *
from .mixing.domain_adaptation import *
from .mixing.transforms import *
from .other.lambda_transform import *
from .other.type_transform import *
from .pixel.transforms import *
from .spectrogram.transform import *
from .text.transforms import *
from .transforms3d.transforms import *
from .utils import *
@@ -0,0 +1,438 @@
"""Functional implementations of various blur operations for image processing.
This module provides a collection of low-level functions for applying different blur effects
to images, including standard blur, median blur, glass blur, defocus, and zoom effects.
These functions form the foundation for the corresponding transform classes.
"""
from __future__ import annotations
import random
from collections.abc import Sequence
from itertools import product
from math import ceil
from typing import Literal
from warnings import warn
import cv2
import numpy as np
from albucore import clipped, float32_io, maybe_process_in_chunks, preserve_channel_dim, uint8_io
from pydantic import ValidationInfo
from albumentations.augmentations.geometric.functional import scale
from albumentations.augmentations.pixel.functional import convolve
from albumentations.core.type_definitions import EIGHT
__all__ = ["box_blur", "central_zoom", "defocus", "glass_blur", "median_blur", "zoom_blur"]
@preserve_channel_dim
def box_blur(img: np.ndarray, ksize: int) -> np.ndarray:
"""Blur an image.
This function applies a blur to an image.
Args:
img (np.ndarray): Input image.
ksize (int): Kernel size.
Returns:
np.ndarray: Blurred image.
"""
blur_fn = maybe_process_in_chunks(cv2.blur, ksize=(ksize, ksize))
return blur_fn(img)
@preserve_channel_dim
@uint8_io
def median_blur(img: np.ndarray, ksize: int) -> np.ndarray:
"""Median blur an image.
This function applies a median blur to an image.
Args:
img (np.ndarray): Input image.
ksize (int): Kernel size.
Returns:
np.ndarray: Median blurred image.
"""
blur_fn = maybe_process_in_chunks(cv2.medianBlur, ksize=ksize)
return blur_fn(img)
@preserve_channel_dim
def glass_blur(
img: np.ndarray,
sigma: float,
max_delta: int,
iterations: int,
dxy: np.ndarray,
mode: Literal["fast", "exact"],
) -> np.ndarray:
"""Glass blur an image.
This function applies a glass blur to an image.
Args:
img (np.ndarray): Input image.
sigma (float): Sigma.
max_delta (int): Maximum delta.
iterations (int): Number of iterations.
dxy (np.ndarray): Dxy.
mode (Literal["fast", "exact"]): Mode.
Returns:
np.ndarray: Glass blurred image.
"""
x = cv2.GaussianBlur(np.array(img), sigmaX=sigma, ksize=(0, 0))
if mode == "fast":
hs = np.arange(img.shape[0] - max_delta, max_delta, -1)
ws = np.arange(img.shape[1] - max_delta, max_delta, -1)
h: int | np.ndarray = np.tile(hs, ws.shape[0])
w: int | np.ndarray = np.repeat(ws, hs.shape[0])
for i in range(iterations):
dy = dxy[:, i, 0]
dx = dxy[:, i, 1]
x[h, w], x[h + dy, w + dx] = x[h + dy, w + dx], x[h, w]
elif mode == "exact":
for ind, (i, h, w) in enumerate(
product(
range(iterations),
range(img.shape[0] - max_delta, max_delta, -1),
range(img.shape[1] - max_delta, max_delta, -1),
),
):
idx = ind if ind < len(dxy) else ind % len(dxy)
dy = dxy[idx, i, 0]
dx = dxy[idx, i, 1]
x[h, w], x[h + dy, w + dx] = x[h + dy, w + dx], x[h, w]
else:
raise ValueError(f"Unsupported mode `{mode}`. Supports only `fast` and `exact`.")
return cv2.GaussianBlur(x, sigmaX=sigma, ksize=(0, 0))
def defocus(img: np.ndarray, radius: int, alias_blur: float) -> np.ndarray:
"""Defocus an image.
This function defocuses an image.
Args:
img (np.ndarray): Input image.
radius (int): Radius.
alias_blur (float): Alias blur.
Returns:
np.ndarray: Defocused image.
"""
length = np.arange(-max(8, radius), max(8, radius) + 1)
ksize = 3 if radius <= EIGHT else 5
x, y = np.meshgrid(length, length)
aliased_disk = np.array((x**2 + y**2) <= radius**2, dtype=np.float32)
aliased_disk /= np.sum(aliased_disk)
kernel = cv2.GaussianBlur(aliased_disk, (ksize, ksize), sigmaX=alias_blur)
return convolve(img, kernel=kernel)
def central_zoom(img: np.ndarray, zoom_factor: int) -> np.ndarray:
"""Central zoom an image.
This function zooms an image.
Args:
img (np.ndarray): Input image.
zoom_factor (int): Zoom factor.
Returns:
np.ndarray: Zoomed image.
"""
height, width = img.shape[:2]
h_ch, w_ch = ceil(height / zoom_factor), ceil(width / zoom_factor)
h_top, w_top = (height - h_ch) // 2, (width - w_ch) // 2
img = scale(img[h_top : h_top + h_ch, w_top : w_top + w_ch], zoom_factor, cv2.INTER_LINEAR)
h_trim_top, w_trim_top = (img.shape[0] - height) // 2, (img.shape[1] - width) // 2
return img[h_trim_top : h_trim_top + height, w_trim_top : w_trim_top + width]
@float32_io
@clipped
def zoom_blur(img: np.ndarray, zoom_factors: np.ndarray | Sequence[int]) -> np.ndarray:
"""Zoom blur an image.
This function zooms and blurs an image.
Args:
img (np.ndarray): Input image.
zoom_factors (np.ndarray | Sequence[int]): Zoom factors.
Returns:
np.ndarray: Zoomed and blurred image.
"""
out = np.zeros_like(img, dtype=np.float32)
for zoom_factor in zoom_factors:
out += central_zoom(img, zoom_factor)
return (img + out) / (len(zoom_factors) + 1)
def _ensure_min_value(result: tuple[int, int], min_value: int, field_name: str | None) -> tuple[int, int]:
if result[0] < min_value or result[1] < min_value:
new_result = (max(min_value, result[0]), max(min_value, result[1]))
warn(
f"{field_name}: Invalid kernel size range {result}. "
f"Values less than {min_value} are not allowed. "
f"Range automatically adjusted to {new_result}.",
UserWarning,
stacklevel=2,
)
return new_result
return result
def _ensure_odd_values(result: tuple[int, int], field_name: str | None = None) -> tuple[int, int]:
new_result = (
result[0] if result[0] == 0 or result[0] % 2 == 1 else result[0] + 1,
result[1] if result[1] == 0 or result[1] % 2 == 1 else result[1] + 1,
)
if new_result != result:
warn(
f"{field_name}: Non-zero kernel sizes must be odd. Range {result} automatically adjusted to {new_result}.",
UserWarning,
stacklevel=2,
)
return new_result
def process_blur_limit(value: int | tuple[int, int], info: ValidationInfo, min_value: int = 0) -> tuple[int, int]:
"""Process blur limit to ensure valid kernel sizes."""
# Convert value to tuple[int, int]
if isinstance(value, Sequence):
if len(value) != 2:
raise ValueError("Sequence must contain exactly 2 elements")
result = (int(value[0]), int(value[1]))
else:
result = (min_value, int(value))
result = _ensure_min_value(result, min_value, info.field_name)
result = _ensure_odd_values(result, info.field_name)
if result[0] > result[1]:
final_result = (result[1], result[1])
warn(
f"{info.field_name}: Invalid range {result} (min > max). Range automatically adjusted to {final_result}.",
UserWarning,
stacklevel=2,
)
return final_result
return result
def create_motion_kernel(
kernel_size: int,
angle: float,
direction: float,
allow_shifted: bool,
random_state: random.Random,
) -> np.ndarray:
"""Create a motion blur kernel.
Args:
kernel_size (int): Size of the kernel (must be odd)
angle (float): Angle in degrees (counter-clockwise)
direction (float): Blur direction (-1.0 to 1.0)
allow_shifted (bool): Allow kernel to be randomly shifted from center
random_state (random.Random): Python's random.Random instance
Returns:
np.ndarray: Motion blur kernel
"""
# Validate direction range to prevent unexpected interpolation results
direction = np.clip(direction, -1.0, 1.0)
kernel = np.zeros((kernel_size, kernel_size), dtype=np.float32)
center = kernel_size // 2
# Convert angle to radians
angle_rad = np.deg2rad(angle)
# Calculate direction vector
dx = np.cos(angle_rad)
dy = np.sin(angle_rad)
# Create line points with direction bias
line_length = kernel_size // 2
# Apply direction bias to control the distribution of blur
if direction < 0:
# Backward bias: interpolate between symmetric and backward-only
# direction = -1: only backward, direction = 0: symmetric
bias_factor = abs(direction)
t_start = float(-line_length)
t_end = line_length * (1 - bias_factor)
elif direction > 0:
# Forward bias: interpolate between symmetric and forward-only
# direction = 1: only forward, direction = 0: symmetric
bias_factor = direction
t_start = -line_length * (1 - bias_factor)
t_end = float(line_length)
else:
# Symmetric case (direction = 0)
t_start = float(-line_length)
t_end = float(line_length)
# Generate points along the biased line
t = np.linspace(t_start, t_end, kernel_size)
# Generate line coordinates
x = center + dx * t
y = center + dy * t
# Apply random shift if allowed
if allow_shifted:
shift_x = random_state.uniform(-1, 1) * line_length / 2
shift_y = random_state.uniform(-1, 1) * line_length / 2
x += shift_x
y += shift_y
# Round coordinates and clip to kernel bounds
x = np.clip(np.round(x), 0, kernel_size - 1).astype(int)
y = np.clip(np.round(y), 0, kernel_size - 1).astype(int)
# Keep only unique points to avoid multiple assignments
points = np.unique(np.column_stack([y, x]), axis=0)
kernel[points[:, 0], points[:, 1]] = 1
# Ensure at least one point is set
if not kernel.any():
kernel[center, center] = 1
return kernel
def sample_odd_from_range(random_state: random.Random, low: int, high: int) -> int:
"""Sample an odd number from the range [low, high] (inclusive).
Args:
random_state (random.Random): instance of random.Random
low (int): lower bound (will be converted to nearest valid odd number)
high (int): upper bound (will be converted to nearest valid odd number)
Returns:
int: Randomly sampled odd number from the range
Note:
- Input values will be converted to nearest valid odd numbers:
* Values less than 3 will become 3
* Even values will be rounded up to next odd number
- After normalization, high must be >= low
"""
# Normalize low value
low = max(3, low + (low % 2 == 0))
# Normalize high value
high = max(3, high + (high % 2 == 0))
# Ensure high >= low after normalization
high = max(high, low)
if low == high:
return low
# Calculate number of possible odd values
num_odd_values = (high - low) // 2 + 1
# Generate random index and convert to corresponding odd number
rand_idx = random_state.randint(0, num_odd_values - 1)
return low + (2 * rand_idx)
def create_gaussian_kernel(sigma: float, ksize: int = 0) -> np.ndarray:
"""Create a Gaussian kernel following PIL's approach.
Args:
sigma (float): Standard deviation for Gaussian kernel.
ksize (int): Kernel size. If 0, size is computed as int(sigma * 3.5) * 2 + 1
to match PIL's implementation. Otherwise, must be positive and odd.
Returns:
np.ndarray: 2D normalized Gaussian kernel.
"""
# PIL's kernel creation approach
size = int(sigma * 3.5) * 2 + 1 if ksize == 0 else ksize
# Ensure odd size
size = size + 1 if size % 2 == 0 else size
# Create x coordinates
x = np.linspace(-(size // 2), size // 2, size)
# Compute 1D kernel using vectorized operations
kernel_1d = np.exp(-0.5 * (x / sigma) ** 2)
kernel_1d = kernel_1d / kernel_1d.sum()
# Create 2D kernel
return kernel_1d[:, np.newaxis] @ kernel_1d[np.newaxis, :]
def create_gaussian_kernel_1d(sigma: float, ksize: int = 0) -> np.ndarray:
"""Create a 1D Gaussian kernel following PIL's approach.
Args:
sigma (float): Standard deviation for Gaussian kernel.
ksize (int): Kernel size. If 0, size is computed as int(sigma * 3.5) * 2 + 1
to match PIL's implementation. Otherwise, must be positive and odd.
Returns:
np.ndarray: 1D normalized Gaussian kernel.
"""
# PIL's kernel creation approach
size = int(sigma * 3.5) * 2 + 1 if ksize == 0 else ksize
# Ensure odd size
size = size + 1 if size % 2 == 0 else size
# Create x coordinates
x = create_gaussian_kernel_input_array(size=size)
# Compute 1D kernel using vectorized operations
kernel_1d = np.exp(-0.5 * (x / sigma) ** 2)
return kernel_1d / kernel_1d.sum()
def create_gaussian_kernel_input_array(size: int) -> np.ndarray:
"""Creates a 1-D array which will create an array of x-coordinates which will be input for the
gaussian function (values from -size/2 to size/2 with step size of 1)
Piecewise function is needed as equivalent python list comprehension is faster than np.linspace
for values of size < 100
Args:
size (int): kernel size
Returns:
np.ndarray: x-coordinate array which will be input for gaussian function that will be used for
separable gaussian blur
"""
if size < 100:
return np.array(list(range(-(size // 2), (size // 2) + 1, 1)))
return np.linspace(-(size // 2), size // 2, size)
@@ -0,0 +1,494 @@
"""Functional implementations of image cropping operations.
This module provides utility functions for performing various cropping operations on images,
bounding boxes, and keypoints. It includes functions to calculate crop coordinates, crop images,
and handle the corresponding transformations for bounding boxes and keypoints to maintain
consistency between different data types during cropping operations.
"""
from __future__ import annotations
from collections.abc import Sequence
from typing import Any
import cv2
import numpy as np
from albucore import maybe_process_in_chunks, preserve_channel_dim
from albumentations.augmentations.geometric import functional as fgeometric
from albumentations.augmentations.utils import handle_empty_array
from albumentations.core.bbox_utils import denormalize_bboxes, normalize_bboxes
__all__ = [
"crop",
"crop_and_pad",
"crop_and_pad_bboxes",
"crop_and_pad_keypoints",
"crop_bboxes_by_coords",
"crop_keypoints_by_coords",
"get_center_crop_coords",
"get_crop_coords",
"pad_along_axes",
"volume_crop_yx",
"volumes_crop_yx",
]
def get_crop_coords(
image_shape: tuple[int, int],
crop_shape: tuple[int, int],
h_start: float,
w_start: float,
) -> tuple[int, int, int, int]:
"""Get crop coordinates.
This function gets the crop coordinates.
Args:
image_shape (tuple[int, int]): Original image shape.
crop_shape (tuple[int, int]): Crop shape.
h_start (float): Start height.
w_start (float): Start width.
Returns:
tuple[int, int, int, int]: Crop coordinates.
"""
# h_start is [0, 1) and should map to [0, (height - crop_height)] (note inclusive)
# This is conceptually equivalent to mapping onto `range(0, (height - crop_height + 1))`
# See: https://github.com/albumentations-team/albumentations/pull/1080
# We want range for coordinated to be [0, image_size], right side is included
height, width = image_shape[:2]
# Clip crop dimensions to image dimensions
crop_height = min(crop_shape[0], height)
crop_width = min(crop_shape[1], width)
y_min = int((height - crop_height + 1) * h_start)
y_max = y_min + crop_height
x_min = int((width - crop_width + 1) * w_start)
x_max = x_min + crop_width
return x_min, y_min, x_max, y_max
def crop_bboxes_by_coords(
bboxes: np.ndarray,
crop_coords: tuple[int, int, int, int],
image_shape: tuple[int, int],
normalized_input: bool = True,
) -> np.ndarray:
"""Crop bounding boxes based on given crop coordinates.
This function adjusts bounding boxes to fit within a cropped image.
Args:
bboxes (np.ndarray): Array of bounding boxes with shape (N, 4+) where each row is
[x_min, y_min, x_max, y_max, ...]. The bounding box coordinates
can be either normalized (in [0, 1]) if normalized_input=True or
absolute pixel values if normalized_input=False.
crop_coords (tuple[int, int, int, int]): Crop coordinates (x_min, y_min, x_max, y_max)
in absolute pixel values.
image_shape (tuple[int, int]): Original image shape (height, width).
normalized_input (bool): Whether input boxes are in normalized coordinates.
If True, assumes input is normalized [0,1] and returns normalized coordinates.
If False, assumes input is in absolute pixels and returns absolute coordinates.
Default: True for backward compatibility.
Returns:
np.ndarray: Array of cropped bounding boxes. Coordinates will be in the same format as input
(normalized if normalized_input=True, absolute pixels if normalized_input=False).
Note:
Bounding boxes that fall completely outside the crop area will be removed.
Bounding boxes that partially overlap with the crop area will be adjusted to fit within it.
"""
if not bboxes.size:
return bboxes
# Convert to absolute coordinates if needed
if normalized_input:
cropped_bboxes = denormalize_bboxes(bboxes.copy().astype(np.float32), image_shape)
else:
cropped_bboxes = bboxes.copy().astype(np.float32)
x_min, y_min = crop_coords[:2]
# Subtract crop coordinates
cropped_bboxes[:, [0, 2]] -= x_min
cropped_bboxes[:, [1, 3]] -= y_min
# Calculate crop shape
crop_height = crop_coords[3] - crop_coords[1]
crop_width = crop_coords[2] - crop_coords[0]
crop_shape = (crop_height, crop_width)
# Return in same format as input
return normalize_bboxes(cropped_bboxes, crop_shape) if normalized_input else cropped_bboxes
@handle_empty_array("keypoints")
def crop_keypoints_by_coords(
keypoints: np.ndarray,
crop_coords: tuple[int, int, int, int],
) -> np.ndarray:
"""Crop keypoints using the provided coordinates of bottom-left and top-right corners in pixels.
Args:
keypoints (np.ndarray): An array of keypoints with shape (N, 4+) where each row is (x, y, angle, scale, ...).
crop_coords (tuple): Crop box coords (x1, y1, x2, y2).
Returns:
np.ndarray: An array of cropped keypoints with the same shape as the input.
"""
x1, y1 = crop_coords[:2]
cropped_keypoints = keypoints.copy()
cropped_keypoints[:, 0] -= x1 # Adjust x coordinates
cropped_keypoints[:, 1] -= y1 # Adjust y coordinates
return cropped_keypoints
def get_center_crop_coords(image_shape: tuple[int, int], crop_shape: tuple[int, int]) -> tuple[int, int, int, int]:
"""Get center crop coordinates.
This function gets the center crop coordinates.
Args:
image_shape (tuple[int, int]): Original image shape.
crop_shape (tuple[int, int]): Crop shape.
Returns:
tuple[int, int, int, int]: Center crop coordinates.
"""
height, width = image_shape[:2]
crop_height, crop_width = crop_shape[:2]
y_min = (height - crop_height) // 2
y_max = y_min + crop_height
x_min = (width - crop_width) // 2
x_max = x_min + crop_width
return x_min, y_min, x_max, y_max
def crop(img: np.ndarray, x_min: int, y_min: int, x_max: int, y_max: int) -> np.ndarray:
"""Crop an image.
This function crops an image.
Args:
img (np.ndarray): Input image.
x_min (int): Minimum x coordinate.
y_min (int): Minimum y coordinate.
x_max (int): Maximum x coordinate.
y_max (int): Maximum y coordinate.
Returns:
np.ndarray: Cropped image.
"""
height, width = img.shape[:2]
if x_max <= x_min or y_max <= y_min:
raise ValueError(
"We should have x_min < x_max and y_min < y_max. But we got"
f" (x_min = {x_min}, y_min = {y_min}, x_max = {x_max}, y_max = {y_max})",
)
if x_min < 0 or x_max > width or y_min < 0 or y_max > height:
raise ValueError(
"Values for crop should be non negative and equal or smaller than image sizes"
f"(x_min = {x_min}, y_min = {y_min}, x_max = {x_max}, y_max = {y_max}, "
f"height = {height}, width = {width})",
)
return img[y_min:y_max, x_min:x_max]
@preserve_channel_dim
def crop_and_pad(
img: np.ndarray,
crop_params: tuple[int, int, int, int] | None,
pad_params: tuple[int, int, int, int] | None,
pad_value: tuple[float, ...] | float | None,
image_shape: tuple[int, int],
interpolation: int,
pad_mode: int,
keep_size: bool,
) -> np.ndarray:
"""Crop and pad an image.
This function crops and pads an image.
Args:
img (np.ndarray): Input image.
crop_params (tuple[int, int, int, int] | None): Crop parameters.
pad_params (tuple[int, int, int, int] | None): Pad parameters.
pad_value (tuple[float, ...] | float | None): Pad value.
image_shape (tuple[int, int]): Original image shape.
interpolation (int): Interpolation method.
pad_mode (int): Pad mode.
keep_size (bool): Whether to keep the original size.
Returns:
np.ndarray: Cropped and padded image.
"""
if crop_params is not None and any(i != 0 for i in crop_params):
img = crop(img, *crop_params)
if pad_params is not None and any(i != 0 for i in pad_params):
img = fgeometric.pad_with_params(
img,
pad_params[0],
pad_params[1],
pad_params[2],
pad_params[3],
border_mode=pad_mode,
value=pad_value,
)
if keep_size:
rows, cols = image_shape[:2]
resize_fn = maybe_process_in_chunks(cv2.resize, dsize=(cols, rows), interpolation=interpolation)
return resize_fn(img)
return img
def crop_and_pad_bboxes(
bboxes: np.ndarray,
crop_params: tuple[int, int, int, int] | None,
pad_params: tuple[int, int, int, int] | None,
image_shape: tuple[int, int],
result_shape: tuple[int, int],
) -> np.ndarray:
"""Crop and pad bounding boxes.
This function crops and pads bounding boxes.
Args:
bboxes (np.ndarray): Array of bounding boxes.
crop_params (tuple[int, int, int, int] | None): Crop parameters.
pad_params (tuple[int, int, int, int] | None): Pad parameters.
image_shape (tuple[int, int]): Original image shape.
result_shape (tuple[int, int]): Result image shape.
Returns:
np.ndarray: Array of cropped and padded bounding boxes.
"""
if len(bboxes) == 0:
return bboxes
# Denormalize bboxes
denormalized_bboxes = denormalize_bboxes(bboxes, image_shape)
if crop_params is not None:
crop_x, crop_y = crop_params[:2]
# Subtract crop values from x and y coordinates
denormalized_bboxes[:, [0, 2]] -= crop_x
denormalized_bboxes[:, [1, 3]] -= crop_y
if pad_params is not None:
top, _, left, _ = pad_params
# Add pad values to x and y coordinates
denormalized_bboxes[:, [0, 2]] += left
denormalized_bboxes[:, [1, 3]] += top
# Normalize bboxes to the result shape
return normalize_bboxes(denormalized_bboxes, result_shape)
@handle_empty_array("keypoints")
def crop_and_pad_keypoints(
keypoints: np.ndarray,
crop_params: tuple[int, int, int, int] | None = None,
pad_params: tuple[int, int, int, int] | None = None,
image_shape: tuple[int, int] = (0, 0),
result_shape: tuple[int, int] = (0, 0),
keep_size: bool = False,
) -> np.ndarray:
"""Crop and pad multiple keypoints simultaneously.
Args:
keypoints (np.ndarray): Array of keypoints with shape (N, 4+) where each row is (x, y, angle, scale, ...).
crop_params (Sequence[int], optional): Crop parameters [crop_x1, crop_y1, ...].
pad_params (Sequence[int], optional): Pad parameters [top, bottom, left, right].
image_shape (Tuple[int, int]): Original image shape (rows, cols).
result_shape (Tuple[int, int]): Result image shape (rows, cols).
keep_size (bool): Whether to keep the original size.
Returns:
np.ndarray: Array of transformed keypoints with the same shape as input.
"""
transformed_keypoints = keypoints.copy()
if crop_params is not None:
crop_x1, crop_y1 = crop_params[:2]
transformed_keypoints[:, 0] -= crop_x1
transformed_keypoints[:, 1] -= crop_y1
if pad_params is not None:
top, _, left, _ = pad_params
transformed_keypoints[:, 0] += left
transformed_keypoints[:, 1] += top
rows, cols = image_shape[:2]
result_rows, result_cols = result_shape[:2]
if keep_size and (result_cols != cols or result_rows != rows):
scale_x = cols / result_cols
scale_y = rows / result_rows
return fgeometric.keypoints_scale(transformed_keypoints, scale_x, scale_y)
return transformed_keypoints
def volume_crop_yx(
volume: np.ndarray,
x_min: int,
y_min: int,
x_max: int,
y_max: int,
) -> np.ndarray:
"""Crop a single volume along Y (height) and X (width) axes only.
Args:
volume (np.ndarray): Input volume with shape (D, H, W) or (D, H, W, C).
x_min (int): Minimum width coordinate.
y_min (int): Minimum height coordinate.
x_max (int): Maximum width coordinate.
y_max (int): Maximum height coordinate.
Returns:
np.ndarray: Cropped volume (D, H_new, W_new, [C]).
Raises:
ValueError: If crop coordinates are invalid.
"""
_, height, width = volume.shape[:3]
if x_max <= x_min or y_max <= y_min:
raise ValueError(
"Crop coordinates must satisfy min < max. Got: "
f"(x_min={x_min}, y_min={y_min}, x_max={x_max}, y_max={y_max})",
)
if x_min < 0 or y_min < 0 or x_max > width or y_max > height:
raise ValueError(
"Crop coordinates must be within image dimensions (H, W). Got: "
f"(x_min={x_min}, y_min={y_min}, x_max={x_max}, y_max={y_max}) "
f"for volume shape {volume.shape[:3]}",
)
# Crop along H (axis 1) and W (axis 2)
return volume[:, y_min:y_max, x_min:x_max]
def volumes_crop_yx(
volumes: np.ndarray,
x_min: int,
y_min: int,
x_max: int,
y_max: int,
) -> np.ndarray:
"""Crop a batch of volumes along Y (height) and X (width) axes only.
Args:
volumes (np.ndarray): Input batch of volumes with shape (B, D, H, W) or (B, D, H, W, C).
x_min (int): Minimum width coordinate.
y_min (int): Minimum height coordinate.
x_max (int): Maximum width coordinate.
y_max (int): Maximum height coordinate.
Returns:
np.ndarray: Cropped batch of volumes (B, D, H_new, W_new, [C]).
Raises:
ValueError: If crop coordinates are invalid or volumes shape is incorrect.
"""
if not 4 <= volumes.ndim <= 5:
raise ValueError(f"Input volumes should have 4 or 5 dimensions, got {volumes.ndim}")
depth, height, width = volumes.shape[1:4]
if x_max <= x_min or y_max <= y_min:
raise ValueError(
"Crop coordinates must satisfy min < max. Got: "
f"(x_min={x_min}, y_min={y_min}, x_max={x_max}, y_max={y_max})",
)
if x_min < 0 or y_min < 0 or x_max > width or y_max > height:
raise ValueError(
"Crop coordinates must be within image dimensions (H, W). Got: "
f"(x_min={x_min}, y_min={y_min}, x_max={x_max}, y_max={y_max}) "
f"for volume shape {(depth, height, width)}",
)
# Crop along H (axis 2) and W (axis 3)
return volumes[:, :, y_min:y_max, x_min:x_max]
def pad_along_axes(
arr: np.ndarray,
pad_top: int,
pad_bottom: int,
pad_left: int,
pad_right: int,
h_axis: int,
w_axis: int,
border_mode: int,
pad_value: float | Sequence[float] = 0,
) -> np.ndarray:
"""Pad an array along specified height (H) and width (W) axes using np.pad.
Args:
arr (np.ndarray): Input array.
pad_top (int): Padding added to the top (start of H axis).
pad_bottom (int): Padding added to the bottom (end of H axis).
pad_left (int): Padding added to the left (start of W axis).
pad_right (int): Padding added to the right (end of W axis).
h_axis (int): Index of the height axis (Y).
w_axis (int): Index of the width axis (X).
border_mode (int): OpenCV border mode.
pad_value (float | Sequence[float]): Value for constant padding.
Returns:
np.ndarray: Padded array.
Raises:
ValueError: If border_mode is unsupported or axis indices are out of bounds.
"""
ndim = arr.ndim
if not (0 <= h_axis < ndim and 0 <= w_axis < ndim):
raise ValueError(f"Axis indices {h_axis}, {w_axis} are out of bounds for array with {ndim} dimensions.")
if h_axis == w_axis:
raise ValueError(f"Height axis {h_axis} and width axis {w_axis} cannot be the same.")
mode_map = {
cv2.BORDER_CONSTANT: "constant",
cv2.BORDER_REPLICATE: "edge",
cv2.BORDER_REFLECT: "reflect",
cv2.BORDER_REFLECT_101: "symmetric",
cv2.BORDER_WRAP: "wrap",
}
if border_mode not in mode_map:
raise ValueError(f"Unsupported border_mode: {border_mode}")
np_mode = mode_map[border_mode]
pad_width = [(0, 0)] * ndim # Initialize padding for all dimensions
pad_width[h_axis] = (pad_top, pad_bottom)
pad_width[w_axis] = (pad_left, pad_right)
# Initialize kwargs with mode
kwargs: dict[str, Any] = {"mode": np_mode}
# Add constant_values only if mode is constant
if np_mode == "constant":
kwargs["constant_values"] = pad_value
return np.pad(arr, pad_width, **kwargs)
@@ -0,0 +1,134 @@
"""Implementation of the Channel Dropout transform for multi-channel images.
This module provides the ChannelDropout transform, which randomly drops (sets to a fill value)
one or more channels in multi-channel images. This augmentation can help models become more
robust to missing or corrupted channel information and encourage learning from all available
channels rather than relying on a subset.
"""
from __future__ import annotations
from typing import Annotated, Any
import numpy as np
from albucore import get_num_channels
from pydantic import AfterValidator
from albumentations.core.pydantic import check_range_bounds
from albumentations.core.transforms_interface import BaseTransformInitSchema, ImageOnlyTransform
from .functional import channel_dropout
__all__ = ["ChannelDropout"]
MIN_DROPOUT_CHANNEL_LIST_LENGTH = 2
class ChannelDropout(ImageOnlyTransform):
"""Randomly drop channels in the input image.
This transform randomly selects a number of channels to drop from the input image
and replaces them with a specified fill value. This can improve model robustness
to missing or corrupted channels.
The technique is conceptually similar to:
- Dropout layers in neural networks, which randomly set input units to 0 during training.
- CoarseDropout augmentation, which drops out regions in the spatial dimensions of the image.
However, ChannelDropout operates on the channel dimension, effectively "dropping out"
entire color channels or feature maps.
Args:
channel_drop_range (tuple[int, int]): Range from which to choose the number
of channels to drop. The actual number will be randomly selected from
the inclusive range [min, max]. Default: (1, 1).
fill (float): Pixel value used to fill the dropped channels.
Default: 0.
p (float): Probability of applying the transform. Must be in the range
[0, 1]. Default: 0.5.
Raises:
NotImplementedError: If the input image has only one channel.
ValueError: If the upper bound of channel_drop_range is greater than or
equal to the number of channels in the input image.
Targets:
image, volume
Image types:
uint8, float32
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> transform = A.ChannelDropout(channel_drop_range=(1, 2), fill=128, p=1.0)
>>> result = transform(image=image)
>>> dropped_image = result['image']
>>> assert dropped_image.shape == image.shape
>>> assert np.any(dropped_image != image) # Some channels should be different
Note:
- The number of channels to drop is randomly chosen within the specified range.
- Channels are randomly selected for dropping.
- This transform is not applicable to single-channel (grayscale) images.
- The transform will raise an error if it's not possible to drop the specified
number of channels (e.g., trying to drop 3 channels from an RGB image).
- This augmentation can be particularly useful for training models to be robust
against missing or corrupted channel data in multi-spectral or hyperspectral imagery.
"""
class InitSchema(BaseTransformInitSchema):
channel_drop_range: Annotated[tuple[int, int], AfterValidator(check_range_bounds(1, None))]
fill: float
def __init__(
self,
channel_drop_range: tuple[int, int] = (1, 1),
fill: float = 0,
p: float = 0.5,
):
super().__init__(p=p)
self.channel_drop_range = channel_drop_range
self.fill = fill
def apply(self, img: np.ndarray, channels_to_drop: list[int], **params: Any) -> np.ndarray:
"""Apply channel dropout to the image.
Args:
img (np.ndarray): Image to apply channel dropout to.
channels_to_drop (list[int]): List of channel indices to drop.
**params (Any): Additional parameters.
Returns:
np.ndarray: Image with dropped channels.
"""
return channel_dropout(img, channels_to_drop, self.fill)
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, list[int]]:
"""Get parameters that depend on input data.
Args:
params (dict[str, Any]): Parameters.
data (dict[str, Any]): Input data.
Returns:
dict[str, list[int]]: Dictionary with channels to drop.
"""
image = data["image"] if "image" in data else data["images"][0]
num_channels = get_num_channels(image)
if num_channels == 1:
msg = "Images has one channel. ChannelDropout is not defined."
raise NotImplementedError(msg)
if self.channel_drop_range[1] >= num_channels:
msg = "Can not drop all channels in ChannelDropout."
raise ValueError(msg)
num_drop_channels = self.py_random.randint(*self.channel_drop_range)
channels_to_drop = self.py_random.sample(range(num_channels), k=num_drop_channels)
return {"channels_to_drop": channels_to_drop}
@@ -0,0 +1,567 @@
"""Implementation of coarse dropout and random erasing augmentations.
This module provides several variations of coarse dropout augmentations, which drop out
rectangular regions from images. It includes CoarseDropout for randomly placed dropouts,
ConstrainedCoarseDropout for dropping out regions based on masks or bounding boxes,
and Erasing for random erasing augmentation. These techniques help models become more
robust to occlusions and varying object completeness.
"""
from __future__ import annotations
from typing import Annotated, Any, Literal
from warnings import warn
import numpy as np
from pydantic import AfterValidator
import albumentations.augmentations.dropout.functional as fdropout
from albumentations.augmentations.dropout.transforms import BaseDropout
from albumentations.core.bbox_utils import denormalize_bboxes
from albumentations.core.pydantic import check_range_bounds, nondecreasing
__all__ = ["CoarseDropout", "ConstrainedCoarseDropout", "Erasing"]
class CoarseDropout(BaseDropout):
"""CoarseDropout randomly drops out rectangular regions from the image and optionally,
the corresponding regions in an associated mask, to simulate occlusion and
varied object sizes found in real-world settings.
This transformation is an evolution of CutOut and RandomErasing, offering more
flexibility in the size, number of dropout regions, and fill values.
Args:
num_holes_range (tuple[int, int]): Range (min, max) for the number of rectangular
regions to drop out. Default: (1, 1)
hole_height_range (tuple[int, int] | tuple[float, float]): Range (min, max) for the height
of dropout regions. If int, specifies absolute pixel values. If float,
interpreted as a fraction of the image height. Default: (0.1, 0.2)
hole_width_range (tuple[int, int] | tuple[float, float]): Range (min, max) for the width
of dropout regions. If int, specifies absolute pixel values. If float,
interpreted as a fraction of the image width. Default: (0.1, 0.2)
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value for the dropped pixels. Can be:
- int or float: all channels are filled with this value
- tuple: tuple of values for each channel
- 'random': each pixel is filled with random values
- 'random_uniform': each hole is filled with a single random color
- 'inpaint_telea': uses OpenCV Telea inpainting method
- 'inpaint_ns': uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Fill value for dropout regions in the mask.
If None, mask regions corresponding to image dropouts are unchanged. Default: None
p (float): Probability of applying the transform. Default: 0.5
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The actual number and size of dropout regions are randomly chosen within the specified ranges for each
application.
- When using float values for hole_height_range and hole_width_range, ensure they are between 0 and 1.
- This implementation includes deprecation warnings for older parameter names (min_holes, max_holes, etc.).
- Inpainting methods ('inpaint_telea', 'inpaint_ns') work only with grayscale or RGB images.
- For 'random_uniform' fill, each hole gets a single random color, unlike 'random' where each pixel
gets its own random value.
Example:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> # Example with random uniform fill
>>> aug_random = A.CoarseDropout(
... num_holes_range=(3, 6),
... hole_height_range=(10, 20),
... hole_width_range=(10, 20),
... fill="random_uniform",
... p=1.0
... )
>>> # Example with inpainting
>>> aug_inpaint = A.CoarseDropout(
... num_holes_range=(3, 6),
... hole_height_range=(10, 20),
... hole_width_range=(10, 20),
... fill="inpaint_ns",
... p=1.0
... )
>>> transformed = aug_random(image=image, mask=mask)
>>> transformed_image, transformed_mask = transformed["image"], transformed["mask"]
References:
- CutOut: https://arxiv.org/abs/1708.04552
- Random Erasing: https://arxiv.org/abs/1708.04896
- OpenCV Inpainting methods: https://docs.opencv.org/master/df/d3d/tutorial_py_inpainting.html
"""
class InitSchema(BaseDropout.InitSchema):
num_holes_range: Annotated[
tuple[int, int],
AfterValidator(check_range_bounds(1, None)),
AfterValidator(nondecreasing),
]
hole_height_range: Annotated[
tuple[float, float] | tuple[int, int],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, None)),
]
hole_width_range: Annotated[
tuple[float, float] | tuple[int, int],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, None)),
]
def __init__(
self,
num_holes_range: tuple[int, int] = (1, 2),
hole_height_range: tuple[float, float] | tuple[int, int] = (0.1, 0.2),
hole_width_range: tuple[float, float] | tuple[int, int] = (0.1, 0.2),
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(fill=fill, fill_mask=fill_mask, p=p)
self.num_holes_range = num_holes_range
self.hole_height_range = hole_height_range
self.hole_width_range = hole_width_range
def calculate_hole_dimensions(
self,
image_shape: tuple[int, int],
height_range: tuple[float, float] | tuple[int, int],
width_range: tuple[float, float] | tuple[int, int],
size: int,
) -> tuple[np.ndarray, np.ndarray]:
"""Calculate random hole dimensions based on the provided ranges."""
height, width = image_shape[:2]
if height_range[1] >= 1:
min_height = height_range[0]
max_height = min(height_range[1], height)
min_width = width_range[0]
max_width = min(width_range[1], width)
hole_heights = self.random_generator.integers(int(min_height), int(max_height + 1), size=size)
hole_widths = self.random_generator.integers(int(min_width), int(max_width + 1), size=size)
else: # Assume float
hole_heights = (height * self.random_generator.uniform(*height_range, size=size)).astype(int)
hole_widths = (width * self.random_generator.uniform(*width_range, size=size)).astype(int)
return hole_heights, hole_widths
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, Any]: Dictionary with parameters for transformation.
"""
image_shape = params["shape"][:2]
num_holes = self.py_random.randint(*self.num_holes_range)
hole_heights, hole_widths = self.calculate_hole_dimensions(
image_shape,
self.hole_height_range,
self.hole_width_range,
size=num_holes,
)
height, width = image_shape[:2]
y_min = self.random_generator.integers(0, height - hole_heights + 1, size=num_holes)
x_min = self.random_generator.integers(0, width - hole_widths + 1, size=num_holes)
y_max = y_min + hole_heights
x_max = x_min + hole_widths
holes = np.stack([x_min, y_min, x_max, y_max], axis=-1)
return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
class Erasing(BaseDropout):
"""Randomly erases rectangular regions in an image, following the Random Erasing Data Augmentation technique.
This augmentation helps improve model robustness by randomly masking out rectangular regions in the image,
simulating occlusions and encouraging the model to learn from partial information. It's particularly
effective for image classification and person re-identification tasks.
Args:
scale (tuple[float, float]): Range for the proportion of image area to erase.
The actual area will be randomly sampled from (scale[0] * image_area, scale[1] * image_area).
Default: (0.02, 0.33)
ratio (tuple[float, float]): Range for the aspect ratio (width/height) of the erased region.
The actual ratio will be randomly sampled from (ratio[0], ratio[1]).
Default: (0.3, 3.3)
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value used to fill the erased regions. Can be:
- int or float: fills all channels with this value
- tuple: fills each channel with corresponding value
- "random": fills each pixel with random values
- "random_uniform": fills entire erased region with a single random color
- "inpaint_telea": uses OpenCV Telea inpainting method
- "inpaint_ns": uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Value used to fill erased regions in the mask.
If None, mask regions are not modified. Default: None
p (float): Probability of applying the transform. Default: 0.5
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The transform attempts to find valid erasing parameters up to 10 times.
If unsuccessful, no erasing is performed.
- The actual erased area and aspect ratio are randomly sampled within
the specified ranges for each application.
- When using inpainting methods, only grayscale or RGB images are supported.
Example:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> # Basic usage with default parameters
>>> transform = A.Erasing()
>>> transformed = transform(image=image)
>>> # Custom configuration
>>> transform = A.Erasing(
... scale=(0.1, 0.4),
... ratio=(0.5, 2.0),
... fill_value="random_uniform",
... p=1.0
... )
>>> transformed = transform(image=image)
References:
- Paper: https://arxiv.org/abs/1708.04896
- Implementation inspired by torchvision:
https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.RandomErasing
"""
class InitSchema(BaseDropout.InitSchema):
scale: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, None)),
]
ratio: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, None)),
]
def __init__(
self,
scale: tuple[float, float] = (0.02, 0.33),
ratio: tuple[float, float] = (0.3, 3.3),
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(fill=fill, fill_mask=fill_mask, p=p)
self.scale = scale
self.ratio = ratio
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Calculate erasing parameters using direct mathematical derivation.
Given:
- Image dimensions (H, W)
- Target area (A)
- Aspect ratio (r = w/h)
We know:
- h * w = A (area equation)
- w = r * h (aspect ratio equation)
Therefore:
- h * (r * h) = A
- h² = A/r
- h = sqrt(A/r)
- w = r * sqrt(A/r) = sqrt(A*r)
"""
height, width = params["shape"][:2]
total_area = height * width
# Calculate maximum valid area based on dimensions and aspect ratio
max_area = total_area * self.scale[1]
min_area = total_area * self.scale[0]
# For each aspect ratio r, the maximum area is constrained by:
# h = sqrt(A/r) ≤ H and w = sqrt(A*r) ≤ W
# Therefore: A ≤ min(r*H², W²/r)
r_min, r_max = self.ratio
def area_constraint_h(r: float) -> float:
return r * height * height
def area_constraint_w(r: float) -> float:
return width * width / r
# Find maximum valid area considering aspect ratio constraints
max_area_h = min(area_constraint_h(r_min), area_constraint_h(r_max))
max_area_w = min(area_constraint_w(r_min), area_constraint_w(r_max))
max_valid_area = min(max_area, max_area_h, max_area_w)
if max_valid_area < min_area:
return {"holes": np.array([], dtype=np.int32).reshape((0, 4))}
# Sample valid area and aspect ratio
erase_area = self.py_random.uniform(min_area, max_valid_area)
# Calculate valid aspect ratio range for this area
max_r = min(r_max, width * width / erase_area)
min_r = max(r_min, erase_area / (height * height))
if min_r > max_r:
return {"holes": np.array([], dtype=np.int32).reshape((0, 4))}
aspect_ratio = self.py_random.uniform(min_r, max_r)
# Calculate dimensions
h = round(np.sqrt(erase_area / aspect_ratio))
w = round(np.sqrt(erase_area * aspect_ratio))
# Sample position
top = self.py_random.randint(0, height - h)
left = self.py_random.randint(0, width - w)
holes = np.array([[left, top, left + w, top + h]], dtype=np.int32)
return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
class ConstrainedCoarseDropout(BaseDropout):
"""Applies coarse dropout to regions containing specific objects in the image.
This augmentation creates holes (dropout regions) for each target object in the image.
Objects can be specified either by their class indices in a segmentation mask or
by their labels in bounding box annotations.
The hole generation differs between mask and box modes:
Mask mode:
1. For each connected component in the mask matching target indices:
- Samples N points randomly from within the object region (with replacement)
- Creates holes centered at these points
- Hole sizes are proportional to sqrt(component area), not total object area
- Each component's holes are sized based on its own area
Box mode:
1. For each bounding box matching target labels:
- Creates N holes with random positions inside the box
- Hole sizes are proportional to the box dimensions
In both modes:
- N is sampled once from num_holes_range and used for all objects
- For example, if num_holes_range=(2,4) and 3 is sampled:
* With 3 target objects, you'll get exactly 3 holes per object (9 total)
* Holes may overlap within or between objects
* All holes are clipped to image boundaries
Args:
num_holes_range (tuple[int, int]): Range for number of holes per object (min, max)
hole_height_range (tuple[float, float]): Range for hole height as proportion
of object height/size (min, max). E.g., (0.2, 0.4) means:
- For boxes: 20-40% of box height
- For masks: 20-40% of sqrt(component area)
hole_width_range (tuple[float, float]): Range for hole width, similar to height
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value used to fill the erased regions. Can be:
- int or float: fills all channels with this value
- tuple: fills each channel with corresponding value
- "random": fills each pixel with random values
- "random_uniform": fills entire erased region with a single random color
- "inpaint_telea": uses OpenCV Telea inpainting method
- "inpaint_ns": uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Value used to fill erased regions in the mask.
If None, mask regions are not modified. Default: None
p (float): Probability of applying the transform
mask_indices (List[int], optional): List of class indices in segmentation mask to target.
Only objects of these classes will be considered for hole placement.
bbox_labels (List[str | int | float], optional): List of object labels in bbox
annotations to target. String labels will be automatically encoded.
When multiple label fields are specified in BboxParams, only the first
label field is used for filtering.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Requires one of:
- 'mask' key with segmentation mask where:
* 0 represents background
* Non-zero values represent different object instances/classes
* Values must correspond to mask_indices
- 'bboxes' key with bounding boxes in format [x_min, y_min, x_max, y_max, label, ...]
Note:
At least one of mask_indices or bbox_labels must be provided.
If both are provided, mask_indices takes precedence.
Examples:
>>> # Using segmentation mask
>>> transform = ConstrainedCoarseDropout(
... num_holes_range=(2, 4), # 2-4 holes per object
... hole_height_range=(0.2, 0.4), # 20-40% of sqrt(object area)
... hole_width_range=(0.2, 0.4), # 20-40% of sqrt(object area)
... mask_indices=[1, 2], # Target objects of class 1 and 2
... fill=0, # Fill holes with black
... )
>>> # Apply to image and its segmentation mask
>>> transformed = transform(image=image, mask=mask)
>>> # Using bounding boxes with Compose
>>> transform = A.Compose([
... ConstrainedCoarseDropout(
... num_holes_range=(1, 3),
... hole_height_range=(0.3, 0.5), # 30-50% of box height
... hole_width_range=(0.3, 0.5), # 30-50% of box width
... bbox_labels=['person'], # Target people
... fill=127, # Fill holes with gray
... )
... ], bbox_params=A.BboxParams(
... format='pascal_voc', # [x_min, y_min, x_max, y_max]
... label_fields=['labels'] # Specify field containing labels
... ))
>>> # Apply to image and its bounding boxes
>>> transformed = transform(
... image=image,
... bboxes=[[0, 0, 100, 100, 'car'], [150, 150, 300, 300, 'person']],
... labels=['car', 'person']
... )
"""
class InitSchema(BaseDropout.InitSchema):
num_holes_range: Annotated[
tuple[int, int],
AfterValidator(check_range_bounds(1, None)),
AfterValidator(nondecreasing),
]
hole_height_range: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0.0, 1.0)),
]
hole_width_range: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0.0, 1.0)),
]
mask_indices: Annotated[
list[int] | None,
AfterValidator(check_range_bounds(1, None)),
]
bbox_labels: list[str | int | float] | None = None
def __init__(
self,
num_holes_range: tuple[int, int] = (1, 1),
hole_height_range: tuple[float, float] = (0.1, 0.1),
hole_width_range: tuple[float, float] = (0.1, 0.1),
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
mask_indices: list[int] | None = None,
bbox_labels: list[str | int | float] | None = None,
):
super().__init__(fill=fill, fill_mask=fill_mask, p=p)
self.num_holes_range = num_holes_range
self.hole_height_range = hole_height_range
self.hole_width_range = hole_width_range
self.mask_indices = mask_indices
self.bbox_labels = bbox_labels
def get_boxes_from_bboxes(self, bboxes: np.ndarray) -> np.ndarray | None:
"""Get bounding boxes that match specified labels.
Uses BboxProcessor's label encoder if bbox_labels contain strings.
"""
if len(bboxes) == 0 or self.bbox_labels is None:
return None
# Get label encoder from BboxProcessor if needed
bbox_processor = self.get_processor("bboxes")
if bbox_processor is None:
return None
if not all(isinstance(label, (int, float)) for label in self.bbox_labels):
label_fields = bbox_processor.params.label_fields
if label_fields is None:
raise ValueError("BboxParams.label_fields must be specified when using string labels")
first_class_label = label_fields[0]
# Access encoder through label_manager's metadata
metadata = bbox_processor.label_manager.metadata["bboxes"][first_class_label]
if metadata.encoder is None:
raise ValueError(f"No encoder found for label field {first_class_label}")
target_labels = metadata.encoder.transform(self.bbox_labels)
else:
target_labels = np.array(self.bbox_labels)
# Filter boxes by labels (usually in column 4)
mask = np.isin(bboxes[:, 4], target_labels)
filtered_boxes = bboxes[mask, :4]
return filtered_boxes if len(filtered_boxes) > 0 else None
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get hole parameters based on either mask indices or bbox labels."""
num_holes_per_obj = self.py_random.randint(*self.num_holes_range)
if self.mask_indices is not None and "mask" in data:
holes = fdropout.get_holes_from_mask(
data["mask"],
num_holes_per_obj,
self.mask_indices,
self.hole_height_range,
self.hole_width_range,
self.random_generator,
)
elif self.bbox_labels is not None and "bboxes" in data:
target_boxes = self.get_boxes_from_bboxes(data["bboxes"])
if target_boxes is None:
holes = np.array([], dtype=np.int32).reshape((0, 4))
else:
target_boxes = denormalize_bboxes(target_boxes, data["image"].shape[:2])
holes = fdropout.get_holes_from_boxes(
target_boxes,
num_holes_per_obj,
self.hole_height_range,
self.hole_width_range,
self.random_generator,
)
else:
warn("Neither valid mask nor bboxes provided, do not apply Constrained Coarse Dropout", stacklevel=2)
holes = np.array([], dtype=np.int32).reshape((0, 4))
return {
"holes": holes,
"seed": self.random_generator.integers(0, 2**32 - 1),
}
@@ -0,0 +1,166 @@
"""Implementation of grid-based dropout augmentation.
This module provides GridDropout, which creates a regular grid over the image and drops out
rectangular regions according to the specified grid pattern. Unlike random dropout methods,
grid dropout enforces a structured pattern of occlusions that can help models learn spatial
relationships and context across the entire image space.
"""
from __future__ import annotations
from typing import Annotated, Any, Literal
from pydantic import AfterValidator, Field
import albumentations.augmentations.dropout.functional as fdropout
from albumentations.augmentations.dropout.transforms import BaseDropout
from albumentations.core.pydantic import check_range_bounds, nondecreasing
__all__ = ["GridDropout"]
class GridDropout(BaseDropout):
"""Apply GridDropout augmentation to images, masks, bounding boxes, and keypoints.
GridDropout drops out rectangular regions of an image and the corresponding mask in a grid fashion.
This technique can help improve model robustness by forcing the network to rely on a broader context
rather than specific local features.
Args:
ratio (float): The ratio of the mask holes to the unit size (same for horizontal and vertical directions).
Must be between 0 and 1. Default: 0.5.
unit_size_range (tuple[int, int] | None): Range from which to sample grid size. Default: None.
Must be between 2 and the image's shorter edge. If None, grid size is calculated based on image size.
holes_number_xy (tuple[int, int] | None): The number of grid units in x and y directions.
First value should be between 1 and image width//2,
Second value should be between 1 and image height//2.
Default: None. If provided, overrides unit_size_range.
random_offset (bool): Whether to offset the grid randomly between 0 and (grid unit size - hole size).
If True, entered shift_xy is ignored and set randomly. Default: True.
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value for the dropped pixels. Can be:
- int or float: all channels are filled with this value
- tuple: tuple of values for each channel
- 'random': each pixel is filled with random values
- 'random_uniform': each hole is filled with a single random color
- 'inpaint_telea': uses OpenCV Telea inpainting method
- 'inpaint_ns': uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Value for the dropped pixels in mask.
If None, the mask is not modified. Default: None.
shift_xy (tuple[int, int]): Offsets of the grid start in x and y directions from (0,0) coordinate.
Only used when random_offset is False. Default: (0, 0).
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- If both unit_size_range and holes_number_xy are None, the grid size is calculated based on the image size.
- The actual number of dropped regions may differ slightly from holes_number_xy due to rounding.
- Inpainting methods ('inpaint_telea', 'inpaint_ns') work only with grayscale or RGB images.
- For 'random_uniform' fill, each grid cell gets a single random color, unlike 'random' where each pixel
gets its own random value.
Example:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> # Example with standard fill value
>>> aug_basic = A.GridDropout(
... ratio=0.3,
... unit_size_range=(10, 20),
... random_offset=True,
... p=1.0
... )
>>> # Example with random uniform fill
>>> aug_random = A.GridDropout(
... ratio=0.3,
... unit_size_range=(10, 20),
... fill="random_uniform",
... p=1.0
... )
>>> # Example with inpainting
>>> aug_inpaint = A.GridDropout(
... ratio=0.3,
... unit_size_range=(10, 20),
... fill="inpaint_ns",
... p=1.0
... )
>>> transformed = aug_random(image=image, mask=mask)
>>> transformed_image, transformed_mask = transformed["image"], transformed["mask"]
Reference:
- Paper: https://arxiv.org/abs/2001.04086
- OpenCV Inpainting methods: https://docs.opencv.org/master/df/d3d/tutorial_py_inpainting.html
"""
class InitSchema(BaseDropout.InitSchema):
ratio: float = Field(gt=0, le=1)
random_offset: bool
unit_size_range: (
Annotated[tuple[int, int], AfterValidator(check_range_bounds(2, None)), AfterValidator(nondecreasing)]
| None
)
shift_xy: Annotated[tuple[int, int], AfterValidator(check_range_bounds(0, None))]
holes_number_xy: Annotated[tuple[int, int], AfterValidator(check_range_bounds(1, None))] | None
def __init__(
self,
ratio: float = 0.5,
random_offset: bool = True,
unit_size_range: tuple[int, int] | None = None,
holes_number_xy: tuple[int, int] | None = None,
shift_xy: tuple[int, int] = (0, 0),
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(fill=fill, fill_mask=fill_mask, p=p)
self.ratio = ratio
self.unit_size_range = unit_size_range
self.holes_number_xy = holes_number_xy
self.random_offset = random_offset
self.shift_xy = shift_xy
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, Any]: Dictionary with parameters for transformation.
"""
image_shape = params["shape"]
if self.holes_number_xy:
grid = self.holes_number_xy
else:
# Calculate grid based on unit_size_range or default
unit_height, unit_width = fdropout.calculate_grid_dimensions(
image_shape,
self.unit_size_range,
self.holes_number_xy,
self.random_generator,
)
grid = (image_shape[0] // unit_height, image_shape[1] // unit_width)
holes = fdropout.generate_grid_holes(
image_shape,
grid,
self.ratio,
self.random_offset,
self.shift_xy,
self.random_generator,
)
return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
@@ -0,0 +1,274 @@
"""Implementation of mask-based dropout augmentation.
This module provides the MaskDropout transform, which identifies objects in a segmentation mask
and drops out random objects completely. This augmentation is particularly useful for instance
segmentation and object detection tasks, as it simulates occlusions or missing objects in a
semantically meaningful way, rather than dropping out random pixels or regions.
"""
from __future__ import annotations
from typing import Any, Literal, cast
import cv2
import numpy as np
import albumentations.augmentations.dropout.functional as fdropout
from albumentations.core.bbox_utils import BboxProcessor, denormalize_bboxes, normalize_bboxes
from albumentations.core.keypoints_utils import KeypointsProcessor
from albumentations.core.pydantic import OnePlusIntRangeType
from albumentations.core.transforms_interface import BaseTransformInitSchema, DualTransform
from albumentations.core.type_definitions import ALL_TARGETS
__all__ = ["MaskDropout"]
class MaskDropout(DualTransform):
"""Apply dropout to random objects in a mask, zeroing out the corresponding regions in both the image and mask.
This transform identifies objects in the mask (where each unique non-zero value represents a distinct object),
randomly selects a number of these objects, and sets their corresponding regions to zero in both the image and mask.
It can also handle bounding boxes and keypoints, removing or adjusting them based on the dropout regions.
Args:
max_objects (int | tuple[int, int]): Maximum number of objects to dropout. If a single int is provided,
it's treated as the upper bound. If a tuple of two ints is provided, it's treated as a range [min, max].
fill (float | Literal["inpaint_telea", "inpaint_ns"]): Value to fill dropped out regions in the image.
Can be one of:
- float: Constant value to fill the regions (e.g., 0 for black, 255 for white)
- "inpaint_telea": Use Telea inpainting algorithm (for 3-channel images only)
- "inpaint_ns": Use Navier-Stokes inpainting algorithm (for 3-channel images only)
fill_mask (float): Value to fill the dropped out regions in the mask.
min_area (float): Minimum area (in pixels) of a bounding box that must remain visible after dropout to be kept.
Only applicable if bounding box augmentation is enabled. Default: 0.0
min_visibility (float): Minimum visibility ratio (visible area / total area) of a bounding box after dropout
to be kept. Only applicable if bounding box augmentation is enabled. Default: 0.0
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The mask should be a single-channel image where 0 represents the background and non-zero values represent
different object instances.
- For bounding box and keypoint augmentation, make sure to set up the corresponding processors in the pipeline.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.zeros((100, 100), dtype=np.uint8)
>>> mask[20:40, 20:40] = 1 # Object 1
>>> mask[60:80, 60:80] = 2 # Object 2
>>> bboxes = np.array([[20, 20, 40, 40], [60, 60, 80, 80]], dtype=np.float32)
>>> bbox_labels = [1, 2]
>>> keypoints = np.array([[30, 30], [70, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1]
>>>
>>> # Define the transform with tuple for max_objects
>>> transform = A.Compose(
... transforms=[
... A.MaskDropout(
... max_objects=(1, 2), # Using tuple to specify min and max objects to drop
... fill=0, # Fill value for dropped regions in image
... fill_mask=0, # Fill value for dropped regions in mask
... p=1.0
... ),
... ],
... bbox_params=A.BboxParams(
... format='pascal_voc',
... label_fields=['bbox_labels'],
... min_area=1,
... min_visibility=0.1
... ),
... keypoint_params=A.KeypointParams(
... format='xy',
... label_fields=['keypoint_labels'],
... remove_invisible=True
... )
... )
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed data
>>> transformed_image = transformed['image'] # Image with dropped out regions
>>> transformed_mask = transformed['mask'] # Mask with dropped out regions
>>> transformed_bboxes = transformed['bboxes'] # Remaining bboxes after dropout
>>> transformed_bbox_labels = transformed['bbox_labels'] # Labels for remaining bboxes
>>> transformed_keypoints = transformed['keypoints'] # Remaining keypoints after dropout
>>> transformed_keypoint_labels = transformed['keypoint_labels'] # Labels for remaining keypoints
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
max_objects: OnePlusIntRangeType
fill: float | Literal["inpaint_telea", "inpaint_ns"]
fill_mask: float
def __init__(
self,
max_objects: tuple[int, int] | int = (1, 1),
fill: float | Literal["inpaint_telea", "inpaint_ns"] = 0,
fill_mask: float = 0,
p: float = 0.5,
):
super().__init__(p=p)
self.max_objects = cast("tuple[int, int]", max_objects)
self.fill = fill # type: ignore[assignment]
self.fill_mask = fill_mask
@property
def targets_as_params(self) -> list[str]:
"""Get targets as parameters.
Returns:
list[str]: List of targets as parameters.
"""
return ["mask"]
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, Any]: Dictionary with parameters for transformation.
"""
mask = data["mask"]
label_image, num_labels = fdropout.label(mask, return_num=True)
if num_labels == 0:
dropout_mask = None
else:
objects_to_drop = self.py_random.randint(*self.max_objects)
objects_to_drop = min(num_labels, objects_to_drop)
if objects_to_drop == num_labels:
dropout_mask = mask > 0
else:
labels_index = self.py_random.sample(range(1, num_labels + 1), objects_to_drop)
dropout_mask = np.zeros(mask.shape[:2], dtype=bool)
for label_index in labels_index:
dropout_mask |= label_image == label_index
return {"dropout_mask": dropout_mask}
def apply(self, img: np.ndarray, dropout_mask: np.ndarray | None, **params: Any) -> np.ndarray:
"""Apply dropout to the image.
Args:
img (np.ndarray): The image to apply the transform to.
dropout_mask (np.ndarray | None): The dropout mask for the image.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed image.
"""
if dropout_mask is None:
return img
if self.fill in {"inpaint_telea", "inpaint_ns"}:
dropout_mask = dropout_mask.astype(np.uint8)
_, _, width, height = cv2.boundingRect(dropout_mask)
radius = min(3, max(width, height) // 2)
return cv2.inpaint(img, dropout_mask, radius, cast("Literal['inpaint_telea', 'inpaint_ns']", self.fill))
img = img.copy()
img[dropout_mask] = self.fill
return img
def apply_to_mask(self, mask: np.ndarray, dropout_mask: np.ndarray | None, **params: Any) -> np.ndarray:
"""Apply dropout to the mask.
Args:
mask (np.ndarray): The mask to apply the transform to.
dropout_mask (np.ndarray | None): The dropout mask for the mask.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed mask.
"""
if dropout_mask is None or self.fill_mask is None:
return mask
mask = mask.copy()
mask[dropout_mask] = self.fill_mask
return mask
def apply_to_bboxes(self, bboxes: np.ndarray, dropout_mask: np.ndarray | None, **params: Any) -> np.ndarray:
"""Apply dropout to bounding boxes.
Args:
bboxes (np.ndarray): The bounding boxes to apply the transform to.
dropout_mask (np.ndarray | None): The dropout mask for the bounding boxes.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed bounding boxes.
"""
if dropout_mask is None:
return bboxes
processor = cast("BboxProcessor", self.get_processor("bboxes"))
if processor is None:
return bboxes
image_shape = params["shape"][:2]
denormalized_bboxes = denormalize_bboxes(bboxes, image_shape)
result = fdropout.mask_dropout_bboxes(
denormalized_bboxes,
dropout_mask,
image_shape,
processor.params.min_area,
processor.params.min_visibility,
)
return normalize_bboxes(result, image_shape)
def apply_to_keypoints(self, keypoints: np.ndarray, dropout_mask: np.ndarray | None, **params: Any) -> np.ndarray:
"""Apply dropout to keypoints.
Args:
keypoints (np.ndarray): The keypoints to apply the transform to.
dropout_mask (np.ndarray | None): The dropout mask for the keypoints.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed keypoints.
"""
if dropout_mask is None:
return keypoints
processor = cast("KeypointsProcessor", self.get_processor("keypoints"))
if processor is None or not processor.params.remove_invisible:
return keypoints
return fdropout.mask_dropout_keypoints(keypoints, dropout_mask)
@@ -0,0 +1,461 @@
"""Transform classes for dropout-based augmentations.
This module contains transform classes for various dropout techniques used in image
augmentation. It provides the base dropout class and specialized implementations like
PixelDropout. These transforms randomly remove or modify pixels, channels, or regions
in images, which can help models become more robust to occlusions and missing information.
"""
from __future__ import annotations
from typing import Any, Literal, cast
import numpy as np
from albucore import get_num_channels
from pydantic import Field
from albumentations.augmentations.dropout import functional as fdropout
from albumentations.augmentations.dropout.functional import (
cutout,
cutout_on_volume,
cutout_on_volumes,
filter_bboxes_by_holes,
filter_keypoints_in_holes,
)
from albumentations.augmentations.pixel import functional as fpixel
from albumentations.core.bbox_utils import BboxProcessor, denormalize_bboxes, normalize_bboxes
from albumentations.core.keypoints_utils import KeypointsProcessor
from albumentations.core.transforms_interface import BaseTransformInitSchema, DualTransform
from albumentations.core.type_definitions import ALL_TARGETS, Targets
__all__ = ["PixelDropout"]
class BaseDropout(DualTransform):
"""Base class for dropout-style transformations.
This class provides common functionality for various dropout techniques,
including applying cutouts to images and masks.
Args:
fill (tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value to fill dropped regions.
fill_mask (tuple[float, ...] | float | None): Value to fill
dropped regions in the mask. If None, the mask is not modified.
p (float): Probability of applying the transform.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Examples:
>>> import numpy as np
>>> import albumentations as A
>>>
>>> # Example of a custom dropout transform inheriting from BaseDropout
>>> class CustomDropout(A.BaseDropout):
... def __init__(self, num_holes_range=(4, 8), hole_size_range=(10, 20), *args, **kwargs):
... super().__init__(*args, **kwargs)
... self.num_holes_range = num_holes_range
... self.hole_size_range = hole_size_range
...
... def get_params_dependent_on_data(self, params, data):
... img = data["image"]
... height, width = img.shape[:2]
...
... # Generate random holes
... num_holes = self.py_random.randint(*self.num_holes_range)
... hole_sizes = self.py_random.randint(*self.hole_size_range, size=num_holes)
...
... holes = []
... for i in range(num_holes):
... # Random position for each hole
... x1 = self.py_random.randint(0, max(1, width - hole_sizes[i]))
... y1 = self.py_random.randint(0, max(1, height - hole_sizes[i]))
... x2 = min(width, x1 + hole_sizes[i])
... y2 = min(height, y1 + hole_sizes[i])
... holes.append([x1, y1, x2, y2])
...
... # Return holes and random seed
... return {
... "holes": np.array(holes) if holes else np.empty((0, 4), dtype=np.int32),
... "seed": self.py_random.integers(0, 100000)
... }
>>>
>>> # Prepare sample data
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> bboxes = np.array([[0.1, 0.1, 0.4, 0.4], [0.6, 0.6, 0.9, 0.9]])
>>>
>>> # Create a transform with custom dropout
>>> transform = A.Compose([
... CustomDropout(
... num_holes_range=(3, 6), # Generate 3-6 random holes
... hole_size_range=(5, 15), # Holes of size 5-15 pixels
... fill=0, # Fill holes with black
... fill_mask=1, # Fill mask holes with 1
... p=1.0 # Always apply for this example
... )
... ], bbox_params=A.BboxParams(format='yolo', min_visibility=0.3))
>>>
>>> # Apply the transform
>>> transformed = transform(image=image, mask=mask, bboxes=bboxes)
>>>
>>> # Get the transformed data
>>> dropout_image = transformed["image"] # Image with random holes filled with 0
>>> dropout_mask = transformed["mask"] # Mask with same holes filled with 1
>>> dropout_bboxes = transformed["bboxes"] # Bboxes filtered by visibility threshold
"""
_targets: tuple[Targets, ...] | Targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]
fill_mask: tuple[float, ...] | float | None
def __init__(
self,
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"],
fill_mask: tuple[float, ...] | float | None,
p: float,
):
super().__init__(p=p)
self.fill = fill # type: ignore[assignment]
self.fill_mask = fill_mask
def apply(self, img: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if holes.size == 0:
return img
if self.fill in {"inpaint_telea", "inpaint_ns"}:
num_channels = get_num_channels(img)
if num_channels not in {1, 3}:
raise ValueError("Inpainting works only for 1 or 3 channel images")
return cutout(img, holes, self.fill, np.random.default_rng(seed))
def apply_to_images(self, images: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if holes.size == 0:
return images
if self.fill in {"inpaint_telea", "inpaint_ns"}:
num_channels = images.shape[3] if images.ndim == 4 else 1
if num_channels not in {1, 3}:
raise ValueError("Inpainting works only for 1 or 3 channel images")
# Images (N, H, W, C) have the same structure as volumes (D, H, W, C)
return cutout_on_volume(images, holes, self.fill, np.random.default_rng(seed))
def apply_to_volume(self, volume: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
# Volume (D, H, W, C) has the same structure as images (N, H, W, C)
# We can reuse the same logic
return self.apply_to_images(volume, holes, seed, **params)
def apply_to_volumes(self, volumes: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if holes.size == 0:
return volumes
if self.fill in {"inpaint_telea", "inpaint_ns"}:
num_channels = volumes.shape[4] if volumes.ndim == 5 else 1
if num_channels not in {1, 3}:
raise ValueError("Inpainting works only for 1 or 3 channel images")
return cutout_on_volumes(volumes, holes, self.fill, np.random.default_rng(seed))
def apply_to_mask3d(self, mask: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if self.fill_mask is None or holes.size == 0:
return mask
return cutout_on_volume(mask, holes, self.fill_mask, np.random.default_rng(seed))
def apply_to_masks3d(self, mask: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if self.fill_mask is None or holes.size == 0:
return mask
return cutout_on_volumes(mask, holes, self.fill_mask, np.random.default_rng(seed))
def apply_to_mask(self, mask: np.ndarray, holes: np.ndarray, seed: int, **params: Any) -> np.ndarray:
if self.fill_mask is None or holes.size == 0:
return mask
return cutout(mask, holes, self.fill_mask, np.random.default_rng(seed))
def apply_to_bboxes(
self,
bboxes: np.ndarray,
holes: np.ndarray,
**params: Any,
) -> np.ndarray:
if holes.size == 0:
return bboxes
processor = cast("BboxProcessor", self.get_processor("bboxes"))
if processor is None:
return bboxes
image_shape = params["shape"][:2]
denormalized_bboxes = denormalize_bboxes(bboxes, image_shape)
return normalize_bboxes(
filter_bboxes_by_holes(
denormalized_bboxes,
holes,
image_shape,
min_area=processor.params.min_area,
min_visibility=processor.params.min_visibility,
),
image_shape,
)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
holes: np.ndarray,
**params: Any,
) -> np.ndarray:
if holes.size == 0:
return keypoints
processor = cast("KeypointsProcessor", self.get_processor("keypoints"))
if processor is None or not processor.params.remove_invisible:
return keypoints
return filter_keypoints_in_holes(keypoints, holes)
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
raise NotImplementedError("Subclasses must implement this method.")
class PixelDropout(DualTransform):
"""Drops random pixels from the image.
This transform randomly sets pixels in the image to a specified value, effectively "dropping out" those pixels.
It can be applied to both the image and its corresponding mask.
Args:
dropout_prob (float): Probability of dropping out each pixel. Should be in the range [0, 1].
Default: 0.01
per_channel (bool): If True, the dropout mask will be generated independently for each channel.
If False, the same dropout mask will be applied to all channels.
Default: False
drop_value (float | tuple[float, ...] | None): Value to assign to the dropped pixels.
If None, the value will be randomly sampled for each application:
- For uint8 images: Random integer in [0, 255]
- For float32 images: Random float in [0, 1]
If a single number, that value will be used for all dropped pixels.
If a sequence, it should contain one value per channel.
Default: 0
mask_drop_value (float | tuple[float, ...] | None): Value to assign to dropped pixels in the mask.
If None, the mask will remain unchanged.
If a single number, that value will be used for all dropped pixels in the mask.
If a sequence, it should contain one value per channel.
Default: None
p (float): Probability of applying the transform. Should be in the range [0, 1].
Default: 0.5
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- When applied to bounding boxes, this transform may cause some boxes to have zero area
if all pixels within the box are dropped. Such boxes will be removed.
- When applied to keypoints, keypoints that fall on dropped pixels will be removed if
the keypoint processor is configured to remove invisible keypoints.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> transform = A.PixelDropout(dropout_prob=0.1, per_channel=True, p=1.0)
>>> result = transform(image=image, mask=mask)
>>> dropped_image, dropped_mask = result['image'], result['mask']
"""
class InitSchema(BaseTransformInitSchema):
dropout_prob: float = Field(ge=0, le=1)
per_channel: bool
drop_value: tuple[float, ...] | float | None
mask_drop_value: tuple[float, ...] | float | None
_targets = ALL_TARGETS
def __init__(
self,
dropout_prob: float = 0.01,
per_channel: bool = False,
drop_value: tuple[float, ...] | float | None = 0,
mask_drop_value: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(p=p)
self.dropout_prob = dropout_prob
self.per_channel = per_channel
self.drop_value = drop_value
self.mask_drop_value = mask_drop_value
def apply(
self,
img: np.ndarray,
drop_mask: np.ndarray,
drop_values: np.ndarray,
**params: Any,
) -> np.ndarray:
"""Apply pixel dropout to the image.
Args:
img (np.ndarray): The image to apply the transform to.
drop_mask (np.ndarray): The dropout mask.
drop_values (np.ndarray): The values to assign to the dropped pixels.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed image.
"""
return fpixel.pixel_dropout(img, drop_mask, drop_values)
def apply_to_mask(
self,
mask: np.ndarray,
mask_drop_mask: np.ndarray,
mask_drop_values: float | np.ndarray,
**params: Any,
) -> np.ndarray:
"""Apply pixel dropout to the mask.
Args:
mask (np.ndarray): The mask to apply the transform to.
mask_drop_mask (np.ndarray): The dropout mask for the mask.
mask_drop_values (float | np.ndarray): The values to assign to the dropped pixels in the mask.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed mask.
"""
if self.mask_drop_value is None:
return mask
return fpixel.pixel_dropout(mask, mask_drop_mask, mask_drop_values)
def apply_to_bboxes(
self,
bboxes: np.ndarray,
drop_mask: np.ndarray | None,
**params: Any,
) -> np.ndarray:
"""Apply pixel dropout to the bounding boxes.
Args:
bboxes (np.ndarray): The bounding boxes to apply the transform to.
drop_mask (np.ndarray | None): The dropout mask for the bounding boxes.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed bounding boxes.
"""
if drop_mask is None or self.per_channel:
return bboxes
processor = cast("BboxProcessor", self.get_processor("bboxes"))
if processor is None:
return bboxes
image_shape = params["shape"][:2]
denormalized_bboxes = denormalize_bboxes(bboxes, image_shape)
# If per_channel is True, we need to create a single channel mask
# by combining the multi-channel mask (considering a pixel dropped if it's dropped in any channel)
if self.per_channel and len(drop_mask.shape) > 2:
# Create a single channel mask where a pixel is considered dropped if it's dropped in any channel
combined_mask = np.any(drop_mask, axis=-1 if drop_mask.shape[-1] <= 4 else 0)
# Ensure the mask has the right shape for the bboxes function
if combined_mask.ndim == 3 and combined_mask.shape[0] == 1:
combined_mask = combined_mask[0]
else:
combined_mask = drop_mask
result = fdropout.mask_dropout_bboxes(
denormalized_bboxes,
combined_mask,
image_shape,
processor.params.min_area,
processor.params.min_visibility,
)
return normalize_bboxes(result, image_shape)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
**params: Any,
) -> np.ndarray:
"""Apply pixel dropout to the keypoints.
Args:
keypoints (np.ndarray): The keypoints to apply the transform to.
**params (Any): Additional parameters for the transform.
Returns:
np.ndarray: The transformed keypoints.
"""
return keypoints
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, Any]:
"""Generate parameters for pixel dropout based on input data.
Args:
params (dict[str, Any]): Transform parameters
data (dict[str, Any]): Input data dictionary
Returns:
dict[str, Any]: Dictionary of parameters for applying the transform
"""
reference_array = data["image"] if "image" in data else data["images"][0]
# Generate drop mask and values for all targets
drop_mask = fpixel.get_drop_mask(
reference_array.shape,
self.per_channel,
self.dropout_prob,
self.random_generator,
)
drop_values = fpixel.prepare_drop_values(
reference_array,
self.drop_value,
self.random_generator,
)
# Handle mask drop values if specified
mask_drop_mask = None
mask_drop_values = None
mask = fpixel.get_mask_array(data)
if self.mask_drop_value is not None and mask is not None:
mask_drop_mask = fpixel.get_drop_mask(
mask.shape,
self.per_channel,
self.dropout_prob,
self.random_generator,
)
mask_drop_values = fpixel.prepare_drop_values(
mask,
self.mask_drop_value,
self.random_generator,
)
return {
"drop_mask": drop_mask,
"drop_values": drop_values,
"mask_drop_mask": mask_drop_mask if mask_drop_mask is not None else None,
"mask_drop_values": mask_drop_values if mask_drop_values is not None else None,
}
@@ -0,0 +1,186 @@
"""Implementation of XY masking for time-frequency domain transformations.
This module provides the XYMasking transform, which applies masking strips along the X and Y axes
of an image. This is particularly useful for audio spectrograms, time-series data visualizations,
and other grid-like data representations where masking in specific directions (time or frequency)
can improve model robustness and generalization.
"""
from __future__ import annotations
from typing import Any, Literal, cast
import numpy as np
from pydantic import model_validator
from typing_extensions import Self
from albumentations.augmentations.dropout.transforms import BaseDropout
from albumentations.core.pydantic import NonNegativeIntRangeType
from albumentations.core.transforms_interface import BaseTransformInitSchema
__all__ = ["XYMasking"]
class XYMasking(BaseDropout):
"""Applies masking strips to an image, either horizontally (X axis) or vertically (Y axis),
simulating occlusions. This transform is useful for training models to recognize images
with varied visibility conditions. It's particularly effective for spectrogram images,
allowing spectral and frequency masking to improve model robustness.
At least one of `max_x_length` or `max_y_length` must be specified, dictating the mask's
maximum size along each axis.
Args:
num_masks_x (int | tuple[int, int]): Number or range of horizontal regions to mask. Defaults to 0.
num_masks_y (int | tuple[int, int]): Number or range of vertical regions to mask. Defaults to 0.
mask_x_length (int | tuple[int, int]): Specifies the length of the masks along
the X (horizontal) axis. If an integer is provided, it sets a fixed mask length.
If a tuple of two integers (min, max) is provided,
the mask length is randomly chosen within this range for each mask.
This allows for variable-length masks in the horizontal direction.
mask_y_length (int | tuple[int, int]): Specifies the height of the masks along
the Y (vertical) axis. Similar to `mask_x_length`, an integer sets a fixed mask height,
while a tuple (min, max) allows for variable-height masks, chosen randomly
within the specified range for each mask. This flexibility facilitates creating masks of various
sizes in the vertical direction.
fill (tuple[float, float] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]):
Value for the dropped pixels. Can be:
- int or float: all channels are filled with this value
- tuple: tuple of values for each channel
- 'random': each pixel is filled with random values
- 'random_uniform': each hole is filled with a single random color
- 'inpaint_telea': uses OpenCV Telea inpainting method
- 'inpaint_ns': uses OpenCV Navier-Stokes inpainting method
Default: 0
fill_mask (tuple[float, float] | float | None): Fill value for dropout regions in the mask.
If None, mask regions corresponding to image dropouts are unchanged. Default: None
p (float): Probability of applying the transform. Defaults to 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note: Either `max_x_length` or `max_y_length` or both must be defined.
"""
class InitSchema(BaseTransformInitSchema):
num_masks_x: NonNegativeIntRangeType
num_masks_y: NonNegativeIntRangeType
mask_x_length: NonNegativeIntRangeType
mask_y_length: NonNegativeIntRangeType
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"]
fill_mask: tuple[float, ...] | float | None
@model_validator(mode="after")
def _check_mask_length(self) -> Self:
if (
isinstance(self.mask_x_length, int)
and self.mask_x_length <= 0
and isinstance(self.mask_y_length, int)
and self.mask_y_length <= 0
):
msg = "At least one of `mask_x_length` or `mask_y_length` Should be a positive number."
raise ValueError(msg)
return self
def __init__(
self,
num_masks_x: tuple[int, int] | int = 0,
num_masks_y: tuple[int, int] | int = 0,
mask_x_length: tuple[int, int] | int = 0,
mask_y_length: tuple[int, int] | int = 0,
fill: tuple[float, ...] | float | Literal["random", "random_uniform", "inpaint_telea", "inpaint_ns"] = 0,
fill_mask: tuple[float, ...] | float | None = None,
p: float = 0.5,
):
super().__init__(p=p, fill=fill, fill_mask=fill_mask)
self.num_masks_x = cast("tuple[int, int]", num_masks_x)
self.num_masks_y = cast("tuple[int, int]", num_masks_y)
self.mask_x_length = cast("tuple[int, int]", mask_x_length)
self.mask_y_length = cast("tuple[int, int]", mask_y_length)
def _validate_mask_length(
self,
mask_length: tuple[int, int] | None,
dimension_size: int,
dimension_name: str,
) -> None:
"""Validate the mask length against the corresponding image dimension size."""
if mask_length is not None:
if isinstance(mask_length, (tuple, list)):
if mask_length[0] < 0 or mask_length[1] > dimension_size:
raise ValueError(
f"{dimension_name} range {mask_length} is out of valid range [0, {dimension_size}]",
)
elif mask_length < 0 or mask_length > dimension_size:
raise ValueError(f"{dimension_name} {mask_length} exceeds image {dimension_name} {dimension_size}")
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, np.ndarray]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, np.ndarray]: Dictionary with parameters for transformation.
"""
image_shape = params["shape"][:2]
height, width = image_shape
self._validate_mask_length(self.mask_x_length, width, "mask_x_length")
self._validate_mask_length(self.mask_y_length, height, "mask_y_length")
masks_x = self._generate_masks(self.num_masks_x, image_shape, self.mask_x_length, axis="x")
masks_y = self._generate_masks(self.num_masks_y, image_shape, self.mask_y_length, axis="y")
holes = np.array(masks_x + masks_y)
return {"holes": holes, "seed": self.random_generator.integers(0, 2**32 - 1)}
def _generate_mask_size(self, mask_length: tuple[int, int]) -> int:
return self.py_random.randint(*mask_length)
def _generate_masks(
self,
num_masks: tuple[int, int],
image_shape: tuple[int, int],
max_length: tuple[int, int] | None,
axis: str,
) -> list[tuple[int, int, int, int]]:
if max_length is None or max_length == 0 or (isinstance(num_masks, (int, float)) and num_masks == 0):
return []
masks = []
num_masks_integer = (
num_masks if isinstance(num_masks, int) else self.py_random.randint(num_masks[0], num_masks[1])
)
height, width = image_shape
for _ in range(num_masks_integer):
length = self._generate_mask_size(max_length)
if axis == "x":
x_min = self.py_random.randint(0, width - length)
y_min = 0
x_max, y_max = x_min + length, height
else: # axis == 'y'
y_min = self.py_random.randint(0, height - length)
x_min = 0
x_max, y_max = width, y_min + length
masks.append((x_min, y_min, x_max, y_max))
return masks
@@ -0,0 +1,651 @@
"""Geometric transformations for flip and symmetry operations.
This module contains transforms that apply various flip and symmetry operations
to images and other target types. These transforms modify the geometric arrangement
of the input data while preserving the pixel values themselves.
Available transforms:
- VerticalFlip: Flips the input upside down (around the x-axis)
- HorizontalFlip: Flips the input left to right (around the y-axis)
- Transpose: Swaps rows and columns (flips around the main diagonal)
- D4: Applies one of eight possible square symmetry transformations (dihedral group D4)
- SquareSymmetry: Alias for D4 with a more intuitive name
These transforms are particularly useful for:
- Data augmentation to improve model generalization
- Addressing orientation biases in training data
- Working with data that doesn't have a natural orientation (e.g., satellite imagery)
- Exploiting symmetries in the problem domain
All transforms support various target types including images, masks, bounding boxes,
keypoints, volumes, and 3D masks, ensuring consistent transformation across
different data modalities.
"""
from __future__ import annotations
from typing import Any, Literal
import numpy as np
from albucore import batch_transform, hflip, vflip
from albumentations.core.transforms_interface import (
BaseTransformInitSchema,
DualTransform,
)
from albumentations.core.type_definitions import (
ALL_TARGETS,
d4_group_elements,
)
from . import functional as fgeometric
__all__ = [
"D4",
"HorizontalFlip",
"SquareSymmetry",
"Transpose",
"VerticalFlip",
]
class VerticalFlip(DualTransform):
"""Flip the input vertically around the x-axis.
Args:
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- This transform flips the image upside down. The top of the image becomes the bottom and vice versa.
- The dimensions of the image remain unchanged.
- For multi-channel images (like RGB), each channel is flipped independently.
- Bounding boxes are adjusted to match their new positions in the flipped image.
- Keypoints are moved to their new positions in the flipped image.
Mathematical Details:
1. For an input image I of shape (H, W, C), the output O is:
O[i, j, k] = I[H-1-i, j, k] for all i in [0, H-1], j in [0, W-1], k in [0, C-1]
2. For bounding boxes with coordinates (x_min, y_min, x_max, y_max):
new_bbox = (x_min, H-y_max, x_max, H-y_min)
3. For keypoints with coordinates (x, y):
new_keypoint = (x, H-y)
where H is the height of the image.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.array([
... [[1, 2, 3], [4, 5, 6]],
... [[7, 8, 9], [10, 11, 12]]
... ])
>>> transform = A.VerticalFlip(p=1.0)
>>> result = transform(image=image)
>>> flipped_image = result['image']
>>> print(flipped_image)
[[[ 7 8 9]
[10 11 12]]
[[ 1 2 3]
[ 4 5 6]]]
# The original image is flipped vertically, with rows reversed
"""
_targets = ALL_TARGETS
def apply(self, img: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the vertical flip to an image.
Args:
img (np.ndarray): Image to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped image.
"""
return vflip(img)
def apply_to_bboxes(self, bboxes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the vertical flip to bounding boxes.
Args:
bboxes (np.ndarray): Bounding boxes to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped bounding boxes.
"""
return fgeometric.bboxes_vflip(bboxes)
def apply_to_keypoints(self, keypoints: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the vertical flip to keypoints.
Args:
keypoints (np.ndarray): Keypoints to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped keypoints.
"""
return fgeometric.keypoints_vflip(keypoints, params["shape"][0])
def apply_to_images(self, images: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the vertical flip to a batch of images.
Args:
images (np.ndarray): Images to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped images.
"""
return fgeometric.volume_vflip(images)
def apply_to_volume(self, volume: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the vertical flip to a volume.
Args:
volume (np.ndarray): Volume to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped volume.
"""
return self.apply_to_images(volume, **params)
def apply_to_volumes(self, volumes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the vertical flip to a batch of volumes.
Args:
volumes (np.ndarray): Volumes to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped volumes.
"""
return fgeometric.volumes_vflip(volumes)
def apply_to_mask3d(self, mask3d: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the vertical flip to a 3D mask.
Args:
mask3d (np.ndarray): 3D mask to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped 3D mask.
"""
return self.apply_to_images(mask3d, **params)
def apply_to_masks3d(self, masks3d: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the vertical flip to a 3D mask.
Args:
masks3d (np.ndarray): 3D masks to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped 3D mask.
"""
return self.apply_to_volumes(masks3d, **params)
class HorizontalFlip(DualTransform):
"""Flip the input horizontally around the y-axis.
Args:
p (float): probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Examples:
>>> import numpy as np
>>> import albumentations as A
>>>
>>> # Prepare sample data
>>> image = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
>>> mask = np.array([[1, 0], [0, 1]])
>>> bboxes = np.array([[0.1, 0.5, 0.3, 0.9]]) # [x_min, y_min, x_max, y_max] format
>>> keypoints = np.array([[0.1, 0.5], [0.9, 0.5]]) # [x, y] format
>>>
>>> # Create a transform with horizontal flip
>>> transform = A.Compose([
... A.HorizontalFlip(p=1.0) # Always apply for this example
... ], bbox_params=A.BboxParams(format='yolo', label_fields=[]),
... keypoint_params=A.KeypointParams(format='normalized'))
>>>
>>> # Apply the transform
>>> transformed = transform(image=image, mask=mask, bboxes=bboxes, keypoints=keypoints)
>>>
>>> # Get the transformed data
>>> flipped_image = transformed["image"] # Image flipped horizontally
>>> flipped_mask = transformed["mask"] # Mask flipped horizontally
>>> flipped_bboxes = transformed["bboxes"] # BBox coordinates adjusted for horizontal flip
>>> flipped_keypoints = transformed["keypoints"] # Keypoint x-coordinates flipped
"""
_targets = ALL_TARGETS
def apply(self, img: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the horizontal flip to an image.
Args:
img (np.ndarray): Image to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped image.
"""
return hflip(img)
def apply_to_bboxes(self, bboxes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the horizontal flip to bounding boxes.
Args:
bboxes (np.ndarray): Bounding boxes to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped bounding boxes.
"""
return fgeometric.bboxes_hflip(bboxes)
def apply_to_keypoints(self, keypoints: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the horizontal flip to keypoints.
Args:
keypoints (np.ndarray): Keypoints to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped keypoints.
"""
return fgeometric.keypoints_hflip(keypoints, params["shape"][1])
def apply_to_images(self, images: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the horizontal flip to a batch of images.
Args:
images (np.ndarray): Images to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped images.
"""
return fgeometric.volume_hflip(images)
def apply_to_volume(self, volume: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the horizontal flip to a volume.
Args:
volume (np.ndarray): Volume to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped volume.
"""
return self.apply_to_images(volume, **params)
def apply_to_volumes(self, volumes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the horizontal flip to a batch of volumes.
Args:
volumes (np.ndarray): Volumes to be flipped.
**params (Any): Additional parameters.
Returns:
np.ndarray: Flipped volumes.
"""
return fgeometric.volumes_hflip(volumes)
def apply_to_mask3d(self, mask3d: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the horizontal flip to a 3D mask.
Args:
mask3d (np.ndarray): 3D mask to be flipped.
**params (Any): Additional parameters.
"""
return self.apply_to_images(mask3d, **params)
def apply_to_masks3d(self, masks3d: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the horizontal flip to a 3D mask.
Args:
masks3d (np.ndarray): 3D masks to be flipped.
**params (Any): Additional parameters.
"""
return self.apply_to_volumes(masks3d, **params)
class Transpose(DualTransform):
"""Transpose the input by swapping its rows and columns.
This transform flips the image over its main diagonal, effectively switching its width and height.
It's equivalent to a 90-degree rotation followed by a horizontal flip.
Args:
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The dimensions of the output will be swapped compared to the input. For example,
an input image of shape (100, 200, 3) will result in an output of shape (200, 100, 3).
- This transform is its own inverse. Applying it twice will return the original input.
- For multi-channel images (like RGB), the channels are preserved in their original order.
- Bounding boxes will have their coordinates adjusted to match the new image dimensions.
- Keypoints will have their x and y coordinates swapped.
Mathematical Details:
1. For an input image I of shape (H, W, C), the output O is:
O[i, j, k] = I[j, i, k] for all i in [0, W-1], j in [0, H-1], k in [0, C-1]
2. For bounding boxes with coordinates (x_min, y_min, x_max, y_max):
new_bbox = (y_min, x_min, y_max, x_max)
3. For keypoints with coordinates (x, y):
new_keypoint = (y, x)
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.array([
... [[1, 2, 3], [4, 5, 6]],
... [[7, 8, 9], [10, 11, 12]]
... ])
>>> transform = A.Transpose(p=1.0)
>>> result = transform(image=image)
>>> transposed_image = result['image']
>>> print(transposed_image)
[[[ 1 2 3]
[ 7 8 9]]
[[ 4 5 6]
[10 11 12]]]
# The original 2x2x3 image is now 2x2x3, with rows and columns swapped
"""
_targets = ALL_TARGETS
def apply(self, img: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the transpose to an image.
Args:
img (np.ndarray): Image to be transposed.
**params (Any): Additional parameters.
Returns:
np.ndarray: Transposed image.
"""
return fgeometric.transpose(img)
def apply_to_bboxes(self, bboxes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the transpose to bounding boxes.
Args:
bboxes (np.ndarray): Bounding boxes to be transposed.
**params (Any): Additional parameters.
Returns:
np.ndarray: Transposed bounding boxes.
"""
return fgeometric.bboxes_transpose(bboxes)
def apply_to_keypoints(self, keypoints: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the transpose to keypoints.
Args:
keypoints (np.ndarray): Keypoints to be transposed.
**params (Any): Additional parameters.
Returns:
np.ndarray: Transposed keypoints.
"""
return fgeometric.keypoints_transpose(keypoints)
class D4(DualTransform):
"""Applies one of the eight possible D4 dihedral group transformations to a square-shaped input,
maintaining the square shape. These transformations correspond to the symmetries of a square,
including rotations and reflections.
The D4 group transformations include:
- 'e' (identity): No transformation is applied.
- 'r90' (rotation by 90 degrees counterclockwise)
- 'r180' (rotation by 180 degrees)
- 'r270' (rotation by 270 degrees counterclockwise)
- 'v' (reflection across the vertical midline)
- 'hvt' (reflection across the anti-diagonal)
- 'h' (reflection across the horizontal midline)
- 't' (reflection across the main diagonal)
Even if the probability (`p`) of applying the transform is set to 1, the identity transformation
'e' may still occur, which means the input will remain unchanged in one out of eight cases.
Args:
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- This transform is particularly useful for augmenting data that does not have a clear orientation,
such as top-view satellite or drone imagery, or certain types of medical images.
- The input image should be square-shaped for optimal results. Non-square inputs may lead to
unexpected behavior or distortions.
- When applied to bounding boxes or keypoints, their coordinates will be adjusted according
to the selected transformation.
- This transform preserves the aspect ratio and size of the input.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> transform = A.Compose([
... A.D4(p=1.0),
... ])
>>> transformed = transform(image=image)
>>> transformed_image = transformed['image']
# The resulting image will be one of the 8 possible D4 transformations of the input
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
pass
def __init__(
self,
p: float = 1,
):
super().__init__(p=p)
def apply(
self,
img: np.ndarray,
group_element: Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"],
**params: Any,
) -> np.ndarray:
"""Apply the D4 transform to an image.
Args:
img (np.ndarray): Image to be transformed.
group_element (Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]): Group element to apply.
**params (Any): Additional parameters.
Returns:
np.ndarray: Transformed image.
"""
return fgeometric.d4(img, group_element)
def apply_to_bboxes(
self,
bboxes: np.ndarray,
group_element: Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"],
**params: Any,
) -> np.ndarray:
"""Apply the D4 transform to bounding boxes.
Args:
bboxes (np.ndarray): Bounding boxes to be transformed.
group_element (Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]): Group element to apply.
**params (Any): Additional parameters.
Returns:
np.ndarray: Transformed bounding boxes.
"""
return fgeometric.bboxes_d4(bboxes, group_element)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
group_element: Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"],
**params: Any,
) -> np.ndarray:
"""Apply the D4 transform to keypoints.
Args:
keypoints (np.ndarray): Keypoints to be transformed.
group_element (Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]): Group element to apply.
**params (Any): Additional parameters.
"""
return fgeometric.keypoints_d4(keypoints, group_element, params["shape"])
@batch_transform("spatial", has_batch_dim=True, has_depth_dim=False)
def apply_to_images(self, images: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the D4 transform to a batch of images.
Args:
images (np.ndarray): Images to be transformed.
**params (Any): Additional parameters.
"""
return self.apply(images, **params)
@batch_transform("spatial", has_batch_dim=False, has_depth_dim=True)
def apply_to_volume(self, volume: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the D4 transform to a volume.
Args:
volume (np.ndarray): Volume to be transformed.
**params (Any): Additional parameters.
"""
return self.apply(volume, **params)
@batch_transform("spatial", has_batch_dim=True, has_depth_dim=True)
def apply_to_volumes(self, volumes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the D4 transform to a batch of volumes.
Args:
volumes (np.ndarray): Volumes to be transformed.
**params (Any): Additional parameters.
"""
return self.apply(volumes, **params)
@batch_transform("spatial", has_batch_dim=True, has_depth_dim=False)
def apply_to_mask3d(self, mask3d: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the D4 transform to a 3D mask.
Args:
mask3d (np.ndarray): 3D mask to be transformed.
**params (Any): Additional parameters.
"""
return self.apply(mask3d, **params)
def get_params(self) -> dict[str, Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]]:
"""Get the parameters for the D4 transform.
Returns:
dict[str, Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]]: Parameters.
"""
return {
"group_element": self.random_generator.choice(d4_group_elements),
}
class SquareSymmetry(D4):
"""Applies one of the eight possible square symmetry transformations to a square-shaped input.
This is an alias for D4 transform with a more intuitive name for those not familiar with group theory.
The square symmetry transformations include:
- Identity: No transformation is applied
- 90° rotation: Rotate 90 degrees counterclockwise
- 180° rotation: Rotate 180 degrees
- 270° rotation: Rotate 270 degrees counterclockwise
- Vertical flip: Mirror across vertical axis
- Anti-diagonal flip: Mirror across anti-diagonal
- Horizontal flip: Mirror across horizontal axis
- Main diagonal flip: Mirror across main diagonal
Args:
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- This transform is particularly useful for augmenting data that does not have a clear orientation,
such as top-view satellite or drone imagery, or certain types of medical images.
- The input image should be square-shaped for optimal results. Non-square inputs may lead to
unexpected behavior or distortions.
- When applied to bounding boxes or keypoints, their coordinates will be adjusted according
to the selected transformation.
- This transform preserves the aspect ratio and size of the input.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> transform = A.Compose([
... A.SquareSymmetry(p=1.0),
... ])
>>> transformed = transform(image=image)
>>> transformed_image = transformed['image']
# The resulting image will be one of the 8 possible square symmetry transformations of the input
"""
@@ -0,0 +1,676 @@
"""Padding transformations for images and related data.
This module provides transformations for padding images and associated data. Padding is the process
of adding pixels to the borders of an image to increase its dimensions. Common use cases include:
- Ensuring uniform sizes for model inputs in a batch
- Making image dimensions divisible by specific values (often required by CNNs)
- Creating space around an image for annotations or visual purposes
- Standardizing data dimensions for processing pipelines
Padding transformations in this module support various border modes (constant, reflection, replication)
and properly handle all target types including images, masks, bounding boxes, and keypoints.
"""
from __future__ import annotations
from numbers import Real
from typing import Any, Literal
import cv2
import numpy as np
from pydantic import (
Field,
model_validator,
)
from typing_extensions import Self
from albumentations.core.bbox_utils import (
denormalize_bboxes,
normalize_bboxes,
)
from albumentations.core.transforms_interface import (
BaseTransformInitSchema,
DualTransform,
)
from albumentations.core.type_definitions import ALL_TARGETS
from . import functional as fgeometric
__all__ = [
"Pad",
"PadIfNeeded",
]
NUM_PADS_XY = 2
NUM_PADS_ALL_SIDES = 4
class Pad(DualTransform):
"""Pad the sides of an image by specified number of pixels.
Args:
padding (int, tuple[int, int] or tuple[int, int, int, int]): Padding values. Can be:
* int - pad all sides by this value
* tuple[int, int] - (pad_x, pad_y) to pad left/right by pad_x and top/bottom by pad_y
* tuple[int, int, int, int] - (left, top, right, bottom) specific padding per side
fill (tuple[float, ...] | float): Padding value if border_mode is cv2.BORDER_CONSTANT
fill_mask (tuple[float, ...] | float): Padding value for mask if border_mode is cv2.BORDER_CONSTANT
border_mode (OpenCV flag): OpenCV border mode
p (float): probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
References:
PyTorch Pad: https://pytorch.org/vision/main/generated/torchvision.transforms.v2.Pad.html
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # 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]
>>>
>>> # Example 1: Pad all sides by the same value
>>> transform = A.Compose([
... A.Pad(padding=20, border_mode=cv2.BORDER_CONSTANT, fill=0),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> padded = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the padded data
>>> padded_image = padded['image'] # Shape will be (140, 140, 3)
>>> padded_mask = padded['mask'] # Shape will be (140, 140)
>>> padded_bboxes = padded['bboxes'] # Bounding boxes coordinates adjusted to the padded image
>>> padded_keypoints = padded['keypoints'] # Keypoints coordinates adjusted to the padded image
>>>
>>> # Example 2: Different padding for sides using (pad_x, pad_y)
>>> transform_xy = A.Compose([
... A.Pad(
... padding=(10, 30), # 10px padding on left/right, 30px on top/bottom
... border_mode=cv2.BORDER_CONSTANT,
... fill=128 # Gray padding color
... ),
... ])
>>>
>>> padded_xy = transform_xy(image=image)
>>> padded_xy_image = padded_xy['image'] # Shape will be (160, 120, 3)
>>>
>>> # Example 3: Different padding for each side
>>> transform_sides = A.Compose([
... A.Pad(
... padding=(5, 10, 15, 20), # (left, top, right, bottom)
... border_mode=cv2.BORDER_CONSTANT,
... fill=0,
... fill_mask=0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))
>>>
>>> padded_sides = transform_sides(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels
... )
>>>
>>> padded_sides_image = padded_sides['image'] # Shape will be (130, 120, 3)
>>> padded_sides_bboxes = padded_sides['bboxes'] # Bounding boxes adjusted to the new coordinates
>>>
>>> # Example 4: Using different border_mode options
>>> # Create a smaller image for better visualization of reflection/wrapping
>>> small_image = np.random.randint(0, 256, (10, 10, 3), dtype=np.uint8)
>>>
>>> # Reflection padding
>>> reflect_pad = A.Compose([
... A.Pad(padding=5, border_mode=cv2.BORDER_REFLECT_101),
... ])
>>> reflected = reflect_pad(image=small_image)
>>> reflected_image = reflected['image'] # Shape will be (20, 20, 3) with reflected edges
>>>
>>> # Replicate padding
>>> replicate_pad = A.Compose([
... A.Pad(padding=5, border_mode=cv2.BORDER_REPLICATE),
... ])
>>> replicated = replicate_pad(image=small_image)
>>> replicated_image = replicated['image'] # Shape will be (20, 20, 3) with replicated edges
>>>
>>> # Example 5: Padding with masks and constant border mode
>>> binary_mask = np.zeros((50, 50), dtype=np.uint8)
>>> binary_mask[10:40, 10:40] = 1 # Set center region to 1
>>>
>>> mask_transform = A.Compose([
... A.Pad(
... padding=10,
... border_mode=cv2.BORDER_CONSTANT,
... fill=0, # Black padding for image
... fill_mask=0 # Use 0 for mask padding (background)
... ),
... ])
>>>
>>> padded_mask_result = mask_transform(image=image, mask=binary_mask)
>>> padded_binary_mask = padded_mask_result['mask'] # Shape will be (70, 70)
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
padding: int | tuple[int, int] | tuple[int, int, int, int]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
]
def __init__(
self,
padding: int | tuple[int, int] | tuple[int, int, int, int] = 0,
fill: tuple[float, ...] | float = 0,
fill_mask: tuple[float, ...] | float = 0,
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
] = cv2.BORDER_CONSTANT,
p: float = 1.0,
):
super().__init__(p=p)
self.padding = padding
self.fill = fill
self.fill_mask = fill_mask
self.border_mode = border_mode
def apply(
self,
img: np.ndarray,
pad_top: int,
pad_bottom: int,
pad_left: int,
pad_right: int,
**params: Any,
) -> np.ndarray:
"""Apply the Pad transform to an image.
Args:
img (np.ndarray): Image to be transformed.
pad_top (int): Top padding.
pad_bottom (int): Bottom padding.
pad_left (int): Left padding.
pad_right (int): Right padding.
**params (Any): Additional parameters.
"""
return fgeometric.pad_with_params(
img,
pad_top,
pad_bottom,
pad_left,
pad_right,
border_mode=self.border_mode,
value=self.fill,
)
def apply_to_mask(
self,
mask: np.ndarray,
pad_top: int,
pad_bottom: int,
pad_left: int,
pad_right: int,
**params: Any,
) -> np.ndarray:
"""Apply the Pad transform to a mask.
Args:
mask (np.ndarray): Mask to be transformed.
pad_top (int): Top padding.
pad_bottom (int): Bottom padding.
pad_left (int): Left padding.
pad_right (int): Right padding.
**params (Any): Additional parameters.
"""
return fgeometric.pad_with_params(
mask,
pad_top,
pad_bottom,
pad_left,
pad_right,
border_mode=self.border_mode,
value=self.fill_mask,
)
def apply_to_bboxes(
self,
bboxes: np.ndarray,
pad_top: int,
pad_bottom: int,
pad_left: int,
pad_right: int,
**params: Any,
) -> np.ndarray:
"""Apply the Pad transform to bounding boxes.
Args:
bboxes (np.ndarray): Bounding boxes to be transformed.
pad_top (int): Top padding.
pad_bottom (int): Bottom padding.
pad_left (int): Left padding.
pad_right (int): Right padding.
**params (Any): Additional parameters.
"""
image_shape = params["shape"][:2]
bboxes_np = denormalize_bboxes(bboxes, params["shape"])
result = fgeometric.pad_bboxes(
bboxes_np,
pad_top,
pad_bottom,
pad_left,
pad_right,
self.border_mode,
image_shape=image_shape,
)
rows, cols = params["shape"][:2]
return normalize_bboxes(
result,
(rows + pad_top + pad_bottom, cols + pad_left + pad_right),
)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
pad_top: int,
pad_bottom: int,
pad_left: int,
pad_right: int,
**params: Any,
) -> np.ndarray:
"""Apply the Pad transform to keypoints.
Args:
keypoints (np.ndarray): Keypoints to be transformed.
pad_top (int): Top padding.
pad_bottom (int): Bottom padding.
pad_left (int): Left padding.
pad_right (int): Right padding.
**params (Any): Additional parameters.
"""
return fgeometric.pad_keypoints(
keypoints,
pad_top,
pad_bottom,
pad_left,
pad_right,
self.border_mode,
image_shape=params["shape"][:2],
)
def apply_to_images(
self,
images: np.ndarray,
pad_top: int,
pad_bottom: int,
pad_left: int,
pad_right: int,
**params: Any,
) -> np.ndarray:
"""Apply the Pad transform to a batch of images.
Args:
images (np.ndarray): Batch of images to be transformed.
pad_top (int): Top padding.
pad_bottom (int): Bottom padding.
pad_left (int): Left padding.
pad_right (int): Right padding.
**params (Any): Additional parameters.
"""
return fgeometric.pad_images_with_params(
images,
pad_top,
pad_bottom,
pad_left,
pad_right,
border_mode=self.border_mode,
value=self.fill,
)
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, Any]:
"""Get the parameters dependent on the data.
Args:
params (dict[str, Any]): Parameters.
data (dict[str, Any]): Data.
Returns:
dict[str, Any]: Parameters.
"""
if isinstance(self.padding, Real):
pad_top = pad_bottom = pad_left = pad_right = self.padding
elif isinstance(self.padding, (tuple, list)):
if len(self.padding) == NUM_PADS_XY:
pad_left = pad_right = self.padding[0]
pad_top = pad_bottom = self.padding[1]
elif len(self.padding) == NUM_PADS_ALL_SIDES:
pad_left, pad_top, pad_right, pad_bottom = self.padding # type: ignore[misc]
else:
raise TypeError(
"Padding must be a single number, a pair of numbers, or a quadruple of numbers",
)
else:
raise TypeError(
"Padding must be a single number, a pair of numbers, or a quadruple of numbers",
)
return {
"pad_top": pad_top,
"pad_bottom": pad_bottom,
"pad_left": pad_left,
"pad_right": pad_right,
}
class PadIfNeeded(Pad):
"""Pads the sides of an image if the image dimensions are less than the specified minimum dimensions.
If the `pad_height_divisor` or `pad_width_divisor` is specified, the function additionally ensures
that the image dimensions are divisible by these values.
Args:
min_height (int | None): Minimum desired height of the image. Ensures image height is at least this value.
If not specified, pad_height_divisor must be provided.
min_width (int | None): Minimum desired width of the image. Ensures image width is at least this value.
If not specified, pad_width_divisor must be provided.
pad_height_divisor (int | None): If set, pads the image height to make it divisible by this value.
If not specified, min_height must be provided.
pad_width_divisor (int | None): If set, pads the image width to make it divisible by this value.
If not specified, min_width must be provided.
position (Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"]):
Position where the image is to be placed after padding. Default is 'center'.
border_mode (int): Specifies the border mode to use if padding is required.
The default is `cv2.BORDER_CONSTANT`.
fill (tuple[float, ...] | float | None): Value to fill the border pixels if the border mode
is `cv2.BORDER_CONSTANT`. Default is None.
fill_mask (tuple[float, ...] | float | None): Similar to `fill` but used for padding masks. Default is None.
p (float): Probability of applying the transform. Default is 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- Either `min_height` or `pad_height_divisor` must be set, but not both.
- Either `min_width` or `pad_width_divisor` must be set, but not both.
- If `border_mode` is set to `cv2.BORDER_CONSTANT`, `value` must be provided.
- The transform will maintain consistency across all targets (image, mask, bboxes, keypoints, volume).
- For bounding boxes, the coordinates will be adjusted to account for the padding.
- For keypoints, their positions will be shifted according to the padding.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # 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]
>>>
>>> # Example 1: Basic usage with min_height and min_width
>>> transform = A.Compose([
... A.PadIfNeeded(min_height=150, min_width=200, border_mode=cv2.BORDER_CONSTANT, fill=0),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> padded = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the padded data
>>> padded_image = padded['image'] # Shape will be (150, 200, 3)
>>> padded_mask = padded['mask'] # Shape will be (150, 200)
>>> padded_bboxes = padded['bboxes'] # Bounding boxes adjusted for the padded image
>>> padded_bbox_labels = padded['bbox_labels'] # Labels remain unchanged
>>> padded_keypoints = padded['keypoints'] # Keypoints adjusted for the padded image
>>> padded_keypoint_labels = padded['keypoint_labels'] # Labels remain unchanged
>>>
>>> # Example 2: Using pad_height_divisor and pad_width_divisor
>>> # This ensures the output dimensions are divisible by the specified values
>>> transform_divisor = A.Compose([
... A.PadIfNeeded(
... pad_height_divisor=32,
... pad_width_divisor=32,
... border_mode=cv2.BORDER_CONSTANT,
... fill=0
... ),
... ])
>>>
>>> padded_divisor = transform_divisor(image=image)
>>> padded_divisor_image = padded_divisor['image'] # Shape will be (128, 128, 3) - divisible by 32
>>>
>>> # Example 3: Different position options
>>> # Create a small recognizable image for better visualization of positioning
>>> small_image = np.zeros((50, 50, 3), dtype=np.uint8)
>>> small_image[20:30, 20:30, :] = 255 # White square in the middle
>>>
>>> # Top-left positioning
>>> top_left_pad = A.Compose([
... A.PadIfNeeded(
... min_height=100,
... min_width=100,
... position="top_left",
... border_mode=cv2.BORDER_CONSTANT,
... fill=128 # Gray padding
... ),
... ])
>>> top_left_result = top_left_pad(image=small_image)
>>> top_left_image = top_left_result['image'] # Image will be at top-left of 100x100 canvas
>>>
>>> # Center positioning (default)
>>> center_pad = A.Compose([
... A.PadIfNeeded(
... min_height=100,
... min_width=100,
... position="center",
... border_mode=cv2.BORDER_CONSTANT,
... fill=128
... ),
... ])
>>> center_result = center_pad(image=small_image)
>>> center_image = center_result['image'] # Image will be centered in 100x100 canvas
>>>
>>> # Example 4: Different border_mode options
>>> # Reflection padding
>>> reflect_pad = A.Compose([
... A.PadIfNeeded(
... min_height=100,
... min_width=100,
... border_mode=cv2.BORDER_REFLECT_101
... ),
... ])
>>> reflected = reflect_pad(image=small_image)
>>> reflected_image = reflected['image'] # Will use reflection for padding
>>>
>>> # Replication padding
>>> replicate_pad = A.Compose([
... A.PadIfNeeded(
... min_height=100,
... min_width=100,
... border_mode=cv2.BORDER_REPLICATE
... ),
... ])
>>> replicated = replicate_pad(image=small_image)
>>> replicated_image = replicated['image'] # Will use edge replication for padding
>>>
>>> # Example 5: Working with masks and custom fill values
>>> binary_mask = np.zeros((50, 50), dtype=np.uint8)
>>> binary_mask[10:40, 10:40] = 1 # Set center region to 1
>>>
>>> mask_transform = A.Compose([
... A.PadIfNeeded(
... min_height=100,
... min_width=100,
... border_mode=cv2.BORDER_CONSTANT,
... fill=0, # Black padding for image
... fill_mask=0 # Use 0 for mask padding (background)
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']))
>>>
>>> padded_mask_result = mask_transform(
... image=image,
... mask=binary_mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels
... )
>>> padded_binary_mask = padded_mask_result['mask'] # Shape will be (100, 100)
>>> padded_result_bboxes = padded_mask_result['bboxes'] # Adjusted for padding
>>> padded_result_bbox_labels = padded_mask_result['bbox_labels'] # Labels remain unchanged
"""
class InitSchema(BaseTransformInitSchema):
min_height: int | None = Field(ge=1)
min_width: int | None = Field(ge=1)
pad_height_divisor: int | None = Field(ge=1)
pad_width_divisor: int | None = Field(ge=1)
position: Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"]
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
@model_validator(mode="after")
def _validate_divisibility(self) -> Self:
if (self.min_height is None) == (self.pad_height_divisor is None):
msg = "Only one of 'min_height' and 'pad_height_divisor' parameters must be set"
raise ValueError(msg)
if (self.min_width is None) == (self.pad_width_divisor is None):
msg = "Only one of 'min_width' and 'pad_width_divisor' parameters must be set"
raise ValueError(msg)
if self.border_mode == cv2.BORDER_CONSTANT and self.fill is None:
msg = "If 'border_mode' is set to 'BORDER_CONSTANT', 'fill' must be provided."
raise ValueError(msg)
return self
def __init__(
self,
min_height: int | None = 1024,
min_width: int | None = 1024,
pad_height_divisor: int | None = None,
pad_width_divisor: int | None = None,
position: Literal["center", "top_left", "top_right", "bottom_left", "bottom_right", "random"] = "center",
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
] = cv2.BORDER_CONSTANT,
fill: tuple[float, ...] | float = 0,
fill_mask: tuple[float, ...] | float = 0,
p: float = 1.0,
):
# Initialize with dummy padding that will be calculated later
super().__init__(
padding=0,
fill=fill,
fill_mask=fill_mask,
border_mode=border_mode,
p=p,
)
self.min_height = min_height
self.min_width = min_width
self.pad_height_divisor = pad_height_divisor
self.pad_width_divisor = pad_width_divisor
self.position = position
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, Any]:
"""Get the parameters dependent on the data.
Args:
params (dict[str, Any]): Parameters.
data (dict[str, Any]): Data.
Returns:
dict[str, Any]: Parameters.
"""
h_pad_top, h_pad_bottom, w_pad_left, w_pad_right = fgeometric.get_padding_params(
image_shape=params["shape"][:2],
min_height=self.min_height,
min_width=self.min_width,
pad_height_divisor=self.pad_height_divisor,
pad_width_divisor=self.pad_width_divisor,
)
h_pad_top, h_pad_bottom, w_pad_left, w_pad_right = fgeometric.adjust_padding_by_position(
h_top=h_pad_top,
h_bottom=h_pad_bottom,
w_left=w_pad_left,
w_right=w_pad_right,
position=self.position,
py_random=self.py_random,
)
return {
"pad_top": h_pad_top,
"pad_bottom": h_pad_bottom,
"pad_left": w_pad_left,
"pad_right": w_pad_right,
}
@@ -0,0 +1,956 @@
"""Transforms for resizing images and associated data.
This module provides transform classes for resizing operations, including uniform resizing,
scaling with aspect ratio preservation, and size-constrained transformations.
"""
from __future__ import annotations
from collections.abc import Sequence
from typing import Any, Literal, cast
import cv2
import numpy as np
from albucore import batch_transform
from pydantic import Field, field_validator, model_validator
from typing_extensions import Self
from albumentations.core.transforms_interface import BaseTransformInitSchema, DualTransform
from albumentations.core.type_definitions import ALL_TARGETS
from albumentations.core.utils import to_tuple
from . import functional as fgeometric
__all__ = ["LongestMaxSize", "RandomScale", "Resize", "SmallestMaxSize"]
class RandomScale(DualTransform):
"""Randomly resize the input. Output image size is different from the input image size.
Args:
scale_limit (float or tuple[float, float]): scaling factor range. If scale_limit is a single float value, the
range will be (-scale_limit, scale_limit). Note that the scale_limit will be biased by 1.
If scale_limit is a tuple, like (low, high), sampling will be done from the range (1 + low, 1 + high).
Default: (-0.1, 0.1).
interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:
cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_LINEAR.
mask_interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm for mask.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
for downscaling. Options:
- None: No automatic interpolation selection, always use the specified interpolation method
- "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
- "image_mask": Use INTER_AREA when downscaling both images and masks
Default: None.
p (float): probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The output image size is different from the input image size.
- Scale factor is sampled independently per image side (width and height).
- Bounding box coordinates are scaled accordingly.
- Keypoint coordinates are scaled accordingly.
- When area_for_downscale is set, INTER_AREA interpolation will be used automatically for
downscaling (scale < 1.0), which provides better quality for size reduction.
Mathematical formulation:
Let (W, H) be the original image dimensions and (W', H') be the output dimensions.
The scale factor s is sampled from the range [1 + scale_limit[0], 1 + scale_limit[1]].
Then, W' = W * s and H' = H * s.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Create sample data for demonstration
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> # Add some shapes to visualize scaling effects
>>> cv2.rectangle(image, (25, 25), (75, 75), (255, 0, 0), -1) # Red square
>>> cv2.circle(image, (50, 50), 10, (0, 255, 0), -1) # Green circle
>>>
>>> # Create a mask for segmentation
>>> mask = np.zeros((100, 100), dtype=np.uint8)
>>> mask[25:75, 25:75] = 1 # Mask covering the red square
>>>
>>> # Create bounding boxes and keypoints
>>> bboxes = np.array([[25, 25, 75, 75]]) # Box around the red square
>>> bbox_labels = [1]
>>> keypoints = np.array([[50, 50]]) # Center of circle
>>> keypoint_labels = [0]
>>>
>>> # Apply RandomScale transform with comprehensive parameters
>>> transform = A.Compose([
... A.RandomScale(
... scale_limit=(-0.3, 0.5), # Scale between 0.7x and 1.5x
... interpolation=cv2.INTER_LINEAR,
... mask_interpolation=cv2.INTER_NEAREST,
... area_for_downscale="image", # Use INTER_AREA for image downscaling
... p=1.0 # Always apply
... )
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform to all targets
>>> result = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed results
>>> scaled_image = result['image'] # Dimensions will be between 70-150 pixels
>>> scaled_mask = result['mask'] # Mask scaled proportionally to image
>>> scaled_bboxes = result['bboxes'] # Bounding boxes adjusted to new dimensions
>>> scaled_bbox_labels = result['bbox_labels'] # Labels remain unchanged
>>> scaled_keypoints = result['keypoints'] # Keypoints adjusted to new dimensions
>>> scaled_keypoint_labels = result['keypoint_labels'] # Labels remain unchanged
>>>
>>> # The image dimensions will vary based on the randomly sampled scale factor
>>> # With scale_limit=(-0.3, 0.5), dimensions could be anywhere from 70% to 150% of original
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
scale_limit: tuple[float, float] | float
area_for_downscale: Literal[None, "image", "image_mask"]
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
@field_validator("scale_limit")
@classmethod
def _check_scale_limit(cls, v: tuple[float, float] | float) -> tuple[float, float]:
return to_tuple(v)
def __init__(
self,
scale_limit: tuple[float, float] | float = (-0.1, 0.1),
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
area_for_downscale: Literal[None, "image", "image_mask"] = None,
p: float = 0.5,
):
super().__init__(p=p)
self.scale_limit = cast("tuple[float, float]", scale_limit)
self.interpolation = interpolation
self.mask_interpolation = mask_interpolation
self.area_for_downscale = area_for_downscale
def get_params(self) -> dict[str, float]:
"""Get parameters for the transform.
Returns:
dict[str, float]: Dictionary with parameters.
"""
return {"scale": self.py_random.uniform(*self.scale_limit) + 1.0}
def apply(
self,
img: np.ndarray,
scale: float,
**params: Any,
) -> np.ndarray:
"""Apply scaling to the image.
Args:
img (np.ndarray): Image to scale.
scale (float): Scaling factor.
**params (Any): Additional parameters.
Returns:
np.ndarray: Scaled image.
"""
interpolation = self.interpolation
if self.area_for_downscale in ["image", "image_mask"] and scale < 1.0:
interpolation = cv2.INTER_AREA
return fgeometric.scale(img, scale, interpolation)
def apply_to_mask(
self,
mask: np.ndarray,
scale: float,
**params: Any,
) -> np.ndarray:
"""Apply scaling to the mask.
Args:
mask (np.ndarray): Mask to scale.
scale (float): Scaling factor.
**params (Any): Additional parameters.
Returns:
np.ndarray: Scaled mask.
"""
interpolation = self.mask_interpolation
if self.area_for_downscale == "image_mask" and scale < 1.0:
interpolation = cv2.INTER_AREA
return fgeometric.scale(mask, scale, interpolation)
def apply_to_bboxes(self, bboxes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the transform to bounding boxes.
Args:
bboxes (np.ndarray): Bounding boxes to transform.
**params (Any): Additional parameters.
Returns:
np.ndarray: Transformed bounding boxes which are scale invariant.
"""
# Bounding box coordinates are scale invariant
return bboxes
def apply_to_keypoints(
self,
keypoints: np.ndarray,
scale: float,
**params: Any,
) -> np.ndarray:
"""Apply scaling to keypoints.
Args:
keypoints (np.ndarray): Keypoints to scale.
scale (float): Scaling factor.
**params (Any): Additional parameters.
Returns:
np.ndarray: Scaled keypoints.
"""
return fgeometric.keypoints_scale(keypoints, scale, scale)
class MaxSizeTransform(DualTransform):
"""Base class for transforms that resize based on maximum size constraints.
This class provides common functionality for derived transforms like LongestMaxSize and
SmallestMaxSize that resize images based on size constraints while preserving aspect ratio.
Args:
max_size (int, Sequence[int], optional): Maximum size constraint. The specific interpretation
depends on the derived class. Default: None.
max_size_hw (tuple[int | None, int | None], optional): Maximum (height, width) constraints.
Either max_size or max_size_hw must be specified, but not both. Default: None.
interpolation (OpenCV flag): Flag for the interpolation algorithm. Should be one of:
cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_LINEAR.
mask_interpolation (OpenCV flag): Flag for the mask interpolation algorithm.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
for downscaling. Options:
- None: No automatic interpolation selection, always use the specified interpolation method
- "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
- "image_mask": Use INTER_AREA when downscaling both images and masks
Default: None.
p (float): Probability of applying the transform. Default: 1.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- This is a base class that should be extended by concrete resize transforms.
- The scaling calculation is implemented in derived classes.
- Aspect ratio is preserved by applying the same scale factor to both dimensions.
- When area_for_downscale is set, INTER_AREA interpolation will be used automatically for
downscaling (scale < 1.0), which provides better quality for size reduction.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Example of creating a custom transform that extends MaxSizeTransform
>>> class CustomMaxSize(A.MaxSizeTransform):
... def get_params_dependent_on_data(self, params, data):
... img_h, img_w = params["shape"][:2]
... # Calculate scale factor - here we scale to make the image area constant
... target_area = 300 * 300 # Target area of 300x300
... current_area = img_h * img_w
... scale = np.sqrt(target_area / current_area)
... return {"scale": scale}
>>>
>>> # Prepare sample data
>>> image = np.zeros((100, 200, 3), dtype=np.uint8)
>>> # Add a rectangle to visualize the effect
>>> cv2.rectangle(image, (50, 20), (150, 80), (255, 0, 0), -1)
>>>
>>> # Create a mask
>>> mask = np.zeros((100, 200), dtype=np.uint8)
>>> mask[20:80, 50:150] = 1
>>>
>>> # Create bounding boxes and keypoints
>>> bboxes = np.array([[50, 20, 150, 80]])
>>> bbox_labels = [1]
>>> keypoints = np.array([[100, 50]])
>>> keypoint_labels = [0]
>>>
>>> # Apply the custom transform
>>> transform = A.Compose([
... CustomMaxSize(
... max_size=None,
... max_size_hw=(None, None), # Not used in our custom implementation
... interpolation=cv2.INTER_LINEAR,
... mask_interpolation=cv2.INTER_NEAREST,
... area_for_downscale="image", # Use INTER_AREA when downscaling images
... p=1.0
... )
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform
>>> result = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get results
>>> transformed_image = result['image'] # Shape will be approximately (122, 245, 3)
>>> transformed_mask = result['mask'] # Shape will be approximately (122, 245)
>>> transformed_bboxes = result['bboxes'] # Bounding boxes are scale invariant
>>> transformed_keypoints = result['keypoints'] # Keypoints scaled proportionally
>>> transformed_bbox_labels = result['bbox_labels'] # Labels remain unchanged
>>> transformed_keypoint_labels = result['keypoint_labels'] # Labels remain unchanged
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
max_size: int | list[int] | None
max_size_hw: tuple[int | None, int | None] | None
area_for_downscale: Literal[None, "image", "image_mask"]
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
@model_validator(mode="after")
def validate_size_parameters(self) -> Self:
if self.max_size is None and self.max_size_hw is None:
raise ValueError("Either max_size or max_size_hw must be specified")
if self.max_size is not None and self.max_size_hw is not None:
raise ValueError("Only one of max_size or max_size_hw should be specified")
return self
def __init__(
self,
max_size: int | Sequence[int] | None = None,
max_size_hw: tuple[int | None, int | None] | None = None,
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
area_for_downscale: Literal[None, "image", "image_mask"] = None,
p: float = 1,
):
super().__init__(p=p)
self.max_size = max_size
self.max_size_hw = max_size_hw
self.interpolation = interpolation
self.mask_interpolation = mask_interpolation
self.area_for_downscale = area_for_downscale
def apply(
self,
img: np.ndarray,
scale: float,
**params: Any,
) -> np.ndarray:
height, width = img.shape[:2]
new_height, new_width = max(1, round(height * scale)), max(1, round(width * scale))
interpolation = self.interpolation
if self.area_for_downscale in ["image", "image_mask"] and scale < 1.0:
interpolation = cv2.INTER_AREA
return fgeometric.resize(img, (new_height, new_width), interpolation=interpolation)
def apply_to_mask(
self,
mask: np.ndarray,
scale: float,
**params: Any,
) -> np.ndarray:
height, width = mask.shape[:2]
new_height, new_width = max(1, round(height * scale)), max(1, round(width * scale))
interpolation = self.mask_interpolation
if self.area_for_downscale == "image_mask" and scale < 1.0:
interpolation = cv2.INTER_AREA
return fgeometric.resize(mask, (new_height, new_width), interpolation=interpolation)
def apply_to_bboxes(self, bboxes: np.ndarray, **params: Any) -> np.ndarray:
# Bounding box coordinates are scale invariant
return bboxes
def apply_to_keypoints(
self,
keypoints: np.ndarray,
scale: float,
**params: Any,
) -> np.ndarray:
return fgeometric.keypoints_scale(keypoints, scale, scale)
@batch_transform("spatial", has_batch_dim=True, has_depth_dim=False)
def apply_to_images(self, images: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
return self.apply(images, *args, **params)
@batch_transform("spatial", has_batch_dim=False, has_depth_dim=True)
def apply_to_volume(self, volume: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
return self.apply(volume, *args, **params)
@batch_transform("spatial", has_batch_dim=True, has_depth_dim=True)
def apply_to_volumes(self, volumes: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
return self.apply(volumes, *args, **params)
@batch_transform("spatial", has_batch_dim=True, has_depth_dim=True)
def apply_to_mask3d(self, mask3d: np.ndarray, *args: Any, **params: Any) -> np.ndarray:
return self.apply_to_mask(mask3d, *args, **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:
return self.apply_to_mask(masks3d, *args, **params)
class LongestMaxSize(MaxSizeTransform):
"""Rescale an image so that the longest side is equal to max_size or sides meet max_size_hw constraints,
keeping the aspect ratio.
Args:
max_size (int, Sequence[int], optional): Maximum size of the longest side after the transformation.
When using a list or tuple, the max size will be randomly selected from the values provided. Default: None.
max_size_hw (tuple[int | None, int | None], optional): Maximum (height, width) constraints. Supports:
- (height, width): Both dimensions must fit within these bounds
- (height, None): Only height is constrained, width scales proportionally
- (None, width): Only width is constrained, height scales proportionally
If specified, max_size must be None. Default: None.
interpolation (OpenCV flag): interpolation method. Default: cv2.INTER_LINEAR.
mask_interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm for mask.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
for downscaling. Options:
- None: No automatic interpolation selection, always use the specified interpolation method
- "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
- "image_mask": Use INTER_AREA when downscaling both images and masks
Default: None.
p (float): probability of applying the transform. Default: 1.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- If the longest side of the image is already equal to max_size, the image will not be resized.
- This transform will not crop the image. The resulting image may be smaller than specified in both dimensions.
- For non-square images, both sides will be scaled proportionally to maintain the aspect ratio.
- Bounding boxes and keypoints are scaled accordingly.
- When area_for_downscale is set, INTER_AREA will be used for downscaling, providing better quality.
Mathematical Details:
Let (W, H) be the original width and height of the image.
When using max_size:
1. The scaling factor s is calculated as:
s = max_size / max(W, H)
2. The new dimensions (W', H') are:
W' = W * s
H' = H * s
When using max_size_hw=(H_target, W_target):
1. For both dimensions specified:
s = min(H_target/H, W_target/W)
This ensures both dimensions fit within the specified bounds.
2. For height only (W_target=None):
s = H_target/H
Width will scale proportionally.
3. For width only (H_target=None):
s = W_target/W
Height will scale proportionally.
4. The new dimensions (W', H') are:
W' = W * s
H' = H * s
Examples:
>>> import albumentations as A
>>> import cv2
>>> # Using max_size
>>> transform1 = A.LongestMaxSize(max_size=1024, area_for_downscale="image")
>>> # Input image (1500, 800) -> Output (1024, 546)
>>>
>>> # Using max_size_hw with both dimensions
>>> transform2 = A.LongestMaxSize(max_size_hw=(800, 1024), area_for_downscale="image_mask")
>>> # Input (1500, 800) -> Output (800, 427)
>>> # Input (800, 1500) -> Output (546, 1024)
>>>
>>> # Using max_size_hw with only height
>>> transform3 = A.LongestMaxSize(max_size_hw=(800, None))
>>> # Input (1500, 800) -> Output (800, 427)
>>>
>>> # Common use case with padding
>>> transform4 = A.Compose([
... A.LongestMaxSize(max_size=1024, area_for_downscale="image"),
... A.PadIfNeeded(min_height=1024, min_width=1024),
... ])
"""
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Calculate parameters that depend on the input data.
Args:
params (dict[str, Any]): Parameters dictionary.
data (dict[str, Any]): Dictionary containing input data.
Returns:
dict[str, Any]: Dictionary with parameters calculated based on input data.
"""
img_h, img_w = params["shape"][:2]
if self.max_size is not None:
if isinstance(self.max_size, (list, tuple)):
max_size = self.py_random.choice(self.max_size)
else:
max_size = self.max_size
scale = max_size / max(img_h, img_w)
elif self.max_size_hw is not None:
# We know max_size_hw is not None here due to model validator
max_h, max_w = self.max_size_hw
if max_h is not None and max_w is not None:
# Scale based on longest side to maintain aspect ratio
h_scale = max_h / img_h
w_scale = max_w / img_w
scale = min(h_scale, w_scale)
elif max_h is not None:
# Only height specified
scale = max_h / img_h
else:
# Only width specified
scale = max_w / img_w
return {"scale": scale}
class SmallestMaxSize(MaxSizeTransform):
"""Rescale an image so that minimum side is equal to max_size or sides meet max_size_hw constraints,
keeping the aspect ratio.
Args:
max_size (int, list of int, optional): Maximum size of smallest side of the image after the transformation.
When using a list, max size will be randomly selected from the values in the list. Default: None.
max_size_hw (tuple[int | None, int | None], optional): Maximum (height, width) constraints. Supports:
- (height, width): Both dimensions must be at least these values
- (height, None): Only height is constrained, width scales proportionally
- (None, width): Only width is constrained, height scales proportionally
If specified, max_size must be None. Default: None.
interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm. Should be one of:
cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_LINEAR.
mask_interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm for mask.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
for downscaling. Options:
- None: No automatic interpolation selection, always use the specified interpolation method
- "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
- "image_mask": Use INTER_AREA when downscaling both images and masks
Default: None.
p (float): Probability of applying the transform. Default: 1.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- If the smallest side of the image is already equal to max_size, the image will not be resized.
- This transform will not crop the image. The resulting image may be larger than specified in both dimensions.
- For non-square images, both sides will be scaled proportionally to maintain the aspect ratio.
- Bounding boxes and keypoints are scaled accordingly.
- When area_for_downscale is set, INTER_AREA will be used for downscaling, providing better quality.
Mathematical Details:
Let (W, H) be the original width and height of the image.
When using max_size:
1. The scaling factor s is calculated as:
s = max_size / min(W, H)
2. The new dimensions (W', H') are:
W' = W * s
H' = H * s
When using max_size_hw=(H_target, W_target):
1. For both dimensions specified:
s = max(H_target/H, W_target/W)
This ensures both dimensions are at least as large as specified.
2. For height only (W_target=None):
s = H_target/H
Width will scale proportionally.
3. For width only (H_target=None):
s = W_target/W
Height will scale proportionally.
4. The new dimensions (W', H') are:
W' = W * s
H' = H * s
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> # Using max_size
>>> transform1 = A.SmallestMaxSize(max_size=120, area_for_downscale="image")
>>> # Input image (100, 150) -> Output (120, 180)
>>>
>>> # Using max_size_hw with both dimensions
>>> transform2 = A.SmallestMaxSize(max_size_hw=(100, 200), area_for_downscale="image_mask")
>>> # Input (80, 160) -> Output (100, 200)
>>> # Input (160, 80) -> Output (400, 200)
>>>
>>> # Using max_size_hw with only height
>>> transform3 = A.SmallestMaxSize(max_size_hw=(100, None))
>>> # Input (80, 160) -> Output (100, 200)
"""
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Calculate parameters that depend on the input data.
Args:
params (dict[str, Any]): Parameters dictionary.
data (dict[str, Any]): Dictionary containing input data.
Returns:
dict[str, Any]: Dictionary with parameters calculated based on input data.
"""
img_h, img_w = params["shape"][:2]
if self.max_size is not None:
if isinstance(self.max_size, (list, tuple)):
max_size = self.py_random.choice(self.max_size)
else:
max_size = self.max_size
scale = max_size / min(img_h, img_w)
elif self.max_size_hw is not None:
max_h, max_w = self.max_size_hw
if max_h is not None and max_w is not None:
# Scale based on smallest side to maintain aspect ratio
h_scale = max_h / img_h
w_scale = max_w / img_w
scale = max(h_scale, w_scale)
elif max_h is not None:
# Only height specified
scale = max_h / img_h
else:
# Only width specified
scale = max_w / img_w
return {"scale": scale}
class Resize(DualTransform):
"""Resize the input to the given height and width.
Args:
height (int): desired height of the output.
width (int): desired width of the output.
interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm. Should be one of:
cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_LINEAR.
mask_interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm for mask.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
area_for_downscale (Literal[None, "image", "image_mask"]): Controls automatic use of INTER_AREA interpolation
for downscaling. Options:
- None: No automatic interpolation selection, always use the specified interpolation method
- "image": Use INTER_AREA when downscaling images, retain specified interpolation for upscaling and masks
- "image_mask": Use INTER_AREA when downscaling both images and masks
Default: None.
p (float): probability of applying the transform. Default: 1.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Create sample data for demonstration
>>> image = np.zeros((100, 100, 3), dtype=np.uint8)
>>> # Add some shapes to visualize resize effects
>>> cv2.rectangle(image, (25, 25), (75, 75), (255, 0, 0), -1) # Red square
>>> cv2.circle(image, (50, 50), 10, (0, 255, 0), -1) # Green circle
>>>
>>> # Create a mask for segmentation
>>> mask = np.zeros((100, 100), dtype=np.uint8)
>>> mask[25:75, 25:75] = 1 # Mask covering the red square
>>>
>>> # Create bounding boxes and keypoints
>>> bboxes = np.array([[25, 25, 75, 75]]) # Box around the red square
>>> bbox_labels = [1]
>>> keypoints = np.array([[50, 50]]) # Center of circle
>>> keypoint_labels = [0]
>>>
>>> # Resize all data to 224x224 (common input size for many CNNs)
>>> transform = A.Compose([
... A.Resize(
... height=224,
... width=224,
... interpolation=cv2.INTER_LINEAR,
... mask_interpolation=cv2.INTER_NEAREST,
... area_for_downscale="image", # Use INTER_AREA when downscaling images
... p=1.0
... )
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>>
>>> # Apply the transform to all targets
>>> result = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>>
>>> # Get the transformed results
>>> resized_image = result['image'] # Shape will be (224, 224, 3)
>>> resized_mask = result['mask'] # Shape will be (224, 224)
>>> resized_bboxes = result['bboxes'] # Bounding boxes scaled to new dimensions
>>> resized_bbox_labels = result['bbox_labels'] # Labels remain unchanged
>>> resized_keypoints = result['keypoints'] # Keypoints scaled to new dimensions
>>> resized_keypoint_labels = result['keypoint_labels'] # Labels remain unchanged
>>>
>>> # Note: When resizing from 100x100 to 224x224:
>>> # - The red square will be scaled from (25-75) to approximately (56-168)
>>> # - The keypoint at (50, 50) will move to approximately (112, 112)
>>> # - All spatial relationships are preserved but coordinates are scaled
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
height: int = Field(ge=1)
width: int = Field(ge=1)
area_for_downscale: Literal[None, "image", "image_mask"]
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
def __init__(
self,
height: int,
width: int,
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
area_for_downscale: Literal[None, "image", "image_mask"] = None,
p: float = 1,
):
super().__init__(p=p)
self.height = height
self.width = width
self.interpolation = interpolation
self.mask_interpolation = mask_interpolation
self.area_for_downscale = area_for_downscale
def apply(self, img: np.ndarray, **params: Any) -> np.ndarray:
"""Apply resizing to the image.
Args:
img (np.ndarray): Image to resize.
**params (Any): Additional parameters.
Returns:
np.ndarray: Resized image.
"""
height, width = img.shape[:2]
is_downscale = (self.height < height) or (self.width < width)
interpolation = self.interpolation
if self.area_for_downscale in ["image", "image_mask"] and is_downscale:
interpolation = cv2.INTER_AREA
return fgeometric.resize(img, (self.height, self.width), interpolation=interpolation)
def apply_to_mask(self, mask: np.ndarray, **params: Any) -> np.ndarray:
"""Apply resizing to the mask.
Args:
mask (np.ndarray): Mask to resize.
**params (Any): Additional parameters.
Returns:
np.ndarray: Resized mask.
"""
height, width = mask.shape[:2]
is_downscale = (self.height < height) or (self.width < width)
interpolation = self.mask_interpolation
if self.area_for_downscale == "image_mask" and is_downscale:
interpolation = cv2.INTER_AREA
return fgeometric.resize(mask, (self.height, self.width), interpolation=interpolation)
def apply_to_bboxes(self, bboxes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the transform to bounding boxes.
Args:
bboxes (np.ndarray): Bounding boxes to transform.
**params (Any): Additional parameters.
Returns:
np.ndarray: Transformed bounding boxes which are scale invariant.
"""
# Bounding box coordinates are scale invariant
return bboxes
def apply_to_keypoints(self, keypoints: np.ndarray, **params: Any) -> np.ndarray:
"""Apply resizing to keypoints.
Args:
keypoints (np.ndarray): Keypoints to resize.
**params (Any): Additional parameters.
Returns:
np.ndarray: Resized keypoints.
"""
height, width = params["shape"][:2]
scale_x = self.width / width
scale_y = self.height / height
return fgeometric.keypoints_scale(keypoints, scale_x, scale_y)
@@ -0,0 +1,850 @@
"""Transforms for rotating images and associated data.
This module provides classes for rotating images, masks, bounding boxes, and keypoints.
Includes transforms for 90-degree rotations and arbitrary angle rotations with various
border handling options.
"""
from __future__ import annotations
import math
from typing import Any, cast
import cv2
import numpy as np
from typing_extensions import Literal
from albumentations.augmentations.crops import functional as fcrops
from albumentations.augmentations.geometric.transforms import Affine
from albumentations.core.pydantic import SymmetricRangeType
from albumentations.core.transforms_interface import (
BaseTransformInitSchema,
DualTransform,
)
from albumentations.core.type_definitions import ALL_TARGETS
from . import functional as fgeometric
__all__ = ["RandomRotate90", "Rotate", "SafeRotate"]
SMALL_NUMBER = 1e-10
class RandomRotate90(DualTransform):
"""Randomly rotate the input by 90 degrees zero or more times.
Even with p=1.0, the transform has a 1/4 probability of being identity:
- With probability p * 1/4: no rotation (0 degrees)
- With probability p * 1/4: rotate 90 degrees
- With probability p * 1/4: rotate 180 degrees
- With probability p * 1/4: rotate 270 degrees
For example:
- With p=1.0: Each rotation angle (including 0°) has 0.25 probability
- With p=0.8: Each rotation angle has 0.2 probability, and no transform has 0.2 probability
- With p=0.5: Each rotation angle has 0.125 probability, and no transform has 0.5 probability
Common applications:
- Aerial/satellite imagery: Objects can appear in any orientation
- Medical imaging: Scans/slides may not have a consistent orientation
- Document analysis: Pages or symbols might be rotated
- Microscopy: Cell orientation is often arbitrary
- Game development: Sprites/textures that should work in multiple orientations
Not recommended for:
- Natural scene images where gravity matters (e.g., landscape photography)
- Face detection/recognition tasks
- Text recognition (unless text can appear rotated)
- Tasks where object orientation is important for classification
Note:
If your domain has both 90-degree rotation AND flip symmetries
(e.g., satellite imagery, microscopy), consider using `D4` transform instead.
`D4` is more efficient and mathematically correct as it:
- Samples uniformly from all 8 possible combinations of rotations and flips
- Properly represents the dihedral group D4 symmetries
- Avoids potential correlation between separate rotation and flip augmentations
Args:
p (float): probability of applying the transform. Default: 1.0.
Note that even with p=1.0, there's still a 0.25 probability
of getting a 0-degree rotation (identity transform).
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> # Create example 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] # Class labels for bounding boxes
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1] # Labels for keypoints
>>> # Define the transform
>>> transform = A.Compose([
... A.RandomRotate90(p=1.0),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>> # Apply the transform to all targets
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>> rotated_image = transformed["image"]
>>> rotated_mask = transformed["mask"]
>>> rotated_bboxes = transformed["bboxes"]
>>> rotated_bbox_labels = transformed["bbox_labels"]
>>> rotated_keypoints = transformed["keypoints"]
>>> rotated_keypoint_labels = transformed["keypoint_labels"]
"""
_targets = ALL_TARGETS
def __init__(
self,
p: float = 1,
):
super().__init__(p=p)
def apply(self, img: np.ndarray, factor: Literal[0, 1, 2, 3], **params: Any) -> np.ndarray:
"""Apply rotation to the input image.
Args:
img (np.ndarray): Image to rotate.
factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
**params (Any): Additional parameters.
Returns:
np.ndarray: Rotated image.
"""
return fgeometric.rot90(img, factor)
def get_params(self) -> dict[str, int]:
"""Get parameters for the transform.
Returns:
dict[str, int]: Dictionary with the rotation factor.
"""
# Random int in the range [0, 3]
return {"factor": self.py_random.randint(0, 3)}
def apply_to_bboxes(
self,
bboxes: np.ndarray,
factor: Literal[0, 1, 2, 3],
**params: Any,
) -> np.ndarray:
"""Apply rotation to bounding boxes.
Args:
bboxes (np.ndarray): Bounding boxes to rotate.
factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
**params (Any): Additional parameters.
Returns:
np.ndarray: Rotated bounding boxes.
"""
return fgeometric.bboxes_rot90(bboxes, factor)
def apply_to_keypoints(
self,
keypoints: np.ndarray,
factor: Literal[0, 1, 2, 3],
**params: Any,
) -> np.ndarray:
"""Apply rotation to keypoints.
Args:
keypoints (np.ndarray): Keypoints to rotate.
factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
**params (Any): Additional parameters.
Returns:
np.ndarray: Rotated keypoints.
"""
return fgeometric.keypoints_rot90(keypoints, factor, params["shape"])
def apply_to_volume(self, volume: np.ndarray, factor: Literal[0, 1, 2, 3], **params: Any) -> np.ndarray:
"""Apply rotation to the input volume.
Args:
volume (np.ndarray): Volume to rotate.
factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
**params (Any): Additional parameters.
Returns:
np.ndarray: Rotated volume.
"""
return fgeometric.volume_rot90(volume, factor)
def apply_to_volumes(self, volumes: np.ndarray, factor: Literal[0, 1, 2, 3], **params: Any) -> np.ndarray:
"""Apply rotation to the input volumes.
Args:
volumes (np.ndarray): Volumes to rotate.
factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
**params (Any): Additional parameters.
Returns:
np.ndarray: Rotated volumes.
"""
return fgeometric.volumes_rot90(volumes, factor)
def apply_to_mask3d(self, mask3d: np.ndarray, factor: Literal[0, 1, 2, 3], **params: Any) -> np.ndarray:
"""Apply rotation to the input mask3d.
Args:
mask3d (np.ndarray): Mask3d to rotate.
factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
**params (Any): Additional parameters.
Returns:
np.ndarray: Rotated mask3d.
"""
return fgeometric.volume_rot90(mask3d, factor)
def apply_to_masks3d(self, masks3d: np.ndarray, factor: Literal[0, 1, 2, 3], **params: Any) -> np.ndarray:
"""Apply rotation to the input masks3d.
Args:
masks3d (np.ndarray): Masks3d to rotate.
factor (Literal[0, 1, 2, 3]): Number of times to rotate by 90 degrees.
**params (Any): Additional parameters.
Returns:
np.ndarray: Rotated masks3d.
"""
return fgeometric.volumes_rot90(masks3d, factor)
class RotateInitSchema(BaseTransformInitSchema):
limit: SymmetricRangeType
interpolation: Literal[cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
]
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float | None
class Rotate(DualTransform):
"""Rotate the input by an angle selected randomly from the uniform distribution.
Args:
limit (float | tuple[float, float]): Range from which a random angle is picked. If limit is a single float,
an angle is picked from (-limit, limit). Default: (-90, 90)
interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm. Should be one of:
cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_LINEAR.
border_mode (OpenCV flag): Flag that is used to specify the pixel extrapolation method. Should be one of:
cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101.
Default: cv2.BORDER_CONSTANT
fill (tuple[float, ...] | float): Padding value if border_mode is cv2.BORDER_CONSTANT.
fill_mask (tuple[float, ...] | float): Padding value if border_mode is cv2.BORDER_CONSTANT applied for masks.
rotate_method (Literal["largest_box", "ellipse"]): Method to rotate bounding boxes.
Should be 'largest_box' or 'ellipse'. Default: 'largest_box'
crop_border (bool): Whether to crop border after rotation. If True, the output image size might differ
from the input. Default: False
mask_interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm for mask.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The rotation angle is randomly selected for each execution within the range specified by 'limit'.
- When 'crop_border' is False, the output image will have the same size as the input, potentially
introducing black triangles in the corners.
- When 'crop_border' is True, the output image is cropped to remove black triangles, which may result
in a smaller image.
- Bounding boxes are rotated and may change size or shape.
- Keypoints are rotated around the center of the image.
Mathematical Details:
1. An angle θ is randomly sampled from the range specified by 'limit'.
2. The image is rotated around its center by θ degrees.
3. The rotation matrix R is:
R = [cos(θ) -sin(θ)]
[sin(θ) cos(θ)]
4. Each point (x, y) in the image is transformed to (x', y') by:
[x'] [cos(θ) -sin(θ)] [x - cx] [cx]
[y'] = [sin(θ) cos(θ)] [y - cy] + [cy]
where (cx, cy) is the center of the image.
5. If 'crop_border' is True, the image is cropped to the largest rectangle that fits inside the rotated image.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> # Create example 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] # Class labels for bounding boxes
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1] # Labels for keypoints
>>> # Define the transform
>>> transform = A.Compose([
... A.Rotate(limit=45, p=1.0),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>> # Apply the transform to all targets
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>> rotated_image = transformed["image"]
>>> rotated_mask = transformed["mask"]
>>> rotated_bboxes = transformed["bboxes"]
>>> rotated_bbox_labels = transformed["bbox_labels"]
>>> rotated_keypoints = transformed["keypoints"]
>>> rotated_keypoint_labels = transformed["keypoint_labels"]
"""
_targets = ALL_TARGETS
class InitSchema(RotateInitSchema):
rotate_method: Literal["largest_box", "ellipse"]
crop_border: bool
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
def __init__(
self,
limit: tuple[float, float] | float = (-90, 90),
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
] = cv2.INTER_LINEAR,
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
] = cv2.BORDER_CONSTANT,
rotate_method: Literal["largest_box", "ellipse"] = "largest_box",
crop_border: bool = False,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
] = cv2.INTER_NEAREST,
fill: tuple[float, ...] | float = 0,
fill_mask: tuple[float, ...] | float = 0,
p: float = 0.5,
):
super().__init__(p=p)
self.limit = cast("tuple[float, float]", limit)
self.interpolation = interpolation
self.mask_interpolation = mask_interpolation
self.border_mode = border_mode
self.fill = fill
self.fill_mask = fill_mask
self.rotate_method = rotate_method
self.crop_border = crop_border
def apply(
self,
img: np.ndarray,
matrix: np.ndarray,
x_min: int,
x_max: int,
y_min: int,
y_max: int,
**params: Any,
) -> np.ndarray:
"""Apply affine transformation to the image.
Args:
img (np.ndarray): Image to transform.
matrix (np.ndarray): Affine transformation matrix.
x_min (int): Minimum x-coordinate for cropping (if crop_border is True).
x_max (int): Maximum x-coordinate for cropping (if crop_border is True).
y_min (int): Minimum y-coordinate for cropping (if crop_border is True).
y_max (int): Maximum y-coordinate for cropping (if crop_border is True).
**params (Any): Additional parameters.
Returns:
np.ndarray: Transformed image.
"""
img_out = fgeometric.warp_affine(
img,
matrix,
self.interpolation,
self.fill,
self.border_mode,
params["shape"][:2],
)
if self.crop_border:
return fcrops.crop(img_out, x_min, y_min, x_max, y_max)
return img_out
def apply_to_mask(
self,
mask: np.ndarray,
matrix: np.ndarray,
x_min: int,
x_max: int,
y_min: int,
y_max: int,
**params: Any,
) -> np.ndarray:
"""Apply affine transformation to the mask.
Args:
mask (np.ndarray): Mask to transform.
matrix (np.ndarray): Affine transformation matrix.
x_min (int): Minimum x-coordinate for cropping (if crop_border is True).
x_max (int): Maximum x-coordinate for cropping (if crop_border is True).
y_min (int): Minimum y-coordinate for cropping (if crop_border is True).
y_max (int): Maximum y-coordinate for cropping (if crop_border is True).
**params (Any): Additional parameters.
Returns:
np.ndarray: Transformed mask.
"""
img_out = fgeometric.warp_affine(
mask,
matrix,
self.mask_interpolation,
self.fill_mask,
self.border_mode,
params["shape"][:2],
)
if self.crop_border:
return fcrops.crop(img_out, x_min, y_min, x_max, y_max)
return img_out
def apply_to_bboxes(
self,
bboxes: np.ndarray,
bbox_matrix: np.ndarray,
x_min: int,
x_max: int,
y_min: int,
y_max: int,
**params: Any,
) -> np.ndarray:
"""Apply affine transformation to bounding boxes.
Args:
bboxes (np.ndarray): Bounding boxes to transform.
bbox_matrix (np.ndarray): Affine transformation matrix for bounding boxes.
x_min (int): Minimum x-coordinate for cropping (if crop_border is True).
x_max (int): Maximum x-coordinate for cropping (if crop_border is True).
y_min (int): Minimum y-coordinate for cropping (if crop_border is True).
y_max (int): Maximum y-coordinate for cropping (if crop_border is True).
**params (Any): Additional parameters.
Returns:
np.ndarray: Transformed bounding boxes.
"""
image_shape = params["shape"][:2]
bboxes_out = fgeometric.bboxes_affine(
bboxes,
bbox_matrix,
self.rotate_method,
image_shape,
self.border_mode,
image_shape,
)
if self.crop_border:
return fcrops.crop_bboxes_by_coords(
bboxes_out,
(x_min, y_min, x_max, y_max),
image_shape,
)
return bboxes_out
def apply_to_keypoints(
self,
keypoints: np.ndarray,
matrix: np.ndarray,
x_min: int,
x_max: int,
y_min: int,
y_max: int,
**params: Any,
) -> np.ndarray:
"""Apply affine transformation to keypoints.
Args:
keypoints (np.ndarray): Keypoints to transform.
matrix (np.ndarray): Affine transformation matrix.
x_min (int): Minimum x-coordinate for cropping (if crop_border is True).
x_max (int): Maximum x-coordinate for cropping (if crop_border is True).
y_min (int): Minimum y-coordinate for cropping (if crop_border is True).
y_max (int): Maximum y-coordinate for cropping (if crop_border is True).
**params (Any): Additional parameters.
Returns:
np.ndarray: Transformed keypoints.
"""
keypoints_out = fgeometric.keypoints_affine(
keypoints,
matrix,
params["shape"][:2],
scale={"x": 1, "y": 1},
border_mode=self.border_mode,
)
if self.crop_border:
return fcrops.crop_keypoints_by_coords(
keypoints_out,
(x_min, y_min, x_max, y_max),
)
return keypoints_out
@staticmethod
def _rotated_rect_with_max_area(
height: int,
width: int,
angle: float,
) -> dict[str, int]:
"""Given a rectangle of size wxh that has been rotated by 'angle' (in
degrees), computes the width and height of the largest possible
axis-aligned rectangle (maximal area) within the rotated rectangle.
References:
Rotate image and crop out black borders: https://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders
"""
angle = math.radians(angle)
width_is_longer = width >= height
side_long, side_short = (width, height) if width_is_longer else (height, width)
# since the solutions for angle, -angle and 180-angle are all the same,
# it is sufficient to look at the first quadrant and the absolute values of sin,cos:
sin_a, cos_a = abs(math.sin(angle)), abs(math.cos(angle))
if side_short <= 2.0 * sin_a * cos_a * side_long or abs(sin_a - cos_a) < SMALL_NUMBER:
# half constrained case: two crop corners touch the longer side,
# the other two corners are on the mid-line parallel to the longer line
x = 0.5 * side_short
wr, hr = (x / sin_a, x / cos_a) if width_is_longer else (x / cos_a, x / sin_a)
else:
# fully constrained case: crop touches all 4 sides
cos_2a = cos_a * cos_a - sin_a * sin_a
wr, hr = (
(width * cos_a - height * sin_a) / cos_2a,
(height * cos_a - width * sin_a) / cos_2a,
)
return {
"x_min": max(0, int(width / 2 - wr / 2)),
"x_max": min(width, int(width / 2 + wr / 2)),
"y_min": max(0, int(height / 2 - hr / 2)),
"y_max": min(height, int(height / 2 + hr / 2)),
}
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, Any]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, Any]: Dictionary with parameters for transformation.
"""
angle = self.py_random.uniform(*self.limit)
if self.crop_border:
height, width = params["shape"][:2]
out_params = self._rotated_rect_with_max_area(height, width, angle)
else:
out_params = {"x_min": -1, "x_max": -1, "y_min": -1, "y_max": -1}
center = fgeometric.center(params["shape"][:2])
bbox_center = fgeometric.center_bbox(params["shape"][:2])
translate: dict[str, int] = {"x": 0, "y": 0}
shear: dict[str, float] = {"x": 0, "y": 0}
scale: dict[str, float] = {"x": 1, "y": 1}
rotate = angle
matrix = fgeometric.create_affine_transformation_matrix(
translate,
shear,
scale,
rotate,
center,
)
bbox_matrix = fgeometric.create_affine_transformation_matrix(
translate,
shear,
scale,
rotate,
bbox_center,
)
out_params["matrix"] = matrix
out_params["bbox_matrix"] = bbox_matrix
return out_params
class SafeRotate(Affine):
"""Rotate the input inside the input's frame by an angle selected randomly from the uniform distribution.
This transformation ensures that the entire rotated image fits within the original frame by scaling it
down if necessary. The resulting image maintains its original dimensions but may contain artifacts due to the
rotation and scaling process.
Args:
limit (float | tuple[float, float]): Range from which a random angle is picked. If limit is a single float,
an angle is picked from (-limit, limit). Default: (-90, 90)
interpolation (OpenCV flag): Flag that is used to specify the interpolation algorithm. Should be one of:
cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_LINEAR.
border_mode (OpenCV flag): Flag that is used to specify the pixel extrapolation method. Should be one of:
cv2.BORDER_CONSTANT, cv2.BORDER_REPLICATE, cv2.BORDER_REFLECT, cv2.BORDER_WRAP, cv2.BORDER_REFLECT_101.
Default: cv2.BORDER_REFLECT_101
fill (tuple[float, float] | float): Padding value if border_mode is cv2.BORDER_CONSTANT.
fill_mask (tuple[float, float] | float): Padding value if border_mode is cv2.BORDER_CONSTANT applied
for masks.
rotate_method (Literal["largest_box", "ellipse"]): Method to rotate bounding boxes.
Should be 'largest_box' or 'ellipse'. Default: 'largest_box'
mask_interpolation (OpenCV flag): flag that is used to specify the interpolation algorithm for mask.
Should be one of: cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4.
Default: cv2.INTER_NEAREST.
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Note:
- The rotation is performed around the center of the image.
- After rotation, the image is scaled to fit within the original frame, which may cause some distortion.
- The output image will always have the same dimensions as the input image.
- Bounding boxes and keypoints are transformed along with the image.
Mathematical Details:
1. An angle θ is randomly sampled from the range specified by 'limit'.
2. The image is rotated around its center by θ degrees.
3. The rotation matrix R is:
R = [cos(θ) -sin(θ)]
[sin(θ) cos(θ)]
4. The scaling factor s is calculated to ensure the rotated image fits within the original frame:
s = min(width / (width * |cos(θ)| + height * |sin(θ)|),
height / (width * |sin(θ)| + height * |cos(θ)|))
5. The combined transformation matrix T is:
T = [s*cos(θ) -s*sin(θ) tx]
[s*sin(θ) s*cos(θ) ty]
where tx and ty are translation factors to keep the image centered.
6. Each point (x, y) in the image is transformed to (x', y') by:
[x'] [s*cos(θ) s*sin(θ)] [x - cx] [cx]
[y'] = [-s*sin(θ) s*cos(θ)] [y - cy] + [cy]
where (cx, cy) is the center of the image.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> # Create example 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] # Class labels for bounding boxes
>>> keypoints = np.array([[20, 30], [60, 70]], dtype=np.float32)
>>> keypoint_labels = [0, 1] # Labels for keypoints
>>> # Define the transform
>>> transform = A.Compose([
... A.SafeRotate(limit=45, p=1.0),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['bbox_labels']),
... keypoint_params=A.KeypointParams(format='xy', label_fields=['keypoint_labels']))
>>> # Apply the transform to all targets
>>> transformed = transform(
... image=image,
... mask=mask,
... bboxes=bboxes,
... bbox_labels=bbox_labels,
... keypoints=keypoints,
... keypoint_labels=keypoint_labels
... )
>>> rotated_image = transformed["image"]
>>> rotated_mask = transformed["mask"]
>>> rotated_bboxes = transformed["bboxes"]
>>> rotated_bbox_labels = transformed["bbox_labels"]
>>> rotated_keypoints = transformed["keypoints"]
>>> rotated_keypoint_labels = transformed["keypoint_labels"]
"""
_targets = ALL_TARGETS
class InitSchema(RotateInitSchema):
rotate_method: Literal["largest_box", "ellipse"]
def __init__(
self,
limit: tuple[float, float] | float = (-90, 90),
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
] = cv2.INTER_LINEAR,
border_mode: Literal[
cv2.BORDER_CONSTANT,
cv2.BORDER_REPLICATE,
cv2.BORDER_REFLECT,
cv2.BORDER_WRAP,
cv2.BORDER_REFLECT_101,
] = cv2.BORDER_CONSTANT,
rotate_method: Literal["largest_box", "ellipse"] = "largest_box",
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
] = cv2.INTER_NEAREST,
fill: tuple[float, ...] | float = 0,
fill_mask: tuple[float, ...] | float = 0,
p: float = 0.5,
):
super().__init__(
rotate=limit,
interpolation=interpolation,
border_mode=border_mode,
fill=fill,
fill_mask=fill_mask,
rotate_method=rotate_method,
fit_output=True,
mask_interpolation=mask_interpolation,
p=p,
)
self.limit = cast("tuple[float, float]", limit)
def _create_safe_rotate_matrix(
self,
angle: float,
center: tuple[float, float],
image_shape: tuple[int, int],
) -> tuple[np.ndarray, dict[str, float]]:
height, width = image_shape[:2]
rotation_mat = cv2.getRotationMatrix2D(center, angle, 1.0)
# Calculate new image size
abs_cos = abs(rotation_mat[0, 0])
abs_sin = abs(rotation_mat[0, 1])
new_w = int(height * abs_sin + width * abs_cos)
new_h = int(height * abs_cos + width * abs_sin)
# Adjust the rotation matrix to take into account the new size
rotation_mat[0, 2] += new_w / 2 - center[0]
rotation_mat[1, 2] += new_h / 2 - center[1]
# Calculate scaling factors
scale_x = width / new_w
scale_y = height / new_h
# Create scaling matrix
scale_mat = np.array([[scale_x, 0, 0], [0, scale_y, 0], [0, 0, 1]])
# Combine rotation and scaling
matrix = scale_mat @ np.vstack([rotation_mat, [0, 0, 1]])
return matrix, {"x": scale_x, "y": scale_y}
def get_params_dependent_on_data(
self,
params: dict[str, Any],
data: dict[str, Any],
) -> dict[str, Any]:
"""Get parameters dependent on the data.
Args:
params (dict[str, Any]): Dictionary containing parameters.
data (dict[str, Any]): Dictionary containing data.
Returns:
dict[str, Any]: Dictionary with parameters for transformation.
"""
image_shape = params["shape"][:2]
angle = self.py_random.uniform(*self.limit)
# Calculate centers for image and bbox
image_center = fgeometric.center(image_shape)
bbox_center = fgeometric.center_bbox(image_shape)
# Create matrices for image and bbox
matrix, scale = self._create_safe_rotate_matrix(
angle,
image_center,
image_shape,
)
bbox_matrix, _ = self._create_safe_rotate_matrix(
angle,
bbox_center,
image_shape,
)
return {
"rotate": angle,
"scale": scale,
"matrix": matrix,
"bbox_matrix": bbox_matrix,
"output_shape": image_shape,
}
@@ -0,0 +1,786 @@
"""Domain adaptation transforms for image augmentation.
This module provides transformations designed to bridge the domain gap between
datasets by adapting the style of an input image to match that of reference images
from a target domain. Adaptations are based on matching statistical properties
like histograms, frequency spectra, or overall pixel distributions.
"""
from __future__ import annotations
import warnings
from collections.abc import Sequence
from typing import Annotated, Any, Callable, Literal, cast
import cv2
import numpy as np
from pydantic import AfterValidator, field_validator, model_validator
from typing_extensions import Self
from albumentations.augmentations.mixing.domain_adaptation_functional import (
adapt_pixel_distribution,
apply_histogram,
fourier_domain_adaptation,
)
from albumentations.augmentations.utils import read_rgb_image
from albumentations.core.pydantic import ZeroOneRangeType, check_range_bounds, nondecreasing
from albumentations.core.transforms_interface import BaseTransformInitSchema, ImageOnlyTransform
__all__ = [
"FDA",
"HistogramMatching",
"PixelDistributionAdaptation",
]
MAX_BETA_LIMIT = 0.5
# Base class for Domain Adaptation Init Schema
class BaseDomainAdaptationInitSchema(BaseTransformInitSchema):
reference_images: Sequence[Any] | None
read_fn: Callable[[Any], np.ndarray] | None
metadata_key: str
@model_validator(mode="after")
def _check_deprecated_args(self) -> Self:
if self.reference_images is not None:
warnings.warn(
"'reference_images' and 'read_fn' arguments are deprecated. "
"Please pass pre-loaded reference images "
f"using the '{self.metadata_key}' key in the input data dictionary.",
DeprecationWarning,
stacklevel=3, # Adjust stacklevel as needed
)
if self.read_fn is None:
msg = "read_fn cannot be None when using the deprecated 'reference_images' argument."
raise ValueError(msg)
return self
class BaseDomainAdaptation(ImageOnlyTransform):
"""Base class for domain adaptation transforms.
Domain adaptation transforms modify source images to match the characteristics of a target domain.
These transforms typically require an additional reference image or dataset from the target domain
to extract style information or domain-specific features.
This base class provides the framework for implementing various domain adaptation techniques such as
color transfer, style transfer, frequency domain adaptation, or histogram matching.
Args:
reference_images (Sequence[Any] | None): Deprecated. Sequence of references to images from the target
domain. Should be used with read_fn to load actual images. Prefer passing pre-loaded images via
metadata_key.
read_fn (Callable[[Any], np.ndarray] | None): Deprecated. Function to read an image from a reference.
Should be used with reference_images.
metadata_key (str): Key in the input data dictionary that contains pre-loaded target domain images.
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image
Image types:
uint8, float32
Notes:
- Subclasses should implement the `apply` method to perform the actual adaptation.
- Use `targets_as_params` property to define what additional data your transform needs.
- Override `get_params_dependent_on_data` to extract the target domain data.
- Domain adaptation often requires per-sample auxiliary data, which should be passed
through the main data dictionary rather than at initialization time.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Implement a simple color transfer domain adaptation transform
>>> class SimpleColorTransfer(A.BaseDomainAdaptation):
... class InitSchema(A.BaseTransformInitSchema):
... intensity: float = Field(gt=0, le=1)
... reference_key: str
...
... def __init__(
... self,
... intensity: float = 0.5,
... reference_key: str = "target_image",
... p: float = 1.0
... ):
... super().__init__(p=p)
... self.intensity = intensity
... self.reference_key = reference_key
...
... @property
... def targets_as_params(self) -> list[str]:
... return [self.reference_key] # We need target domain image
...
... def get_params_dependent_on_data(
... self,
... params: dict[str, Any],
... data: dict[str, Any]
... ) -> dict[str, Any]:
... target_image = data.get(self.reference_key)
... if target_image is None:
... # Fallback if target image is not provided
... return {"target_image": None}
... return {"target_image": target_image}
...
... def apply(
... self,
... img: np.ndarray,
... target_image: np.ndarray = None,
... **params
... ) -> np.ndarray:
... if target_image is None:
... return img
...
... # Simple color transfer implementation
... # Calculate mean and std of source and target images
... src_mean = np.mean(img, axis=(0, 1))
... src_std = np.std(img, axis=(0, 1))
... tgt_mean = np.mean(target_image, axis=(0, 1))
... tgt_std = np.std(target_image, axis=(0, 1))
...
... # Normalize source image
... normalized = (img - src_mean) / (src_std + 1e-7)
...
... # Scale by target statistics and blend with original
... transformed = normalized * tgt_std + tgt_mean
... transformed = np.clip(transformed, 0, 255).astype(np.uint8)
...
... # Blend the result based on intensity
... result = cv2.addWeighted(img, 1 - self.intensity, transformed, self.intensity, 0)
... return result
>>>
>>> # Usage example with a target image from a different domain
>>> source_image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> target_image = np.random.randint(100, 200, (200, 200, 3), dtype=np.uint8) # Different domain image
>>>
>>> # Create the transform with the pipeline
>>> transform = A.Compose([
... SimpleColorTransfer(intensity=0.7, reference_key="target_img", p=1.0),
... ])
>>>
>>> # Apply the transform with the target image passed in the data dictionary
>>> result = transform(image=source_image, target_img=target_image)
>>> adapted_image = result["image"] # Image with characteristics transferred from target domain
"""
InitSchema: type[BaseDomainAdaptationInitSchema]
def __init__(
self,
reference_images: Sequence[Any] | None,
read_fn: Callable[[Any], np.ndarray] | None,
metadata_key: str,
p: float = 0.5,
):
super().__init__(p=p)
self.reference_images = reference_images
self.read_fn = read_fn
self.metadata_key = metadata_key
@property
def targets_as_params(self) -> list[str]:
return [self.metadata_key]
def _get_reference_image(self, data: dict[str, Any]) -> np.ndarray:
"""Retrieves the reference image from metadata or deprecated arguments."""
reference_image = None
if metadata_images := data.get(self.metadata_key):
if not isinstance(metadata_images, Sequence) or not metadata_images:
raise ValueError(
f"Metadata key '{self.metadata_key}' should contain a non-empty sequence of numpy arrays.",
)
if not isinstance(metadata_images[0], np.ndarray):
raise ValueError(
f"Images in metadata key '{self.metadata_key}' should be numpy arrays.",
)
reference_image = self.py_random.choice(metadata_images)
if self.reference_images is not None:
warnings.warn(
f"Both 'reference_images' (deprecated constructor argument) and metadata via "
f"'{self.metadata_key}' were provided. Prioritizing metadata.",
UserWarning,
stacklevel=3, # Adjust stacklevel as needed
)
elif self.reference_images is not None:
# Deprecation warning is handled by the InitSchema validator
if self.read_fn is None:
# This case should ideally be caught by InitSchema, but safety check
msg = "read_fn cannot be None when using the deprecated 'reference_images' argument."
raise ValueError(msg)
ref_source = self.py_random.choice(self.reference_images)
reference_image = self.read_fn(ref_source)
else:
raise ValueError(
f"{self.__class__.__name__} requires reference images. Provide them via the `metadata_key` "
f"'{self.metadata_key}' in the input data, or use the deprecated 'reference_images' argument.",
)
if reference_image is None:
# Should not happen if logic above is correct, but safety check
msg = "Could not obtain a reference image."
raise RuntimeError(msg)
return reference_image
def to_dict_private(self) -> dict[str, Any]:
"""Convert the transform to a dictionary for serialization.
Raises:
NotImplementedError: Domain adaptation transforms cannot be reliably serialized
when using metadata key or deprecated arguments.
"""
if self.reference_images is not None:
msg = (
f"{self.__class__.__name__} cannot be reliably serialized when using the deprecated 'reference_images'."
)
raise NotImplementedError(msg)
msg = (
f"{self.__class__.__name__} cannot be reliably serialized due to its dependency "
"on external data via metadata."
)
raise NotImplementedError(msg)
class HistogramMatching(BaseDomainAdaptation):
"""Adjust the pixel value distribution of an input image to match a reference image.
This transform modifies the pixel intensities of the input image so that its histogram
matches the histogram of a provided reference image. This process is applied independently
to each channel of the image if it is multi-channel.
Why use Histogram Matching?
**Domain Adaptation:** Helps bridge the gap between images from different sources
(e.g., different cameras, lighting conditions, synthetic vs. real data) by aligning
their overall intensity and contrast characteristics.
*Use Case Example:* Imagine you have labeled training images from one source (e.g., daytime photos,
medical scans from Hospital A) but expect your model to work on images from a different
source at test time (e.g., nighttime photos, scans from Hospital B). You might only have
unlabeled images from the target (test) domain. HistogramMatching can be used to make your
labeled training images resemble the *style* (intensity and contrast distribution) of the
unlabeled target images. By training on these adapted images, your model may generalize
better to the target domain without needing labels for it.
How it works:
The core idea is to map the pixel values of the input image such that its cumulative
distribution function (CDF) matches the CDF of the reference image. This effectively
reshapes the input image's histogram to resemble the reference's histogram.
Args:
metadata_key (str): Key in the input `data` dictionary to retrieve the reference image(s).
The value should be a sequence (e.g., list) of numpy arrays (pre-loaded images).
Default: "hm_metadata".
blend_ratio (tuple[float, float]): Range for the blending factor between the original
and the histogram-matched image. A value of 0 means the original image is returned,
1 means the fully matched image is returned. A random value within this range [min, max]
is sampled for each application. This allows for varying degrees of adaptation.
Default: (0.5, 1.0).
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image
Image types:
uint8, float32
Note:
- Requires at least one reference image to be provided via the `metadata_key` argument.
- The `reference_images` and `read_fn` constructor arguments are deprecated.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Create sample images for demonstration
>>> # Source image: dark image with low contrast
>>> source_image = np.ones((100, 100, 3), dtype=np.uint8) * 50 # Dark gray image
>>> source_image[30:70, 30:70] = 100 # Add slightly brighter square in center
>>>
>>> # Target image: higher brightness and contrast
>>> target_image = np.ones((100, 100, 3), dtype=np.uint8) * 150 # Bright image
>>> target_image[20:80, 20:80] = 200 # Add even brighter square
>>>
>>> # Initialize the histogram matching transform with custom settings
>>> transform = A.Compose([
... A.HistogramMatching(
... blend_ratio=(0.7, 0.9), # Control the strength of histogram matching
... metadata_key="reference_imgs", # Custom metadata key
... p=1.0
... )
... ])
>>>
>>> # Apply the transform
>>> result = transform(
... image=source_image,
... reference_imgs=[target_image] # Pass reference image via metadata key
... )
>>>
>>> # Get the histogram-matched image
>>> matched_image = result["image"]
>>>
>>> # The matched_image will have brightness and contrast similar to target_image
>>> # while preserving the content of source_image
>>>
>>> # Multiple reference images can be provided:
>>> ref_imgs = [
... target_image,
... np.random.randint(100, 200, (100, 100, 3), dtype=np.uint8) # Another reference image
... ]
>>> multiple_refs_result = transform(image=source_image, reference_imgs=ref_imgs)
>>> # A random reference image from the list will be chosen for each transform application
References:
Histogram Matching in scikit-image:
https://scikit-image.org/docs/dev/auto_examples/color_exposure/plot_histogram_matching.html
"""
class InitSchema(BaseDomainAdaptationInitSchema):
blend_ratio: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, 1)),
]
def __init__(
self,
reference_images: Sequence[Any] | None = None,
blend_ratio: tuple[float, float] = (0.5, 1.0),
read_fn: Callable[[Any], np.ndarray] | None = read_rgb_image,
metadata_key: str = "hm_metadata",
p: float = 0.5,
):
super().__init__(reference_images=reference_images, read_fn=read_fn, metadata_key=metadata_key, p=p)
self.blend_ratio = blend_ratio
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Generate parameters for the transform based on input data.
Args:
params (dict[str, Any]): Parameters from the previous transform in the pipeline
data (dict[str, Any]): Input data dictionary containing the image and metadata
Returns:
dict[str, Any]: Dictionary containing the reference image and blend ratio
"""
reference_image = self._get_reference_image(data)
return {
"reference_image": reference_image,
"blend_ratio": self.py_random.uniform(*self.blend_ratio),
}
def apply(
self,
img: np.ndarray,
reference_image: np.ndarray,
blend_ratio: float,
**params: Any,
) -> np.ndarray:
"""Apply histogram matching to the input image.
Args:
img (np.ndarray): Input image to be transformed
reference_image (np.ndarray): Reference image for histogram matching
blend_ratio (float): Blending factor between the original and matched image
**params (Any): Additional parameters
Returns:
np.ndarray: Transformed image with histogram matched to the reference image
"""
return apply_histogram(img, reference_image, blend_ratio)
class FDA(BaseDomainAdaptation):
"""Fourier Domain Adaptation (FDA).
Adapts the style of the input image to match the style of a reference image
by manipulating their frequency components in the Fourier domain. This is
particularly useful for unsupervised domain adaptation (UDA).
Why use FDA?
**Domain Adaptation:** FDA helps bridge the domain gap between source and target
datasets (e.g., synthetic vs. real, day vs. night) by aligning their low-frequency
Fourier spectrum components. This can improve model performance on the target domain
without requiring target labels.
*Use Case Example:* Imagine you have labeled training data acquired under certain conditions
(e.g., images from Hospital A using a specific scanner) but need your model to perform well
on data from a different distribution (e.g., unlabeled images from Hospital B with a different scanner).
FDA can adapt the labeled source images to match the *style* (frequency characteristics)
of the unlabeled target images, potentially improving the model's generalization to the
target domain at test time.
How it works:
FDA operates in the frequency domain. It replaces the low-frequency components
of the source image's Fourier transform with the low-frequency components from the
reference (target domain) image's Fourier transform. The `beta_limit` parameter
controls the size of the frequency window being swapped.
Args:
metadata_key (str): Key in the input `data` dictionary to retrieve the reference image(s).
The value should be a sequence (e.g., list) of numpy arrays (pre-loaded images).
Default: "fda_metadata".
beta_limit (tuple[float, float] | float): Controls the extent of the low-frequency
spectrum swap. A larger beta means more components are swapped. Corresponds to the L
parameter in the original paper. Should be in the range [0, 0.5]. Sampling is uniform
within the provided range [min, max]. Default: (0, 0.1).
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image
Image types:
uint8, float32
Note:
- Requires at least one reference image to be provided via the `metadata_key` argument.
- The `reference_images` and `read_fn` constructor arguments are deprecated.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Create sample images for demonstration
>>> # Source image: synthetic or simulated image (e.g., from a rendered game environment)
>>> source_img = np.zeros((100, 100, 3), dtype=np.uint8)
>>> # Create a pattern in the source image
>>> source_img[20:80, 20:80, 0] = 200 # Red square
>>> source_img[40:60, 40:60, 1] = 200 # Green inner square
>>>
>>> # Target domain image: real-world image with different texture/frequency characteristics
>>> # For this example, we'll create an image with different frequency patterns
>>> target_img = np.zeros((100, 100, 3), dtype=np.uint8)
>>> for i in range(100):
... for j in range(100):
... # Create a high-frequency pattern
... target_img[i, j, 0] = ((i + j) % 8) * 30
... target_img[i, j, 1] = ((i - j) % 8) * 30
... target_img[i, j, 2] = ((i * j) % 8) * 30
>>>
>>> # Example 1: FDA with minimal adaptation (small beta value)
>>> # This will subtly adjust the frequency characteristics
>>> minimal_fda = A.Compose([
... A.FDA(
... beta_limit=(0.01, 0.05), # Small beta range for subtle adaptation
... metadata_key="target_domain", # Custom metadata key
... p=1.0
... )
... ])
>>>
>>> # Apply the transform with minimal adaptation
>>> minimal_result = minimal_fda(
... image=source_img,
... target_domain=[target_img] # Pass reference image via custom metadata key
... )
>>> minimal_adapted_img = minimal_result["image"]
>>>
>>> # Example 2: FDA with moderate adaptation (medium beta value)
>>> moderate_fda = A.Compose([
... A.FDA(
... beta_limit=(0.1, 0.2), # Medium beta range
... metadata_key="target_domain",
... p=1.0
... )
... ])
>>>
>>> moderate_result = moderate_fda(image=source_img, target_domain=[target_img])
>>> moderate_adapted_img = moderate_result["image"]
>>>
>>> # Example 3: FDA with strong adaptation (larger beta value)
>>> strong_fda = A.Compose([
... A.FDA(
... beta_limit=(0.3, 0.5), # Larger beta range (upper limit is MAX_BETA_LIMIT)
... metadata_key="target_domain",
... p=1.0
... )
... ])
>>>
>>> strong_result = strong_fda(image=source_img, target_domain=[target_img])
>>> strong_adapted_img = strong_result["image"]
>>>
>>> # Example 4: Using multiple target domain images
>>> # Creating a list of target domain images with different characteristics
>>> target_imgs = [target_img]
>>>
>>> # Add another target image with different pattern
>>> another_target = np.zeros((100, 100, 3), dtype=np.uint8)
>>> for i in range(100):
... for j in range(100):
... another_target[i, j, 0] = (i // 10) * 25
... another_target[i, j, 1] = (j // 10) * 25
... another_target[i, j, 2] = ((i + j) // 10) * 25
>>> target_imgs.append(another_target)
>>>
>>> # Using default FDA settings with multiple target images
>>> multi_target_fda = A.Compose([
... A.FDA(p=1.0) # Using default settings with default metadata_key="fda_metadata"
... ])
>>>
>>> # A random target image will be selected from the list for each application
>>> multi_target_result = multi_target_fda(image=source_img, fda_metadata=target_imgs)
>>> adapted_image = multi_target_result["image"]
References:
- FDA: https://github.com/YanchaoYang/FDA
- FDA: https://openaccess.thecvf.com/content_CVPR_2020/papers/Yang_FDA_Fourier_Domain_Adaptation_for_Semantic_Segmentation_CVPR_2020_paper.pdf
"""
class InitSchema(BaseDomainAdaptationInitSchema):
beta_limit: ZeroOneRangeType
@field_validator("beta_limit")
@classmethod
def _check_ranges(cls, value: tuple[float, float]) -> tuple[float, float]:
bounds = 0, MAX_BETA_LIMIT
if not bounds[0] <= value[0] <= value[1] <= bounds[1]:
raise ValueError(f"Values should be in the range {bounds} got {value} ")
return value
def __init__(
self,
reference_images: Sequence[Any] | None = None,
beta_limit: tuple[float, float] | float = (0, 0.1),
read_fn: Callable[[Any], np.ndarray] | None = read_rgb_image,
metadata_key: str = "fda_metadata",
p: float = 0.5,
):
super().__init__(reference_images=reference_images, read_fn=read_fn, metadata_key=metadata_key, p=p)
self.beta_limit = cast("tuple[float, float]", beta_limit)
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Generate parameters for the transform based on input data."""
target_image = self._get_reference_image(data)
height, width = params["shape"][:2]
# Resize the target image to match the input image dimensions
target_image_resized = cv2.resize(target_image, dsize=(width, height))
return {"target_image": target_image_resized, "beta": self.py_random.uniform(*self.beta_limit)}
def apply(
self,
img: np.ndarray,
target_image: np.ndarray,
beta: float,
**params: Any,
) -> np.ndarray:
"""Apply Fourier Domain Adaptation to the input image.
Args:
img (np.ndarray): Input image to be transformed
target_image (np.ndarray): Target domain image for adaptation
beta (float): Coefficient controlling the extent of frequency component swapping
**params (Any): Additional parameters
Returns:
np.ndarray: Transformed image with adapted frequency components
"""
return fourier_domain_adaptation(img, target_image, beta)
class PixelDistributionAdaptation(BaseDomainAdaptation):
"""Adapts the pixel value distribution of an input image to match a reference image
using statistical transformations (PCA, StandardScaler, or MinMaxScaler).
This transform aims to harmonize images from different domains by aligning their pixel-level
statistical properties.
Why use Pixel Distribution Adaptation?
**Domain Adaptation:** Useful for aligning images across domains with differing pixel statistics
(e.g., caused by different sensors, lighting, or post-processing).
*Use Case Example:* Consider having labeled data from Scanner A and needing the model to perform
well on unlabeled data from Scanner B, where images might have different overall brightness,
contrast, or color biases. This transform can adapt the labeled images from Scanner A to
mimic the pixel distribution *style* of the images from Scanner B, potentially improving
generalization without needing labels for Scanner B data.
How it works:
1. A chosen statistical transform (`transform_type`) is fitted to both the input (source) image
and the reference (target) image separately.
2. The input image is transformed using the transform fitted on it (moving it to a standardized space).
3. The inverse transform *fitted on the reference image* is applied to the result from step 2
(moving the standardized input into the reference image's statistical space).
4. The result is optionally blended with the original input image using `blend_ratio`.
Args:
metadata_key (str): Key in the input `data` dictionary to retrieve the reference image(s).
The value should be a sequence (e.g., list) of numpy arrays (pre-loaded images).
Default: "pda_metadata".
blend_ratio (tuple[float, float]): Specifies the minimum and maximum blend ratio for mixing
the adapted image with the original. A value of 0 means the original image is returned,
1 means the fully adapted image is returned. A random value within this range [min, max]
is sampled for each application. Default: (0.25, 1.0).
transform_type (Literal["pca", "standard", "minmax"]): Specifies the type of statistical
transformation to apply:
- "pca": Principal Component Analysis.
- "standard": StandardScaler (zero mean, unit variance).
- "minmax": MinMaxScaler (scales to [0, 1] range).
Default: "pca".
p (float): The probability of applying the transform. Default: 0.5.
Targets:
image
Image types:
uint8, float32
Note:
- Requires at least one reference image to be provided via the `metadata_key` argument.
- The `reference_images` and `read_fn` constructor arguments are deprecated.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Create sample images for demonstration
>>> # Source image: simulated image from domain A (e.g., medical scan from one scanner)
>>> source_image = np.random.normal(100, 20, (100, 100, 3)).clip(0, 255).astype(np.uint8)
>>>
>>> # Reference image: image from domain B with different statistical properties
>>> # (e.g., scan from a different scanner with different intensity distribution)
>>> reference_image = np.random.normal(150, 30, (100, 100, 3)).clip(0, 255).astype(np.uint8)
>>>
>>> # Example 1: Using PCA transformation (default)
>>> pca_transform = A.Compose([
... A.PixelDistributionAdaptation(
... transform_type="pca",
... blend_ratio=(0.8, 1.0), # Strong adaptation
... metadata_key="reference_images",
... p=1.0
... )
... ])
>>>
>>> # Apply the transform with the reference image
>>> pca_result = pca_transform(
... image=source_image,
... reference_images=[reference_image]
... )
>>>
>>> # Get the adapted image
>>> pca_adapted_image = pca_result["image"]
>>>
>>> # Example 2: Using StandardScaler transformation
>>> standard_transform = A.Compose([
... A.PixelDistributionAdaptation(
... transform_type="standard",
... blend_ratio=(0.5, 0.7), # Moderate adaptation
... metadata_key="reference_images",
... p=1.0
... )
... ])
>>>
>>> standard_result = standard_transform(
... image=source_image,
... reference_images=[reference_image]
... )
>>> standard_adapted_image = standard_result["image"]
>>>
>>> # Example 3: Using MinMaxScaler transformation
>>> minmax_transform = A.Compose([
... A.PixelDistributionAdaptation(
... transform_type="minmax",
... blend_ratio=(0.3, 0.5), # Subtle adaptation
... metadata_key="reference_images",
... p=1.0
... )
... ])
>>>
>>> minmax_result = minmax_transform(
... image=source_image,
... reference_images=[reference_image]
... )
>>> minmax_adapted_image = minmax_result["image"]
>>>
>>> # Example 4: Using multiple reference images
>>> # When multiple reference images are provided, one is randomly selected for each transformation
>>> multiple_references = [
... reference_image,
... np.random.normal(180, 25, (100, 100, 3)).clip(0, 255).astype(np.uint8),
... np.random.normal(120, 40, (100, 100, 3)).clip(0, 255).astype(np.uint8)
... ]
>>>
>>> multi_ref_transform = A.Compose([
... A.PixelDistributionAdaptation(p=1.0) # Using default settings
... ])
>>>
>>> # Each time the transform is applied, it randomly selects one of the reference images
>>> multi_ref_result = multi_ref_transform(
... image=source_image,
... pda_metadata=multiple_references # Using the default metadata key
... )
>>> adapted_image = multi_ref_result["image"]
References:
Qudida: https://github.com/arsenyinfo/qudida
"""
class InitSchema(BaseDomainAdaptationInitSchema):
blend_ratio: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, 1)),
]
transform_type: Literal["pca", "standard", "minmax"]
def __init__(
self,
reference_images: Sequence[Any] | None = None,
blend_ratio: tuple[float, float] = (0.25, 1.0),
read_fn: Callable[[Any], np.ndarray] | None = read_rgb_image,
transform_type: Literal["pca", "standard", "minmax"] = "pca",
metadata_key: str = "pda_metadata",
p: float = 0.5,
):
super().__init__(reference_images=reference_images, read_fn=read_fn, metadata_key=metadata_key, p=p)
self.blend_ratio = blend_ratio
self.transform_type = transform_type
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters for the transform."""
reference_image = self._get_reference_image(data)
return {
"reference_image": reference_image,
"blend_ratio": self.py_random.uniform(*self.blend_ratio),
}
def apply(self, img: np.ndarray, reference_image: np.ndarray, blend_ratio: float, **params: Any) -> np.ndarray:
"""Apply pixel distribution adaptation to the input image.
Args:
img (np.ndarray): Input image to be transformed
reference_image (np.ndarray): Reference image for distribution adaptation
blend_ratio (float): Blending factor between the original and adapted image
**params (Any): Additional parameters
Returns:
np.ndarray: Transformed image with pixel distribution adapted to the reference image
"""
return adapt_pixel_distribution(
img,
ref=reference_image,
weight=blend_ratio,
transform_type=self.transform_type,
)
@@ -0,0 +1,453 @@
"""Functional implementations for domain adaptation image transformations.
This module provides low-level functions and classes for performing domain adaptation
between images. It includes implementations for histogram matching, Fourier domain adaptation,
and pixel distribution matching with various normalization techniques.
"""
from __future__ import annotations
import abc
from copy import deepcopy
from typing import Literal
import cv2
import numpy as np
from albucore import add_weighted, clip, clipped, from_float, get_num_channels, preserve_channel_dim, to_float, uint8_io
from typing_extensions import Protocol
import albumentations.augmentations.geometric.functional as fgeometric
from albumentations.augmentations.utils import PCA
from albumentations.core.type_definitions import MONO_CHANNEL_DIMENSIONS
__all__ = [
"adapt_pixel_distribution",
"apply_histogram",
"fourier_domain_adaptation",
]
class BaseScaler:
def __init__(self) -> None:
self.data_min: np.ndarray | None = None
self.data_max: np.ndarray | None = None
self.mean: np.ndarray | None = None
self.var: np.ndarray | None = None
self.scale: np.ndarray | None = None
def fit(self, x: np.ndarray) -> None:
raise NotImplementedError
def transform(self, x: np.ndarray) -> np.ndarray:
raise NotImplementedError
def fit_transform(self, x: np.ndarray) -> np.ndarray:
self.fit(x)
return self.transform(x)
def inverse_transform(self, x: np.ndarray) -> np.ndarray:
raise NotImplementedError
class MinMaxScaler(BaseScaler):
def __init__(self, feature_range: tuple[float, float] = (0.0, 1.0)) -> None:
super().__init__()
self.min: float = feature_range[0]
self.max: float = feature_range[1]
self.data_range: np.ndarray | None = None
def fit(self, x: np.ndarray) -> None:
self.data_min = np.min(x, axis=0)
self.data_max = np.max(x, axis=0)
self.data_range = self.data_max - self.data_min
# Handle case where data_min equals data_max
self.data_range[self.data_range == 0] = 1
def transform(self, x: np.ndarray) -> np.ndarray:
if self.data_min is None or self.data_max is None or self.data_range is None:
raise ValueError(
"This MinMaxScaler instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
x_std = np.subtract(x, self.data_min).astype(float)
np.divide(x_std, self.data_range, out=x_std)
np.multiply(x_std, (self.max - self.min), out=x_std)
np.add(x_std, self.min, out=x_std)
return x_std
def inverse_transform(self, x: np.ndarray) -> np.ndarray:
if self.data_min is None or self.data_max is None or self.data_range is None:
raise ValueError(
"This MinMaxScaler instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
x_std = ((x - self.min) / (self.max - self.min)).astype(float)
return x_std * self.data_range + self.data_min
class StandardScaler(BaseScaler):
def __init__(self) -> None:
super().__init__()
def fit(self, x: np.ndarray) -> None:
self.mean = np.mean(x, axis=0)
self.var = np.var(x, axis=0)
self.scale = np.sqrt(self.var)
# Handle case where variance is zero
self.scale[self.scale == 0] = 1
def transform(self, x: np.ndarray) -> np.ndarray:
if self.mean is None or self.scale is None:
raise ValueError(
"This StandardScaler instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
return (x - self.mean) / self.scale
def inverse_transform(self, x: np.ndarray) -> np.ndarray:
if self.mean is None or self.scale is None:
raise ValueError(
"This StandardScaler instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
return (x * self.scale) + self.mean
class TransformerInterface(Protocol):
@abc.abstractmethod
def inverse_transform(self, x: np.ndarray) -> np.ndarray: ...
@abc.abstractmethod
def fit(self, x: np.ndarray, y: np.ndarray | None = None) -> np.ndarray: ...
@abc.abstractmethod
def transform(self, x: np.ndarray, y: np.ndarray | None = None) -> np.ndarray: ...
class DomainAdapter:
def __init__(
self,
transformer: TransformerInterface,
ref_img: np.ndarray,
color_conversions: tuple[None, None] = (None, None),
):
self.color_in, self.color_out = color_conversions
self.source_transformer = deepcopy(transformer)
self.target_transformer = transformer
self.num_channels = get_num_channels(ref_img)
self.target_transformer.fit(self.flatten(ref_img))
def to_colorspace(self, img: np.ndarray) -> np.ndarray:
return img if self.color_in is None else cv2.cvtColor(img, self.color_in)
def from_colorspace(self, img: np.ndarray) -> np.ndarray:
if self.color_out is None:
return img
return cv2.cvtColor(clip(img, np.uint8, inplace=True), self.color_out)
def flatten(self, img: np.ndarray) -> np.ndarray:
img = self.to_colorspace(img)
img = to_float(img)
return img.reshape(-1, self.num_channels)
def reconstruct(self, pixels: np.ndarray, height: int, width: int) -> np.ndarray:
pixels = clip(pixels, np.uint8, inplace=True)
if self.num_channels == 1:
return self.from_colorspace(pixels.reshape(height, width))
return self.from_colorspace(pixels.reshape(height, width, self.num_channels))
@staticmethod
def _pca_sign(x: np.ndarray) -> np.ndarray:
return np.sign(np.trace(x.components_))
def __call__(self, image: np.ndarray) -> np.ndarray:
height, width = image.shape[:2]
pixels = self.flatten(image)
self.source_transformer.fit(pixels)
if (
hasattr(self.target_transformer, "components_")
and hasattr(self.source_transformer, "components_")
and self._pca_sign(self.target_transformer) != self._pca_sign(self.source_transformer)
):
self.target_transformer.components_ *= -1
representation = self.source_transformer.transform(pixels)
result = self.target_transformer.inverse_transform(representation)
return self.reconstruct(result, height, width)
@clipped
@preserve_channel_dim
def adapt_pixel_distribution(
img: np.ndarray,
ref: np.ndarray,
transform_type: Literal["pca", "standard", "minmax"],
weight: float,
) -> np.ndarray:
"""Adapt the pixel distribution of an image to match a reference image.
This function adapts the pixel distribution of an image to match a reference image
using a specified transformation type and weight.
Args:
img (np.ndarray): The input image to be adapted.
ref (np.ndarray): The reference image.
transform_type (Literal["pca", "standard", "minmax"]): The type of transformation to use.
weight (float): The weight of the transformation.
Returns:
np.ndarray: The adapted image.
Raises:
ValueError: If the input image and reference image have different dtypes or numbers of channels.
"""
if img.dtype != ref.dtype:
raise ValueError("Input image and reference image must have the same dtype.")
img_num_channels = get_num_channels(img)
ref_num_channels = get_num_channels(ref)
if img_num_channels != ref_num_channels:
raise ValueError("Input image and reference image must have the same number of channels.")
if img_num_channels == 1:
img = np.squeeze(img)
ref = np.squeeze(ref)
if img.shape != ref.shape:
ref = cv2.resize(ref, dsize=img.shape[:2], interpolation=cv2.INTER_AREA)
original_dtype = img.dtype
if original_dtype == np.float32:
img = from_float(img, np.uint8)
ref = from_float(ref, np.uint8)
transformer = {"pca": PCA, "standard": StandardScaler, "minmax": MinMaxScaler}[transform_type]()
adapter = DomainAdapter(transformer=transformer, ref_img=ref)
transformed = adapter(img).astype(np.float32)
result = img.astype(np.float32) * (1 - weight) + transformed * weight
return result if original_dtype == np.uint8 else to_float(result)
def low_freq_mutate(amp_src: np.ndarray, amp_trg: np.ndarray, beta: float) -> np.ndarray:
image_shape = amp_src.shape[:2]
border = int(np.floor(min(image_shape) * beta))
center_x, center_y = fgeometric.center(image_shape)
height, width = image_shape
h1, h2 = max(0, int(center_y - border)), min(int(center_y + border), height)
w1, w2 = max(0, int(center_x - border)), min(int(center_x + border), width)
amp_src[h1:h2, w1:w2] = amp_trg[h1:h2, w1:w2]
return amp_src
@clipped
@preserve_channel_dim
def fourier_domain_adaptation(img: np.ndarray, target_img: np.ndarray, beta: float) -> np.ndarray:
"""Apply Fourier Domain Adaptation to the input image using a target image.
This function performs domain adaptation in the frequency domain by modifying the amplitude
spectrum of the source image based on the target image's amplitude spectrum. It preserves
the phase information of the source image, which helps maintain its content while adapting
its style to match the target image.
Args:
img (np.ndarray): The source image to be adapted. Can be grayscale or RGB.
target_img (np.ndarray): The target image used as a reference for adaptation.
Should have the same dimensions as the source image.
beta (float): The adaptation strength, typically in the range [0, 1].
Higher values result in stronger adaptation towards the target image's style.
Returns:
np.ndarray: The adapted image with the same shape and type as the input image.
Raises:
ValueError: If the source and target images have different shapes.
Note:
- Both input images are converted to float32 for processing.
- The function handles both grayscale (2D) and color (3D) images.
- For grayscale images, an extra dimension is added to facilitate uniform processing.
- The adaptation is performed channel-wise for color images.
- The output is clipped to the valid range and preserves the original number of channels.
The adaptation process involves the following steps for each channel:
1. Compute the 2D Fourier Transform of both source and target images.
2. Shift the zero frequency component to the center of the spectrum.
3. Extract amplitude and phase information from the source image's spectrum.
4. Mutate the source amplitude using the target amplitude and the beta parameter.
5. Combine the mutated amplitude with the original phase.
6. Perform the inverse Fourier Transform to obtain the adapted channel.
The `low_freq_mutate` function (not shown here) is responsible for the actual
amplitude mutation, focusing on low-frequency components which carry style information.
Example:
>>> import numpy as np
>>> import albumentations as A
>>> source_img = np.random.rand(100, 100, 3).astype(np.float32)
>>> target_img = np.random.rand(100, 100, 3).astype(np.float32)
>>> adapted_img = A.fourier_domain_adaptation(source_img, target_img, beta=0.5)
>>> assert adapted_img.shape == source_img.shape
References:
FDA: Fourier Domain Adaptation for Semantic Segmentation: Yang and Soatto, 2020, CVPR
https://openaccess.thecvf.com/content_CVPR_2020/papers/Yang_FDA_Fourier_Domain_Adaptation_for_Semantic_Segmentation_CVPR_2020_paper.pdf
"""
src_img = img.astype(np.float32)
trg_img = target_img.astype(np.float32)
if src_img.ndim == MONO_CHANNEL_DIMENSIONS:
src_img = np.expand_dims(src_img, axis=-1)
if trg_img.ndim == MONO_CHANNEL_DIMENSIONS:
trg_img = np.expand_dims(trg_img, axis=-1)
num_channels = src_img.shape[-1]
# Prepare container for the output image
src_in_trg = np.zeros_like(src_img)
for channel_id in range(num_channels):
# Perform FFT on each channel
fft_src = np.fft.fft2(src_img[:, :, channel_id])
fft_trg = np.fft.fft2(trg_img[:, :, channel_id])
# Shift the zero frequency component to the center
fft_src_shifted = np.fft.fftshift(fft_src)
fft_trg_shifted = np.fft.fftshift(fft_trg)
# Extract amplitude and phase
amp_src, pha_src = np.abs(fft_src_shifted), np.angle(fft_src_shifted)
amp_trg = np.abs(fft_trg_shifted)
# Mutate the amplitude part of the source with the target
mutated_amp = low_freq_mutate(amp_src.copy(), amp_trg, beta)
# Combine the mutated amplitude with the original phase
fft_src_mutated = np.fft.ifftshift(mutated_amp * np.exp(1j * pha_src))
# Perform inverse FFT
src_in_trg_channel = np.fft.ifft2(fft_src_mutated)
# Store the result in the corresponding channel of the output image
src_in_trg[:, :, channel_id] = np.real(src_in_trg_channel)
return src_in_trg
@clipped
@preserve_channel_dim
def apply_histogram(img: np.ndarray, reference_image: np.ndarray, blend_ratio: float) -> np.ndarray:
"""Apply histogram matching to an input image using a reference image and blend the result.
This function performs histogram matching between the input image and a reference image,
then blends the result with the original input image based on the specified blend ratio.
Args:
img (np.ndarray): The input image to be transformed. Can be either grayscale or RGB.
Supported dtypes: uint8, float32 (values should be in [0, 1] range).
reference_image (np.ndarray): The reference image used for histogram matching.
Should have the same number of channels as the input image.
Supported dtypes: uint8, float32 (values should be in [0, 1] range).
blend_ratio (float): The ratio for blending the matched image with the original image.
Should be in the range [0, 1], where 0 means no change and 1 means full histogram matching.
Returns:
np.ndarray: The transformed image after histogram matching and blending.
The output will have the same shape and dtype as the input image.
Supported image types:
- Grayscale images: 2D arrays
- RGB images: 3D arrays with 3 channels
- Multispectral images: 3D arrays with more than 3 channels
Note:
- If the input and reference images have different sizes, the reference image
will be resized to match the input image's dimensions.
- The function uses a custom implementation of histogram matching based on OpenCV and NumPy.
- The @clipped and @preserve_channel_dim decorators ensure the output is within
the valid range and maintains the original number of dimensions.
"""
# Resize reference image only if necessary
if img.shape[:2] != reference_image.shape[:2]:
reference_image = cv2.resize(reference_image, dsize=(img.shape[1], img.shape[0]))
img = np.squeeze(img)
reference_image = np.squeeze(reference_image)
# Match histograms between the images
matched = match_histograms(img, reference_image)
# Blend the original image and the matched image
return add_weighted(matched, blend_ratio, img, 1 - blend_ratio)
@uint8_io
@preserve_channel_dim
def match_histograms(image: np.ndarray, reference: np.ndarray) -> np.ndarray:
"""Adjust an image so that its cumulative histogram matches that of another.
The adjustment is applied separately for each channel.
Args:
image (np.ndarray): Input image. Can be gray-scale or in color.
reference (np.ndarray): Image to match histogram of. Must have the same number of channels as image.
channel_axis (int | None): If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this indicates which axis of the array corresponds to channels.
Returns:
np.ndarray: Transformed input image.
Raises:
ValueError: Thrown when the number of channels in the input image and the reference differ.
"""
if reference.dtype != np.uint8:
reference = from_float(reference, np.uint8)
if image.ndim != reference.ndim:
raise ValueError("Image and reference must have the same number of dimensions.")
# Expand dimensions for grayscale images
if image.ndim == 2:
image = np.expand_dims(image, axis=-1)
if reference.ndim == 2:
reference = np.expand_dims(reference, axis=-1)
matched = np.empty(image.shape, dtype=np.uint8)
num_channels = image.shape[-1]
for channel in range(num_channels):
matched_channel = _match_cumulative_cdf(image[..., channel], reference[..., channel]).astype(np.uint8)
matched[..., channel] = matched_channel
return matched
def _match_cumulative_cdf(source: np.ndarray, template: np.ndarray) -> np.ndarray:
src_lookup = source.reshape(-1)
src_counts = np.bincount(src_lookup)
tmpl_counts = np.bincount(template.reshape(-1))
# omit values where the count was 0
tmpl_values = np.nonzero(tmpl_counts)[0]
tmpl_counts = tmpl_counts[tmpl_values]
# calculate normalized quantiles for each array
src_quantiles = np.cumsum(src_counts) / source.size
tmpl_quantiles = np.cumsum(tmpl_counts) / template.size
interp_a_values = np.interp(src_quantiles, tmpl_quantiles, tmpl_values)
return interp_a_values[src_lookup].reshape(source.shape).astype(np.uint8)
@@ -0,0 +1,878 @@
"""Functional implementations for image mixing operations.
This module provides utility functions for blending and combining images,
such as copy-and-paste operations with masking.
"""
from __future__ import annotations
import random
from collections.abc import Sequence
from typing import Any, Literal, TypedDict, cast
from warnings import warn
import cv2
import numpy as np
import albumentations.augmentations.geometric.functional as fgeometric
from albumentations.augmentations.crops.transforms import Crop
from albumentations.augmentations.geometric.resize import LongestMaxSize, SmallestMaxSize
from albumentations.core.bbox_utils import BboxProcessor, denormalize_bboxes, normalize_bboxes
from albumentations.core.composition import Compose
from albumentations.core.keypoints_utils import KeypointsProcessor
from albumentations.core.type_definitions import (
NUM_BBOXES_COLUMNS_IN_ALBUMENTATIONS,
NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS,
)
# Type definition for a processed mosaic item
class ProcessedMosaicItem(TypedDict):
"""Represents a single data item (primary or additional) after preprocessing.
Includes the original image/mask and the *preprocessed* annotations.
"""
image: np.ndarray # Image is mandatory
mask: np.ndarray | None
bboxes: np.ndarray | None
keypoints: np.ndarray | None
def copy_and_paste_blend(
base_image: np.ndarray,
overlay_image: np.ndarray,
overlay_mask: np.ndarray,
offset: tuple[int, int],
) -> np.ndarray:
"""Blend images by copying pixels from an overlay image to a base image using a mask.
This function copies pixels from the overlay image to the base image only where
the mask has non-zero values. The overlay is placed at the specified offset
from the top-left corner of the base image.
Args:
base_image (np.ndarray): The destination image that will be modified.
overlay_image (np.ndarray): The source image containing pixels to copy.
overlay_mask (np.ndarray): Binary mask indicating which pixels to copy from the overlay.
Pixels are copied where mask > 0.
offset (tuple[int, int]): The (y, x) offset specifying where to place the
top-left corner of the overlay relative to the base image.
Returns:
np.ndarray: The blended image with the overlay applied to the base image.
"""
y_offset, x_offset = offset
blended_image = base_image.copy()
mask_indices = np.where(overlay_mask > 0)
blended_image[mask_indices[0] + y_offset, mask_indices[1] + x_offset] = overlay_image[
mask_indices[0],
mask_indices[1],
]
return blended_image
def calculate_mosaic_center_point(
grid_yx: tuple[int, int],
cell_shape: tuple[int, int],
target_size: tuple[int, int],
center_range: tuple[float, float],
py_random: random.Random,
) -> tuple[int, int]:
"""Calculates the center point for the mosaic crop using proportional sampling within the valid zone.
Ensures the center point allows a crop of target_size to overlap
all grid cells, applying randomness based on center_range proportionally
within the valid region where the center can lie.
Args:
grid_yx (tuple[int, int]): The (rows, cols) of the mosaic grid.
cell_shape (tuple[int, int]): Shape of each cell in the mosaic grid.
target_size (tuple[int, int]): The final output (height, width).
center_range (tuple[float, float]): Range [0.0-1.0] for sampling center proportionally
within the valid zone.
py_random (random.Random): Random state instance.
Returns:
tuple[int, int]: The calculated (x, y) center point relative to the
top-left of the conceptual large grid.
"""
rows, cols = grid_yx
cell_h, cell_w = cell_shape
target_h, target_w = target_size
large_grid_h = rows * cell_h
large_grid_w = cols * cell_w
# Define valid center range bounds (inclusive)
# The center must be far enough from edges so the crop window fits
min_cx = target_w // 2
max_cx = large_grid_w - (target_w + 1) // 2
min_cy = target_h // 2
max_cy = large_grid_h - (target_h + 1) // 2
# Calculate valid range dimensions (size of the safe zone)
valid_w = max_cx - min_cx + 1
valid_h = max_cy - min_cy + 1
# Sample relative position within the valid range using center_range
rel_x = py_random.uniform(*center_range)
rel_y = py_random.uniform(*center_range)
# Calculate center coordinates by scaling relative position within valid range
# Add the minimum bound to shift the range start
center_x = min_cx + int(valid_w * rel_x)
center_y = min_cy + int(valid_h * rel_y)
# Ensure the result is strictly within the calculated bounds after int conversion
# (This clip is mostly a safety measure, shouldn't be needed with correct int conversion)
center_x = max(min_cx, min(center_x, max_cx))
center_y = max(min_cy, min(center_y, max_cy))
return center_x, center_y
def calculate_cell_placements(
grid_yx: tuple[int, int],
cell_shape: tuple[int, int],
target_size: tuple[int, int],
center_xy: tuple[int, int],
) -> list[tuple[int, int, int, int]]:
"""Calculates placements by clipping arange-defined grid lines to the crop window.
Args:
grid_yx (tuple[int, int]): The (rows, cols) of the mosaic grid.
cell_shape (tuple[int, int]): Shape of each cell in the mosaic grid.
target_size (tuple[int, int]): The final output (height, width).
center_xy (tuple[int, int]): The calculated (x, y) center of the final crop window,
relative to the top-left of the conceptual large grid.
Returns:
list[tuple[int, int, int, int]]:
A list containing placement coordinates `(x_min, y_min, x_max, y_max)`
for each resulting cell part on the final output canvas.
"""
rows, cols = grid_yx
cell_h, cell_w = cell_shape
target_h, target_w = target_size
center_x, center_y = center_xy
# 1. Generate grid line coordinates using arange for the large grid
y_coords_large = np.arange(rows + 1) * cell_h
x_coords_large = np.arange(cols + 1) * cell_w
# 2. Calculate Crop Window boundaries
crop_x_min = center_x - target_w // 2
crop_y_min = center_y - target_h // 2
crop_x_max = crop_x_min + target_w
crop_y_max = crop_y_min + target_h
def _clip_coords(coords: np.ndarray, min_val: int, max_val: int) -> np.ndarray:
clipped_coords = np.clip(coords, min_val, max_val)
# Subtract min_val to convert absolute clipped coordinates
# into coordinates relative to the crop window's origin (min_val becomes 0).
return np.unique(clipped_coords) - min_val
y_coords_clipped = _clip_coords(y_coords_large, crop_y_min, crop_y_max)
x_coords_clipped = _clip_coords(x_coords_large, crop_x_min, crop_x_max)
# 4. Form all cell coordinates efficiently
num_x_intervals = len(x_coords_clipped) - 1
num_y_intervals = len(y_coords_clipped) - 1
result = []
for y_idx in range(num_y_intervals):
y_min = y_coords_clipped[y_idx]
y_max = y_coords_clipped[y_idx + 1]
for x_idx in range(num_x_intervals):
x_min = x_coords_clipped[x_idx]
x_max = x_coords_clipped[x_idx + 1]
result.append((int(x_min), int(y_min), int(x_max), int(y_max)))
return result
def _check_data_compatibility(
primary_data: np.ndarray | None,
item_data: np.ndarray | None,
data_key: Literal["image", "mask"],
) -> tuple[bool, str | None]: # Returns (is_compatible, error_message)
"""Checks if the dimensions and channels of item_data match primary_data."""
# 1. Check if item has the required data (image is always required)
if item_data is None:
if data_key == "image":
return False, "Item is missing required key 'image'"
# Mask is optional, missing is compatible
return True, None
# 2. If item data exists, check against primary data (if primary data exists)
if primary_data is None: # No primary data to compare against
return True, None
# Both primary and item data exist, compare them
primary_ndim = primary_data.ndim
item_ndim = item_data.ndim
if primary_ndim != item_ndim:
return False, (
f"Item '{data_key}' has {item_ndim} dimensions, but primary has {primary_ndim}. "
f"Primary shape: {primary_data.shape}, Item shape: {item_data.shape}"
)
if primary_ndim == 3:
primary_channels = primary_data.shape[-1]
item_channels = item_data.shape[-1]
if primary_channels != item_channels:
return False, (
f"Item '{data_key}' has {item_channels} channels, but primary has {primary_channels}. "
f"Primary shape: {primary_data.shape}, Item shape: {item_data.shape}"
)
# Dimensions match (either both 2D or both 3D with same channels)
return True, None
def filter_valid_metadata(
metadata_input: Sequence[dict[str, Any]] | None,
metadata_key_name: str,
data: dict[str, Any],
) -> list[dict[str, Any]]:
"""Filters a list of metadata dicts, keeping only valid ones based on data compatibility."""
if not isinstance(metadata_input, Sequence):
warn(
f"Metadata under key '{metadata_key_name}' is not a Sequence (e.g., list or tuple). "
f"Returning empty list for additional items.",
UserWarning,
stacklevel=3,
)
return []
valid_items = []
primary_image = data.get("image")
primary_mask = data.get("mask")
for i, item in enumerate(metadata_input):
if not isinstance(item, dict):
warn(
f"Item at index {i} in '{metadata_key_name}' is not a dict and will be skipped.",
UserWarning,
stacklevel=4,
)
continue
item_is_valid = True # Assume valid initially
for target_key, primary_target_data in [
("image", primary_image),
("mask", primary_mask),
]:
item_target_data = item.get(target_key)
is_compatible, error_msg = _check_data_compatibility(
primary_target_data,
item_target_data,
cast("Literal['image', 'mask']", target_key),
)
if not is_compatible:
msg = (
f"Item at index {i} in '{metadata_key_name}' skipped due "
f"to incompatibility in '{target_key}': {error_msg}"
)
warn(msg, UserWarning, stacklevel=4)
item_is_valid = False
break # Stop checking other targets for this item
if item_is_valid:
valid_items.append(item)
return valid_items
def assign_items_to_grid_cells(
num_items: int,
cell_placements: list[tuple[int, int, int, int]],
py_random: random.Random,
) -> dict[tuple[int, int, int, int], int]:
"""Assigns item indices to placement coordinate tuples.
Assigns the primary item (index 0) to the placement with the largest area,
and assigns the remaining items (indices 1 to num_items-1) randomly to the
remaining placements.
Args:
num_items (int): The total number of items to assign (primary + additional + replicas).
cell_placements (list[tuple[int, int, int, int]]): List of placement
coords (x1, y1, x2, y2) for cells to be filled.
py_random (random.Random): Random state instance.
Returns:
dict[tuple[int, int, int, int], int]: Dict mapping placement coords (x1, y1, x2, y2)
to assigned item index.
"""
if not cell_placements:
return {}
# Find the placement tuple with the largest area for primary assignment
primary_placement = max(
cell_placements,
key=lambda coords: (coords[2] - coords[0]) * (coords[3] - coords[1]),
)
placement_to_item_index: dict[tuple[int, int, int, int], int] = {
primary_placement: 0,
}
# Use list comprehension for potentially better performance
remaining_placements = [coords for coords in cell_placements if coords != primary_placement]
# Indices for additional/replicated items start from 1
remaining_item_indices = list(range(1, num_items))
py_random.shuffle(remaining_item_indices)
num_to_assign = min(len(remaining_placements), len(remaining_item_indices))
for i in range(num_to_assign):
placement_to_item_index[remaining_placements[i]] = remaining_item_indices[i]
return placement_to_item_index
def _preprocess_item_annotations(
item: dict[str, Any],
processor: BboxProcessor | KeypointsProcessor | None,
data_key: Literal["bboxes", "keypoints"],
) -> np.ndarray | None:
"""Helper to preprocess annotations (bboxes or keypoints) for a single item."""
original_data = item.get(data_key)
# Check if processor exists and the relevant data key is in the item
if processor and data_key in item and item.get(data_key) is not None:
# === Add validation for required label fields ===
required_labels = processor.params.label_fields
if required_labels and [field for field in required_labels if field not in item]:
raise ValueError(
f"Item contains '{data_key}' but is missing required label "
"fields: {[field for field in required_labels if field not in item]}. "
f"Ensure all label fields declared in {type(processor.params).__name__} "
f"({required_labels}) are present in the item dictionary when '{data_key}' is present.",
)
# === End validation ===
# Create a temporary minimal dict for the processor
temp_data = {
"image": item["image"],
data_key: item[data_key],
}
# Add declared label fields if they exist in the item (already validated above)
if required_labels:
for field in required_labels:
# Check again just in case validation logic changes, avoids KeyError
if field in item:
temp_data[field] = item[field]
# Preprocess modifies temp_data in-place
processor.preprocess(temp_data)
# Return the potentially modified data from the temp dict
return temp_data.get(data_key)
# Return original data if no processor or data key wasn't in item
return original_data
def preprocess_selected_mosaic_items(
selected_raw_items: list[dict[str, Any]],
bbox_processor: BboxProcessor | None, # Allow None
keypoint_processor: KeypointsProcessor | None, # Allow None
) -> list[ProcessedMosaicItem]:
"""Preprocesses bboxes/keypoints for selected raw additional items.
Iterates through items, preprocesses annotations individually using processors
(updating label encoders), and returns a list of dicts with original image/mask
and the corresponding preprocessed bboxes/keypoints.
"""
if not selected_raw_items:
return []
result_data_items: list[ProcessedMosaicItem] = []
for item in selected_raw_items:
processed_bboxes = _preprocess_item_annotations(item, bbox_processor, "bboxes")
processed_keypoints = _preprocess_item_annotations(item, keypoint_processor, "keypoints")
# Construct the final processed item dict
processed_item_dict: ProcessedMosaicItem = {
"image": item["image"],
"mask": item.get("mask"),
"bboxes": processed_bboxes, # Already np.ndarray or None
"keypoints": processed_keypoints, # Already np.ndarray or None
}
result_data_items.append(processed_item_dict)
return result_data_items
def get_opposite_crop_coords(
cell_size: tuple[int, int],
crop_size: tuple[int, int],
cell_position: Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"],
) -> tuple[int, int, int, int]:
"""Calculates crop coordinates positioned opposite to the specified cell_position.
Given a cell of `cell_size`, this function determines the top-left (x_min, y_min)
and bottom-right (x_max, y_max) coordinates for a crop of `crop_size`, such
that the crop is located in the corner or center opposite to `cell_position`.
For example, if `cell_position` is "top_left", the crop coordinates will
correspond to the bottom-right region of the cell.
Args:
cell_size: The (height, width) of the cell from which to crop.
crop_size: The (height, width) of the desired crop.
cell_position: The reference position within the cell. The crop will be
taken from the opposite position.
Returns:
tuple[int, int, int, int]: (x_min, y_min, x_max, y_max) representing the crop coordinates.
Raises:
ValueError: If crop_size is larger than cell_size in either dimension.
"""
cell_h, cell_w = cell_size
crop_h, crop_w = crop_size
if crop_h > cell_h or crop_w > cell_w:
raise ValueError(f"Crop size {crop_size} cannot be larger than cell size {cell_size}")
# Determine top-left corner (x_min, y_min) based on the OPPOSITE position
if cell_position == "top_left": # Crop from bottom_right
x_min = cell_w - crop_w
y_min = cell_h - crop_h
elif cell_position == "top_right": # Crop from bottom_left
x_min = 0
y_min = cell_h - crop_h
elif cell_position == "bottom_left": # Crop from top_right
x_min = cell_w - crop_w
y_min = 0
elif cell_position == "bottom_right": # Crop from top_left
x_min = 0
y_min = 0
elif cell_position == "center": # Crop from center
x_min = (cell_w - crop_w) // 2
y_min = (cell_h - crop_h) // 2
else:
# Should be unreachable due to Literal type hint, but good practice
raise ValueError(f"Invalid cell_position: {cell_position}")
# Calculate bottom-right corner
x_max = x_min + crop_w
y_max = y_min + crop_h
return x_min, y_min, x_max, y_max
def process_cell_geometry(
cell_shape: tuple[int, int],
item: ProcessedMosaicItem,
target_shape: tuple[int, int],
fill: float | tuple[float, ...],
fill_mask: float | tuple[float, ...],
fit_mode: Literal["cover", "contain"],
interpolation: int,
mask_interpolation: int,
cell_position: Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"],
) -> ProcessedMosaicItem:
"""Applies geometric transformations (padding and/or cropping) to a single mosaic item.
Uses a Compose pipeline with PadIfNeeded and Crop to ensure the output
matches the target cell dimensions exactly, handling both padding and cropping cases.
Args:
cell_shape: (tuple[int, int]): Shape of the cell.
item: (ProcessedMosaicItem): The preprocessed mosaic item dictionary.
target_shape: (tuple[int, int]): Target shape of the cell.
fill: (float | tuple[float, ...]): Fill value for image padding.
fill_mask: (float | tuple[float, ...]): Fill value for mask padding.
fit_mode: (Literal["cover", "contain"]): Fit mode for the mosaic.
interpolation: (int): Interpolation method for image.
mask_interpolation: (int): Interpolation method for mask.
cell_position: (Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"]): Position
of the cell.
Returns: (ProcessedMosaicItem): Dictionary containing the geometrically processed image,
mask, bboxes, and keypoints, fitting the target dimensions.
"""
# Define the pipeline: PadIfNeeded first, then Crop
compose_kwargs: dict[str, Any] = {"p": 1.0}
if item.get("bboxes") is not None:
compose_kwargs["bbox_params"] = {"format": "albumentations"}
if item.get("keypoints") is not None:
compose_kwargs["keypoint_params"] = {"format": "albumentations"}
crop_coords = get_opposite_crop_coords(cell_shape, target_shape, cell_position)
if fit_mode == "cover":
geom_pipeline = Compose(
[
SmallestMaxSize(
max_size_hw=cell_shape,
interpolation=interpolation,
mask_interpolation=mask_interpolation,
p=1.0,
),
Crop(
x_min=crop_coords[0],
y_min=crop_coords[1],
x_max=crop_coords[2],
y_max=crop_coords[3],
),
],
**compose_kwargs,
)
elif fit_mode == "contain":
geom_pipeline = Compose(
[
LongestMaxSize(
max_size_hw=cell_shape,
interpolation=interpolation,
mask_interpolation=mask_interpolation,
p=1.0,
),
Crop(
x_min=crop_coords[0],
y_min=crop_coords[1],
x_max=crop_coords[2],
y_max=crop_coords[3],
pad_if_needed=True,
fill=fill,
fill_mask=fill_mask,
p=1.0,
),
],
**compose_kwargs,
)
else:
raise ValueError(f"Invalid fit_mode: {fit_mode}. Must be 'cover' or 'contain'.")
# Prepare input data for the pipeline
geom_input = {"image": item["image"]}
if item.get("mask") is not None:
geom_input["mask"] = item["mask"]
if item.get("bboxes") is not None:
# Compose expects bboxes in a specific format, ensure it's compatible
# Assuming item['bboxes'] is already preprocessed correctly
geom_input["bboxes"] = item["bboxes"]
if item.get("keypoints") is not None:
geom_input["keypoints"] = item["keypoints"]
# Apply the pipeline
processed_item = geom_pipeline(**geom_input)
# Ensure output dict has the same structure as ProcessedMosaicItem
# Compose might not return None for missing keys, handle explicitly
return {
"image": processed_item["image"],
"mask": processed_item.get("mask"),
"bboxes": processed_item.get("bboxes"),
"keypoints": processed_item.get("keypoints"),
}
def shift_cell_coordinates(
processed_item_geom: ProcessedMosaicItem,
placement_coords: tuple[int, int, int, int],
) -> ProcessedMosaicItem:
"""Shifts the coordinates of geometrically processed bboxes and keypoints.
Args:
processed_item_geom: (ProcessedMosaicItem): The output from process_cell_geometry.
placement_coords: (tuple[int, int, int, int]): The (x1, y1, x2, y2) placement on the final canvas.
Returns: (ProcessedMosaicItem): A dictionary with keys 'bboxes' and 'keypoints', containing the shifted
numpy arrays (potentially empty).
"""
tgt_x1, tgt_y1, _, _ = placement_coords
shifted_bboxes = None
shifted_keypoints = None
bboxes_geom = processed_item_geom.get("bboxes")
if bboxes_geom is not None and np.asarray(bboxes_geom).size > 0:
bboxes_geom_arr = np.asarray(bboxes_geom) # Ensure it's an array
bbox_shift_vector = np.array([tgt_x1, tgt_y1, tgt_x1, tgt_y1], dtype=np.int32)
shifted_bboxes = fgeometric.shift_bboxes(bboxes_geom_arr, bbox_shift_vector)
keypoints_geom = processed_item_geom.get("keypoints")
if keypoints_geom is not None and np.asarray(keypoints_geom).size > 0:
keypoints_geom_arr = np.asarray(keypoints_geom) # Ensure it's an array
kp_shift_vector = np.array([tgt_x1, tgt_y1, 0], dtype=keypoints_geom_arr.dtype)
shifted_keypoints = fgeometric.shift_keypoints(keypoints_geom_arr, kp_shift_vector)
return {
"bboxes": shifted_bboxes,
"keypoints": shifted_keypoints,
"image": processed_item_geom["image"],
"mask": processed_item_geom.get("mask"),
}
def assemble_mosaic_from_processed_cells(
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
target_shape: tuple[int, ...], # Use full canvas shape (H, W) or (H, W, C)
dtype: np.dtype,
data_key: Literal["image", "mask"],
fill: float | tuple[float, ...] | None, # Value for image fill or mask fill
) -> np.ndarray:
"""Assembles the final mosaic image or mask from processed cell data onto a canvas.
Initializes the canvas with the fill value and overwrites with processed segments.
Handles potentially multi-channel masks.
Addresses potential broadcasting errors if mask segments have unexpected dimensions.
Assumes input data is valid and correctly sized.
Args:
processed_cells (dict[tuple[int, int, int, int], dict[str, Any]]): Dictionary mapping
placement coords to processed cell data.
target_shape (tuple[int, ...]): The target shape of the output canvas (e.g., (H, W) or (H, W, C)).
dtype (np.dtype): NumPy dtype for the canvas.
data_key (Literal["image", "mask"]): Specifies whether to assemble 'image' or 'mask'.
fill (float | tuple[float, ...] | None): Value used to initialize the canvas (image fill or mask fill).
Should be a float/int or a tuple matching the number of channels.
If None, defaults to 0.
Returns:
np.ndarray: The assembled mosaic canvas.
"""
# Use 0 as default fill if None is provided
actual_fill = fill if fill is not None else 0
# Convert fill to numpy array to handle broadcasting in np.full
fill_value = np.array(actual_fill, dtype=dtype)
# Initialize canvas with the fill value.
# If fill_value shape is incompatible with target_shape, np.full will raise ValueError.
canvas = np.full(target_shape, fill_value=fill_value, dtype=dtype)
# Iterate and paste segments onto the pre-filled canvas
for placement_coords, cell_data in processed_cells.items():
segment = cell_data.get(data_key)
# If segment exists, paste it over the filled background
if segment is not None:
tgt_x1, tgt_y1, tgt_x2, tgt_y2 = placement_coords
canvas[tgt_y1:tgt_y2, tgt_x1:tgt_x2] = segment
return canvas
def process_all_mosaic_geometries(
canvas_shape: tuple[int, int],
cell_shape: tuple[int, int],
placement_to_item_index: dict[tuple[int, int, int, int], int],
final_items_for_grid: list[ProcessedMosaicItem],
fill: float | tuple[float, ...],
fill_mask: float | tuple[float, ...],
fit_mode: Literal["cover", "contain"],
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
],
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
],
) -> dict[tuple[int, int, int, int], ProcessedMosaicItem]:
"""Processes the geometry (cropping/padding) for all assigned mosaic cells.
Iterates through assigned placements, applies geometric transforms via process_cell_geometry,
and returns a dictionary mapping final placement coordinates to the processed item data.
The bbox/keypoint coordinates in the returned dict are *not* shifted yet.
Args:
canvas_shape (tuple[int, int]): The shape of the canvas.
cell_shape (tuple[int, int]): Shape of each cell in the mosaic grid.
placement_to_item_index (dict[tuple[int, int, int, int], int]): Mapping from placement
coordinates (x1, y1, x2, y2) to assigned item index.
final_items_for_grid (list[ProcessedMosaicItem]): List of all preprocessed items available.
fill (float | tuple[float, ...]): Fill value for image padding.
fill_mask (float | tuple[float, ...]): Fill value for mask padding.
fit_mode (Literal["cover", "contain"]): Fit mode for the mosaic.
interpolation (int): Interpolation method for image.
mask_interpolation (int): Interpolation method for mask.
Returns:
dict[tuple[int, int, int, int], ProcessedMosaicItem]: Dictionary mapping final placement
coordinates (x1, y1, x2, y2) to the geometrically processed item data (image, mask, un-shifted bboxes/kps).
"""
processed_cells_geom: dict[tuple[int, int, int, int], ProcessedMosaicItem] = {}
# Iterate directly over placements and their assigned item indices
for placement_coords, item_idx in placement_to_item_index.items():
item = final_items_for_grid[item_idx]
tgt_x1, tgt_y1, tgt_x2, tgt_y2 = placement_coords
target_h = tgt_y2 - tgt_y1
target_w = tgt_x2 - tgt_x1
cell_position = get_cell_relative_position(placement_coords, canvas_shape)
# Apply geometric processing (crop/pad)
processed_cells_geom[placement_coords] = process_cell_geometry(
cell_shape=cell_shape,
item=item,
target_shape=(target_h, target_w),
fill=fill,
fill_mask=fill_mask,
fit_mode=fit_mode,
interpolation=interpolation,
mask_interpolation=mask_interpolation,
cell_position=cell_position,
)
return processed_cells_geom
def get_cell_relative_position(
placement_coords: tuple[int, int, int, int],
target_shape: tuple[int, int],
) -> Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"]:
"""Determines the position of a cell relative to the center of the target canvas.
Compares the cell center to the canvas center and returns its quadrant
or "center" if it lies on or very close to a central axis.
Args:
placement_coords (tuple[int, int, int, int]): The (x_min, y_min, x_max, y_max) coordinates
of the cell.
target_shape (tuple[int, int]): The (height, width) of the overall target canvas.
Returns:
Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"]:
The position of the cell relative to the center of the target canvas.
"""
target_h, target_w = target_shape
x1, y1, x2, y2 = placement_coords
canvas_center_x = target_w / 2.0
canvas_center_y = target_h / 2.0
cell_center_x = (x1 + x2) / 2.0
cell_center_y = (y1 + y2) / 2.0
# Determine vertical position
if cell_center_y < canvas_center_y:
v_pos = "top"
elif cell_center_y > canvas_center_y:
v_pos = "bottom"
else: # Exactly on the horizontal center line
v_pos = "center"
# Determine horizontal position
if cell_center_x < canvas_center_x:
h_pos = "left"
elif cell_center_x > canvas_center_x:
h_pos = "right"
else: # Exactly on the vertical center line
h_pos = "center"
# Map positions to the final string
position_map = {
("top", "left"): "top_left",
("top", "right"): "top_right",
("bottom", "left"): "bottom_left",
("bottom", "right"): "bottom_right",
}
# Default to "center" if the combination is not in the map
# (which happens if either v_pos or h_pos is "center")
return cast(
"Literal['top_left', 'top_right', 'center', 'bottom_left', 'bottom_right']",
position_map.get((v_pos, h_pos), "center"),
)
def shift_all_coordinates(
processed_cells_geom: dict[tuple[int, int, int, int], ProcessedMosaicItem],
canvas_shape: tuple[int, int],
) -> dict[tuple[int, int, int, int], ProcessedMosaicItem]: # Return type matches input, but values are updated
"""Shifts coordinates for all geometrically processed cells.
Iterates through the processed cells (keyed by placement coords), applies coordinate
shifting to bboxes/keypoints, and returns a new dictionary with the same keys
but updated ProcessedMosaicItem values containing the *shifted* coordinates.
Args:
processed_cells_geom (dict[tuple[int, int, int, int], ProcessedMosaicItem]):
Output from process_all_mosaic_geometries (keyed by placement coords).
canvas_shape (tuple[int, int]): The shape of the canvas.
Returns:
dict[tuple[int, int, int, int], ProcessedMosaicItem]: Final dictionary mapping
placement coords (x1, y1, x2, y2) to processed cell data with shifted coordinates.
"""
final_processed_cells: dict[tuple[int, int, int, int], ProcessedMosaicItem] = {}
canvas_h, canvas_w = canvas_shape
for placement_coords, cell_data_geom in processed_cells_geom.items():
tgt_x1, tgt_y1 = placement_coords[:2]
cell_width = placement_coords[2] - placement_coords[0]
cell_height = placement_coords[3] - placement_coords[1]
# Extract geometrically processed bboxes/keypoints
bboxes_geom = cell_data_geom.get("bboxes")
keypoints_geom = cell_data_geom.get("keypoints")
final_cell_data = {
"image": cell_data_geom["image"],
"mask": cell_data_geom.get("mask"),
}
# Perform shifting if data exists
if bboxes_geom is not None and bboxes_geom.size > 0:
bboxes_geom_arr = np.asarray(bboxes_geom)
bbox_denoramlized = denormalize_bboxes(bboxes_geom_arr, {"height": cell_height, "width": cell_width})
bbox_shift_vector = np.array([tgt_x1, tgt_y1, tgt_x1, tgt_y1], dtype=np.float32)
shifted_bboxes_denormalized = fgeometric.shift_bboxes(bbox_denoramlized, bbox_shift_vector)
shifted_bboxes = normalize_bboxes(shifted_bboxes_denormalized, {"height": canvas_h, "width": canvas_w})
final_cell_data["bboxes"] = shifted_bboxes
else:
final_cell_data["bboxes"] = np.empty((0, NUM_BBOXES_COLUMNS_IN_ALBUMENTATIONS))
if keypoints_geom is not None and keypoints_geom.size > 0:
keypoints_geom_arr = np.asarray(keypoints_geom)
# Ensure shift vector matches keypoint dtype (usually float)
kp_shift_vector = np.array([tgt_x1, tgt_y1, 0], dtype=keypoints_geom_arr.dtype)
shifted_keypoints = fgeometric.shift_keypoints(keypoints_geom_arr, kp_shift_vector)
final_cell_data["keypoints"] = shifted_keypoints
else:
final_cell_data["keypoints"] = np.empty((0, NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS))
final_processed_cells[placement_coords] = cast("ProcessedMosaicItem", final_cell_data)
return final_processed_cells
@@ -0,0 +1,832 @@
"""Transforms that combine multiple images and their associated annotations.
This module contains transformations that take multiple input sources (e.g., a primary image
and additional images provided via metadata) and combine them into a single output.
Examples include overlaying elements (`OverlayElements`) or creating complex compositions
like `Mosaic`.
"""
from __future__ import annotations
import random
from copy import deepcopy
from typing import Annotated, Any, Literal, cast
import cv2
import numpy as np
from pydantic import AfterValidator, model_validator
from typing_extensions import Self
from albumentations.augmentations.mixing import functional as fmixing
from albumentations.core.bbox_utils import BboxProcessor, check_bboxes, denormalize_bboxes, filter_bboxes
from albumentations.core.keypoints_utils import KeypointsProcessor
from albumentations.core.pydantic import check_range_bounds, nondecreasing
from albumentations.core.transforms_interface import BaseTransformInitSchema, DualTransform
from albumentations.core.type_definitions import LENGTH_RAW_BBOX, Targets
__all__ = ["Mosaic", "OverlayElements"]
class OverlayElements(DualTransform):
"""Apply overlay elements such as images and masks onto an input image. This transformation can be used to add
various objects (e.g., stickers, logos) to images with optional masks and bounding boxes for better placement
control.
Args:
metadata_key (str): Additional target key for metadata. Default `overlay_metadata`.
p (float): Probability of applying the transformation. Default: 0.5.
Possible Metadata Fields:
- image (np.ndarray): The overlay image to be applied. This is a required field.
- bbox (list[int]): The bounding box specifying the region where the overlay should be applied. It should
contain four floats: [y_min, x_min, y_max, x_max]. If `label_id` is provided, it should
be appended as the fifth element in the bbox. BBox should be in Albumentations format,
that is the same as normalized Pascal VOC format
[x_min / width, y_min / height, x_max / width, y_max / height]
- mask (np.ndarray): An optional mask that defines the non-rectangular region of the overlay image. If not
provided, the entire overlay image is used.
- mask_id (int): An optional identifier for the mask. If provided, the regions specified by the mask will
be labeled with this identifier in the output mask.
Targets:
image, mask
Image types:
uint8, float32
References:
doc-augmentation: https://github.com/danaaubakirova/doc-augmentation
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare primary data (base image and mask)
>>> image = np.zeros((300, 300, 3), dtype=np.uint8)
>>> mask = np.zeros((300, 300), dtype=np.uint8)
>>>
>>> # 1. Create a simple overlay image (a red square)
>>> overlay_image1 = np.zeros((50, 50, 3), dtype=np.uint8)
>>> overlay_image1[:, :, 0] = 255 # Red color
>>>
>>> # 2. Create another overlay with a mask (a blue circle with transparency)
>>> overlay_image2 = np.zeros((80, 80, 3), dtype=np.uint8)
>>> overlay_image2[:, :, 2] = 255 # Blue color
>>> overlay_mask2 = np.zeros((80, 80), dtype=np.uint8)
>>> # Create a circular mask
>>> center = (40, 40)
>>> radius = 30
>>> for i in range(80):
... for j in range(80):
... if (i - center[0])**2 + (j - center[1])**2 < radius**2:
... overlay_mask2[i, j] = 255
>>>
>>> # 3. Create an overlay with both bbox and mask_id
>>> overlay_image3 = np.zeros((60, 120, 3), dtype=np.uint8)
>>> overlay_image3[:, :, 1] = 255 # Green color
>>> # Create a rectangular mask with rounded corners
>>> overlay_mask3 = np.zeros((60, 120), dtype=np.uint8)
>>> cv2.rectangle(overlay_mask3, (10, 10), (110, 50), 255, -1)
>>>
>>> # Create the metadata list - each item is a dictionary with overlay information
>>> overlay_metadata = [
... {
... 'image': overlay_image1,
... # No bbox provided - will be placed randomly
... },
... {
... 'image': overlay_image2,
... 'bbox': [0.6, 0.1, 0.9, 0.4], # Normalized coordinates [x_min, y_min, x_max, y_max]
... 'mask': overlay_mask2,
... 'mask_id': 1 # This overlay will update the mask with id 1
... },
... {
... 'image': overlay_image3,
... 'bbox': [0.1, 0.7, 0.5, 0.9], # Bottom left placement
... 'mask': overlay_mask3,
... 'mask_id': 2 # This overlay will update the mask with id 2
... }
... ]
>>>
>>> # Create the transform
>>> transform = A.Compose([
... A.OverlayElements(p=1.0),
... ])
>>>
>>> # Apply the transform
>>> result = transform(
... image=image,
... mask=mask,
... overlay_metadata=overlay_metadata # Pass metadata using the default key
... )
>>>
>>> # Get results with overlays applied
>>> result_image = result['image'] # Image with the three overlays applied
>>> result_mask = result['mask'] # Mask with regions labeled using the mask_id values
>>>
>>> # Let's verify the mask contains the specified mask_id values
>>> has_mask_id_1 = np.any(result_mask == 1) # Should be True
>>> has_mask_id_2 = np.any(result_mask == 2) # Should be True
"""
_targets = (Targets.IMAGE, Targets.MASK)
class InitSchema(BaseTransformInitSchema):
metadata_key: str
def __init__(
self,
metadata_key: str = "overlay_metadata",
p: float = 0.5,
):
super().__init__(p=p)
self.metadata_key = metadata_key
@property
def targets_as_params(self) -> list[str]:
"""Get list of targets that should be passed as parameters to transforms.
Returns:
list[str]: List containing the metadata key name
"""
return [self.metadata_key]
@staticmethod
def preprocess_metadata(
metadata: dict[str, Any],
img_shape: tuple[int, int],
random_state: random.Random,
) -> dict[str, Any]:
"""Process overlay metadata to prepare for application.
Args:
metadata (dict[str, Any]): Dictionary containing overlay data such as image, mask, bbox
img_shape (tuple[int, int]): Shape of the target image as (height, width)
random_state (random.Random): Random state object for reproducible randomness
Returns:
dict[str, Any]: Processed overlay data including resized overlay image, mask,
offset coordinates, and bounding box information
"""
overlay_image = metadata["image"]
overlay_height, overlay_width = overlay_image.shape[:2]
image_height, image_width = img_shape[:2]
if "bbox" in metadata:
bbox = metadata["bbox"]
bbox_np = np.array([bbox])
check_bboxes(bbox_np)
denormalized_bbox = denormalize_bboxes(bbox_np, img_shape[:2])[0]
x_min, y_min, x_max, y_max = (int(x) for x in denormalized_bbox[:4])
if "mask" in metadata:
mask = metadata["mask"]
mask = cv2.resize(mask, (x_max - x_min, y_max - y_min), interpolation=cv2.INTER_NEAREST)
else:
mask = np.ones((y_max - y_min, x_max - x_min), dtype=np.uint8)
overlay_image = cv2.resize(overlay_image, (x_max - x_min, y_max - y_min), interpolation=cv2.INTER_AREA)
offset = (y_min, x_min)
if len(bbox) == LENGTH_RAW_BBOX and "bbox_id" in metadata:
bbox = [x_min, y_min, x_max, y_max, metadata["bbox_id"]]
else:
bbox = (x_min, y_min, x_max, y_max, *bbox[4:])
else:
if image_height < overlay_height or image_width < overlay_width:
overlay_image = cv2.resize(overlay_image, (image_width, image_height), interpolation=cv2.INTER_AREA)
overlay_height, overlay_width = overlay_image.shape[:2]
mask = metadata["mask"] if "mask" in metadata else np.ones_like(overlay_image, dtype=np.uint8)
max_x_offset = image_width - overlay_width
max_y_offset = image_height - overlay_height
offset_x = random_state.randint(0, max_x_offset)
offset_y = random_state.randint(0, max_y_offset)
offset = (offset_y, offset_x)
bbox = [
offset_x,
offset_y,
offset_x + overlay_width,
offset_y + overlay_height,
]
if "bbox_id" in metadata:
bbox = [*bbox, metadata["bbox_id"]]
result = {
"overlay_image": overlay_image,
"overlay_mask": mask,
"offset": offset,
"bbox": bbox,
}
if "mask_id" in metadata:
result["mask_id"] = metadata["mask_id"]
return result
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Generate parameters for overlay transform based on input data.
Args:
params (dict[str, Any]): Dictionary of existing parameters
data (dict[str, Any]): Dictionary containing input data with image and metadata
Returns:
dict[str, Any]: Dictionary containing processed overlay data ready for application
"""
metadata = data[self.metadata_key]
img_shape = params["shape"]
if isinstance(metadata, list):
overlay_data = [self.preprocess_metadata(md, img_shape, self.py_random) for md in metadata]
else:
overlay_data = [self.preprocess_metadata(metadata, img_shape, self.py_random)]
return {
"overlay_data": overlay_data,
}
def apply(
self,
img: np.ndarray,
overlay_data: list[dict[str, Any]],
**params: Any,
) -> np.ndarray:
"""Apply overlay elements to the input image.
Args:
img (np.ndarray): Input image
overlay_data (list[dict[str, Any]]): List of dictionaries containing overlay information
**params (Any): Additional parameters
Returns:
np.ndarray: Image with overlays applied
"""
for data in overlay_data:
overlay_image = data["overlay_image"]
overlay_mask = data["overlay_mask"]
offset = data["offset"]
img = fmixing.copy_and_paste_blend(img, overlay_image, overlay_mask, offset=offset)
return img
def apply_to_mask(
self,
mask: np.ndarray,
overlay_data: list[dict[str, Any]],
**params: Any,
) -> np.ndarray:
"""Apply overlay masks to the input mask.
Args:
mask (np.ndarray): Input mask
overlay_data (list[dict[str, Any]]): List of dictionaries containing overlay information
**params (Any): Additional parameters
Returns:
np.ndarray: Mask with overlay masks applied using the specified mask_id values
"""
for data in overlay_data:
if "mask_id" in data and data["mask_id"] is not None:
overlay_mask = data["overlay_mask"]
offset = data["offset"]
mask_id = data["mask_id"]
y_min, x_min = offset
y_max = y_min + overlay_mask.shape[0]
x_max = x_min + overlay_mask.shape[1]
mask_section = mask[y_min:y_max, x_min:x_max]
mask_section[overlay_mask > 0] = mask_id
return mask
class Mosaic(DualTransform):
"""Combine multiple images and their annotations into a single image using a mosaic grid layout.
This transform takes a primary input image (and its annotations) and combines it with
additional images/annotations provided via metadata. It calculates the geometry for
a mosaic grid, selects additional items, preprocesses annotations consistently
(handling label encoding updates), applies geometric transformations, and assembles
the final output.
Args:
grid_yx (tuple[int, int]): The number of rows (y) and columns (x) in the mosaic grid.
Determines the maximum number of images involved (grid_yx[0] * grid_yx[1]).
Default: (2, 2).
target_size (tuple[int, int]): The desired output (height, width) for the final mosaic image.
after cropping the mosaic grid.
cell_shape (tuple[int, int]): cell shape of each cell in the mosaic grid.
metadata_key (str): Key in the input dictionary specifying the list of additional data dictionaries
for the mosaic. Each dictionary in the list should represent one potential additional item.
Expected keys: 'image' (required, np.ndarray), and optionally 'mask' (np.ndarray),
'bboxes' (np.ndarray), 'keypoints' (np.ndarray), and any relevant label fields
(e.g., 'class_labels') corresponding to those specified in `Compose`'s `bbox_params` or
`keypoint_params`. Default: "mosaic_metadata".
center_range (tuple[float, float]): Range [0.0-1.0] to sample the center point of the mosaic view
relative to the valid central region of the conceptual large grid. This affects which parts
of the assembled grid are visible in the final crop. Default: (0.3, 0.7).
interpolation (int): OpenCV interpolation flag used for resizing images during geometric processing.
Default: cv2.INTER_LINEAR.
mask_interpolation (int): OpenCV interpolation flag used for resizing masks during geometric processing.
Default: cv2.INTER_NEAREST.
fill (tuple[float, ...] | float): Value used for padding images if needed during geometric processing.
Default: 0.
fill_mask (tuple[float, ...] | float): Value used for padding masks if needed during geometric processing.
Default: 0.
p (float): Probability of applying the transform. Default: 0.5.
Workflow (`get_params_dependent_on_data`):
1. Calculate Geometry & Visible Cells: Determine which grid cells are visible in the final
`target_size` crop and their placement coordinates on the output canvas.
2. Validate Raw Additional Metadata: Filter the list provided via `metadata_key`,
keeping only valid items (dicts with an 'image' key).
3. Select Subset of Raw Additional Metadata: Choose a subset of the valid raw items based
on the number of visible cells requiring additional data.
4. Preprocess Selected Raw Additional Items: Preprocess bboxes/keypoints for the *selected*
additional items *only*. This uses shared processors from `Compose`, updating their
internal state (e.g., `LabelEncoder`) based on labels in these selected items.
5. Prepare Primary Data: Extract preprocessed primary data fields from the input `data` dictionary
into a `primary` dictionary.
6. Determine & Perform Replication: If fewer additional items were selected than needed,
replicate the preprocessed primary data as required.
7. Combine Final Items: Create the list of all preprocessed items (primary, selected additional,
replicated primary) that will be used.
8. Assign Items to VISIBLE Grid Cells
9. Process Geometry & Shift Coordinates: For each assigned item:
a. Apply geometric transforms (Crop, Resize, Pad) to image/mask.
b. Apply geometric shift to the *preprocessed* bboxes/keypoints based on cell placement.
10. Return Parameters: Return the processed cell data (image, mask, shifted bboxes, shifted kps)
keyed by placement coordinates.
Label Handling:
- The transform relies on `bbox_processor` and `keypoint_processor` provided by `Compose`.
- `Compose.preprocess` initially fits the processors' `LabelEncoder` on the primary data.
- This transform (`Mosaic`) preprocesses the *selected* additional raw items using the same
processors. If new labels are found, the shared `LabelEncoder` state is updated via its
`update` method.
- `Compose.postprocess` uses the final updated encoder state to decode all labels present
in the mosaic output for the current `Compose` call.
- The encoder state is transient per `Compose` call.
Targets:
image, mask, bboxes, keypoints
Image types:
uint8, float32
Reference:
YOLOv4: Optimal Speed and Accuracy of Object Detection: https://arxiv.org/pdf/2004.10934
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare primary data
>>> primary_image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> primary_mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> primary_bboxes = np.array([[10, 10, 40, 40], [50, 50, 90, 90]], dtype=np.float32)
>>> primary_labels = [1, 2]
>>>
>>> # Prepare additional images for mosaic
>>> additional_image1 = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> additional_mask1 = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> additional_bboxes1 = np.array([[20, 20, 60, 60]], dtype=np.float32)
>>> additional_labels1 = [3]
>>>
>>> additional_image2 = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> additional_mask2 = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> additional_bboxes2 = np.array([[30, 30, 70, 70]], dtype=np.float32)
>>> additional_labels2 = [4]
>>>
>>> additional_image3 = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> additional_mask3 = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> additional_bboxes3 = np.array([[5, 5, 45, 45]], dtype=np.float32)
>>> additional_labels3 = [5]
>>>
>>> # Create metadata for additional images - structured as a list of dicts
>>> mosaic_metadata = [
... {
... 'image': additional_image1,
... 'mask': additional_mask1,
... 'bboxes': additional_bboxes1,
... 'labels': additional_labels1
... },
... {
... 'image': additional_image2,
... 'mask': additional_mask2,
... 'bboxes': additional_bboxes2,
... 'labels': additional_labels2
... },
... {
... 'image': additional_image3,
... 'mask': additional_mask3,
... 'bboxes': additional_bboxes3,
... 'labels': additional_labels3
... }
... ]
>>>
>>> # Create the transform with Mosaic
>>> transform = A.Compose([
... A.Mosaic(
... grid_yx=(2, 2),
... target_size=(200, 200),
... cell_shape=(120, 120),
... center_range=(0.4, 0.6),
... fit_mode="cover",
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['labels']))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=primary_image,
... mask=primary_mask,
... bboxes=primary_bboxes,
... labels=primary_labels,
... mosaic_metadata=mosaic_metadata # Pass the metadata using the default key
... )
>>>
>>> # Access the transformed data
>>> mosaic_image = transformed['image'] # Combined mosaic image
>>> mosaic_mask = transformed['mask'] # Combined mosaic mask
>>> mosaic_bboxes = transformed['bboxes'] # Combined and repositioned bboxes
>>> mosaic_labels = transformed['labels'] # Combined labels from all images
"""
_targets = (Targets.IMAGE, Targets.MASK, Targets.BBOXES, Targets.KEYPOINTS)
class InitSchema(BaseTransformInitSchema):
grid_yx: tuple[int, int]
target_size: Annotated[
tuple[int, int],
AfterValidator(check_range_bounds(1, None)),
]
cell_shape: Annotated[
tuple[int, int],
AfterValidator(check_range_bounds(1, None)),
]
metadata_key: str
center_range: Annotated[
tuple[float, float],
AfterValidator(check_range_bounds(0, 1)),
AfterValidator(nondecreasing),
]
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
fit_mode: Literal["cover", "contain"]
@model_validator(mode="after")
def _check_cell_shape(self) -> Self:
if (
self.cell_shape[0] * self.grid_yx[0] < self.target_size[0]
or self.cell_shape[1] * self.grid_yx[1] < self.target_size[1]
):
raise ValueError("Target size should be smaller than cell cell_size * grid_yx")
return self
def __init__(
self,
grid_yx: tuple[int, int] = (2, 2),
target_size: tuple[int, int] = (512, 512),
cell_shape: tuple[int, int] = (512, 512),
center_range: tuple[float, float] = (0.3, 0.7),
fit_mode: Literal["cover", "contain"] = "cover",
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
fill: tuple[float, ...] | float = 0,
fill_mask: tuple[float, ...] | float = 0,
metadata_key: str = "mosaic_metadata",
p: float = 0.5,
) -> None:
super().__init__(p=p)
self.grid_yx = grid_yx
self.target_size = target_size
self.metadata_key = metadata_key
self.center_range = center_range
self.interpolation = interpolation
self.mask_interpolation = mask_interpolation
self.fill = fill
self.fill_mask = fill_mask
self.fit_mode = fit_mode
self.cell_shape = cell_shape
@property
def targets_as_params(self) -> list[str]:
"""Get list of targets that should be passed as parameters to transforms.
Returns:
list[str]: List containing the metadata key name
"""
return [self.metadata_key]
def _calculate_geometry(self, data: dict[str, Any]) -> list[tuple[int, int, int, int]]:
# Step 1: Calculate Geometry & Cell Placements
center_xy = fmixing.calculate_mosaic_center_point(
grid_yx=self.grid_yx,
cell_shape=self.cell_shape,
target_size=self.target_size,
center_range=self.center_range,
py_random=self.py_random,
)
return fmixing.calculate_cell_placements(
grid_yx=self.grid_yx,
cell_shape=self.cell_shape,
target_size=self.target_size,
center_xy=center_xy,
)
def _select_additional_items(self, data: dict[str, Any], num_additional_needed: int) -> list[dict[str, Any]]:
valid_items = fmixing.filter_valid_metadata(data.get(self.metadata_key), self.metadata_key, data)
if len(valid_items) > num_additional_needed:
return self.py_random.sample(valid_items, num_additional_needed)
return valid_items
def _preprocess_additional_items(
self,
additional_items: list[dict[str, Any]],
data: dict[str, Any],
) -> list[fmixing.ProcessedMosaicItem]:
if "bboxes" in data or "keypoints" in data:
bbox_processor = cast("BboxProcessor", self.get_processor("bboxes"))
keypoint_processor = cast("KeypointsProcessor", self.get_processor("keypoints"))
return fmixing.preprocess_selected_mosaic_items(additional_items, bbox_processor, keypoint_processor)
return cast("list[fmixing.ProcessedMosaicItem]", list(additional_items))
def _prepare_final_items(
self,
primary: fmixing.ProcessedMosaicItem,
additional_items: list[fmixing.ProcessedMosaicItem],
num_needed: int,
) -> list[fmixing.ProcessedMosaicItem]:
num_replications = max(0, num_needed - len(additional_items))
replicated = [deepcopy(primary) for _ in range(num_replications)]
return [primary, *additional_items, *replicated]
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Orchestrates the steps to calculate mosaic parameters by calling helper methods."""
cell_placements = self._calculate_geometry(data)
num_cells = len(cell_placements)
num_additional_needed = max(0, num_cells - 1)
additional_items = self._select_additional_items(data, num_additional_needed)
preprocessed_additional = self._preprocess_additional_items(additional_items, data)
primary = self.get_primary_data(data)
final_items = self._prepare_final_items(primary, preprocessed_additional, num_additional_needed)
placement_to_item_index = fmixing.assign_items_to_grid_cells(
num_items=len(final_items),
cell_placements=cell_placements,
py_random=self.py_random,
)
processed_cells = fmixing.process_all_mosaic_geometries(
canvas_shape=self.target_size,
cell_shape=self.cell_shape,
placement_to_item_index=placement_to_item_index,
final_items_for_grid=final_items,
fill=self.fill,
fill_mask=self.fill_mask if self.fill_mask is not None else self.fill,
fit_mode=self.fit_mode,
interpolation=self.interpolation,
mask_interpolation=self.mask_interpolation,
)
if "bboxes" in data or "keypoints" in data:
processed_cells = fmixing.shift_all_coordinates(processed_cells, canvas_shape=self.target_size)
result = {"processed_cells": processed_cells, "target_shape": self._get_target_shape(data["image"].shape)}
if "mask" in data:
result["target_mask_shape"] = self._get_target_shape(data["mask"].shape)
return result
@staticmethod
def get_primary_data(data: dict[str, Any]) -> fmixing.ProcessedMosaicItem:
"""Get a copy of the primary data (data passed in `data` parameter) to avoid modifying the original data.
Args:
data (dict[str, Any]): Dictionary containing the primary data.
Returns:
fmixing.ProcessedMosaicItem: A copy of the primary data.
"""
mask = data.get("mask")
if mask is not None:
mask = mask.copy()
bboxes = data.get("bboxes")
if bboxes is not None:
bboxes = bboxes.copy()
keypoints = data.get("keypoints")
if keypoints is not None:
keypoints = keypoints.copy()
return {
"image": data["image"],
"mask": mask,
"bboxes": bboxes,
"keypoints": keypoints,
}
def _get_target_shape(self, np_shape: tuple[int, ...]) -> list[int]:
target_shape = list(np_shape)
target_shape[0] = self.target_size[0]
target_shape[1] = self.target_size[1]
return target_shape
def apply(
self,
img: np.ndarray,
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
target_shape: tuple[int, int],
**params: Any,
) -> np.ndarray:
"""Apply mosaic transformation to the input image.
Args:
img (np.ndarray): Input image
processed_cells (dict[tuple[int, int, int, int], dict[str, Any]]): Dictionary of processed cell data
target_shape (tuple[int, int]): Shape of the target image.
**params (Any): Additional parameters
Returns:
np.ndarray: Mosaic transformed image
"""
return fmixing.assemble_mosaic_from_processed_cells(
processed_cells=processed_cells,
target_shape=target_shape,
dtype=img.dtype,
data_key="image",
fill=self.fill,
)
def apply_to_mask(
self,
mask: np.ndarray,
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
target_mask_shape: tuple[int, int],
**params: Any,
) -> np.ndarray:
"""Apply mosaic transformation to the input mask.
Args:
mask (np.ndarray): Input mask.
processed_cells (dict): Dictionary of processed cell data containing cropped/padded mask segments.
target_mask_shape (tuple[int, int]): Shape of the target mask.
**params (Any): Additional parameters (unused).
Returns:
np.ndarray: Mosaic transformed mask.
"""
return fmixing.assemble_mosaic_from_processed_cells(
processed_cells=processed_cells,
target_shape=target_mask_shape,
dtype=mask.dtype,
data_key="mask",
fill=self.fill_mask,
)
def apply_to_bboxes(
self,
bboxes: np.ndarray, # Original bboxes - ignored
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
**params: Any,
) -> np.ndarray:
"""Applies mosaic transformation to bounding boxes.
Args:
bboxes (np.ndarray): Original bounding boxes (ignored).
processed_cells (dict): Dictionary mapping placement coords to processed cell data
(containing shifted bboxes in absolute pixel coords).
**params (Any): Additional parameters (unused).
Returns:
np.ndarray: Final combined, filtered, bounding boxes.
"""
all_shifted_bboxes = []
for cell_data in processed_cells.values():
shifted_bboxes = cell_data["bboxes"]
if shifted_bboxes.size > 0:
all_shifted_bboxes.append(shifted_bboxes)
if not all_shifted_bboxes:
return np.empty((0, bboxes.shape[1]), dtype=bboxes.dtype)
# Concatenate (these are absolute pixel coordinates)
combined_bboxes = np.concatenate(all_shifted_bboxes, axis=0)
# Apply filtering using processor parameters
bbox_processor = cast("BboxProcessor", self.get_processor("bboxes"))
# Assume processor exists if bboxes are being processed
shape_dict: dict[Literal["depth", "height", "width"], int] = {
"height": self.target_size[0],
"width": self.target_size[1],
}
return filter_bboxes(
combined_bboxes,
shape_dict,
min_area=bbox_processor.params.min_area,
min_visibility=bbox_processor.params.min_visibility,
min_width=bbox_processor.params.min_width,
min_height=bbox_processor.params.min_height,
max_accept_ratio=bbox_processor.params.max_accept_ratio,
)
def apply_to_keypoints(
self,
keypoints: np.ndarray, # Original keypoints - ignored
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
**params: Any,
) -> np.ndarray:
"""Applies mosaic transformation to keypoints.
Args:
keypoints (np.ndarray): Original keypoints (ignored).
processed_cells (dict): Dictionary mapping placement coords to processed cell data
(containing shifted keypoints).
**params (Any): Additional parameters (unused).
Returns:
np.ndarray: Final combined, filtered keypoints.
"""
all_shifted_keypoints = []
for cell_data in processed_cells.values():
shifted_keypoints = cell_data["keypoints"]
if shifted_keypoints.size > 0:
all_shifted_keypoints.append(shifted_keypoints)
if not all_shifted_keypoints:
return np.empty((0, keypoints.shape[1]), dtype=keypoints.dtype)
combined_keypoints = np.concatenate(all_shifted_keypoints, axis=0)
# Filter out keypoints outside the target canvas boundaries
target_h, target_w = self.target_size
valid_indices = (
(combined_keypoints[:, 0] >= 0)
& (combined_keypoints[:, 0] < target_w)
& (combined_keypoints[:, 1] >= 0)
& (combined_keypoints[:, 1] < target_h)
)
return combined_keypoints[valid_indices]
@@ -0,0 +1,180 @@
"""Lambda transform module for creating custom user-defined transformations.
This module provides a flexible transform class that allows users to define their own
custom transformation functions for different targets (image, mask, keypoints, bboxes).
It's particularly useful for implementing custom logic that isn't available in the
standard transforms.
The Lambda transform accepts different callable functions for each target type and
applies them when the transform is executed. This allows for maximum flexibility
while maintaining compatibility with the Albumentations pipeline structure.
Key features:
- Apply different custom functions to different target types
- Compatible with all Albumentations pipeline features
- Support for all image types and formats
- Ability to handle any number of channels
- Warning system for lambda expressions and multiprocessing compatibility
Note that using actual lambda expressions (rather than named functions) can cause
issues with multiprocessing, as lambdas cannot be properly pickled.
"""
from __future__ import annotations
import warnings
from types import LambdaType
from typing import Any, Callable
import numpy as np
from albumentations.augmentations.pixel import functional as fpixel
from albumentations.core.transforms_interface import NoOp
from albumentations.core.utils import format_args
__all__ = ["Lambda"]
class Lambda(NoOp):
"""A flexible transformation class for using user-defined transformation functions per targets.
Function signature must include **kwargs to accept optional arguments like interpolation method, image size, etc:
Args:
image (Callable[..., Any] | None): Image transformation function.
mask (Callable[..., Any] | None): Mask transformation function.
keypoints (Callable[..., Any] | None): Keypoints transformation function.
bboxes (Callable[..., Any] | None): BBoxes transformation function.
p (float): probability of applying the transform. Default: 1.0.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Number of channels:
Any
"""
def __init__(
self,
image: Callable[..., Any] | None = None,
mask: Callable[..., Any] | None = None,
keypoints: Callable[..., Any] | None = None,
bboxes: Callable[..., Any] | None = None,
name: str | None = None,
p: float = 1.0,
):
super().__init__(p=p)
self.name = name
self.custom_apply_fns = dict.fromkeys(("image", "mask", "keypoints", "bboxes"), fpixel.noop)
for target_name, custom_apply_fn in {
"image": image,
"mask": mask,
"keypoints": keypoints,
"bboxes": bboxes,
}.items():
if custom_apply_fn is not None:
if isinstance(custom_apply_fn, LambdaType) and custom_apply_fn.__name__ == "<lambda>":
warnings.warn(
"Using lambda is incompatible with multiprocessing. "
"Consider using regular functions or partial().",
stacklevel=2,
)
self.custom_apply_fns[target_name] = custom_apply_fn
def apply(self, img: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the Lambda transform to the input image.
Args:
img (np.ndarray): The input image to apply the Lambda transform to.
**params (Any): Additional parameters (not used in this transform).
Returns:
np.ndarray: The image with the applied Lambda transform.
"""
fn = self.custom_apply_fns["image"]
return fn(img, **params)
def apply_to_mask(self, mask: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the Lambda transform to the input mask.
Args:
mask (np.ndarray): The input mask to apply the Lambda transform to.
**params (Any): Additional parameters (not used in this transform).
Returns:
np.ndarray: The mask with the applied Lambda transform.
"""
fn = self.custom_apply_fns["mask"]
return fn(mask, **params)
def apply_to_bboxes(self, bboxes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the Lambda transform to the input bounding boxes.
Args:
bboxes (np.ndarray): The input bounding boxes to apply the Lambda transform to.
**params (Any): Additional parameters (not used in this transform).
Returns:
np.ndarray: The bounding boxes with the applied Lambda transform.
"""
fn = self.custom_apply_fns["bboxes"]
return fn(bboxes, **params)
def apply_to_keypoints(self, keypoints: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the Lambda transform to the input keypoints.
Args:
keypoints (np.ndarray): The input keypoints to apply the Lambda transform to.
**params (Any): Additional parameters (not used in this transform).
Returns:
np.ndarray: The keypoints with the applied Lambda transform.
"""
fn = self.custom_apply_fns["keypoints"]
return fn(keypoints, **params)
@classmethod
def is_serializable(cls) -> bool:
"""Check if the Lambda transform is serializable.
Returns:
bool: True if the transform is serializable, False otherwise.
"""
return False
def to_dict_private(self) -> dict[str, Any]:
"""Convert the Lambda transform to a dictionary.
Returns:
dict[str, Any]: The dictionary representation of the transform.
"""
if self.name is None:
msg = (
"To make a Lambda transform serializable you should provide the `name` argument, "
"e.g. `Lambda(name='my_transform', image=<some func>, ...)`."
)
raise ValueError(msg)
return {"__class_fullname__": self.get_class_fullname(), "__name__": self.name}
def __repr__(self) -> str:
"""Return the string representation of the Lambda transform.
Returns:
str: The string representation of the Lambda transform.
"""
state = {"name": self.name}
state.update(self.custom_apply_fns.items()) # type: ignore[arg-type]
state.update(self.get_base_init_args())
return f"{self.__class__.__name__}({format_args(state)})"
@@ -0,0 +1,223 @@
"""Transforms for type conversion between float and other data types.
This module provides transform classes for converting image data types, primarily
for converting between floating point and integer representations. These transforms
are useful for preprocessing before neural network input (ToFloat) and for converting
network outputs back to standard image formats (FromFloat).
"""
from __future__ import annotations
from typing import Any
import numpy as np
from albucore import (
clip,
from_float,
get_max_value,
to_float,
)
from pydantic import (
model_validator,
)
from typing_extensions import Literal, Self
from albumentations.core.transforms_interface import (
BaseTransformInitSchema,
ImageOnlyTransform,
)
__all__ = [
"FromFloat",
"ToFloat",
]
class ToFloat(ImageOnlyTransform):
"""Convert the input image to a floating-point representation.
This transform divides pixel values by `max_value` to get a float32 output array
where all values lie in the range [0, 1.0]. It's useful for normalizing image data
before feeding it into neural networks or other algorithms that expect float input.
Args:
max_value (float | None): The maximum possible input value. If None, the transform
will try to infer the maximum value by inspecting the data type of the input image:
- uint8: 255
- uint16: 65535
- uint32: 4294967295
- float32: 1.0
Default: None.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, volume
Image types:
uint8, uint16, uint32, float32
Returns:
np.ndarray: Image in floating point representation, with values in range [0, 1.0].
Note:
- If the input image is already float32 with values in [0, 1], it will be returned unchanged.
- For integer types (uint8, uint16, uint32), the function will scale the values to [0, 1] range.
- The output will always be float32, regardless of the input type.
- This transform is often used as a preprocessing step before applying other transformations
or feeding the image into a neural network.
Raises:
TypeError: If the input image data type is not supported.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>>
# Convert uint8 image to float
>>> image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> transform = A.ToFloat(max_value=None)
>>> float_image = transform(image=image)['image']
>>> assert float_image.dtype == np.float32
>>> assert 0 <= float_image.min() <= float_image.max() <= 1.0
>>>
# Convert uint16 image to float with custom max_value
>>> image = np.random.randint(0, 4096, (100, 100, 3), dtype=np.uint16)
>>> transform = A.ToFloat(max_value=4095)
>>> float_image = transform(image=image)['image']
>>> assert float_image.dtype == np.float32
>>> assert 0 <= float_image.min() <= float_image.max() <= 1.0
See Also:
FromFloat: The inverse operation, converting from float back to the original data type.
"""
class InitSchema(BaseTransformInitSchema):
max_value: float | None
def __init__(
self,
max_value: float | None = None,
p: float = 1.0,
):
super().__init__(p=p)
self.max_value = max_value
def apply(self, img: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the ToFloat transform to the input image.
Args:
img (np.ndarray): The input image to apply the ToFloat transform to.
**params (Any): Additional parameters (not used in this transform).
Returns:
np.ndarray: The image with the applied ToFloat transform.
"""
return to_float(img, self.max_value)
class FromFloat(ImageOnlyTransform):
"""Convert an image from floating point representation to the specified data type.
This transform is designed to convert images from a normalized floating-point representation
(typically with values in the range [0, 1]) to other data types, scaling the values appropriately.
Args:
dtype (str): The desired output data type. Supported types include 'uint8', 'uint16',
'uint32'. Default: 'uint8'.
max_value (float | None): The maximum value for the output dtype. If None, the transform
will attempt to infer the maximum value based on the dtype.
Default: None.
p (float): Probability of applying the transform. Default: 1.0.
Targets:
image, volume
Image types:
float32, float64
Note:
- This is the inverse transform for ToFloat.
- Input images are expected to be in floating point format with values in the range [0, 1].
- For integer output types (uint8, uint16, uint32), the function will scale the values
to the appropriate range (e.g., 0-255 for uint8).
- For float output types (float32, float64), the values will remain in the [0, 1] range.
- The transform uses the `from_float` function internally, which ensures output values
are within the valid range for the specified dtype.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> transform = A.FromFloat(dtype='uint8', max_value=None, p=1.0)
>>> image = np.random.rand(100, 100, 3).astype(np.float32) # Float image in [0, 1] range
>>> result = transform(image=image)
>>> uint8_image = result['image']
>>> assert uint8_image.dtype == np.uint8
>>> assert uint8_image.min() >= 0 and uint8_image.max() <= 255
"""
class InitSchema(BaseTransformInitSchema):
dtype: Literal["uint8", "uint16", "uint32"]
max_value: float | None
@model_validator(mode="after")
def _update_max_value(self) -> Self:
if self.max_value is None:
self.max_value = get_max_value(np.dtype(self.dtype))
return self
def __init__(
self,
dtype: Literal["uint8", "uint16", "uint32"] = "uint8",
max_value: float | None = None,
p: float = 1.0,
):
super().__init__(p=p)
self.dtype = dtype
self.max_value = max_value
def apply(self, img: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the FromFloat transform to the input image.
Args:
img (np.ndarray): The input image to apply the FromFloat transform to.
**params (Any): Additional parameters (not used in this transform).
Returns:
np.ndarray: The image with the applied FromFloat transform.
"""
return from_float(img, np.dtype(self.dtype), self.max_value)
def apply_to_images(self, images: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the FromFloat transform to the input images.
Args:
images (np.ndarray): The input images to apply the FromFloat transform to.
**params (Any): Additional parameters (not used in this transform).
"""
return clip(np.rint(images * self.max_value), np.dtype(self.dtype), inplace=True)
def apply_to_volume(self, volume: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the FromFloat transform to the input volume.
Args:
volume (np.ndarray): The input volume to apply the FromFloat transform to.
**params (Any): Additional parameters (not used in this transform).
"""
return self.apply_to_images(volume, **params)
def apply_to_volumes(self, volumes: np.ndarray, **params: Any) -> np.ndarray:
"""Apply the FromFloat transform to the input volumes.
Args:
volumes (np.ndarray): The input volumes to apply the FromFloat transform to.
**params (Any): Additional parameters (not used in this transform).
"""
return self.apply_to_images(volumes, **params)
@@ -0,0 +1,220 @@
"""Transforms for spectrogram augmentation.
This module provides transforms specifically designed for augmenting spectrograms
in audio processing tasks. Includes time reversal, time masking, and frequency
masking transforms commonly used in audio machine learning applications.
"""
from __future__ import annotations
from warnings import warn
from pydantic import Field
from albumentations.augmentations.dropout.xy_masking import XYMasking
from albumentations.augmentations.geometric.flip import HorizontalFlip
from albumentations.core.transforms_interface import BaseTransformInitSchema
from albumentations.core.type_definitions import ALL_TARGETS
__all__ = [
"FrequencyMasking",
"TimeMasking",
"TimeReverse",
]
class TimeReverse(HorizontalFlip):
"""Reverse the time axis of a spectrogram image, also known as time inversion.
Time inversion of a spectrogram is analogous to the random flip of an image,
an augmentation technique widely used in the visual domain. This can be relevant
in the context of audio classification tasks when working with spectrograms.
The technique was successfully applied in the AudioCLIP paper, which extended
CLIP to handle image, text, and audio inputs.
This transform is implemented as a subclass of HorizontalFlip since reversing
time in a spectrogram is equivalent to flipping the image horizontally.
Args:
p (float): probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Number of channels:
Any
Note:
This transform is functionally identical to HorizontalFlip but provides
a more semantically meaningful name when working with spectrograms and
other time-series visualizations.
References:
- AudioCLIP paper: https://arxiv.org/abs/2106.13043
- Audiomentations: https://iver56.github.io/audiomentations/waveform_transforms/reverse/
"""
_targets = ALL_TARGETS
class InitSchema(BaseTransformInitSchema):
pass
def __init__(
self,
p: float = 0.5,
):
warn(
"TimeReverse is an alias for HorizontalFlip transform. "
"Consider using HorizontalFlip directly from albumentations.HorizontalFlip. ",
UserWarning,
stacklevel=2,
)
super().__init__(p=p)
class TimeMasking(XYMasking):
"""Apply masking to a spectrogram in the time domain.
This transform masks random segments along the time axis of a spectrogram,
implementing the time masking technique proposed in the SpecAugment paper.
Time masking helps in training models to be robust against temporal variations
and missing information in audio signals.
This is a specialized version of XYMasking configured for time masking only.
For more advanced use cases (e.g., multiple masks, frequency masking, or custom
fill values), consider using XYMasking directly.
Args:
time_mask_param (int): Maximum possible length of the mask in the time domain.
Must be a positive integer. Length of the mask is uniformly sampled from (0, time_mask_param).
p (float): probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Number of channels:
Any
Note:
This transform is implemented as a subset of XYMasking with fixed parameters:
- Single horizontal mask (num_masks_x=1)
- No vertical masks (num_masks_y=0)
- Zero fill value
- Random mask length up to time_mask_param
For more flexibility, including:
- Multiple masks
- Custom fill values
- Frequency masking
- Combined time-frequency masking
Consider using albumentations.XYMasking directly.
References:
- SpecAugment paper: https://arxiv.org/abs/1904.08779
- Original implementation: https://pytorch.org/audio/stable/transforms.html#timemask
"""
class InitSchema(BaseTransformInitSchema):
time_mask_param: int = Field(gt=0)
def __init__(
self,
time_mask_param: int = 40,
p: float = 0.5,
):
warn(
"TimeMasking is a specialized version of XYMasking. "
"For more flexibility (multiple masks, custom fill values, frequency masking), "
"consider using XYMasking directly from albumentations.XYMasking.",
UserWarning,
stacklevel=2,
)
super().__init__(
num_masks_x=1,
num_masks_y=0,
mask_x_length=(0, time_mask_param),
fill=0,
fill_mask=0,
p=p,
)
self.time_mask_param = time_mask_param
class FrequencyMasking(XYMasking):
"""Apply masking to a spectrogram in the frequency domain.
This transform masks random segments along the frequency axis of a spectrogram,
implementing the frequency masking technique proposed in the SpecAugment paper.
Frequency masking helps in training models to be robust against frequency variations
and missing spectral information in audio signals.
This is a specialized version of XYMasking configured for frequency masking only.
For more advanced use cases (e.g., multiple masks, time masking, or custom
fill values), consider using XYMasking directly.
Args:
freq_mask_param (int): Maximum possible length of the mask in the frequency domain.
Must be a positive integer. Length of the mask is uniformly sampled from (0, freq_mask_param).
p (float): probability of applying the transform. Default: 0.5.
Targets:
image, mask, bboxes, keypoints, volume, mask3d
Image types:
uint8, float32
Number of channels:
Any
Note:
This transform is implemented as a subset of XYMasking with fixed parameters:
- Single vertical mask (num_masks_y=1)
- No horizontal masks (num_masks_x=0)
- Zero fill value
- Random mask length up to freq_mask_param
For more flexibility, including:
- Multiple masks
- Custom fill values
- Time masking
- Combined time-frequency masking
Consider using albumentations.XYMasking directly.
References:
- SpecAugment paper: https://arxiv.org/abs/1904.08779
- Original implementation: https://pytorch.org/audio/stable/transforms.html#freqmask
"""
class InitSchema(BaseTransformInitSchema):
freq_mask_param: int = Field(gt=0)
def __init__(
self,
freq_mask_param: int = 30,
p: float = 0.5,
):
warn(
"FrequencyMasking is a specialized version of XYMasking. "
"For more flexibility (multiple masks, custom fill values, time masking), "
"consider using XYMasking directly from albumentations.XYMasking.",
UserWarning,
stacklevel=2,
)
super().__init__(
p=p,
fill=0,
fill_mask=0,
mask_y_length=(0, freq_mask_param),
num_masks_x=0,
num_masks_y=1,
)
self.freq_mask_param = freq_mask_param
@@ -0,0 +1,272 @@
"""Functional implementations for text manipulation and rendering.
This module provides utility functions for manipulating text in strings and
rendering text onto images. Includes functions for word manipulation, text drawing,
and handling text regions in images.
"""
from __future__ import annotations
import random
from typing import TYPE_CHECKING, Any
import cv2
import numpy as np
from albucore import (
MONO_CHANNEL_DIMENSIONS,
NUM_MULTI_CHANNEL_DIMENSIONS,
NUM_RGB_CHANNELS,
preserve_channel_dim,
uint8_io,
)
from albumentations.core.type_definitions import PAIR
# Importing wordnet and other dependencies only for type checking
if TYPE_CHECKING:
from PIL import Image
def delete_random_words(words: list[str], num_words: int, py_random: random.Random) -> str:
"""Delete a specified number of random words from a list.
This function randomly removes words from the input list and joins the remaining
words with spaces to form a new string.
Args:
words (list[str]): List of words to process.
num_words (int): Number of words to delete.
py_random (random.Random): Random number generator for reproducibility.
Returns:
str: New string with specified words removed. Returns empty string if
num_words is greater than or equal to the length of words.
"""
if num_words >= len(words):
return ""
indices_to_delete = py_random.sample(range(len(words)), num_words)
new_words = [word for idx, word in enumerate(words) if idx not in indices_to_delete]
return " ".join(new_words)
def swap_random_words(words: list[str], num_words: int, py_random: random.Random) -> str:
"""Swap random pairs of words in a list of words.
This function randomly selects pairs of words and swaps their positions
a specified number of times.
Args:
words (list[str]): List of words to process.
num_words (int): Number of swaps to perform.
py_random (random.Random): Random number generator for reproducibility.
Returns:
str: New string with words swapped. If num_words is 0 or the list has fewer
than 2 words, returns the original string.
"""
if num_words == 0 or len(words) < PAIR:
return " ".join(words)
words = words.copy()
for _ in range(num_words):
idx1, idx2 = py_random.sample(range(len(words)), 2)
words[idx1], words[idx2] = words[idx2], words[idx1]
return " ".join(words)
def insert_random_stopwords(
words: list[str],
num_insertions: int,
stopwords: tuple[str, ...] | None,
py_random: random.Random,
) -> str:
"""Insert random stopwords into a list of words.
This function randomly inserts stopwords at random positions in the
list of words a specified number of times.
Args:
words (list[str]): List of words to process.
num_insertions (int): Number of stopwords to insert.
stopwords (tuple[str, ...] | None): Tuple of stopwords to choose from.
If None, default stopwords will be used.
py_random (random.Random): Random number generator for reproducibility.
Returns:
str: New string with stopwords inserted.
"""
if stopwords is None:
stopwords = ("and", "the", "is", "in", "at", "of") # Default stopwords if none provided
for _ in range(num_insertions):
idx = py_random.randint(0, len(words))
words.insert(idx, py_random.choice(stopwords))
return " ".join(words)
def convert_image_to_pil(image: np.ndarray) -> Image:
"""Convert a NumPy array image to a PIL image."""
try:
from PIL import Image
except ImportError:
raise ImportError("Pillow is not installed") from ImportError
if image.ndim == MONO_CHANNEL_DIMENSIONS: # (height, width)
return Image.fromarray(image)
if image.ndim == NUM_MULTI_CHANNEL_DIMENSIONS and image.shape[2] == 1: # (height, width, 1)
return Image.fromarray(image[:, :, 0], mode="L")
if image.ndim == NUM_MULTI_CHANNEL_DIMENSIONS and image.shape[2] == NUM_RGB_CHANNELS: # (height, width, 3)
return Image.fromarray(image)
raise TypeError(f"Unsupported image shape: {image.shape}")
def draw_text_on_pil_image(pil_image: Image, metadata_list: list[dict[str, Any]]) -> Image:
"""Draw text on a PIL image."""
try:
from PIL import ImageDraw
except ImportError:
raise ImportError("Pillow is not installed") from ImportError
draw = ImageDraw.Draw(pil_image)
for metadata in metadata_list:
bbox_coords = metadata["bbox_coords"]
text = metadata["text"]
font = metadata["font"]
font_color = metadata["font_color"]
# Adapt font_color based on image mode
if pil_image.mode == "L": # Grayscale
# For grayscale images, use only the first value or average the RGB values
if isinstance(font_color, tuple):
if len(font_color) >= 3:
# Average RGB values for grayscale
font_color = int(sum(font_color[:3]) / 3)
elif len(font_color) == 1:
font_color = int(font_color[0])
# For RGB and other modes, ensure font_color is a tuple of integers
elif isinstance(font_color, tuple):
font_color = tuple(int(c) for c in font_color)
position = bbox_coords[:2]
draw.text(position, text, font=font, fill=font_color)
return pil_image
def draw_text_on_multi_channel_image(image: np.ndarray, metadata_list: list[dict[str, Any]]) -> np.ndarray:
"""Draw text on a multi-channel image with more than three channels."""
try:
from PIL import Image, ImageDraw
except ImportError:
raise ImportError("Pillow is not installed") from ImportError
channels = [Image.fromarray(image[:, :, i]) for i in range(image.shape[2])]
pil_images = [ImageDraw.Draw(channel) for channel in channels]
for metadata in metadata_list:
bbox_coords = metadata["bbox_coords"]
text = metadata["text"]
font = metadata["font"]
font_color = metadata["font_color"]
# Handle font_color as tuple[float, ...]
# Ensure we have enough color values for all channels
if len(font_color) < image.shape[2]:
# If fewer values than channels, pad with zeros
font_color = tuple(list(font_color) + [0] * (image.shape[2] - len(font_color)))
elif len(font_color) > image.shape[2]:
# If more values than channels, truncate
font_color = font_color[: image.shape[2]]
# Convert to integers for PIL
font_color = [int(c) for c in font_color]
position = bbox_coords[:2]
# For each channel, use the corresponding color value
for channel_id, pil_image in enumerate(pil_images):
# For single-channel PIL images, color must be an integer
pil_image.text(position, text, font=font, fill=font_color[channel_id])
return np.stack([np.array(channel) for channel in channels], axis=2)
@uint8_io
@preserve_channel_dim
def render_text(image: np.ndarray, metadata_list: list[dict[str, Any]], clear_bg: bool) -> np.ndarray:
"""Render text onto an image based on provided metadata.
This function draws text on an image using metadata that specifies text content,
position, font, and color. It can optionally clear the background before rendering.
The function handles different image types (grayscale, RGB, multi-channel).
Args:
image (np.ndarray): Image to draw text on.
metadata_list (list[dict[str, Any]]): List of metadata dictionaries containing:
- bbox_coords: Bounding box coordinates (x_min, y_min, x_max, y_max)
- text: Text string to render
- font: PIL ImageFont object
- font_color: Color for the text
clear_bg (bool): Whether to clear (inpaint) the background under the text.
Returns:
np.ndarray: Image with text rendered on it.
"""
# First clean background under boxes using seamless clone if clear_bg is True
if clear_bg:
image = inpaint_text_background(image, metadata_list)
if len(image.shape) == MONO_CHANNEL_DIMENSIONS or (
len(image.shape) == NUM_MULTI_CHANNEL_DIMENSIONS and image.shape[2] in {1, NUM_RGB_CHANNELS}
):
pil_image = convert_image_to_pil(image)
pil_image = draw_text_on_pil_image(pil_image, metadata_list)
return np.array(pil_image)
return draw_text_on_multi_channel_image(image, metadata_list)
def inpaint_text_background(
image: np.ndarray,
metadata_list: list[dict[str, Any]],
method: int = cv2.INPAINT_TELEA,
) -> np.ndarray:
"""Inpaint (clear) regions in an image where text will be rendered.
This function creates a clean background for text by inpainting rectangular
regions specified in the metadata. It removes any existing content in those
regions to provide a clean slate for rendering text.
Args:
image (np.ndarray): Image to inpaint.
metadata_list (list[dict[str, Any]]): List of metadata dictionaries containing:
- bbox_coords: Bounding box coordinates (x_min, y_min, x_max, y_max)
method (int, optional): Inpainting method to use. Defaults to cv2.INPAINT_TELEA.
Options include:
- cv2.INPAINT_TELEA: Fast Marching Method
- cv2.INPAINT_NS: Navier-Stokes method
Returns:
np.ndarray: Image with specified regions inpainted.
"""
result_image = image.copy()
mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
for metadata in metadata_list:
x_min, y_min, x_max, y_max = metadata["bbox_coords"]
# Black out the region
result_image[y_min:y_max, x_min:x_max] = 0
# Update the mask to indicate the region to inpaint
mask[y_min:y_max, x_min:x_max] = 255
# Inpaint the blacked-out regions
return cv2.inpaint(result_image, mask, inpaintRadius=3, flags=method)
@@ -0,0 +1,299 @@
"""Transforms for text rendering and augmentation on images.
This module provides transforms for adding and manipulating text on images,
including text augmentation techniques like word insertion, deletion, and swapping.
"""
from __future__ import annotations
import re
from pathlib import Path
from typing import Annotated, Any, Literal
import numpy as np
from pydantic import AfterValidator
import albumentations.augmentations.text.functional as ftext
from albumentations.core.bbox_utils import check_bboxes, denormalize_bboxes
from albumentations.core.pydantic import check_range_bounds, nondecreasing
from albumentations.core.transforms_interface import BaseTransformInitSchema, ImageOnlyTransform
__all__ = ["TextImage"]
class TextImage(ImageOnlyTransform):
"""Apply text rendering transformations on images.
This class supports rendering text directly onto images using a variety of configurations,
such as custom fonts, font sizes, colors, and augmentation methods. The text can be placed
inside specified bounding boxes.
Args:
font_path (str | Path): Path to the font file to use for rendering text.
stopwords (list[str] | None): List of stopwords for text augmentation.
augmentations (tuple[str | None, ...]): List of text augmentations to apply.
None: text is printed as is
"insertion": insert random stop words into the text.
"swap": swap random words in the text.
"deletion": delete random words from the text.
fraction_range (tuple[float, float]): Range for selecting a fraction of bounding boxes to modify.
font_size_fraction_range (tuple[float, float]): Range for selecting the font size as a fraction of
bounding box height.
font_color (tuple[float, ...]): Font color as RGB values (e.g., (0, 0, 0) for black).
clear_bg (bool): Whether to clear the background before rendering text.
metadata_key (str): Key to access metadata in the parameters.
p (float): Probability of applying the transform.
Targets:
image, volume
Image types:
uint8, float32
References:
doc-augmentation: https://github.com/danaaubakirova/doc-augmentation
Examples:
>>> import albumentations as A
>>> transform = A.Compose([
A.TextImage(
font_path=Path("/path/to/font.ttf"),
stopwords=("the", "is", "in"),
augmentations=("insertion", "deletion"),
fraction_range=(0.5, 1.0),
font_size_fraction_range=(0.5, 0.9),
font_color=(255, 0, 0), # red in RGB
metadata_key="text_metadata",
p=0.5
)
])
>>> transformed = transform(image=my_image, text_metadata=my_metadata)
>>> image = transformed['image']
# This will render text on `my_image` based on the metadata provided in `my_metadata`.
"""
class InitSchema(BaseTransformInitSchema):
font_path: str | Path
stopwords: tuple[str, ...]
augmentations: tuple[str | None, ...]
fraction_range: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, 1)),
]
font_size_fraction_range: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, 1)),
]
font_color: tuple[float, ...]
clear_bg: bool
metadata_key: str
def __init__(
self,
font_path: str | Path,
stopwords: tuple[str, ...] = ("the", "is", "in", "at", "of"),
augmentations: tuple[Literal["insertion", "swap", "deletion"] | None, ...] = (None,),
fraction_range: tuple[float, float] = (1.0, 1.0),
font_size_fraction_range: tuple[float, float] = (0.8, 0.9),
font_color: tuple[float, ...] = (0, 0, 0), # black in RGB
clear_bg: bool = False,
metadata_key: str = "textimage_metadata",
p: float = 0.5,
) -> None:
super().__init__(p=p)
self.metadata_key = metadata_key
self.font_path = font_path
self.fraction_range = fraction_range
self.stopwords = stopwords
self.augmentations = list(augmentations)
self.font_size_fraction_range = font_size_fraction_range
self.font_color = font_color
self.clear_bg = clear_bg
@property
def targets_as_params(self) -> list[str]:
"""Get list of targets that should be passed as parameters to transforms.
Returns:
list[str]: List containing the metadata key name
"""
return [self.metadata_key]
def random_aug(
self,
text: str,
fraction: float,
choice: Literal["insertion", "swap", "deletion"],
) -> str:
"""Apply a random text augmentation to the input text.
Args:
text (str): Original text to augment
fraction (float): Fraction of words to modify
choice (Literal["insertion", "swap", "deletion"]): Type of augmentation to apply
Returns:
str: Augmented text or empty string if no change was made
Raises:
ValueError: If an invalid choice is provided
"""
words = [word for word in text.strip().split() if word]
num_words = len(words)
num_words_to_modify = max(1, int(fraction * num_words))
if choice == "insertion":
result_sentence = ftext.insert_random_stopwords(words, num_words_to_modify, self.stopwords, self.py_random)
elif choice == "swap":
result_sentence = ftext.swap_random_words(words, num_words_to_modify, self.py_random)
elif choice == "deletion":
result_sentence = ftext.delete_random_words(words, num_words_to_modify, self.py_random)
else:
raise ValueError("Invalid choice. Choose from 'insertion', 'swap', or 'deletion'.")
result_sentence = re.sub(" +", " ", result_sentence).strip()
return result_sentence if result_sentence != text else ""
def preprocess_metadata(
self,
image: np.ndarray,
bbox: tuple[float, float, float, float],
text: str,
bbox_index: int,
) -> dict[str, Any]:
"""Preprocess text metadata for a single bounding box.
Args:
image (np.ndarray): Input image
bbox (tuple[float, float, float, float]): Normalized bounding box coordinates
text (str): Text to render in the bounding box
bbox_index (int): Index of the bounding box in the original metadata
Returns:
dict[str, Any]: Processed metadata including font, position, and text information
Raises:
ImportError: If PIL.ImageFont is not installed
"""
try:
from PIL import ImageFont
except ImportError as err:
raise ImportError(
"ImageFont from PIL is required to use TextImage transform. Install it with `pip install Pillow`.",
) from err
check_bboxes(np.array([bbox]))
denormalized_bbox = denormalize_bboxes(np.array([bbox]), image.shape[:2])[0]
x_min, y_min, x_max, y_max = (int(x) for x in denormalized_bbox[:4])
bbox_height = y_max - y_min
font_size_fraction = self.py_random.uniform(*self.font_size_fraction_range)
font = ImageFont.truetype(str(self.font_path), int(font_size_fraction * bbox_height))
if not self.augmentations or self.augmentations is None:
augmented_text = text
else:
augmentation = self.py_random.choice(self.augmentations)
augmented_text = text if augmentation is None else self.random_aug(text, 0.5, choice=augmentation)
font_color = self.font_color
return {
"bbox_coords": (x_min, y_min, x_max, y_max),
"bbox_index": bbox_index,
"original_text": text,
"text": augmented_text,
"font": font,
"font_color": font_color,
}
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Generate parameters based on input data.
Args:
params (dict[str, Any]): Dictionary of existing parameters
data (dict[str, Any]): Dictionary containing input data with image and metadata
Returns:
dict[str, Any]: Dictionary containing the overlay data for text rendering
"""
image = data["image"] if "image" in data else data["images"][0]
metadata = data[self.metadata_key]
if metadata == []:
return {
"overlay_data": [],
}
if isinstance(metadata, dict):
metadata = [metadata]
fraction = self.py_random.uniform(*self.fraction_range)
num_bboxes_to_modify = int(len(metadata) * fraction)
bbox_indices_to_update = self.py_random.sample(range(len(metadata)), num_bboxes_to_modify)
overlay_data = [
self.preprocess_metadata(image, metadata[bbox_index]["bbox"], metadata[bbox_index]["text"], bbox_index)
for bbox_index in bbox_indices_to_update
]
return {
"overlay_data": overlay_data,
}
def apply(
self,
img: np.ndarray,
overlay_data: list[dict[str, Any]],
**params: Any,
) -> np.ndarray:
"""Apply text rendering to the input image.
Args:
img (np.ndarray): Input image
overlay_data (list[dict[str, Any]]): List of dictionaries containing text rendering information
**params (Any): Additional parameters
Returns:
np.ndarray: Image with rendered text
"""
return ftext.render_text(img, overlay_data, clear_bg=self.clear_bg)
def apply_with_params(self, params: dict[str, Any], *args: Any, **kwargs: Any) -> dict[str, Any]:
"""Apply the transform and include overlay data in the result.
Args:
params (dict[str, Any]): Parameters for the transform
*args (Any): Additional positional arguments
**kwargs (Any): Additional keyword arguments
Returns:
dict[str, Any]: Dictionary containing the transformed data and simplified overlay information
"""
res = super().apply_with_params(params, *args, **kwargs)
res["overlay_data"] = [
{
"bbox_coords": overlay["bbox_coords"],
"text": overlay["text"],
"original_text": overlay["original_text"],
"bbox_index": overlay["bbox_index"],
"font_color": overlay["font_color"],
}
for overlay in params["overlay_data"]
]
return res
@@ -0,0 +1,393 @@
"""Module containing functional implementations of 3D transformations.
This module provides a collection of utility functions for manipulating and transforming
3D volumetric data (such as medical imaging volumes). The functions here implement the core
algorithms for operations like padding, cropping, rotation, and other spatial manipulations
specifically designed for 3D data.
"""
from __future__ import annotations
import random
from typing import Literal
import numpy as np
from albumentations.augmentations.utils import handle_empty_array
from albumentations.core.type_definitions import NUM_VOLUME_DIMENSIONS
def adjust_padding_by_position3d(
paddings: list[tuple[int, int]], # [(front, back), (top, bottom), (left, right)]
position: Literal["center", "random"],
py_random: random.Random,
) -> tuple[int, int, int, int, int, int]:
"""Adjust padding values based on desired position for 3D data.
Args:
paddings (list[tuple[int, int]]): List of tuples containing padding pairs
for each dimension [(d_pad), (h_pad), (w_pad)]
position (Literal["center", "random"]): Position of the image after padding.
py_random (random.Random): Random number generator
Returns:
tuple[int, int, int, int, int, int]: Final padding values (d_front, d_back, h_top, h_bottom, w_left, w_right)
"""
if position == "center":
return (
paddings[0][0], # d_front
paddings[0][1], # d_back
paddings[1][0], # h_top
paddings[1][1], # h_bottom
paddings[2][0], # w_left
paddings[2][1], # w_right
)
# For random position, redistribute padding for each dimension
d_pad = sum(paddings[0])
h_pad = sum(paddings[1])
w_pad = sum(paddings[2])
return (
py_random.randint(0, d_pad), # d_front
d_pad - py_random.randint(0, d_pad), # d_back
py_random.randint(0, h_pad), # h_top
h_pad - py_random.randint(0, h_pad), # h_bottom
py_random.randint(0, w_pad), # w_left
w_pad - py_random.randint(0, w_pad), # w_right
)
def pad_3d_with_params(
volume: np.ndarray,
padding: tuple[int, int, int, int, int, int],
value: tuple[float, ...] | float,
) -> np.ndarray:
"""Pad 3D volume with given parameters.
Args:
volume (np.ndarray): Input volume with shape (depth, height, width) or (depth, height, width, channels)
padding (tuple[int, int, int, int, int, int]): Padding values in format:
(depth_front, depth_back, height_top, height_bottom, width_left, width_right)
where:
- depth_front/back: padding at start/end of depth axis (z)
- height_top/bottom: padding at start/end of height axis (y)
- width_left/right: padding at start/end of width axis (x)
value (tuple[float, ...] | float): Value to fill the padding
Returns:
np.ndarray: Padded volume with same number of dimensions as input
Note:
The padding order matches the volume dimensions (depth, height, width).
For each dimension, the first value is padding at the start (smaller indices),
and the second value is padding at the end (larger indices).
"""
depth_front, depth_back, height_top, height_bottom, width_left, width_right = padding
# Skip if no padding is needed
if all(p == 0 for p in padding):
return volume
# Handle both 3D and 4D arrays
pad_width = [
(depth_front, depth_back), # depth (z) padding
(height_top, height_bottom), # height (y) padding
(width_left, width_right), # width (x) padding
]
# Add channel padding if 4D array
if volume.ndim == NUM_VOLUME_DIMENSIONS:
pad_width.append((0, 0)) # no padding for channels
return np.pad(
volume,
pad_width=pad_width,
mode="constant",
constant_values=value,
)
def crop3d(
volume: np.ndarray,
crop_coords: tuple[int, int, int, int, int, int],
) -> np.ndarray:
"""Crop 3D volume using coordinates.
Args:
volume (np.ndarray): Input volume with shape (z, y, x) or (z, y, x, channels)
crop_coords (tuple[int, int, int, int, int, int]):
(z_min, z_max, y_min, y_max, x_min, x_max) coordinates for cropping
Returns:
np.ndarray: Cropped volume with same number of dimensions as input
"""
z_min, z_max, y_min, y_max, x_min, x_max = crop_coords
return volume[z_min:z_max, y_min:y_max, x_min:x_max]
def cutout3d(volume: np.ndarray, holes: np.ndarray, fill: tuple[float, ...] | float) -> np.ndarray:
"""Cut out holes in 3D volume and fill them with a given value.
Args:
volume (np.ndarray): Input volume with shape (depth, height, width) or (depth, height, width, channels)
holes (np.ndarray): Array of holes with shape (num_holes, 6).
Each hole is represented as [z1, y1, x1, z2, y2, x2]
fill (tuple[float, ...] | float): Value to fill the holes
Returns:
np.ndarray: Volume with holes filled with the given value
"""
volume = volume.copy()
for z1, y1, x1, z2, y2, x2 in holes:
volume[z1:z2, y1:y2, x1:x2] = fill
return volume
def transform_cube(cube: np.ndarray, index: int) -> np.ndarray:
"""Transform cube by index (0-47)
Args:
cube (np.ndarray): Input array with shape (D, H, W) or (D, H, W, C)
index (int): Integer from 0 to 47 specifying which transformation to apply
Returns:
np.ndarray: Transformed cube with same shape as input
"""
if not (0 <= index < 48):
raise ValueError("Index must be between 0 and 47")
transformations = {
# First 4: rotate around axis 0 (indices 0-3)
0: lambda x: x,
1: lambda x: np.rot90(x, k=1, axes=(1, 2)),
2: lambda x: np.rot90(x, k=2, axes=(1, 2)),
3: lambda x: np.rot90(x, k=3, axes=(1, 2)),
# Next 4: flip 180° about axis 1, then rotate around axis 0 (indices 4-7)
4: lambda x: x[::-1, :, ::-1], # was: np.flip(x, axis=(0, 2))
5: lambda x: np.rot90(np.rot90(x, k=2, axes=(0, 2)), k=1, axes=(1, 2)),
6: lambda x: x[::-1, ::-1, :], # was: np.flip(x, axis=(0, 1))
7: lambda x: np.rot90(np.rot90(x, k=2, axes=(0, 2)), k=3, axes=(1, 2)),
# Next 8: split between 90° and 270° about axis 1, then rotate around axis 2 (indices 8-15)
8: lambda x: np.rot90(x, k=1, axes=(0, 2)),
9: lambda x: np.rot90(np.rot90(x, k=1, axes=(0, 2)), k=1, axes=(0, 1)),
10: lambda x: np.rot90(np.rot90(x, k=1, axes=(0, 2)), k=2, axes=(0, 1)),
11: lambda x: x.transpose(1, 2, 0, *range(3, x.ndim)),
12: lambda x: np.rot90(x, k=-1, axes=(0, 2)),
13: lambda x: np.rot90(np.rot90(x, k=-1, axes=(0, 2)), k=1, axes=(0, 1)),
14: lambda x: np.rot90(np.rot90(x, k=-1, axes=(0, 2)), k=2, axes=(0, 1)),
15: lambda x: np.rot90(np.rot90(x, k=-1, axes=(0, 2)), k=3, axes=(0, 1)),
# Final 8: split between rotations about axis 2, then rotate around axis 1 (indices 16-23)
16: lambda x: np.rot90(x, k=1, axes=(0, 1)),
17: lambda x: np.rot90(np.rot90(x, k=1, axes=(0, 1)), k=1, axes=(0, 2)),
18: lambda x: np.rot90(np.rot90(x, k=1, axes=(0, 1)), k=2, axes=(0, 2)),
19: lambda x: x.transpose(2, 0, 1, *range(3, x.ndim)),
20: lambda x: np.rot90(x, k=-1, axes=(0, 1)),
21: lambda x: np.rot90(np.rot90(x, k=-1, axes=(0, 1)), k=1, axes=(0, 2)),
22: lambda x: np.rot90(np.rot90(x, k=-1, axes=(0, 1)), k=2, axes=(0, 2)),
23: lambda x: np.rot90(np.rot90(x, k=-1, axes=(0, 1)), k=3, axes=(0, 2)),
# Reflected versions (24-47) - same as above but with initial reflection
24: lambda x: x[:, :, ::-1], # was: np.flip(x, axis=2)
25: lambda x: x.transpose(0, 2, 1, *range(3, x.ndim)),
26: lambda x: x[:, ::-1, :], # was: np.flip(x, axis=1)
27: lambda x: np.rot90(x[:, :, ::-1], k=3, axes=(1, 2)),
28: lambda x: x[::-1, :, :], # was: np.flip(x, axis=0)
29: lambda x: np.rot90(x[::-1, :, :], k=1, axes=(1, 2)),
30: lambda x: x[::-1, ::-1, ::-1], # was: np.flip(x, axis=(0, 1, 2))
31: lambda x: np.rot90(x[::-1, :, :], k=-1, axes=(1, 2)),
32: lambda x: x.transpose(2, 1, 0, *range(3, x.ndim)),
33: lambda x: x.transpose(1, 2, 0, *range(3, x.ndim))[::-1, :, :],
34: lambda x: x.transpose(2, 1, 0, *range(3, x.ndim))[::-1, ::-1, :],
35: lambda x: x.transpose(1, 2, 0, *range(3, x.ndim))[:, ::-1, :],
36: lambda x: np.rot90(x[:, :, ::-1], k=-1, axes=(0, 2)),
37: lambda x: x.transpose(1, 2, 0, *range(3, x.ndim))[::-1, ::-1, ::-1],
38: lambda x: x.transpose(2, 1, 0, *range(3, x.ndim))[:, ::-1, ::-1],
39: lambda x: x.transpose(1, 2, 0, *range(3, x.ndim))[:, :, ::-1],
40: lambda x: np.rot90(x[:, :, ::-1], k=1, axes=(0, 1)),
41: lambda x: x.transpose(2, 0, 1, *range(3, x.ndim))[:, :, ::-1],
42: lambda x: x.transpose(1, 0, 2, *range(3, x.ndim)),
43: lambda x: x.transpose(2, 0, 1, *range(3, x.ndim))[::-1, :, :],
44: lambda x: np.rot90(x[:, :, ::-1], k=-1, axes=(0, 1)),
45: lambda x: x.transpose(2, 0, 1, *range(3, x.ndim))[:, ::-1, :],
46: lambda x: x.transpose(1, 0, 2, *range(3, x.ndim))[::-1, ::-1, :],
47: lambda x: x.transpose(2, 0, 1, *range(3, x.ndim))[::-1, ::-1, ::-1],
}
return transformations[index](cube.copy())
@handle_empty_array("keypoints")
def filter_keypoints_in_holes3d(keypoints: np.ndarray, holes: np.ndarray) -> np.ndarray:
"""Filter out keypoints that are inside any of the 3D holes.
Args:
keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+).
The first three columns are x, y, z coordinates.
holes (np.ndarray): Array of holes with shape (num_holes, 6).
Each hole is represented as [z1, y1, x1, z2, y2, x2].
Returns:
np.ndarray: Array of keypoints that are not inside any hole.
"""
if holes.size == 0:
return keypoints
# Broadcast keypoints and holes for vectorized comparison
# Convert keypoints from XYZ to ZYX for comparison with holes
kp_z = keypoints[:, 2][:, np.newaxis] # Shape: (num_keypoints, 1)
kp_y = keypoints[:, 1][:, np.newaxis] # Shape: (num_keypoints, 1)
kp_x = keypoints[:, 0][:, np.newaxis] # Shape: (num_keypoints, 1)
# Extract hole coordinates (in ZYX order)
hole_z1 = holes[:, 0] # Shape: (num_holes,)
hole_y1 = holes[:, 1]
hole_x1 = holes[:, 2]
hole_z2 = holes[:, 3]
hole_y2 = holes[:, 4]
hole_x2 = holes[:, 5]
# Check if each keypoint is inside each hole
inside_hole = (
(kp_z >= hole_z1)
& (kp_z < hole_z2)
& (kp_y >= hole_y1)
& (kp_y < hole_y2)
& (kp_x >= hole_x1)
& (kp_x < hole_x2)
)
# A keypoint is valid if it's not inside any hole
valid_keypoints = ~np.any(inside_hole, axis=1)
# Return filtered keypoints with same dtype as input
result = keypoints[valid_keypoints]
if len(result) == 0:
# Ensure empty result has correct shape and dtype
return np.array([], dtype=keypoints.dtype).reshape(0, keypoints.shape[1])
return result
def keypoints_rot90(
keypoints: np.ndarray,
k: int,
axes: tuple[int, int],
volume_shape: tuple[int, int, int],
) -> np.ndarray:
"""Rotate keypoints 90 degrees k times around the specified axes.
Args:
keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+).
The first three columns are x, y, z coordinates.
k (int): Number of times to rotate by 90 degrees.
axes (tuple[int, int]): Axes to rotate around.
volume_shape (tuple[int, int, int]): Shape of the volume (depth, height, width).
Returns:
np.ndarray: Rotated keypoints with same shape as input.
"""
if k == 0 or len(keypoints) == 0:
return keypoints
# Normalize factor to range [0, 3]
k = ((k % 4) + 4) % 4
result = keypoints.copy()
# Get dimensions for the rotation axes
dims = [volume_shape[ax] for ax in axes]
# Get coordinates to rotate
coords1 = result[:, axes[0]].copy()
coords2 = result[:, axes[1]].copy()
# Apply rotation based on factor (counterclockwise)
if k == 1: # 90 degrees CCW
result[:, axes[0]] = (dims[1] - 1) - coords2
result[:, axes[1]] = coords1
elif k == 2: # 180 degrees
result[:, axes[0]] = (dims[0] - 1) - coords1
result[:, axes[1]] = (dims[1] - 1) - coords2
elif k == 3: # 270 degrees CCW
result[:, axes[0]] = coords2
result[:, axes[1]] = (dims[0] - 1) - coords1
return result
@handle_empty_array("keypoints")
def transform_cube_keypoints(
keypoints: np.ndarray,
index: int,
volume_shape: tuple[int, int, int],
) -> np.ndarray:
"""Transform keypoints according to the cube transformation specified by index.
Args:
keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+).
The first three columns are x, y, z coordinates.
index (int): Integer from 0 to 47 specifying which transformation to apply.
volume_shape (tuple[int, int, int]): Shape of the volume (depth, height, width).
Returns:
np.ndarray: Transformed keypoints with same shape as input.
"""
if not (0 <= index < 48):
raise ValueError("Index must be between 0 and 47")
# Create working copy preserving all columns
working_points = keypoints.copy()
# Convert only XYZ coordinates to HWD, keeping other columns unchanged
xyz = working_points[:, :3] # Get first 3 columns (XYZ)
xyz = xyz[:, [2, 1, 0]] # XYZ -> HWD
working_points[:, :3] = xyz # Put back transformed coordinates
current_shape = volume_shape
# Handle reflection first (indices 24-47)
if index >= 24:
working_points[:, 2] = current_shape[2] - 1 - working_points[:, 2] # Reflect W axis
rotation_index = index % 24
# Apply the same rotation logic as transform_cube
if rotation_index < 4:
# First 4: rotate around axis 0
result = keypoints_rot90(working_points, k=rotation_index, axes=(1, 2), volume_shape=current_shape)
elif rotation_index < 8:
# Next 4: flip 180° about axis 1, then rotate around axis 0
temp = keypoints_rot90(working_points, k=2, axes=(0, 2), volume_shape=current_shape)
result = keypoints_rot90(temp, k=rotation_index - 4, axes=(1, 2), volume_shape=volume_shape)
elif rotation_index < 16:
if rotation_index < 12:
temp = keypoints_rot90(working_points, k=1, axes=(0, 2), volume_shape=current_shape)
temp_shape = (current_shape[2], current_shape[1], current_shape[0])
result = keypoints_rot90(temp, k=rotation_index - 8, axes=(0, 1), volume_shape=temp_shape)
else:
temp = keypoints_rot90(working_points, k=3, axes=(0, 2), volume_shape=current_shape)
temp_shape = (current_shape[2], current_shape[1], current_shape[0])
result = keypoints_rot90(temp, k=rotation_index - 12, axes=(0, 1), volume_shape=temp_shape)
elif rotation_index < 20:
temp = keypoints_rot90(working_points, k=1, axes=(0, 1), volume_shape=current_shape)
temp_shape = (current_shape[1], current_shape[0], current_shape[2])
result = keypoints_rot90(temp, k=rotation_index - 16, axes=(0, 2), volume_shape=temp_shape)
else:
temp = keypoints_rot90(working_points, k=3, axes=(0, 1), volume_shape=current_shape)
temp_shape = (current_shape[1], current_shape[0], current_shape[2])
result = keypoints_rot90(temp, k=rotation_index - 20, axes=(0, 2), volume_shape=temp_shape)
# Convert back from HWD to XYZ coordinates for first 3 columns only
xyz = result[:, :3]
xyz = xyz[:, [2, 1, 0]] # HWD -> XYZ
result[:, :3] = xyz
return result
@@ -0,0 +1,249 @@
"""Module containing utility functions for augmentation operations.
This module provides a collection of helper functions and utilities used throughout
the augmentation pipeline. It includes functions for image loading, type checking,
error handling, mathematical operations, and decorators that add functionality to
other functions in the codebase. These utilities help ensure consistent behavior
and simplify common operations across different augmentation transforms.
"""
from __future__ import annotations
import functools
from functools import wraps
from typing import TYPE_CHECKING, Any, Callable, TypeVar, cast
import cv2
import numpy as np
from albucore.utils import (
is_grayscale_image,
is_multispectral_image,
is_rgb_image,
)
from typing_extensions import Concatenate, ParamSpec
from albumentations.core.keypoints_utils import angle_to_2pi_range
if TYPE_CHECKING:
from pathlib import Path
__all__ = [
"angle_2pi_range",
"non_rgb_error",
"read_bgr_image",
"read_grayscale",
"read_rgb_image",
]
P = ParamSpec("P")
T = TypeVar("T", bound=np.ndarray)
F = TypeVar("F", bound=Callable[..., Any])
def read_bgr_image(path: str | Path) -> np.ndarray:
"""Read an image in BGR format from the specified path.
Args:
path (str | Path): Path to the image file.
Returns:
np.ndarray: Image in BGR format as a numpy array.
"""
return cv2.imread(str(path), cv2.IMREAD_COLOR)
def read_rgb_image(path: str | Path) -> np.ndarray:
"""Read an image in RGB format from the specified path.
This function reads an image in BGR format using OpenCV and then
converts it to RGB format.
Args:
path (str | Path): Path to the image file.
Returns:
np.ndarray: Image in RGB format as a numpy array.
"""
image = read_bgr_image(path)
return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
def read_grayscale(path: str | Path) -> np.ndarray:
"""Read a grayscale image from the specified path.
Args:
path (str | Path): Path to the image file.
Returns:
np.ndarray: Grayscale image as a numpy array.
"""
return cv2.imread(str(path), cv2.IMREAD_GRAYSCALE)
def angle_2pi_range(
func: Callable[Concatenate[np.ndarray, P], np.ndarray],
) -> Callable[Concatenate[np.ndarray, P], np.ndarray]:
"""Decorator to normalize angle values to the range [0, 2π).
This decorator wraps a function that processes keypoints, ensuring that
angle values (stored in the 4th column, index 3) are normalized to the
range [0, 2π) after the wrapped function executes.
Args:
func (Callable): Function that processes keypoints and returns a numpy array.
The function should take a keypoints array as its first parameter.
Returns:
Callable: Wrapped function that normalizes angles after processing keypoints.
"""
@wraps(func)
def wrapped_function(keypoints: np.ndarray, *args: P.args, **kwargs: P.kwargs) -> np.ndarray:
result = func(keypoints, *args, **kwargs)
if len(result) > 0 and result.shape[1] > 3:
result[:, 3] = angle_to_2pi_range(result[:, 3])
return result
return wrapped_function
def non_rgb_error(image: np.ndarray) -> None:
"""Check if the input image is RGB and raise a ValueError if it's not.
This function is used to ensure that certain transformations are only applied to
RGB images. It provides helpful error messages for grayscale and multi-spectral images.
Args:
image (np.ndarray): The input image to check. Expected to be a numpy array
representing an image.
Raises:
ValueError: If the input image is not an RGB image (i.e., does not have exactly 3 channels).
The error message includes specific instructions for grayscale images
and a note about incompatibility with multi-spectral images.
Note:
- RGB images are expected to have exactly 3 channels.
- Grayscale images (1 channel) will trigger an error with conversion instructions.
- Multi-spectral images (more than 3 channels) will trigger an error stating incompatibility.
Example:
>>> import numpy as np
>>> rgb_image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> non_rgb_error(rgb_image) # No error raised
>>>
>>> grayscale_image = np.random.randint(0, 256, (100, 100), dtype=np.uint8)
>>> non_rgb_error(grayscale_image) # Raises ValueError with conversion instructions
>>>
>>> multispectral_image = np.random.randint(0, 256, (100, 100, 5), dtype=np.uint8)
>>> non_rgb_error(multispectral_image) # Raises ValueError stating incompatibility
"""
if not is_rgb_image(image):
message = "This transformation expects 3-channel images"
if is_grayscale_image(image):
message += "\nYou can convert your grayscale image to RGB using cv2.cvtColor(image, cv2.COLOR_GRAY2RGB))"
if is_multispectral_image(image): # Any image with a number of channels other than 1 and 3
message += "\nThis transformation cannot be applied to multi-spectral images"
raise ValueError(message)
def check_range(value: tuple[float, float], lower_bound: float, upper_bound: float, name: str | None) -> None:
"""Checks if the given value is within the specified bounds
Args:
value (tuple[float, float]): The value to check and convert. Can be a single float or a tuple of floats.
lower_bound (float): The lower bound for the range check.
upper_bound (float): The upper bound for the range check.
name (str | None): The name of the parameter being checked. Used for error messages.
Raises:
ValueError: If the value is outside the bounds or if the tuple values are not ordered correctly.
"""
if not all(lower_bound <= x <= upper_bound for x in value):
raise ValueError(f"All values in {name} must be within [{lower_bound}, {upper_bound}] for tuple inputs.")
if not value[0] <= value[1]:
raise ValueError(f"{name!s} tuple values must be ordered as (min, max). Got: {value}")
class PCA:
def __init__(self, n_components: int | None = None) -> None:
if n_components is not None and n_components <= 0:
raise ValueError("Number of components must be greater than zero.")
self.n_components = n_components
self.mean: np.ndarray | None = None
self.components_: np.ndarray | None = None
self.explained_variance_: np.ndarray | None = None
def fit(self, x: np.ndarray) -> None:
x = x.astype(np.float64, copy=False) # avoid unnecessary copy if already float64
n_samples, n_features = x.shape
# Determine the number of components if not set
if self.n_components is None:
self.n_components = min(n_samples, n_features)
self.mean, eigenvectors, eigenvalues = cv2.PCACompute2(x, mean=None, maxComponents=self.n_components)
self.components_ = eigenvectors
self.explained_variance_ = eigenvalues.flatten()
def transform(self, x: np.ndarray) -> np.ndarray:
if self.components_ is None:
raise ValueError(
"This PCA instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
x = x.astype(np.float64, copy=False) # avoid unnecessary copy if already float64
return cv2.PCAProject(x, self.mean, self.components_)
def fit_transform(self, x: np.ndarray) -> np.ndarray:
self.fit(x)
return self.transform(x)
def inverse_transform(self, x: np.ndarray) -> np.ndarray:
if self.components_ is None:
raise ValueError(
"This PCA instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
return cv2.PCABackProject(x, self.mean, self.components_)
def explained_variance_ratio(self) -> np.ndarray:
if self.explained_variance_ is None:
raise ValueError(
"This PCA instance is not fitted yet. Call 'fit' with appropriate arguments before using this method.",
)
total_variance = np.sum(self.explained_variance_)
return self.explained_variance_ / total_variance
def cumulative_explained_variance_ratio(self) -> np.ndarray:
return np.cumsum(self.explained_variance_ratio())
def handle_empty_array(param_name: str) -> Callable[[F], F]:
def decorator(func: F) -> F:
@functools.wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
# Check if the parameter is passed as positional argument
if len(args) > 0:
array = args[0]
# Check if the parameter is passed as keyword argument
elif param_name in kwargs:
array = kwargs[param_name]
else:
raise ValueError(f"Missing required argument: {param_name}")
if len(array) == 0:
return array
return func(*args, **kwargs)
return cast("F", wrapper)
return decorator