Skip to content

Domain Adaptation functional transforms (augmentations.domain_adaptation.functional)

def apply_histogram (img, reference_image, blend_ratio) [view source on GitHub]

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.

Parameters:

Name Type Description
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:

Type Description
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.
Source code in albumentations/augmentations/domain_adaptation/functional.py
Python
@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)

def fourier_domain_adaptation (img, target_img, beta) [view source on GitHub]

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.

Parameters:

Name Type Description
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:

Type Description
np.ndarray

The adapted image with the same shape and type as the input image.

Exceptions:

Type Description
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.

Examples:

Python
>>> 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

Source code in albumentations/augmentations/domain_adaptation/functional.py
Python
@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 len(src_img.shape) == MONO_CHANNEL_DIMENSIONS:
        src_img = np.expand_dims(src_img, axis=-1)
    if len(trg_img.shape) == 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

def match_histograms (image, reference) [view source on GitHub]

Adjust an image so that its cumulative histogram matches that of another.

The adjustment is applied separately for each channel.

Parameters:

Name Type Description
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

If None, the image is assumed to be a grayscale (single channel) image. Otherwise, this parameter indicates which axis of the array corresponds to channels.

Returns:

Type Description
np.ndarray

Transformed input image.

Exceptions:

Type Description
ValueError

Thrown when the number of channels in the input image and the reference differ.

Source code in albumentations/augmentations/domain_adaptation/functional.py
Python
@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: Input image. Can be gray-scale or in color.
        reference: Image to match histogram of. Must have the same number of channels as image.
        channel_axis: If None, the image is assumed to be a grayscale (single channel) image.
            Otherwise, this parameter 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:  # noqa: PLR2004
        image = np.expand_dims(image, axis=-1)
    if reference.ndim == 2:  # noqa: PLR2004
        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