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,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,
}