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,786 @@
"""Domain adaptation transforms for image augmentation.
This module provides transformations designed to bridge the domain gap between
datasets by adapting the style of an input image to match that of reference images
from a target domain. Adaptations are based on matching statistical properties
like histograms, frequency spectra, or overall pixel distributions.
"""
from __future__ import annotations
import warnings
from collections.abc import Sequence
from typing import Annotated, Any, Callable, Literal, cast
import cv2
import numpy as np
from pydantic import AfterValidator, field_validator, model_validator
from typing_extensions import Self
from albumentations.augmentations.mixing.domain_adaptation_functional import (
adapt_pixel_distribution,
apply_histogram,
fourier_domain_adaptation,
)
from albumentations.augmentations.utils import read_rgb_image
from albumentations.core.pydantic import ZeroOneRangeType, check_range_bounds, nondecreasing
from albumentations.core.transforms_interface import BaseTransformInitSchema, ImageOnlyTransform
__all__ = [
"FDA",
"HistogramMatching",
"PixelDistributionAdaptation",
]
MAX_BETA_LIMIT = 0.5
# Base class for Domain Adaptation Init Schema
class BaseDomainAdaptationInitSchema(BaseTransformInitSchema):
reference_images: Sequence[Any] | None
read_fn: Callable[[Any], np.ndarray] | None
metadata_key: str
@model_validator(mode="after")
def _check_deprecated_args(self) -> Self:
if self.reference_images is not None:
warnings.warn(
"'reference_images' and 'read_fn' arguments are deprecated. "
"Please pass pre-loaded reference images "
f"using the '{self.metadata_key}' key in the input data dictionary.",
DeprecationWarning,
stacklevel=3, # Adjust stacklevel as needed
)
if self.read_fn is None:
msg = "read_fn cannot be None when using the deprecated 'reference_images' argument."
raise ValueError(msg)
return self
class BaseDomainAdaptation(ImageOnlyTransform):
"""Base class for domain adaptation transforms.
Domain adaptation transforms modify source images to match the characteristics of a target domain.
These transforms typically require an additional reference image or dataset from the target domain
to extract style information or domain-specific features.
This base class provides the framework for implementing various domain adaptation techniques such as
color transfer, style transfer, frequency domain adaptation, or histogram matching.
Args:
reference_images (Sequence[Any] | None): Deprecated. Sequence of references to images from the target
domain. Should be used with read_fn to load actual images. Prefer passing pre-loaded images via
metadata_key.
read_fn (Callable[[Any], np.ndarray] | None): Deprecated. Function to read an image from a reference.
Should be used with reference_images.
metadata_key (str): Key in the input data dictionary that contains pre-loaded target domain images.
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image
Image types:
uint8, float32
Notes:
- Subclasses should implement the `apply` method to perform the actual adaptation.
- Use `targets_as_params` property to define what additional data your transform needs.
- Override `get_params_dependent_on_data` to extract the target domain data.
- Domain adaptation often requires per-sample auxiliary data, which should be passed
through the main data dictionary rather than at initialization time.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Implement a simple color transfer domain adaptation transform
>>> class SimpleColorTransfer(A.BaseDomainAdaptation):
... class InitSchema(A.BaseTransformInitSchema):
... intensity: float = Field(gt=0, le=1)
... reference_key: str
...
... def __init__(
... self,
... intensity: float = 0.5,
... reference_key: str = "target_image",
... p: float = 1.0
... ):
... super().__init__(p=p)
... self.intensity = intensity
... self.reference_key = reference_key
...
... @property
... def targets_as_params(self) -> list[str]:
... return [self.reference_key] # We need target domain image
...
... def get_params_dependent_on_data(
... self,
... params: dict[str, Any],
... data: dict[str, Any]
... ) -> dict[str, Any]:
... target_image = data.get(self.reference_key)
... if target_image is None:
... # Fallback if target image is not provided
... return {"target_image": None}
... return {"target_image": target_image}
...
... def apply(
... self,
... img: np.ndarray,
... target_image: np.ndarray = None,
... **params
... ) -> np.ndarray:
... if target_image is None:
... return img
...
... # Simple color transfer implementation
... # Calculate mean and std of source and target images
... src_mean = np.mean(img, axis=(0, 1))
... src_std = np.std(img, axis=(0, 1))
... tgt_mean = np.mean(target_image, axis=(0, 1))
... tgt_std = np.std(target_image, axis=(0, 1))
...
... # Normalize source image
... normalized = (img - src_mean) / (src_std + 1e-7)
...
... # Scale by target statistics and blend with original
... transformed = normalized * tgt_std + tgt_mean
... transformed = np.clip(transformed, 0, 255).astype(np.uint8)
...
... # Blend the result based on intensity
... result = cv2.addWeighted(img, 1 - self.intensity, transformed, self.intensity, 0)
... return result
>>>
>>> # Usage example with a target image from a different domain
>>> source_image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> target_image = np.random.randint(100, 200, (200, 200, 3), dtype=np.uint8) # Different domain image
>>>
>>> # Create the transform with the pipeline
>>> transform = A.Compose([
... SimpleColorTransfer(intensity=0.7, reference_key="target_img", p=1.0),
... ])
>>>
>>> # Apply the transform with the target image passed in the data dictionary
>>> result = transform(image=source_image, target_img=target_image)
>>> adapted_image = result["image"] # Image with characteristics transferred from target domain
"""
InitSchema: type[BaseDomainAdaptationInitSchema]
def __init__(
self,
reference_images: Sequence[Any] | None,
read_fn: Callable[[Any], np.ndarray] | None,
metadata_key: str,
p: float = 0.5,
):
super().__init__(p=p)
self.reference_images = reference_images
self.read_fn = read_fn
self.metadata_key = metadata_key
@property
def targets_as_params(self) -> list[str]:
return [self.metadata_key]
def _get_reference_image(self, data: dict[str, Any]) -> np.ndarray:
"""Retrieves the reference image from metadata or deprecated arguments."""
reference_image = None
if metadata_images := data.get(self.metadata_key):
if not isinstance(metadata_images, Sequence) or not metadata_images:
raise ValueError(
f"Metadata key '{self.metadata_key}' should contain a non-empty sequence of numpy arrays.",
)
if not isinstance(metadata_images[0], np.ndarray):
raise ValueError(
f"Images in metadata key '{self.metadata_key}' should be numpy arrays.",
)
reference_image = self.py_random.choice(metadata_images)
if self.reference_images is not None:
warnings.warn(
f"Both 'reference_images' (deprecated constructor argument) and metadata via "
f"'{self.metadata_key}' were provided. Prioritizing metadata.",
UserWarning,
stacklevel=3, # Adjust stacklevel as needed
)
elif self.reference_images is not None:
# Deprecation warning is handled by the InitSchema validator
if self.read_fn is None:
# This case should ideally be caught by InitSchema, but safety check
msg = "read_fn cannot be None when using the deprecated 'reference_images' argument."
raise ValueError(msg)
ref_source = self.py_random.choice(self.reference_images)
reference_image = self.read_fn(ref_source)
else:
raise ValueError(
f"{self.__class__.__name__} requires reference images. Provide them via the `metadata_key` "
f"'{self.metadata_key}' in the input data, or use the deprecated 'reference_images' argument.",
)
if reference_image is None:
# Should not happen if logic above is correct, but safety check
msg = "Could not obtain a reference image."
raise RuntimeError(msg)
return reference_image
def to_dict_private(self) -> dict[str, Any]:
"""Convert the transform to a dictionary for serialization.
Raises:
NotImplementedError: Domain adaptation transforms cannot be reliably serialized
when using metadata key or deprecated arguments.
"""
if self.reference_images is not None:
msg = (
f"{self.__class__.__name__} cannot be reliably serialized when using the deprecated 'reference_images'."
)
raise NotImplementedError(msg)
msg = (
f"{self.__class__.__name__} cannot be reliably serialized due to its dependency "
"on external data via metadata."
)
raise NotImplementedError(msg)
class HistogramMatching(BaseDomainAdaptation):
"""Adjust the pixel value distribution of an input image to match a reference image.
This transform modifies the pixel intensities of the input image so that its histogram
matches the histogram of a provided reference image. This process is applied independently
to each channel of the image if it is multi-channel.
Why use Histogram Matching?
**Domain Adaptation:** Helps bridge the gap between images from different sources
(e.g., different cameras, lighting conditions, synthetic vs. real data) by aligning
their overall intensity and contrast characteristics.
*Use Case Example:* Imagine you have labeled training images from one source (e.g., daytime photos,
medical scans from Hospital A) but expect your model to work on images from a different
source at test time (e.g., nighttime photos, scans from Hospital B). You might only have
unlabeled images from the target (test) domain. HistogramMatching can be used to make your
labeled training images resemble the *style* (intensity and contrast distribution) of the
unlabeled target images. By training on these adapted images, your model may generalize
better to the target domain without needing labels for it.
How it works:
The core idea is to map the pixel values of the input image such that its cumulative
distribution function (CDF) matches the CDF of the reference image. This effectively
reshapes the input image's histogram to resemble the reference's histogram.
Args:
metadata_key (str): Key in the input `data` dictionary to retrieve the reference image(s).
The value should be a sequence (e.g., list) of numpy arrays (pre-loaded images).
Default: "hm_metadata".
blend_ratio (tuple[float, float]): Range for the blending factor between the original
and the histogram-matched image. A value of 0 means the original image is returned,
1 means the fully matched image is returned. A random value within this range [min, max]
is sampled for each application. This allows for varying degrees of adaptation.
Default: (0.5, 1.0).
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image
Image types:
uint8, float32
Note:
- Requires at least one reference image to be provided via the `metadata_key` argument.
- The `reference_images` and `read_fn` constructor arguments are deprecated.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Create sample images for demonstration
>>> # Source image: dark image with low contrast
>>> source_image = np.ones((100, 100, 3), dtype=np.uint8) * 50 # Dark gray image
>>> source_image[30:70, 30:70] = 100 # Add slightly brighter square in center
>>>
>>> # Target image: higher brightness and contrast
>>> target_image = np.ones((100, 100, 3), dtype=np.uint8) * 150 # Bright image
>>> target_image[20:80, 20:80] = 200 # Add even brighter square
>>>
>>> # Initialize the histogram matching transform with custom settings
>>> transform = A.Compose([
... A.HistogramMatching(
... blend_ratio=(0.7, 0.9), # Control the strength of histogram matching
... metadata_key="reference_imgs", # Custom metadata key
... p=1.0
... )
... ])
>>>
>>> # Apply the transform
>>> result = transform(
... image=source_image,
... reference_imgs=[target_image] # Pass reference image via metadata key
... )
>>>
>>> # Get the histogram-matched image
>>> matched_image = result["image"]
>>>
>>> # The matched_image will have brightness and contrast similar to target_image
>>> # while preserving the content of source_image
>>>
>>> # Multiple reference images can be provided:
>>> ref_imgs = [
... target_image,
... np.random.randint(100, 200, (100, 100, 3), dtype=np.uint8) # Another reference image
... ]
>>> multiple_refs_result = transform(image=source_image, reference_imgs=ref_imgs)
>>> # A random reference image from the list will be chosen for each transform application
References:
Histogram Matching in scikit-image:
https://scikit-image.org/docs/dev/auto_examples/color_exposure/plot_histogram_matching.html
"""
class InitSchema(BaseDomainAdaptationInitSchema):
blend_ratio: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, 1)),
]
def __init__(
self,
reference_images: Sequence[Any] | None = None,
blend_ratio: tuple[float, float] = (0.5, 1.0),
read_fn: Callable[[Any], np.ndarray] | None = read_rgb_image,
metadata_key: str = "hm_metadata",
p: float = 0.5,
):
super().__init__(reference_images=reference_images, read_fn=read_fn, metadata_key=metadata_key, p=p)
self.blend_ratio = blend_ratio
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Generate parameters for the transform based on input data.
Args:
params (dict[str, Any]): Parameters from the previous transform in the pipeline
data (dict[str, Any]): Input data dictionary containing the image and metadata
Returns:
dict[str, Any]: Dictionary containing the reference image and blend ratio
"""
reference_image = self._get_reference_image(data)
return {
"reference_image": reference_image,
"blend_ratio": self.py_random.uniform(*self.blend_ratio),
}
def apply(
self,
img: np.ndarray,
reference_image: np.ndarray,
blend_ratio: float,
**params: Any,
) -> np.ndarray:
"""Apply histogram matching to the input image.
Args:
img (np.ndarray): Input image to be transformed
reference_image (np.ndarray): Reference image for histogram matching
blend_ratio (float): Blending factor between the original and matched image
**params (Any): Additional parameters
Returns:
np.ndarray: Transformed image with histogram matched to the reference image
"""
return apply_histogram(img, reference_image, blend_ratio)
class FDA(BaseDomainAdaptation):
"""Fourier Domain Adaptation (FDA).
Adapts the style of the input image to match the style of a reference image
by manipulating their frequency components in the Fourier domain. This is
particularly useful for unsupervised domain adaptation (UDA).
Why use FDA?
**Domain Adaptation:** FDA helps bridge the domain gap between source and target
datasets (e.g., synthetic vs. real, day vs. night) by aligning their low-frequency
Fourier spectrum components. This can improve model performance on the target domain
without requiring target labels.
*Use Case Example:* Imagine you have labeled training data acquired under certain conditions
(e.g., images from Hospital A using a specific scanner) but need your model to perform well
on data from a different distribution (e.g., unlabeled images from Hospital B with a different scanner).
FDA can adapt the labeled source images to match the *style* (frequency characteristics)
of the unlabeled target images, potentially improving the model's generalization to the
target domain at test time.
How it works:
FDA operates in the frequency domain. It replaces the low-frequency components
of the source image's Fourier transform with the low-frequency components from the
reference (target domain) image's Fourier transform. The `beta_limit` parameter
controls the size of the frequency window being swapped.
Args:
metadata_key (str): Key in the input `data` dictionary to retrieve the reference image(s).
The value should be a sequence (e.g., list) of numpy arrays (pre-loaded images).
Default: "fda_metadata".
beta_limit (tuple[float, float] | float): Controls the extent of the low-frequency
spectrum swap. A larger beta means more components are swapped. Corresponds to the L
parameter in the original paper. Should be in the range [0, 0.5]. Sampling is uniform
within the provided range [min, max]. Default: (0, 0.1).
p (float): Probability of applying the transform. Default: 0.5.
Targets:
image
Image types:
uint8, float32
Note:
- Requires at least one reference image to be provided via the `metadata_key` argument.
- The `reference_images` and `read_fn` constructor arguments are deprecated.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Create sample images for demonstration
>>> # Source image: synthetic or simulated image (e.g., from a rendered game environment)
>>> source_img = np.zeros((100, 100, 3), dtype=np.uint8)
>>> # Create a pattern in the source image
>>> source_img[20:80, 20:80, 0] = 200 # Red square
>>> source_img[40:60, 40:60, 1] = 200 # Green inner square
>>>
>>> # Target domain image: real-world image with different texture/frequency characteristics
>>> # For this example, we'll create an image with different frequency patterns
>>> target_img = np.zeros((100, 100, 3), dtype=np.uint8)
>>> for i in range(100):
... for j in range(100):
... # Create a high-frequency pattern
... target_img[i, j, 0] = ((i + j) % 8) * 30
... target_img[i, j, 1] = ((i - j) % 8) * 30
... target_img[i, j, 2] = ((i * j) % 8) * 30
>>>
>>> # Example 1: FDA with minimal adaptation (small beta value)
>>> # This will subtly adjust the frequency characteristics
>>> minimal_fda = A.Compose([
... A.FDA(
... beta_limit=(0.01, 0.05), # Small beta range for subtle adaptation
... metadata_key="target_domain", # Custom metadata key
... p=1.0
... )
... ])
>>>
>>> # Apply the transform with minimal adaptation
>>> minimal_result = minimal_fda(
... image=source_img,
... target_domain=[target_img] # Pass reference image via custom metadata key
... )
>>> minimal_adapted_img = minimal_result["image"]
>>>
>>> # Example 2: FDA with moderate adaptation (medium beta value)
>>> moderate_fda = A.Compose([
... A.FDA(
... beta_limit=(0.1, 0.2), # Medium beta range
... metadata_key="target_domain",
... p=1.0
... )
... ])
>>>
>>> moderate_result = moderate_fda(image=source_img, target_domain=[target_img])
>>> moderate_adapted_img = moderate_result["image"]
>>>
>>> # Example 3: FDA with strong adaptation (larger beta value)
>>> strong_fda = A.Compose([
... A.FDA(
... beta_limit=(0.3, 0.5), # Larger beta range (upper limit is MAX_BETA_LIMIT)
... metadata_key="target_domain",
... p=1.0
... )
... ])
>>>
>>> strong_result = strong_fda(image=source_img, target_domain=[target_img])
>>> strong_adapted_img = strong_result["image"]
>>>
>>> # Example 4: Using multiple target domain images
>>> # Creating a list of target domain images with different characteristics
>>> target_imgs = [target_img]
>>>
>>> # Add another target image with different pattern
>>> another_target = np.zeros((100, 100, 3), dtype=np.uint8)
>>> for i in range(100):
... for j in range(100):
... another_target[i, j, 0] = (i // 10) * 25
... another_target[i, j, 1] = (j // 10) * 25
... another_target[i, j, 2] = ((i + j) // 10) * 25
>>> target_imgs.append(another_target)
>>>
>>> # Using default FDA settings with multiple target images
>>> multi_target_fda = A.Compose([
... A.FDA(p=1.0) # Using default settings with default metadata_key="fda_metadata"
... ])
>>>
>>> # A random target image will be selected from the list for each application
>>> multi_target_result = multi_target_fda(image=source_img, fda_metadata=target_imgs)
>>> adapted_image = multi_target_result["image"]
References:
- FDA: https://github.com/YanchaoYang/FDA
- FDA: https://openaccess.thecvf.com/content_CVPR_2020/papers/Yang_FDA_Fourier_Domain_Adaptation_for_Semantic_Segmentation_CVPR_2020_paper.pdf
"""
class InitSchema(BaseDomainAdaptationInitSchema):
beta_limit: ZeroOneRangeType
@field_validator("beta_limit")
@classmethod
def _check_ranges(cls, value: tuple[float, float]) -> tuple[float, float]:
bounds = 0, MAX_BETA_LIMIT
if not bounds[0] <= value[0] <= value[1] <= bounds[1]:
raise ValueError(f"Values should be in the range {bounds} got {value} ")
return value
def __init__(
self,
reference_images: Sequence[Any] | None = None,
beta_limit: tuple[float, float] | float = (0, 0.1),
read_fn: Callable[[Any], np.ndarray] | None = read_rgb_image,
metadata_key: str = "fda_metadata",
p: float = 0.5,
):
super().__init__(reference_images=reference_images, read_fn=read_fn, metadata_key=metadata_key, p=p)
self.beta_limit = cast("tuple[float, float]", beta_limit)
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Generate parameters for the transform based on input data."""
target_image = self._get_reference_image(data)
height, width = params["shape"][:2]
# Resize the target image to match the input image dimensions
target_image_resized = cv2.resize(target_image, dsize=(width, height))
return {"target_image": target_image_resized, "beta": self.py_random.uniform(*self.beta_limit)}
def apply(
self,
img: np.ndarray,
target_image: np.ndarray,
beta: float,
**params: Any,
) -> np.ndarray:
"""Apply Fourier Domain Adaptation to the input image.
Args:
img (np.ndarray): Input image to be transformed
target_image (np.ndarray): Target domain image for adaptation
beta (float): Coefficient controlling the extent of frequency component swapping
**params (Any): Additional parameters
Returns:
np.ndarray: Transformed image with adapted frequency components
"""
return fourier_domain_adaptation(img, target_image, beta)
class PixelDistributionAdaptation(BaseDomainAdaptation):
"""Adapts the pixel value distribution of an input image to match a reference image
using statistical transformations (PCA, StandardScaler, or MinMaxScaler).
This transform aims to harmonize images from different domains by aligning their pixel-level
statistical properties.
Why use Pixel Distribution Adaptation?
**Domain Adaptation:** Useful for aligning images across domains with differing pixel statistics
(e.g., caused by different sensors, lighting, or post-processing).
*Use Case Example:* Consider having labeled data from Scanner A and needing the model to perform
well on unlabeled data from Scanner B, where images might have different overall brightness,
contrast, or color biases. This transform can adapt the labeled images from Scanner A to
mimic the pixel distribution *style* of the images from Scanner B, potentially improving
generalization without needing labels for Scanner B data.
How it works:
1. A chosen statistical transform (`transform_type`) is fitted to both the input (source) image
and the reference (target) image separately.
2. The input image is transformed using the transform fitted on it (moving it to a standardized space).
3. The inverse transform *fitted on the reference image* is applied to the result from step 2
(moving the standardized input into the reference image's statistical space).
4. The result is optionally blended with the original input image using `blend_ratio`.
Args:
metadata_key (str): Key in the input `data` dictionary to retrieve the reference image(s).
The value should be a sequence (e.g., list) of numpy arrays (pre-loaded images).
Default: "pda_metadata".
blend_ratio (tuple[float, float]): Specifies the minimum and maximum blend ratio for mixing
the adapted image with the original. A value of 0 means the original image is returned,
1 means the fully adapted image is returned. A random value within this range [min, max]
is sampled for each application. Default: (0.25, 1.0).
transform_type (Literal["pca", "standard", "minmax"]): Specifies the type of statistical
transformation to apply:
- "pca": Principal Component Analysis.
- "standard": StandardScaler (zero mean, unit variance).
- "minmax": MinMaxScaler (scales to [0, 1] range).
Default: "pca".
p (float): The probability of applying the transform. Default: 0.5.
Targets:
image
Image types:
uint8, float32
Note:
- Requires at least one reference image to be provided via the `metadata_key` argument.
- The `reference_images` and `read_fn` constructor arguments are deprecated.
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Create sample images for demonstration
>>> # Source image: simulated image from domain A (e.g., medical scan from one scanner)
>>> source_image = np.random.normal(100, 20, (100, 100, 3)).clip(0, 255).astype(np.uint8)
>>>
>>> # Reference image: image from domain B with different statistical properties
>>> # (e.g., scan from a different scanner with different intensity distribution)
>>> reference_image = np.random.normal(150, 30, (100, 100, 3)).clip(0, 255).astype(np.uint8)
>>>
>>> # Example 1: Using PCA transformation (default)
>>> pca_transform = A.Compose([
... A.PixelDistributionAdaptation(
... transform_type="pca",
... blend_ratio=(0.8, 1.0), # Strong adaptation
... metadata_key="reference_images",
... p=1.0
... )
... ])
>>>
>>> # Apply the transform with the reference image
>>> pca_result = pca_transform(
... image=source_image,
... reference_images=[reference_image]
... )
>>>
>>> # Get the adapted image
>>> pca_adapted_image = pca_result["image"]
>>>
>>> # Example 2: Using StandardScaler transformation
>>> standard_transform = A.Compose([
... A.PixelDistributionAdaptation(
... transform_type="standard",
... blend_ratio=(0.5, 0.7), # Moderate adaptation
... metadata_key="reference_images",
... p=1.0
... )
... ])
>>>
>>> standard_result = standard_transform(
... image=source_image,
... reference_images=[reference_image]
... )
>>> standard_adapted_image = standard_result["image"]
>>>
>>> # Example 3: Using MinMaxScaler transformation
>>> minmax_transform = A.Compose([
... A.PixelDistributionAdaptation(
... transform_type="minmax",
... blend_ratio=(0.3, 0.5), # Subtle adaptation
... metadata_key="reference_images",
... p=1.0
... )
... ])
>>>
>>> minmax_result = minmax_transform(
... image=source_image,
... reference_images=[reference_image]
... )
>>> minmax_adapted_image = minmax_result["image"]
>>>
>>> # Example 4: Using multiple reference images
>>> # When multiple reference images are provided, one is randomly selected for each transformation
>>> multiple_references = [
... reference_image,
... np.random.normal(180, 25, (100, 100, 3)).clip(0, 255).astype(np.uint8),
... np.random.normal(120, 40, (100, 100, 3)).clip(0, 255).astype(np.uint8)
... ]
>>>
>>> multi_ref_transform = A.Compose([
... A.PixelDistributionAdaptation(p=1.0) # Using default settings
... ])
>>>
>>> # Each time the transform is applied, it randomly selects one of the reference images
>>> multi_ref_result = multi_ref_transform(
... image=source_image,
... pda_metadata=multiple_references # Using the default metadata key
... )
>>> adapted_image = multi_ref_result["image"]
References:
Qudida: https://github.com/arsenyinfo/qudida
"""
class InitSchema(BaseDomainAdaptationInitSchema):
blend_ratio: Annotated[
tuple[float, float],
AfterValidator(nondecreasing),
AfterValidator(check_range_bounds(0, 1)),
]
transform_type: Literal["pca", "standard", "minmax"]
def __init__(
self,
reference_images: Sequence[Any] | None = None,
blend_ratio: tuple[float, float] = (0.25, 1.0),
read_fn: Callable[[Any], np.ndarray] | None = read_rgb_image,
transform_type: Literal["pca", "standard", "minmax"] = "pca",
metadata_key: str = "pda_metadata",
p: float = 0.5,
):
super().__init__(reference_images=reference_images, read_fn=read_fn, metadata_key=metadata_key, p=p)
self.blend_ratio = blend_ratio
self.transform_type = transform_type
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Get parameters for the transform."""
reference_image = self._get_reference_image(data)
return {
"reference_image": reference_image,
"blend_ratio": self.py_random.uniform(*self.blend_ratio),
}
def apply(self, img: np.ndarray, reference_image: np.ndarray, blend_ratio: float, **params: Any) -> np.ndarray:
"""Apply pixel distribution adaptation to the input image.
Args:
img (np.ndarray): Input image to be transformed
reference_image (np.ndarray): Reference image for distribution adaptation
blend_ratio (float): Blending factor between the original and adapted image
**params (Any): Additional parameters
Returns:
np.ndarray: Transformed image with pixel distribution adapted to the reference image
"""
return adapt_pixel_distribution(
img,
ref=reference_image,
weight=blend_ratio,
transform_type=self.transform_type,
)
@@ -0,0 +1,453 @@
"""Functional implementations for domain adaptation image transformations.
This module provides low-level functions and classes for performing domain adaptation
between images. It includes implementations for histogram matching, Fourier domain adaptation,
and pixel distribution matching with various normalization techniques.
"""
from __future__ import annotations
import abc
from copy import deepcopy
from typing import Literal
import cv2
import numpy as np
from albucore import add_weighted, clip, clipped, from_float, get_num_channels, preserve_channel_dim, to_float, uint8_io
from typing_extensions import Protocol
import albumentations.augmentations.geometric.functional as fgeometric
from albumentations.augmentations.utils import PCA
from albumentations.core.type_definitions import MONO_CHANNEL_DIMENSIONS
__all__ = [
"adapt_pixel_distribution",
"apply_histogram",
"fourier_domain_adaptation",
]
class BaseScaler:
def __init__(self) -> None:
self.data_min: np.ndarray | None = None
self.data_max: np.ndarray | None = None
self.mean: np.ndarray | None = None
self.var: np.ndarray | None = None
self.scale: np.ndarray | None = None
def fit(self, x: np.ndarray) -> None:
raise NotImplementedError
def transform(self, x: np.ndarray) -> np.ndarray:
raise NotImplementedError
def fit_transform(self, x: np.ndarray) -> np.ndarray:
self.fit(x)
return self.transform(x)
def inverse_transform(self, x: np.ndarray) -> np.ndarray:
raise NotImplementedError
class MinMaxScaler(BaseScaler):
def __init__(self, feature_range: tuple[float, float] = (0.0, 1.0)) -> None:
super().__init__()
self.min: float = feature_range[0]
self.max: float = feature_range[1]
self.data_range: np.ndarray | None = None
def fit(self, x: np.ndarray) -> None:
self.data_min = np.min(x, axis=0)
self.data_max = np.max(x, axis=0)
self.data_range = self.data_max - self.data_min
# Handle case where data_min equals data_max
self.data_range[self.data_range == 0] = 1
def transform(self, x: np.ndarray) -> np.ndarray:
if self.data_min is None or self.data_max is None or self.data_range is None:
raise ValueError(
"This MinMaxScaler instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
x_std = np.subtract(x, self.data_min).astype(float)
np.divide(x_std, self.data_range, out=x_std)
np.multiply(x_std, (self.max - self.min), out=x_std)
np.add(x_std, self.min, out=x_std)
return x_std
def inverse_transform(self, x: np.ndarray) -> np.ndarray:
if self.data_min is None or self.data_max is None or self.data_range is None:
raise ValueError(
"This MinMaxScaler instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
x_std = ((x - self.min) / (self.max - self.min)).astype(float)
return x_std * self.data_range + self.data_min
class StandardScaler(BaseScaler):
def __init__(self) -> None:
super().__init__()
def fit(self, x: np.ndarray) -> None:
self.mean = np.mean(x, axis=0)
self.var = np.var(x, axis=0)
self.scale = np.sqrt(self.var)
# Handle case where variance is zero
self.scale[self.scale == 0] = 1
def transform(self, x: np.ndarray) -> np.ndarray:
if self.mean is None or self.scale is None:
raise ValueError(
"This StandardScaler instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
return (x - self.mean) / self.scale
def inverse_transform(self, x: np.ndarray) -> np.ndarray:
if self.mean is None or self.scale is None:
raise ValueError(
"This StandardScaler instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this estimator.",
)
return (x * self.scale) + self.mean
class TransformerInterface(Protocol):
@abc.abstractmethod
def inverse_transform(self, x: np.ndarray) -> np.ndarray: ...
@abc.abstractmethod
def fit(self, x: np.ndarray, y: np.ndarray | None = None) -> np.ndarray: ...
@abc.abstractmethod
def transform(self, x: np.ndarray, y: np.ndarray | None = None) -> np.ndarray: ...
class DomainAdapter:
def __init__(
self,
transformer: TransformerInterface,
ref_img: np.ndarray,
color_conversions: tuple[None, None] = (None, None),
):
self.color_in, self.color_out = color_conversions
self.source_transformer = deepcopy(transformer)
self.target_transformer = transformer
self.num_channels = get_num_channels(ref_img)
self.target_transformer.fit(self.flatten(ref_img))
def to_colorspace(self, img: np.ndarray) -> np.ndarray:
return img if self.color_in is None else cv2.cvtColor(img, self.color_in)
def from_colorspace(self, img: np.ndarray) -> np.ndarray:
if self.color_out is None:
return img
return cv2.cvtColor(clip(img, np.uint8, inplace=True), self.color_out)
def flatten(self, img: np.ndarray) -> np.ndarray:
img = self.to_colorspace(img)
img = to_float(img)
return img.reshape(-1, self.num_channels)
def reconstruct(self, pixels: np.ndarray, height: int, width: int) -> np.ndarray:
pixels = clip(pixels, np.uint8, inplace=True)
if self.num_channels == 1:
return self.from_colorspace(pixels.reshape(height, width))
return self.from_colorspace(pixels.reshape(height, width, self.num_channels))
@staticmethod
def _pca_sign(x: np.ndarray) -> np.ndarray:
return np.sign(np.trace(x.components_))
def __call__(self, image: np.ndarray) -> np.ndarray:
height, width = image.shape[:2]
pixels = self.flatten(image)
self.source_transformer.fit(pixels)
if (
hasattr(self.target_transformer, "components_")
and hasattr(self.source_transformer, "components_")
and self._pca_sign(self.target_transformer) != self._pca_sign(self.source_transformer)
):
self.target_transformer.components_ *= -1
representation = self.source_transformer.transform(pixels)
result = self.target_transformer.inverse_transform(representation)
return self.reconstruct(result, height, width)
@clipped
@preserve_channel_dim
def adapt_pixel_distribution(
img: np.ndarray,
ref: np.ndarray,
transform_type: Literal["pca", "standard", "minmax"],
weight: float,
) -> np.ndarray:
"""Adapt the pixel distribution of an image to match a reference image.
This function adapts the pixel distribution of an image to match a reference image
using a specified transformation type and weight.
Args:
img (np.ndarray): The input image to be adapted.
ref (np.ndarray): The reference image.
transform_type (Literal["pca", "standard", "minmax"]): The type of transformation to use.
weight (float): The weight of the transformation.
Returns:
np.ndarray: The adapted image.
Raises:
ValueError: If the input image and reference image have different dtypes or numbers of channels.
"""
if img.dtype != ref.dtype:
raise ValueError("Input image and reference image must have the same dtype.")
img_num_channels = get_num_channels(img)
ref_num_channels = get_num_channels(ref)
if img_num_channels != ref_num_channels:
raise ValueError("Input image and reference image must have the same number of channels.")
if img_num_channels == 1:
img = np.squeeze(img)
ref = np.squeeze(ref)
if img.shape != ref.shape:
ref = cv2.resize(ref, dsize=img.shape[:2], interpolation=cv2.INTER_AREA)
original_dtype = img.dtype
if original_dtype == np.float32:
img = from_float(img, np.uint8)
ref = from_float(ref, np.uint8)
transformer = {"pca": PCA, "standard": StandardScaler, "minmax": MinMaxScaler}[transform_type]()
adapter = DomainAdapter(transformer=transformer, ref_img=ref)
transformed = adapter(img).astype(np.float32)
result = img.astype(np.float32) * (1 - weight) + transformed * weight
return result if original_dtype == np.uint8 else to_float(result)
def low_freq_mutate(amp_src: np.ndarray, amp_trg: np.ndarray, beta: float) -> np.ndarray:
image_shape = amp_src.shape[:2]
border = int(np.floor(min(image_shape) * beta))
center_x, center_y = fgeometric.center(image_shape)
height, width = image_shape
h1, h2 = max(0, int(center_y - border)), min(int(center_y + border), height)
w1, w2 = max(0, int(center_x - border)), min(int(center_x + border), width)
amp_src[h1:h2, w1:w2] = amp_trg[h1:h2, w1:w2]
return amp_src
@clipped
@preserve_channel_dim
def fourier_domain_adaptation(img: np.ndarray, target_img: np.ndarray, beta: float) -> np.ndarray:
"""Apply Fourier Domain Adaptation to the input image using a target image.
This function performs domain adaptation in the frequency domain by modifying the amplitude
spectrum of the source image based on the target image's amplitude spectrum. It preserves
the phase information of the source image, which helps maintain its content while adapting
its style to match the target image.
Args:
img (np.ndarray): The source image to be adapted. Can be grayscale or RGB.
target_img (np.ndarray): The target image used as a reference for adaptation.
Should have the same dimensions as the source image.
beta (float): The adaptation strength, typically in the range [0, 1].
Higher values result in stronger adaptation towards the target image's style.
Returns:
np.ndarray: The adapted image with the same shape and type as the input image.
Raises:
ValueError: If the source and target images have different shapes.
Note:
- Both input images are converted to float32 for processing.
- The function handles both grayscale (2D) and color (3D) images.
- For grayscale images, an extra dimension is added to facilitate uniform processing.
- The adaptation is performed channel-wise for color images.
- The output is clipped to the valid range and preserves the original number of channels.
The adaptation process involves the following steps for each channel:
1. Compute the 2D Fourier Transform of both source and target images.
2. Shift the zero frequency component to the center of the spectrum.
3. Extract amplitude and phase information from the source image's spectrum.
4. Mutate the source amplitude using the target amplitude and the beta parameter.
5. Combine the mutated amplitude with the original phase.
6. Perform the inverse Fourier Transform to obtain the adapted channel.
The `low_freq_mutate` function (not shown here) is responsible for the actual
amplitude mutation, focusing on low-frequency components which carry style information.
Example:
>>> import numpy as np
>>> import albumentations as A
>>> source_img = np.random.rand(100, 100, 3).astype(np.float32)
>>> target_img = np.random.rand(100, 100, 3).astype(np.float32)
>>> adapted_img = A.fourier_domain_adaptation(source_img, target_img, beta=0.5)
>>> assert adapted_img.shape == source_img.shape
References:
FDA: Fourier Domain Adaptation for Semantic Segmentation: Yang and Soatto, 2020, CVPR
https://openaccess.thecvf.com/content_CVPR_2020/papers/Yang_FDA_Fourier_Domain_Adaptation_for_Semantic_Segmentation_CVPR_2020_paper.pdf
"""
src_img = img.astype(np.float32)
trg_img = target_img.astype(np.float32)
if src_img.ndim == MONO_CHANNEL_DIMENSIONS:
src_img = np.expand_dims(src_img, axis=-1)
if trg_img.ndim == MONO_CHANNEL_DIMENSIONS:
trg_img = np.expand_dims(trg_img, axis=-1)
num_channels = src_img.shape[-1]
# Prepare container for the output image
src_in_trg = np.zeros_like(src_img)
for channel_id in range(num_channels):
# Perform FFT on each channel
fft_src = np.fft.fft2(src_img[:, :, channel_id])
fft_trg = np.fft.fft2(trg_img[:, :, channel_id])
# Shift the zero frequency component to the center
fft_src_shifted = np.fft.fftshift(fft_src)
fft_trg_shifted = np.fft.fftshift(fft_trg)
# Extract amplitude and phase
amp_src, pha_src = np.abs(fft_src_shifted), np.angle(fft_src_shifted)
amp_trg = np.abs(fft_trg_shifted)
# Mutate the amplitude part of the source with the target
mutated_amp = low_freq_mutate(amp_src.copy(), amp_trg, beta)
# Combine the mutated amplitude with the original phase
fft_src_mutated = np.fft.ifftshift(mutated_amp * np.exp(1j * pha_src))
# Perform inverse FFT
src_in_trg_channel = np.fft.ifft2(fft_src_mutated)
# Store the result in the corresponding channel of the output image
src_in_trg[:, :, channel_id] = np.real(src_in_trg_channel)
return src_in_trg
@clipped
@preserve_channel_dim
def apply_histogram(img: np.ndarray, reference_image: np.ndarray, blend_ratio: float) -> np.ndarray:
"""Apply histogram matching to an input image using a reference image and blend the result.
This function performs histogram matching between the input image and a reference image,
then blends the result with the original input image based on the specified blend ratio.
Args:
img (np.ndarray): The input image to be transformed. Can be either grayscale or RGB.
Supported dtypes: uint8, float32 (values should be in [0, 1] range).
reference_image (np.ndarray): The reference image used for histogram matching.
Should have the same number of channels as the input image.
Supported dtypes: uint8, float32 (values should be in [0, 1] range).
blend_ratio (float): The ratio for blending the matched image with the original image.
Should be in the range [0, 1], where 0 means no change and 1 means full histogram matching.
Returns:
np.ndarray: The transformed image after histogram matching and blending.
The output will have the same shape and dtype as the input image.
Supported image types:
- Grayscale images: 2D arrays
- RGB images: 3D arrays with 3 channels
- Multispectral images: 3D arrays with more than 3 channels
Note:
- If the input and reference images have different sizes, the reference image
will be resized to match the input image's dimensions.
- The function uses a custom implementation of histogram matching based on OpenCV and NumPy.
- The @clipped and @preserve_channel_dim decorators ensure the output is within
the valid range and maintains the original number of dimensions.
"""
# Resize reference image only if necessary
if img.shape[:2] != reference_image.shape[:2]:
reference_image = cv2.resize(reference_image, dsize=(img.shape[1], img.shape[0]))
img = np.squeeze(img)
reference_image = np.squeeze(reference_image)
# Match histograms between the images
matched = match_histograms(img, reference_image)
# Blend the original image and the matched image
return add_weighted(matched, blend_ratio, img, 1 - blend_ratio)
@uint8_io
@preserve_channel_dim
def match_histograms(image: np.ndarray, reference: np.ndarray) -> np.ndarray:
"""Adjust an image so that its cumulative histogram matches that of another.
The adjustment is applied separately for each channel.
Args:
image (np.ndarray): Input image. Can be gray-scale or in color.
reference (np.ndarray): Image to match histogram of. Must have the same number of channels as image.
channel_axis (int | None): If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this indicates which axis of the array corresponds to channels.
Returns:
np.ndarray: Transformed input image.
Raises:
ValueError: Thrown when the number of channels in the input image and the reference differ.
"""
if reference.dtype != np.uint8:
reference = from_float(reference, np.uint8)
if image.ndim != reference.ndim:
raise ValueError("Image and reference must have the same number of dimensions.")
# Expand dimensions for grayscale images
if image.ndim == 2:
image = np.expand_dims(image, axis=-1)
if reference.ndim == 2:
reference = np.expand_dims(reference, axis=-1)
matched = np.empty(image.shape, dtype=np.uint8)
num_channels = image.shape[-1]
for channel in range(num_channels):
matched_channel = _match_cumulative_cdf(image[..., channel], reference[..., channel]).astype(np.uint8)
matched[..., channel] = matched_channel
return matched
def _match_cumulative_cdf(source: np.ndarray, template: np.ndarray) -> np.ndarray:
src_lookup = source.reshape(-1)
src_counts = np.bincount(src_lookup)
tmpl_counts = np.bincount(template.reshape(-1))
# omit values where the count was 0
tmpl_values = np.nonzero(tmpl_counts)[0]
tmpl_counts = tmpl_counts[tmpl_values]
# calculate normalized quantiles for each array
src_quantiles = np.cumsum(src_counts) / source.size
tmpl_quantiles = np.cumsum(tmpl_counts) / template.size
interp_a_values = np.interp(src_quantiles, tmpl_quantiles, tmpl_values)
return interp_a_values[src_lookup].reshape(source.shape).astype(np.uint8)
@@ -0,0 +1,878 @@
"""Functional implementations for image mixing operations.
This module provides utility functions for blending and combining images,
such as copy-and-paste operations with masking.
"""
from __future__ import annotations
import random
from collections.abc import Sequence
from typing import Any, Literal, TypedDict, cast
from warnings import warn
import cv2
import numpy as np
import albumentations.augmentations.geometric.functional as fgeometric
from albumentations.augmentations.crops.transforms import Crop
from albumentations.augmentations.geometric.resize import LongestMaxSize, SmallestMaxSize
from albumentations.core.bbox_utils import BboxProcessor, denormalize_bboxes, normalize_bboxes
from albumentations.core.composition import Compose
from albumentations.core.keypoints_utils import KeypointsProcessor
from albumentations.core.type_definitions import (
NUM_BBOXES_COLUMNS_IN_ALBUMENTATIONS,
NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS,
)
# Type definition for a processed mosaic item
class ProcessedMosaicItem(TypedDict):
"""Represents a single data item (primary or additional) after preprocessing.
Includes the original image/mask and the *preprocessed* annotations.
"""
image: np.ndarray # Image is mandatory
mask: np.ndarray | None
bboxes: np.ndarray | None
keypoints: np.ndarray | None
def copy_and_paste_blend(
base_image: np.ndarray,
overlay_image: np.ndarray,
overlay_mask: np.ndarray,
offset: tuple[int, int],
) -> np.ndarray:
"""Blend images by copying pixels from an overlay image to a base image using a mask.
This function copies pixels from the overlay image to the base image only where
the mask has non-zero values. The overlay is placed at the specified offset
from the top-left corner of the base image.
Args:
base_image (np.ndarray): The destination image that will be modified.
overlay_image (np.ndarray): The source image containing pixels to copy.
overlay_mask (np.ndarray): Binary mask indicating which pixels to copy from the overlay.
Pixels are copied where mask > 0.
offset (tuple[int, int]): The (y, x) offset specifying where to place the
top-left corner of the overlay relative to the base image.
Returns:
np.ndarray: The blended image with the overlay applied to the base image.
"""
y_offset, x_offset = offset
blended_image = base_image.copy()
mask_indices = np.where(overlay_mask > 0)
blended_image[mask_indices[0] + y_offset, mask_indices[1] + x_offset] = overlay_image[
mask_indices[0],
mask_indices[1],
]
return blended_image
def calculate_mosaic_center_point(
grid_yx: tuple[int, int],
cell_shape: tuple[int, int],
target_size: tuple[int, int],
center_range: tuple[float, float],
py_random: random.Random,
) -> tuple[int, int]:
"""Calculates the center point for the mosaic crop using proportional sampling within the valid zone.
Ensures the center point allows a crop of target_size to overlap
all grid cells, applying randomness based on center_range proportionally
within the valid region where the center can lie.
Args:
grid_yx (tuple[int, int]): The (rows, cols) of the mosaic grid.
cell_shape (tuple[int, int]): Shape of each cell in the mosaic grid.
target_size (tuple[int, int]): The final output (height, width).
center_range (tuple[float, float]): Range [0.0-1.0] for sampling center proportionally
within the valid zone.
py_random (random.Random): Random state instance.
Returns:
tuple[int, int]: The calculated (x, y) center point relative to the
top-left of the conceptual large grid.
"""
rows, cols = grid_yx
cell_h, cell_w = cell_shape
target_h, target_w = target_size
large_grid_h = rows * cell_h
large_grid_w = cols * cell_w
# Define valid center range bounds (inclusive)
# The center must be far enough from edges so the crop window fits
min_cx = target_w // 2
max_cx = large_grid_w - (target_w + 1) // 2
min_cy = target_h // 2
max_cy = large_grid_h - (target_h + 1) // 2
# Calculate valid range dimensions (size of the safe zone)
valid_w = max_cx - min_cx + 1
valid_h = max_cy - min_cy + 1
# Sample relative position within the valid range using center_range
rel_x = py_random.uniform(*center_range)
rel_y = py_random.uniform(*center_range)
# Calculate center coordinates by scaling relative position within valid range
# Add the minimum bound to shift the range start
center_x = min_cx + int(valid_w * rel_x)
center_y = min_cy + int(valid_h * rel_y)
# Ensure the result is strictly within the calculated bounds after int conversion
# (This clip is mostly a safety measure, shouldn't be needed with correct int conversion)
center_x = max(min_cx, min(center_x, max_cx))
center_y = max(min_cy, min(center_y, max_cy))
return center_x, center_y
def calculate_cell_placements(
grid_yx: tuple[int, int],
cell_shape: tuple[int, int],
target_size: tuple[int, int],
center_xy: tuple[int, int],
) -> list[tuple[int, int, int, int]]:
"""Calculates placements by clipping arange-defined grid lines to the crop window.
Args:
grid_yx (tuple[int, int]): The (rows, cols) of the mosaic grid.
cell_shape (tuple[int, int]): Shape of each cell in the mosaic grid.
target_size (tuple[int, int]): The final output (height, width).
center_xy (tuple[int, int]): The calculated (x, y) center of the final crop window,
relative to the top-left of the conceptual large grid.
Returns:
list[tuple[int, int, int, int]]:
A list containing placement coordinates `(x_min, y_min, x_max, y_max)`
for each resulting cell part on the final output canvas.
"""
rows, cols = grid_yx
cell_h, cell_w = cell_shape
target_h, target_w = target_size
center_x, center_y = center_xy
# 1. Generate grid line coordinates using arange for the large grid
y_coords_large = np.arange(rows + 1) * cell_h
x_coords_large = np.arange(cols + 1) * cell_w
# 2. Calculate Crop Window boundaries
crop_x_min = center_x - target_w // 2
crop_y_min = center_y - target_h // 2
crop_x_max = crop_x_min + target_w
crop_y_max = crop_y_min + target_h
def _clip_coords(coords: np.ndarray, min_val: int, max_val: int) -> np.ndarray:
clipped_coords = np.clip(coords, min_val, max_val)
# Subtract min_val to convert absolute clipped coordinates
# into coordinates relative to the crop window's origin (min_val becomes 0).
return np.unique(clipped_coords) - min_val
y_coords_clipped = _clip_coords(y_coords_large, crop_y_min, crop_y_max)
x_coords_clipped = _clip_coords(x_coords_large, crop_x_min, crop_x_max)
# 4. Form all cell coordinates efficiently
num_x_intervals = len(x_coords_clipped) - 1
num_y_intervals = len(y_coords_clipped) - 1
result = []
for y_idx in range(num_y_intervals):
y_min = y_coords_clipped[y_idx]
y_max = y_coords_clipped[y_idx + 1]
for x_idx in range(num_x_intervals):
x_min = x_coords_clipped[x_idx]
x_max = x_coords_clipped[x_idx + 1]
result.append((int(x_min), int(y_min), int(x_max), int(y_max)))
return result
def _check_data_compatibility(
primary_data: np.ndarray | None,
item_data: np.ndarray | None,
data_key: Literal["image", "mask"],
) -> tuple[bool, str | None]: # Returns (is_compatible, error_message)
"""Checks if the dimensions and channels of item_data match primary_data."""
# 1. Check if item has the required data (image is always required)
if item_data is None:
if data_key == "image":
return False, "Item is missing required key 'image'"
# Mask is optional, missing is compatible
return True, None
# 2. If item data exists, check against primary data (if primary data exists)
if primary_data is None: # No primary data to compare against
return True, None
# Both primary and item data exist, compare them
primary_ndim = primary_data.ndim
item_ndim = item_data.ndim
if primary_ndim != item_ndim:
return False, (
f"Item '{data_key}' has {item_ndim} dimensions, but primary has {primary_ndim}. "
f"Primary shape: {primary_data.shape}, Item shape: {item_data.shape}"
)
if primary_ndim == 3:
primary_channels = primary_data.shape[-1]
item_channels = item_data.shape[-1]
if primary_channels != item_channels:
return False, (
f"Item '{data_key}' has {item_channels} channels, but primary has {primary_channels}. "
f"Primary shape: {primary_data.shape}, Item shape: {item_data.shape}"
)
# Dimensions match (either both 2D or both 3D with same channels)
return True, None
def filter_valid_metadata(
metadata_input: Sequence[dict[str, Any]] | None,
metadata_key_name: str,
data: dict[str, Any],
) -> list[dict[str, Any]]:
"""Filters a list of metadata dicts, keeping only valid ones based on data compatibility."""
if not isinstance(metadata_input, Sequence):
warn(
f"Metadata under key '{metadata_key_name}' is not a Sequence (e.g., list or tuple). "
f"Returning empty list for additional items.",
UserWarning,
stacklevel=3,
)
return []
valid_items = []
primary_image = data.get("image")
primary_mask = data.get("mask")
for i, item in enumerate(metadata_input):
if not isinstance(item, dict):
warn(
f"Item at index {i} in '{metadata_key_name}' is not a dict and will be skipped.",
UserWarning,
stacklevel=4,
)
continue
item_is_valid = True # Assume valid initially
for target_key, primary_target_data in [
("image", primary_image),
("mask", primary_mask),
]:
item_target_data = item.get(target_key)
is_compatible, error_msg = _check_data_compatibility(
primary_target_data,
item_target_data,
cast("Literal['image', 'mask']", target_key),
)
if not is_compatible:
msg = (
f"Item at index {i} in '{metadata_key_name}' skipped due "
f"to incompatibility in '{target_key}': {error_msg}"
)
warn(msg, UserWarning, stacklevel=4)
item_is_valid = False
break # Stop checking other targets for this item
if item_is_valid:
valid_items.append(item)
return valid_items
def assign_items_to_grid_cells(
num_items: int,
cell_placements: list[tuple[int, int, int, int]],
py_random: random.Random,
) -> dict[tuple[int, int, int, int], int]:
"""Assigns item indices to placement coordinate tuples.
Assigns the primary item (index 0) to the placement with the largest area,
and assigns the remaining items (indices 1 to num_items-1) randomly to the
remaining placements.
Args:
num_items (int): The total number of items to assign (primary + additional + replicas).
cell_placements (list[tuple[int, int, int, int]]): List of placement
coords (x1, y1, x2, y2) for cells to be filled.
py_random (random.Random): Random state instance.
Returns:
dict[tuple[int, int, int, int], int]: Dict mapping placement coords (x1, y1, x2, y2)
to assigned item index.
"""
if not cell_placements:
return {}
# Find the placement tuple with the largest area for primary assignment
primary_placement = max(
cell_placements,
key=lambda coords: (coords[2] - coords[0]) * (coords[3] - coords[1]),
)
placement_to_item_index: dict[tuple[int, int, int, int], int] = {
primary_placement: 0,
}
# Use list comprehension for potentially better performance
remaining_placements = [coords for coords in cell_placements if coords != primary_placement]
# Indices for additional/replicated items start from 1
remaining_item_indices = list(range(1, num_items))
py_random.shuffle(remaining_item_indices)
num_to_assign = min(len(remaining_placements), len(remaining_item_indices))
for i in range(num_to_assign):
placement_to_item_index[remaining_placements[i]] = remaining_item_indices[i]
return placement_to_item_index
def _preprocess_item_annotations(
item: dict[str, Any],
processor: BboxProcessor | KeypointsProcessor | None,
data_key: Literal["bboxes", "keypoints"],
) -> np.ndarray | None:
"""Helper to preprocess annotations (bboxes or keypoints) for a single item."""
original_data = item.get(data_key)
# Check if processor exists and the relevant data key is in the item
if processor and data_key in item and item.get(data_key) is not None:
# === Add validation for required label fields ===
required_labels = processor.params.label_fields
if required_labels and [field for field in required_labels if field not in item]:
raise ValueError(
f"Item contains '{data_key}' but is missing required label "
"fields: {[field for field in required_labels if field not in item]}. "
f"Ensure all label fields declared in {type(processor.params).__name__} "
f"({required_labels}) are present in the item dictionary when '{data_key}' is present.",
)
# === End validation ===
# Create a temporary minimal dict for the processor
temp_data = {
"image": item["image"],
data_key: item[data_key],
}
# Add declared label fields if they exist in the item (already validated above)
if required_labels:
for field in required_labels:
# Check again just in case validation logic changes, avoids KeyError
if field in item:
temp_data[field] = item[field]
# Preprocess modifies temp_data in-place
processor.preprocess(temp_data)
# Return the potentially modified data from the temp dict
return temp_data.get(data_key)
# Return original data if no processor or data key wasn't in item
return original_data
def preprocess_selected_mosaic_items(
selected_raw_items: list[dict[str, Any]],
bbox_processor: BboxProcessor | None, # Allow None
keypoint_processor: KeypointsProcessor | None, # Allow None
) -> list[ProcessedMosaicItem]:
"""Preprocesses bboxes/keypoints for selected raw additional items.
Iterates through items, preprocesses annotations individually using processors
(updating label encoders), and returns a list of dicts with original image/mask
and the corresponding preprocessed bboxes/keypoints.
"""
if not selected_raw_items:
return []
result_data_items: list[ProcessedMosaicItem] = []
for item in selected_raw_items:
processed_bboxes = _preprocess_item_annotations(item, bbox_processor, "bboxes")
processed_keypoints = _preprocess_item_annotations(item, keypoint_processor, "keypoints")
# Construct the final processed item dict
processed_item_dict: ProcessedMosaicItem = {
"image": item["image"],
"mask": item.get("mask"),
"bboxes": processed_bboxes, # Already np.ndarray or None
"keypoints": processed_keypoints, # Already np.ndarray or None
}
result_data_items.append(processed_item_dict)
return result_data_items
def get_opposite_crop_coords(
cell_size: tuple[int, int],
crop_size: tuple[int, int],
cell_position: Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"],
) -> tuple[int, int, int, int]:
"""Calculates crop coordinates positioned opposite to the specified cell_position.
Given a cell of `cell_size`, this function determines the top-left (x_min, y_min)
and bottom-right (x_max, y_max) coordinates for a crop of `crop_size`, such
that the crop is located in the corner or center opposite to `cell_position`.
For example, if `cell_position` is "top_left", the crop coordinates will
correspond to the bottom-right region of the cell.
Args:
cell_size: The (height, width) of the cell from which to crop.
crop_size: The (height, width) of the desired crop.
cell_position: The reference position within the cell. The crop will be
taken from the opposite position.
Returns:
tuple[int, int, int, int]: (x_min, y_min, x_max, y_max) representing the crop coordinates.
Raises:
ValueError: If crop_size is larger than cell_size in either dimension.
"""
cell_h, cell_w = cell_size
crop_h, crop_w = crop_size
if crop_h > cell_h or crop_w > cell_w:
raise ValueError(f"Crop size {crop_size} cannot be larger than cell size {cell_size}")
# Determine top-left corner (x_min, y_min) based on the OPPOSITE position
if cell_position == "top_left": # Crop from bottom_right
x_min = cell_w - crop_w
y_min = cell_h - crop_h
elif cell_position == "top_right": # Crop from bottom_left
x_min = 0
y_min = cell_h - crop_h
elif cell_position == "bottom_left": # Crop from top_right
x_min = cell_w - crop_w
y_min = 0
elif cell_position == "bottom_right": # Crop from top_left
x_min = 0
y_min = 0
elif cell_position == "center": # Crop from center
x_min = (cell_w - crop_w) // 2
y_min = (cell_h - crop_h) // 2
else:
# Should be unreachable due to Literal type hint, but good practice
raise ValueError(f"Invalid cell_position: {cell_position}")
# Calculate bottom-right corner
x_max = x_min + crop_w
y_max = y_min + crop_h
return x_min, y_min, x_max, y_max
def process_cell_geometry(
cell_shape: tuple[int, int],
item: ProcessedMosaicItem,
target_shape: tuple[int, int],
fill: float | tuple[float, ...],
fill_mask: float | tuple[float, ...],
fit_mode: Literal["cover", "contain"],
interpolation: int,
mask_interpolation: int,
cell_position: Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"],
) -> ProcessedMosaicItem:
"""Applies geometric transformations (padding and/or cropping) to a single mosaic item.
Uses a Compose pipeline with PadIfNeeded and Crop to ensure the output
matches the target cell dimensions exactly, handling both padding and cropping cases.
Args:
cell_shape: (tuple[int, int]): Shape of the cell.
item: (ProcessedMosaicItem): The preprocessed mosaic item dictionary.
target_shape: (tuple[int, int]): Target shape of the cell.
fill: (float | tuple[float, ...]): Fill value for image padding.
fill_mask: (float | tuple[float, ...]): Fill value for mask padding.
fit_mode: (Literal["cover", "contain"]): Fit mode for the mosaic.
interpolation: (int): Interpolation method for image.
mask_interpolation: (int): Interpolation method for mask.
cell_position: (Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"]): Position
of the cell.
Returns: (ProcessedMosaicItem): Dictionary containing the geometrically processed image,
mask, bboxes, and keypoints, fitting the target dimensions.
"""
# Define the pipeline: PadIfNeeded first, then Crop
compose_kwargs: dict[str, Any] = {"p": 1.0}
if item.get("bboxes") is not None:
compose_kwargs["bbox_params"] = {"format": "albumentations"}
if item.get("keypoints") is not None:
compose_kwargs["keypoint_params"] = {"format": "albumentations"}
crop_coords = get_opposite_crop_coords(cell_shape, target_shape, cell_position)
if fit_mode == "cover":
geom_pipeline = Compose(
[
SmallestMaxSize(
max_size_hw=cell_shape,
interpolation=interpolation,
mask_interpolation=mask_interpolation,
p=1.0,
),
Crop(
x_min=crop_coords[0],
y_min=crop_coords[1],
x_max=crop_coords[2],
y_max=crop_coords[3],
),
],
**compose_kwargs,
)
elif fit_mode == "contain":
geom_pipeline = Compose(
[
LongestMaxSize(
max_size_hw=cell_shape,
interpolation=interpolation,
mask_interpolation=mask_interpolation,
p=1.0,
),
Crop(
x_min=crop_coords[0],
y_min=crop_coords[1],
x_max=crop_coords[2],
y_max=crop_coords[3],
pad_if_needed=True,
fill=fill,
fill_mask=fill_mask,
p=1.0,
),
],
**compose_kwargs,
)
else:
raise ValueError(f"Invalid fit_mode: {fit_mode}. Must be 'cover' or 'contain'.")
# Prepare input data for the pipeline
geom_input = {"image": item["image"]}
if item.get("mask") is not None:
geom_input["mask"] = item["mask"]
if item.get("bboxes") is not None:
# Compose expects bboxes in a specific format, ensure it's compatible
# Assuming item['bboxes'] is already preprocessed correctly
geom_input["bboxes"] = item["bboxes"]
if item.get("keypoints") is not None:
geom_input["keypoints"] = item["keypoints"]
# Apply the pipeline
processed_item = geom_pipeline(**geom_input)
# Ensure output dict has the same structure as ProcessedMosaicItem
# Compose might not return None for missing keys, handle explicitly
return {
"image": processed_item["image"],
"mask": processed_item.get("mask"),
"bboxes": processed_item.get("bboxes"),
"keypoints": processed_item.get("keypoints"),
}
def shift_cell_coordinates(
processed_item_geom: ProcessedMosaicItem,
placement_coords: tuple[int, int, int, int],
) -> ProcessedMosaicItem:
"""Shifts the coordinates of geometrically processed bboxes and keypoints.
Args:
processed_item_geom: (ProcessedMosaicItem): The output from process_cell_geometry.
placement_coords: (tuple[int, int, int, int]): The (x1, y1, x2, y2) placement on the final canvas.
Returns: (ProcessedMosaicItem): A dictionary with keys 'bboxes' and 'keypoints', containing the shifted
numpy arrays (potentially empty).
"""
tgt_x1, tgt_y1, _, _ = placement_coords
shifted_bboxes = None
shifted_keypoints = None
bboxes_geom = processed_item_geom.get("bboxes")
if bboxes_geom is not None and np.asarray(bboxes_geom).size > 0:
bboxes_geom_arr = np.asarray(bboxes_geom) # Ensure it's an array
bbox_shift_vector = np.array([tgt_x1, tgt_y1, tgt_x1, tgt_y1], dtype=np.int32)
shifted_bboxes = fgeometric.shift_bboxes(bboxes_geom_arr, bbox_shift_vector)
keypoints_geom = processed_item_geom.get("keypoints")
if keypoints_geom is not None and np.asarray(keypoints_geom).size > 0:
keypoints_geom_arr = np.asarray(keypoints_geom) # Ensure it's an array
kp_shift_vector = np.array([tgt_x1, tgt_y1, 0], dtype=keypoints_geom_arr.dtype)
shifted_keypoints = fgeometric.shift_keypoints(keypoints_geom_arr, kp_shift_vector)
return {
"bboxes": shifted_bboxes,
"keypoints": shifted_keypoints,
"image": processed_item_geom["image"],
"mask": processed_item_geom.get("mask"),
}
def assemble_mosaic_from_processed_cells(
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
target_shape: tuple[int, ...], # Use full canvas shape (H, W) or (H, W, C)
dtype: np.dtype,
data_key: Literal["image", "mask"],
fill: float | tuple[float, ...] | None, # Value for image fill or mask fill
) -> np.ndarray:
"""Assembles the final mosaic image or mask from processed cell data onto a canvas.
Initializes the canvas with the fill value and overwrites with processed segments.
Handles potentially multi-channel masks.
Addresses potential broadcasting errors if mask segments have unexpected dimensions.
Assumes input data is valid and correctly sized.
Args:
processed_cells (dict[tuple[int, int, int, int], dict[str, Any]]): Dictionary mapping
placement coords to processed cell data.
target_shape (tuple[int, ...]): The target shape of the output canvas (e.g., (H, W) or (H, W, C)).
dtype (np.dtype): NumPy dtype for the canvas.
data_key (Literal["image", "mask"]): Specifies whether to assemble 'image' or 'mask'.
fill (float | tuple[float, ...] | None): Value used to initialize the canvas (image fill or mask fill).
Should be a float/int or a tuple matching the number of channels.
If None, defaults to 0.
Returns:
np.ndarray: The assembled mosaic canvas.
"""
# Use 0 as default fill if None is provided
actual_fill = fill if fill is not None else 0
# Convert fill to numpy array to handle broadcasting in np.full
fill_value = np.array(actual_fill, dtype=dtype)
# Initialize canvas with the fill value.
# If fill_value shape is incompatible with target_shape, np.full will raise ValueError.
canvas = np.full(target_shape, fill_value=fill_value, dtype=dtype)
# Iterate and paste segments onto the pre-filled canvas
for placement_coords, cell_data in processed_cells.items():
segment = cell_data.get(data_key)
# If segment exists, paste it over the filled background
if segment is not None:
tgt_x1, tgt_y1, tgt_x2, tgt_y2 = placement_coords
canvas[tgt_y1:tgt_y2, tgt_x1:tgt_x2] = segment
return canvas
def process_all_mosaic_geometries(
canvas_shape: tuple[int, int],
cell_shape: tuple[int, int],
placement_to_item_index: dict[tuple[int, int, int, int], int],
final_items_for_grid: list[ProcessedMosaicItem],
fill: float | tuple[float, ...],
fill_mask: float | tuple[float, ...],
fit_mode: Literal["cover", "contain"],
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
],
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
],
) -> dict[tuple[int, int, int, int], ProcessedMosaicItem]:
"""Processes the geometry (cropping/padding) for all assigned mosaic cells.
Iterates through assigned placements, applies geometric transforms via process_cell_geometry,
and returns a dictionary mapping final placement coordinates to the processed item data.
The bbox/keypoint coordinates in the returned dict are *not* shifted yet.
Args:
canvas_shape (tuple[int, int]): The shape of the canvas.
cell_shape (tuple[int, int]): Shape of each cell in the mosaic grid.
placement_to_item_index (dict[tuple[int, int, int, int], int]): Mapping from placement
coordinates (x1, y1, x2, y2) to assigned item index.
final_items_for_grid (list[ProcessedMosaicItem]): List of all preprocessed items available.
fill (float | tuple[float, ...]): Fill value for image padding.
fill_mask (float | tuple[float, ...]): Fill value for mask padding.
fit_mode (Literal["cover", "contain"]): Fit mode for the mosaic.
interpolation (int): Interpolation method for image.
mask_interpolation (int): Interpolation method for mask.
Returns:
dict[tuple[int, int, int, int], ProcessedMosaicItem]: Dictionary mapping final placement
coordinates (x1, y1, x2, y2) to the geometrically processed item data (image, mask, un-shifted bboxes/kps).
"""
processed_cells_geom: dict[tuple[int, int, int, int], ProcessedMosaicItem] = {}
# Iterate directly over placements and their assigned item indices
for placement_coords, item_idx in placement_to_item_index.items():
item = final_items_for_grid[item_idx]
tgt_x1, tgt_y1, tgt_x2, tgt_y2 = placement_coords
target_h = tgt_y2 - tgt_y1
target_w = tgt_x2 - tgt_x1
cell_position = get_cell_relative_position(placement_coords, canvas_shape)
# Apply geometric processing (crop/pad)
processed_cells_geom[placement_coords] = process_cell_geometry(
cell_shape=cell_shape,
item=item,
target_shape=(target_h, target_w),
fill=fill,
fill_mask=fill_mask,
fit_mode=fit_mode,
interpolation=interpolation,
mask_interpolation=mask_interpolation,
cell_position=cell_position,
)
return processed_cells_geom
def get_cell_relative_position(
placement_coords: tuple[int, int, int, int],
target_shape: tuple[int, int],
) -> Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"]:
"""Determines the position of a cell relative to the center of the target canvas.
Compares the cell center to the canvas center and returns its quadrant
or "center" if it lies on or very close to a central axis.
Args:
placement_coords (tuple[int, int, int, int]): The (x_min, y_min, x_max, y_max) coordinates
of the cell.
target_shape (tuple[int, int]): The (height, width) of the overall target canvas.
Returns:
Literal["top_left", "top_right", "center", "bottom_left", "bottom_right"]:
The position of the cell relative to the center of the target canvas.
"""
target_h, target_w = target_shape
x1, y1, x2, y2 = placement_coords
canvas_center_x = target_w / 2.0
canvas_center_y = target_h / 2.0
cell_center_x = (x1 + x2) / 2.0
cell_center_y = (y1 + y2) / 2.0
# Determine vertical position
if cell_center_y < canvas_center_y:
v_pos = "top"
elif cell_center_y > canvas_center_y:
v_pos = "bottom"
else: # Exactly on the horizontal center line
v_pos = "center"
# Determine horizontal position
if cell_center_x < canvas_center_x:
h_pos = "left"
elif cell_center_x > canvas_center_x:
h_pos = "right"
else: # Exactly on the vertical center line
h_pos = "center"
# Map positions to the final string
position_map = {
("top", "left"): "top_left",
("top", "right"): "top_right",
("bottom", "left"): "bottom_left",
("bottom", "right"): "bottom_right",
}
# Default to "center" if the combination is not in the map
# (which happens if either v_pos or h_pos is "center")
return cast(
"Literal['top_left', 'top_right', 'center', 'bottom_left', 'bottom_right']",
position_map.get((v_pos, h_pos), "center"),
)
def shift_all_coordinates(
processed_cells_geom: dict[tuple[int, int, int, int], ProcessedMosaicItem],
canvas_shape: tuple[int, int],
) -> dict[tuple[int, int, int, int], ProcessedMosaicItem]: # Return type matches input, but values are updated
"""Shifts coordinates for all geometrically processed cells.
Iterates through the processed cells (keyed by placement coords), applies coordinate
shifting to bboxes/keypoints, and returns a new dictionary with the same keys
but updated ProcessedMosaicItem values containing the *shifted* coordinates.
Args:
processed_cells_geom (dict[tuple[int, int, int, int], ProcessedMosaicItem]):
Output from process_all_mosaic_geometries (keyed by placement coords).
canvas_shape (tuple[int, int]): The shape of the canvas.
Returns:
dict[tuple[int, int, int, int], ProcessedMosaicItem]: Final dictionary mapping
placement coords (x1, y1, x2, y2) to processed cell data with shifted coordinates.
"""
final_processed_cells: dict[tuple[int, int, int, int], ProcessedMosaicItem] = {}
canvas_h, canvas_w = canvas_shape
for placement_coords, cell_data_geom in processed_cells_geom.items():
tgt_x1, tgt_y1 = placement_coords[:2]
cell_width = placement_coords[2] - placement_coords[0]
cell_height = placement_coords[3] - placement_coords[1]
# Extract geometrically processed bboxes/keypoints
bboxes_geom = cell_data_geom.get("bboxes")
keypoints_geom = cell_data_geom.get("keypoints")
final_cell_data = {
"image": cell_data_geom["image"],
"mask": cell_data_geom.get("mask"),
}
# Perform shifting if data exists
if bboxes_geom is not None and bboxes_geom.size > 0:
bboxes_geom_arr = np.asarray(bboxes_geom)
bbox_denoramlized = denormalize_bboxes(bboxes_geom_arr, {"height": cell_height, "width": cell_width})
bbox_shift_vector = np.array([tgt_x1, tgt_y1, tgt_x1, tgt_y1], dtype=np.float32)
shifted_bboxes_denormalized = fgeometric.shift_bboxes(bbox_denoramlized, bbox_shift_vector)
shifted_bboxes = normalize_bboxes(shifted_bboxes_denormalized, {"height": canvas_h, "width": canvas_w})
final_cell_data["bboxes"] = shifted_bboxes
else:
final_cell_data["bboxes"] = np.empty((0, NUM_BBOXES_COLUMNS_IN_ALBUMENTATIONS))
if keypoints_geom is not None and keypoints_geom.size > 0:
keypoints_geom_arr = np.asarray(keypoints_geom)
# Ensure shift vector matches keypoint dtype (usually float)
kp_shift_vector = np.array([tgt_x1, tgt_y1, 0], dtype=keypoints_geom_arr.dtype)
shifted_keypoints = fgeometric.shift_keypoints(keypoints_geom_arr, kp_shift_vector)
final_cell_data["keypoints"] = shifted_keypoints
else:
final_cell_data["keypoints"] = np.empty((0, NUM_KEYPOINTS_COLUMNS_IN_ALBUMENTATIONS))
final_processed_cells[placement_coords] = cast("ProcessedMosaicItem", final_cell_data)
return final_processed_cells
@@ -0,0 +1,832 @@
"""Transforms that combine multiple images and their associated annotations.
This module contains transformations that take multiple input sources (e.g., a primary image
and additional images provided via metadata) and combine them into a single output.
Examples include overlaying elements (`OverlayElements`) or creating complex compositions
like `Mosaic`.
"""
from __future__ import annotations
import random
from copy import deepcopy
from typing import Annotated, Any, Literal, cast
import cv2
import numpy as np
from pydantic import AfterValidator, model_validator
from typing_extensions import Self
from albumentations.augmentations.mixing import functional as fmixing
from albumentations.core.bbox_utils import BboxProcessor, check_bboxes, denormalize_bboxes, filter_bboxes
from albumentations.core.keypoints_utils import KeypointsProcessor
from albumentations.core.pydantic import check_range_bounds, nondecreasing
from albumentations.core.transforms_interface import BaseTransformInitSchema, DualTransform
from albumentations.core.type_definitions import LENGTH_RAW_BBOX, Targets
__all__ = ["Mosaic", "OverlayElements"]
class OverlayElements(DualTransform):
"""Apply overlay elements such as images and masks onto an input image. This transformation can be used to add
various objects (e.g., stickers, logos) to images with optional masks and bounding boxes for better placement
control.
Args:
metadata_key (str): Additional target key for metadata. Default `overlay_metadata`.
p (float): Probability of applying the transformation. Default: 0.5.
Possible Metadata Fields:
- image (np.ndarray): The overlay image to be applied. This is a required field.
- bbox (list[int]): The bounding box specifying the region where the overlay should be applied. It should
contain four floats: [y_min, x_min, y_max, x_max]. If `label_id` is provided, it should
be appended as the fifth element in the bbox. BBox should be in Albumentations format,
that is the same as normalized Pascal VOC format
[x_min / width, y_min / height, x_max / width, y_max / height]
- mask (np.ndarray): An optional mask that defines the non-rectangular region of the overlay image. If not
provided, the entire overlay image is used.
- mask_id (int): An optional identifier for the mask. If provided, the regions specified by the mask will
be labeled with this identifier in the output mask.
Targets:
image, mask
Image types:
uint8, float32
References:
doc-augmentation: https://github.com/danaaubakirova/doc-augmentation
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare primary data (base image and mask)
>>> image = np.zeros((300, 300, 3), dtype=np.uint8)
>>> mask = np.zeros((300, 300), dtype=np.uint8)
>>>
>>> # 1. Create a simple overlay image (a red square)
>>> overlay_image1 = np.zeros((50, 50, 3), dtype=np.uint8)
>>> overlay_image1[:, :, 0] = 255 # Red color
>>>
>>> # 2. Create another overlay with a mask (a blue circle with transparency)
>>> overlay_image2 = np.zeros((80, 80, 3), dtype=np.uint8)
>>> overlay_image2[:, :, 2] = 255 # Blue color
>>> overlay_mask2 = np.zeros((80, 80), dtype=np.uint8)
>>> # Create a circular mask
>>> center = (40, 40)
>>> radius = 30
>>> for i in range(80):
... for j in range(80):
... if (i - center[0])**2 + (j - center[1])**2 < radius**2:
... overlay_mask2[i, j] = 255
>>>
>>> # 3. Create an overlay with both bbox and mask_id
>>> overlay_image3 = np.zeros((60, 120, 3), dtype=np.uint8)
>>> overlay_image3[:, :, 1] = 255 # Green color
>>> # Create a rectangular mask with rounded corners
>>> overlay_mask3 = np.zeros((60, 120), dtype=np.uint8)
>>> cv2.rectangle(overlay_mask3, (10, 10), (110, 50), 255, -1)
>>>
>>> # Create the metadata list - each item is a dictionary with overlay information
>>> overlay_metadata = [
... {
... 'image': overlay_image1,
... # No bbox provided - will be placed randomly
... },
... {
... 'image': overlay_image2,
... 'bbox': [0.6, 0.1, 0.9, 0.4], # Normalized coordinates [x_min, y_min, x_max, y_max]
... 'mask': overlay_mask2,
... 'mask_id': 1 # This overlay will update the mask with id 1
... },
... {
... 'image': overlay_image3,
... 'bbox': [0.1, 0.7, 0.5, 0.9], # Bottom left placement
... 'mask': overlay_mask3,
... 'mask_id': 2 # This overlay will update the mask with id 2
... }
... ]
>>>
>>> # Create the transform
>>> transform = A.Compose([
... A.OverlayElements(p=1.0),
... ])
>>>
>>> # Apply the transform
>>> result = transform(
... image=image,
... mask=mask,
... overlay_metadata=overlay_metadata # Pass metadata using the default key
... )
>>>
>>> # Get results with overlays applied
>>> result_image = result['image'] # Image with the three overlays applied
>>> result_mask = result['mask'] # Mask with regions labeled using the mask_id values
>>>
>>> # Let's verify the mask contains the specified mask_id values
>>> has_mask_id_1 = np.any(result_mask == 1) # Should be True
>>> has_mask_id_2 = np.any(result_mask == 2) # Should be True
"""
_targets = (Targets.IMAGE, Targets.MASK)
class InitSchema(BaseTransformInitSchema):
metadata_key: str
def __init__(
self,
metadata_key: str = "overlay_metadata",
p: float = 0.5,
):
super().__init__(p=p)
self.metadata_key = metadata_key
@property
def targets_as_params(self) -> list[str]:
"""Get list of targets that should be passed as parameters to transforms.
Returns:
list[str]: List containing the metadata key name
"""
return [self.metadata_key]
@staticmethod
def preprocess_metadata(
metadata: dict[str, Any],
img_shape: tuple[int, int],
random_state: random.Random,
) -> dict[str, Any]:
"""Process overlay metadata to prepare for application.
Args:
metadata (dict[str, Any]): Dictionary containing overlay data such as image, mask, bbox
img_shape (tuple[int, int]): Shape of the target image as (height, width)
random_state (random.Random): Random state object for reproducible randomness
Returns:
dict[str, Any]: Processed overlay data including resized overlay image, mask,
offset coordinates, and bounding box information
"""
overlay_image = metadata["image"]
overlay_height, overlay_width = overlay_image.shape[:2]
image_height, image_width = img_shape[:2]
if "bbox" in metadata:
bbox = metadata["bbox"]
bbox_np = np.array([bbox])
check_bboxes(bbox_np)
denormalized_bbox = denormalize_bboxes(bbox_np, img_shape[:2])[0]
x_min, y_min, x_max, y_max = (int(x) for x in denormalized_bbox[:4])
if "mask" in metadata:
mask = metadata["mask"]
mask = cv2.resize(mask, (x_max - x_min, y_max - y_min), interpolation=cv2.INTER_NEAREST)
else:
mask = np.ones((y_max - y_min, x_max - x_min), dtype=np.uint8)
overlay_image = cv2.resize(overlay_image, (x_max - x_min, y_max - y_min), interpolation=cv2.INTER_AREA)
offset = (y_min, x_min)
if len(bbox) == LENGTH_RAW_BBOX and "bbox_id" in metadata:
bbox = [x_min, y_min, x_max, y_max, metadata["bbox_id"]]
else:
bbox = (x_min, y_min, x_max, y_max, *bbox[4:])
else:
if image_height < overlay_height or image_width < overlay_width:
overlay_image = cv2.resize(overlay_image, (image_width, image_height), interpolation=cv2.INTER_AREA)
overlay_height, overlay_width = overlay_image.shape[:2]
mask = metadata["mask"] if "mask" in metadata else np.ones_like(overlay_image, dtype=np.uint8)
max_x_offset = image_width - overlay_width
max_y_offset = image_height - overlay_height
offset_x = random_state.randint(0, max_x_offset)
offset_y = random_state.randint(0, max_y_offset)
offset = (offset_y, offset_x)
bbox = [
offset_x,
offset_y,
offset_x + overlay_width,
offset_y + overlay_height,
]
if "bbox_id" in metadata:
bbox = [*bbox, metadata["bbox_id"]]
result = {
"overlay_image": overlay_image,
"overlay_mask": mask,
"offset": offset,
"bbox": bbox,
}
if "mask_id" in metadata:
result["mask_id"] = metadata["mask_id"]
return result
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Generate parameters for overlay transform based on input data.
Args:
params (dict[str, Any]): Dictionary of existing parameters
data (dict[str, Any]): Dictionary containing input data with image and metadata
Returns:
dict[str, Any]: Dictionary containing processed overlay data ready for application
"""
metadata = data[self.metadata_key]
img_shape = params["shape"]
if isinstance(metadata, list):
overlay_data = [self.preprocess_metadata(md, img_shape, self.py_random) for md in metadata]
else:
overlay_data = [self.preprocess_metadata(metadata, img_shape, self.py_random)]
return {
"overlay_data": overlay_data,
}
def apply(
self,
img: np.ndarray,
overlay_data: list[dict[str, Any]],
**params: Any,
) -> np.ndarray:
"""Apply overlay elements to the input image.
Args:
img (np.ndarray): Input image
overlay_data (list[dict[str, Any]]): List of dictionaries containing overlay information
**params (Any): Additional parameters
Returns:
np.ndarray: Image with overlays applied
"""
for data in overlay_data:
overlay_image = data["overlay_image"]
overlay_mask = data["overlay_mask"]
offset = data["offset"]
img = fmixing.copy_and_paste_blend(img, overlay_image, overlay_mask, offset=offset)
return img
def apply_to_mask(
self,
mask: np.ndarray,
overlay_data: list[dict[str, Any]],
**params: Any,
) -> np.ndarray:
"""Apply overlay masks to the input mask.
Args:
mask (np.ndarray): Input mask
overlay_data (list[dict[str, Any]]): List of dictionaries containing overlay information
**params (Any): Additional parameters
Returns:
np.ndarray: Mask with overlay masks applied using the specified mask_id values
"""
for data in overlay_data:
if "mask_id" in data and data["mask_id"] is not None:
overlay_mask = data["overlay_mask"]
offset = data["offset"]
mask_id = data["mask_id"]
y_min, x_min = offset
y_max = y_min + overlay_mask.shape[0]
x_max = x_min + overlay_mask.shape[1]
mask_section = mask[y_min:y_max, x_min:x_max]
mask_section[overlay_mask > 0] = mask_id
return mask
class Mosaic(DualTransform):
"""Combine multiple images and their annotations into a single image using a mosaic grid layout.
This transform takes a primary input image (and its annotations) and combines it with
additional images/annotations provided via metadata. It calculates the geometry for
a mosaic grid, selects additional items, preprocesses annotations consistently
(handling label encoding updates), applies geometric transformations, and assembles
the final output.
Args:
grid_yx (tuple[int, int]): The number of rows (y) and columns (x) in the mosaic grid.
Determines the maximum number of images involved (grid_yx[0] * grid_yx[1]).
Default: (2, 2).
target_size (tuple[int, int]): The desired output (height, width) for the final mosaic image.
after cropping the mosaic grid.
cell_shape (tuple[int, int]): cell shape of each cell in the mosaic grid.
metadata_key (str): Key in the input dictionary specifying the list of additional data dictionaries
for the mosaic. Each dictionary in the list should represent one potential additional item.
Expected keys: 'image' (required, np.ndarray), and optionally 'mask' (np.ndarray),
'bboxes' (np.ndarray), 'keypoints' (np.ndarray), and any relevant label fields
(e.g., 'class_labels') corresponding to those specified in `Compose`'s `bbox_params` or
`keypoint_params`. Default: "mosaic_metadata".
center_range (tuple[float, float]): Range [0.0-1.0] to sample the center point of the mosaic view
relative to the valid central region of the conceptual large grid. This affects which parts
of the assembled grid are visible in the final crop. Default: (0.3, 0.7).
interpolation (int): OpenCV interpolation flag used for resizing images during geometric processing.
Default: cv2.INTER_LINEAR.
mask_interpolation (int): OpenCV interpolation flag used for resizing masks during geometric processing.
Default: cv2.INTER_NEAREST.
fill (tuple[float, ...] | float): Value used for padding images if needed during geometric processing.
Default: 0.
fill_mask (tuple[float, ...] | float): Value used for padding masks if needed during geometric processing.
Default: 0.
p (float): Probability of applying the transform. Default: 0.5.
Workflow (`get_params_dependent_on_data`):
1. Calculate Geometry & Visible Cells: Determine which grid cells are visible in the final
`target_size` crop and their placement coordinates on the output canvas.
2. Validate Raw Additional Metadata: Filter the list provided via `metadata_key`,
keeping only valid items (dicts with an 'image' key).
3. Select Subset of Raw Additional Metadata: Choose a subset of the valid raw items based
on the number of visible cells requiring additional data.
4. Preprocess Selected Raw Additional Items: Preprocess bboxes/keypoints for the *selected*
additional items *only*. This uses shared processors from `Compose`, updating their
internal state (e.g., `LabelEncoder`) based on labels in these selected items.
5. Prepare Primary Data: Extract preprocessed primary data fields from the input `data` dictionary
into a `primary` dictionary.
6. Determine & Perform Replication: If fewer additional items were selected than needed,
replicate the preprocessed primary data as required.
7. Combine Final Items: Create the list of all preprocessed items (primary, selected additional,
replicated primary) that will be used.
8. Assign Items to VISIBLE Grid Cells
9. Process Geometry & Shift Coordinates: For each assigned item:
a. Apply geometric transforms (Crop, Resize, Pad) to image/mask.
b. Apply geometric shift to the *preprocessed* bboxes/keypoints based on cell placement.
10. Return Parameters: Return the processed cell data (image, mask, shifted bboxes, shifted kps)
keyed by placement coordinates.
Label Handling:
- The transform relies on `bbox_processor` and `keypoint_processor` provided by `Compose`.
- `Compose.preprocess` initially fits the processors' `LabelEncoder` on the primary data.
- This transform (`Mosaic`) preprocesses the *selected* additional raw items using the same
processors. If new labels are found, the shared `LabelEncoder` state is updated via its
`update` method.
- `Compose.postprocess` uses the final updated encoder state to decode all labels present
in the mosaic output for the current `Compose` call.
- The encoder state is transient per `Compose` call.
Targets:
image, mask, bboxes, keypoints
Image types:
uint8, float32
Reference:
YOLOv4: Optimal Speed and Accuracy of Object Detection: https://arxiv.org/pdf/2004.10934
Examples:
>>> import numpy as np
>>> import albumentations as A
>>> import cv2
>>>
>>> # Prepare primary data
>>> primary_image = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> primary_mask = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> primary_bboxes = np.array([[10, 10, 40, 40], [50, 50, 90, 90]], dtype=np.float32)
>>> primary_labels = [1, 2]
>>>
>>> # Prepare additional images for mosaic
>>> additional_image1 = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> additional_mask1 = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> additional_bboxes1 = np.array([[20, 20, 60, 60]], dtype=np.float32)
>>> additional_labels1 = [3]
>>>
>>> additional_image2 = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> additional_mask2 = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> additional_bboxes2 = np.array([[30, 30, 70, 70]], dtype=np.float32)
>>> additional_labels2 = [4]
>>>
>>> additional_image3 = np.random.randint(0, 256, (100, 100, 3), dtype=np.uint8)
>>> additional_mask3 = np.random.randint(0, 2, (100, 100), dtype=np.uint8)
>>> additional_bboxes3 = np.array([[5, 5, 45, 45]], dtype=np.float32)
>>> additional_labels3 = [5]
>>>
>>> # Create metadata for additional images - structured as a list of dicts
>>> mosaic_metadata = [
... {
... 'image': additional_image1,
... 'mask': additional_mask1,
... 'bboxes': additional_bboxes1,
... 'labels': additional_labels1
... },
... {
... 'image': additional_image2,
... 'mask': additional_mask2,
... 'bboxes': additional_bboxes2,
... 'labels': additional_labels2
... },
... {
... 'image': additional_image3,
... 'mask': additional_mask3,
... 'bboxes': additional_bboxes3,
... 'labels': additional_labels3
... }
... ]
>>>
>>> # Create the transform with Mosaic
>>> transform = A.Compose([
... A.Mosaic(
... grid_yx=(2, 2),
... target_size=(200, 200),
... cell_shape=(120, 120),
... center_range=(0.4, 0.6),
... fit_mode="cover",
... p=1.0
... ),
... ], bbox_params=A.BboxParams(format='pascal_voc', label_fields=['labels']))
>>>
>>> # Apply the transform
>>> transformed = transform(
... image=primary_image,
... mask=primary_mask,
... bboxes=primary_bboxes,
... labels=primary_labels,
... mosaic_metadata=mosaic_metadata # Pass the metadata using the default key
... )
>>>
>>> # Access the transformed data
>>> mosaic_image = transformed['image'] # Combined mosaic image
>>> mosaic_mask = transformed['mask'] # Combined mosaic mask
>>> mosaic_bboxes = transformed['bboxes'] # Combined and repositioned bboxes
>>> mosaic_labels = transformed['labels'] # Combined labels from all images
"""
_targets = (Targets.IMAGE, Targets.MASK, Targets.BBOXES, Targets.KEYPOINTS)
class InitSchema(BaseTransformInitSchema):
grid_yx: tuple[int, int]
target_size: Annotated[
tuple[int, int],
AfterValidator(check_range_bounds(1, None)),
]
cell_shape: Annotated[
tuple[int, int],
AfterValidator(check_range_bounds(1, None)),
]
metadata_key: str
center_range: Annotated[
tuple[float, float],
AfterValidator(check_range_bounds(0, 1)),
AfterValidator(nondecreasing),
]
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
]
fill: tuple[float, ...] | float
fill_mask: tuple[float, ...] | float
fit_mode: Literal["cover", "contain"]
@model_validator(mode="after")
def _check_cell_shape(self) -> Self:
if (
self.cell_shape[0] * self.grid_yx[0] < self.target_size[0]
or self.cell_shape[1] * self.grid_yx[1] < self.target_size[1]
):
raise ValueError("Target size should be smaller than cell cell_size * grid_yx")
return self
def __init__(
self,
grid_yx: tuple[int, int] = (2, 2),
target_size: tuple[int, int] = (512, 512),
cell_shape: tuple[int, int] = (512, 512),
center_range: tuple[float, float] = (0.3, 0.7),
fit_mode: Literal["cover", "contain"] = "cover",
interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_LINEAR,
mask_interpolation: Literal[
cv2.INTER_NEAREST,
cv2.INTER_NEAREST_EXACT,
cv2.INTER_LINEAR,
cv2.INTER_CUBIC,
cv2.INTER_AREA,
cv2.INTER_LANCZOS4,
cv2.INTER_LINEAR_EXACT,
] = cv2.INTER_NEAREST,
fill: tuple[float, ...] | float = 0,
fill_mask: tuple[float, ...] | float = 0,
metadata_key: str = "mosaic_metadata",
p: float = 0.5,
) -> None:
super().__init__(p=p)
self.grid_yx = grid_yx
self.target_size = target_size
self.metadata_key = metadata_key
self.center_range = center_range
self.interpolation = interpolation
self.mask_interpolation = mask_interpolation
self.fill = fill
self.fill_mask = fill_mask
self.fit_mode = fit_mode
self.cell_shape = cell_shape
@property
def targets_as_params(self) -> list[str]:
"""Get list of targets that should be passed as parameters to transforms.
Returns:
list[str]: List containing the metadata key name
"""
return [self.metadata_key]
def _calculate_geometry(self, data: dict[str, Any]) -> list[tuple[int, int, int, int]]:
# Step 1: Calculate Geometry & Cell Placements
center_xy = fmixing.calculate_mosaic_center_point(
grid_yx=self.grid_yx,
cell_shape=self.cell_shape,
target_size=self.target_size,
center_range=self.center_range,
py_random=self.py_random,
)
return fmixing.calculate_cell_placements(
grid_yx=self.grid_yx,
cell_shape=self.cell_shape,
target_size=self.target_size,
center_xy=center_xy,
)
def _select_additional_items(self, data: dict[str, Any], num_additional_needed: int) -> list[dict[str, Any]]:
valid_items = fmixing.filter_valid_metadata(data.get(self.metadata_key), self.metadata_key, data)
if len(valid_items) > num_additional_needed:
return self.py_random.sample(valid_items, num_additional_needed)
return valid_items
def _preprocess_additional_items(
self,
additional_items: list[dict[str, Any]],
data: dict[str, Any],
) -> list[fmixing.ProcessedMosaicItem]:
if "bboxes" in data or "keypoints" in data:
bbox_processor = cast("BboxProcessor", self.get_processor("bboxes"))
keypoint_processor = cast("KeypointsProcessor", self.get_processor("keypoints"))
return fmixing.preprocess_selected_mosaic_items(additional_items, bbox_processor, keypoint_processor)
return cast("list[fmixing.ProcessedMosaicItem]", list(additional_items))
def _prepare_final_items(
self,
primary: fmixing.ProcessedMosaicItem,
additional_items: list[fmixing.ProcessedMosaicItem],
num_needed: int,
) -> list[fmixing.ProcessedMosaicItem]:
num_replications = max(0, num_needed - len(additional_items))
replicated = [deepcopy(primary) for _ in range(num_replications)]
return [primary, *additional_items, *replicated]
def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
"""Orchestrates the steps to calculate mosaic parameters by calling helper methods."""
cell_placements = self._calculate_geometry(data)
num_cells = len(cell_placements)
num_additional_needed = max(0, num_cells - 1)
additional_items = self._select_additional_items(data, num_additional_needed)
preprocessed_additional = self._preprocess_additional_items(additional_items, data)
primary = self.get_primary_data(data)
final_items = self._prepare_final_items(primary, preprocessed_additional, num_additional_needed)
placement_to_item_index = fmixing.assign_items_to_grid_cells(
num_items=len(final_items),
cell_placements=cell_placements,
py_random=self.py_random,
)
processed_cells = fmixing.process_all_mosaic_geometries(
canvas_shape=self.target_size,
cell_shape=self.cell_shape,
placement_to_item_index=placement_to_item_index,
final_items_for_grid=final_items,
fill=self.fill,
fill_mask=self.fill_mask if self.fill_mask is not None else self.fill,
fit_mode=self.fit_mode,
interpolation=self.interpolation,
mask_interpolation=self.mask_interpolation,
)
if "bboxes" in data or "keypoints" in data:
processed_cells = fmixing.shift_all_coordinates(processed_cells, canvas_shape=self.target_size)
result = {"processed_cells": processed_cells, "target_shape": self._get_target_shape(data["image"].shape)}
if "mask" in data:
result["target_mask_shape"] = self._get_target_shape(data["mask"].shape)
return result
@staticmethod
def get_primary_data(data: dict[str, Any]) -> fmixing.ProcessedMosaicItem:
"""Get a copy of the primary data (data passed in `data` parameter) to avoid modifying the original data.
Args:
data (dict[str, Any]): Dictionary containing the primary data.
Returns:
fmixing.ProcessedMosaicItem: A copy of the primary data.
"""
mask = data.get("mask")
if mask is not None:
mask = mask.copy()
bboxes = data.get("bboxes")
if bboxes is not None:
bboxes = bboxes.copy()
keypoints = data.get("keypoints")
if keypoints is not None:
keypoints = keypoints.copy()
return {
"image": data["image"],
"mask": mask,
"bboxes": bboxes,
"keypoints": keypoints,
}
def _get_target_shape(self, np_shape: tuple[int, ...]) -> list[int]:
target_shape = list(np_shape)
target_shape[0] = self.target_size[0]
target_shape[1] = self.target_size[1]
return target_shape
def apply(
self,
img: np.ndarray,
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
target_shape: tuple[int, int],
**params: Any,
) -> np.ndarray:
"""Apply mosaic transformation to the input image.
Args:
img (np.ndarray): Input image
processed_cells (dict[tuple[int, int, int, int], dict[str, Any]]): Dictionary of processed cell data
target_shape (tuple[int, int]): Shape of the target image.
**params (Any): Additional parameters
Returns:
np.ndarray: Mosaic transformed image
"""
return fmixing.assemble_mosaic_from_processed_cells(
processed_cells=processed_cells,
target_shape=target_shape,
dtype=img.dtype,
data_key="image",
fill=self.fill,
)
def apply_to_mask(
self,
mask: np.ndarray,
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
target_mask_shape: tuple[int, int],
**params: Any,
) -> np.ndarray:
"""Apply mosaic transformation to the input mask.
Args:
mask (np.ndarray): Input mask.
processed_cells (dict): Dictionary of processed cell data containing cropped/padded mask segments.
target_mask_shape (tuple[int, int]): Shape of the target mask.
**params (Any): Additional parameters (unused).
Returns:
np.ndarray: Mosaic transformed mask.
"""
return fmixing.assemble_mosaic_from_processed_cells(
processed_cells=processed_cells,
target_shape=target_mask_shape,
dtype=mask.dtype,
data_key="mask",
fill=self.fill_mask,
)
def apply_to_bboxes(
self,
bboxes: np.ndarray, # Original bboxes - ignored
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
**params: Any,
) -> np.ndarray:
"""Applies mosaic transformation to bounding boxes.
Args:
bboxes (np.ndarray): Original bounding boxes (ignored).
processed_cells (dict): Dictionary mapping placement coords to processed cell data
(containing shifted bboxes in absolute pixel coords).
**params (Any): Additional parameters (unused).
Returns:
np.ndarray: Final combined, filtered, bounding boxes.
"""
all_shifted_bboxes = []
for cell_data in processed_cells.values():
shifted_bboxes = cell_data["bboxes"]
if shifted_bboxes.size > 0:
all_shifted_bboxes.append(shifted_bboxes)
if not all_shifted_bboxes:
return np.empty((0, bboxes.shape[1]), dtype=bboxes.dtype)
# Concatenate (these are absolute pixel coordinates)
combined_bboxes = np.concatenate(all_shifted_bboxes, axis=0)
# Apply filtering using processor parameters
bbox_processor = cast("BboxProcessor", self.get_processor("bboxes"))
# Assume processor exists if bboxes are being processed
shape_dict: dict[Literal["depth", "height", "width"], int] = {
"height": self.target_size[0],
"width": self.target_size[1],
}
return filter_bboxes(
combined_bboxes,
shape_dict,
min_area=bbox_processor.params.min_area,
min_visibility=bbox_processor.params.min_visibility,
min_width=bbox_processor.params.min_width,
min_height=bbox_processor.params.min_height,
max_accept_ratio=bbox_processor.params.max_accept_ratio,
)
def apply_to_keypoints(
self,
keypoints: np.ndarray, # Original keypoints - ignored
processed_cells: dict[tuple[int, int, int, int], dict[str, Any]],
**params: Any,
) -> np.ndarray:
"""Applies mosaic transformation to keypoints.
Args:
keypoints (np.ndarray): Original keypoints (ignored).
processed_cells (dict): Dictionary mapping placement coords to processed cell data
(containing shifted keypoints).
**params (Any): Additional parameters (unused).
Returns:
np.ndarray: Final combined, filtered keypoints.
"""
all_shifted_keypoints = []
for cell_data in processed_cells.values():
shifted_keypoints = cell_data["keypoints"]
if shifted_keypoints.size > 0:
all_shifted_keypoints.append(shifted_keypoints)
if not all_shifted_keypoints:
return np.empty((0, keypoints.shape[1]), dtype=keypoints.dtype)
combined_keypoints = np.concatenate(all_shifted_keypoints, axis=0)
# Filter out keypoints outside the target canvas boundaries
target_h, target_w = self.target_size
valid_indices = (
(combined_keypoints[:, 0] >= 0)
& (combined_keypoints[:, 0] < target_w)
& (combined_keypoints[:, 1] >= 0)
& (combined_keypoints[:, 1] < target_h)
)
return combined_keypoints[valid_indices]