Skip to content

transform

Module diagram

classDiagram
  class transform {
  }
  class augmentation {
  }
  class api {
  }
  class augment_function {
  }
  class augment_transform {
  }
  class base_transform {
  }
  class builder {
  }
  class compose {
  }
  class base_compose {
  }
  class builder {
  }
  class compose {
  }
  class box_function {
  }
  class function_util {
  }
  class image_function {
  }
  class image_load {
  }
  class polygon_function {
  }
  class resize {
  }
  class roi {
  }
  class api {
  }
  class roi_calculator {
  }
  class roi_handler {
  }
  class transform {
  }
  class typevar {
  }
  augmentation --> builder
  api --> augment_function
  augment_transform --> augment_function
  augment_transform --> base_transform
  builder --> augment_transform
  builder --> builder
  builder --> compose
  compose --> base_compose
  box_function --> polygon_function
  box_function --> typevar
  function_util --> typevar
  image_function --> typevar
  image_load --> image_function
  polygon_function --> augment_function
  polygon_function --> typevar
  resize --> box_function
  resize --> image_function
  resize --> polygon_function
  resize --> typevar
  roi --> api
  roi --> roi_handler
  api --> roi_handler
  roi_handler --> roi_calculator
  transform --> augmentation
  transform --> image_function
  transform --> image_load
  transform --> resize
  transform --> roi_handler

data.transform

End-to-end 데이터 변환을 지원하는 Transform 클래스를 제공하는 모듈입니다.

Transfrom 클래스는 다음과 같은 순서로 transform을 적용합니다. 1. load PIL Image 2. 원본 이미지가 inspection_size_wh를 넘지 않도록 resize 했을 때의 image scale 계산 3. ROI 적용 (crop) @. roi_mask_first=True인 경우 ROI 적용 (blind mask) 4. 2번과 resize_factor를 하나로 묶어서 resize @. roi_mask_first=False인 경우 ROI 적용 (blind mask) 5. data augmentation

Note

roi_mask_first 옵션에 따라서 ROI의 blind mask를 적용하는 시점이 달라집니다. - roi_mask_first=True: ROI crop -> ROI mask -> resize - roi_mask_first=False: ROI crop -> resize -> ROI mask 일반적으로 resize 후에 mask를 적용하는 것이 더 효율적입니다.

augmentation

Data augmentation을 위한 기본 BaseTransform 클래스 및 Transform 구현, 그리고 여러 Data Transform들을 하나로 묶어서 관리해주는 기본 BaseCompose 클래스 및 Compose 구현을 제공합니다.

api

Image Augmentation Preview를 위한 API를 제공합니다.

ImageProcessor 클래스를 통해 각 augmentation들이 특정 파라미터 값에 대해 이미지를 어떻게 변형 시키는지 확인할 수 있습니다.

_APIDecorator

ImageProcessor에서 정의된 함수들을 decorate 해주는 헬퍼입니다.

staticmethod 와 decorator를 함께 사용할 경우 Cythonize시 제대로 동작하지 않는 이슈를 해결하기 위한 패치입니다. 참고: https://github.com/cython/cython/issues/1434

ImageProcessor의 각 함수에 다음과 같은 decorator를 씌우는 것과 동일한 역할을 합니다.

@staticmethod
@error_handler
@support_multi_image
@support_3dim_gray_image
def image_processor_function(image: np.ndarray, ...):
    ...

ImageProcessor

Bases: _APIDecorator

Image Augmentation Preview를 위한 API 입니다. 각 augmentation들이 특정 파라미터 값에 대해 이미지를 어떻게 변형 시키는지 확인할 수 있습니다.

Note1

일반적으로 학습 시에는 파라미터를 특정 이 아닌 범위로 설정하여 해당 범위에서 매번 랜덤한 값을 선택해 이미지에 적용합니다. 따라서 preview API의 입력 파라미터와 학습 시 넘겨주는 파라미터는 대부분 vs 범위의 차이를 가지게 됩니다. 예를 들어 preview API에서 rotate의 경우 angle (float) 값을 받지만, 학습 config에서는 angle_limit (List[float]) 범위를 받게됩니다. 각 augmentation을 학습에 사용시 필요한 config는 각 함수 설명의 Trainer Config 섹션을 참고하세요.

Note2

API 기획상, augmentation의 실제 자유도보다, 유저가 설정할 수 있는 파라미터가 적은 경우가 있습니다. (각 변 혹은 꼭짓점 마다 독립적으로 적용되는 ratio_jitter나 perspective_transform의 경우) 이러한 augmentation들은 api 호출 시, '값'을 입력 받아서, 이 '값'으로 부터 정의된 '범위'에서 필요한 값들을 랜덤하게 샘플링하게 됩니다. 이러한 augmentation들의 preview 함수를 정의할 때는, 인풋에 fixed_aug_params를 받을 수 있도록 해주어야합니다. (ImageProcessor.ratio_jitter 참고)

Usage

rotate augmentation preview 예제입니다. 상세 설명은 각 함수 설명 참고.

image = np.zeros((100, 100, 3), dtype=np.unit8)
error, augmented_result = ImageProcessor.rotate(image=image, angle=15)
augmented_image, augmentation_parameters = augmented_result

# In the case of 'rotate' augmentation, `augmentation_parameters` is None

vertical_flip
vertical_flip(image: ndarray) -> Tuple[ndarray, None]

image를 상하로 뒤집습니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.vertical_flip(image=image)
Trainer Config
{
    "_target_": "vertical_flip",
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def vertical_flip(image: np.ndarray) -> Tuple[np.ndarray, None]:
    """image를 상하로 뒤집습니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.vertical_flip(image=image)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "vertical_flip",
        }
        ```
    """
    return vertical_flip(image=image), None
horizontal_flip
horizontal_flip(image: ndarray) -> Tuple[ndarray, None]

image를 좌우로 뒤집습니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.horizontal_flip(image=image)
Trainer Config
{
    "_target_": "horizontal_flip",
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def horizontal_flip(image: np.ndarray) -> Tuple[np.ndarray, None]:
    """image를 좌우로 뒤집습니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.horizontal_flip(image=image)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "horizontal_flip",
        }
        ```
    """
    return horizontal_flip(image=image), None
rotate
rotate(image: ndarray, angle: float = 0.0) -> Tuple[ndarray, None]

image를 angle만큼 회전시킵니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • angle (float, default: 0.0 ) –

    회전하는 각도 입니다. 유효 범위는 다음과 같습니다. [-360.0, 360.0]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.rotate(image=image, angle=60.0)
Trainer Config
{
    "_target_": "rotate",
    "angle_limit": List[float],  # angle 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def rotate(image: np.ndarray, angle: float = 0.0) -> Tuple[np.ndarray, None]:
    """image를 angle만큼 회전시킵니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        angle (float, optional): 회전하는 각도 입니다. 유효 범위는 다음과 같습니다. [-360.0, 360.0]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.rotate(image=image, angle=60.0)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "rotate",
            "angle_limit": List[float],  # angle 최소 최대 범위
        }
        ```
    """
    return (
        rotate(
            image=image,
            angle=angle,
            interpolation=cv2.INTER_LINEAR,
            border_mode=cv2.BORDER_REFLECT_101,
            value=0,
            crop_border=False,
        ),
        None,
    )
random_rotate90
random_rotate90(image: ndarray, factor: int = 0) -> Tuple[ndarray, None]

image를 [0, 90, 180, 270] 중 랜덤한 각도만큼 회전시킵니다.

NOTE
  • 모든 이미지 픽셀은 유지되며, 회전 후 이미지 크기가 변경될 수 있습니다.
  • 예시: factor가 1일 경우 90도 회전하며, 이미지 사이즈는 (W, H) -> (H, W)로 변경됩니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • factor (int, default: 0 ) –

    회전하는 각도 입니다. factor에 90을 곱한 값만큼 회전합니다. (ex. factor가 1일 경우 90도) 유효범위는 다음과 같습니다 [0, 3]. Defaults to 0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.random_rotate90(image=image, factor=1)
Trainer Config
{
    "_target_": "random_rotate90",
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def random_rotate90(image: np.ndarray, factor: int = 0) -> Tuple[np.ndarray, None]:
    """image를 [0, 90, 180, 270] 중 랜덤한 각도만큼 회전시킵니다.

    NOTE:
        - 모든 이미지 픽셀은 유지되며, 회전 후 이미지 크기가 변경될 수 있습니다.
        - 예시: factor가 1일 경우 90도 회전하며, 이미지 사이즈는 (W, H) -> (H, W)로 변경됩니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        factor (int, optional): 회전하는 각도 입니다. factor에 90을 곱한 값만큼 회전합니다. (ex. factor가 1일 경우 90도)
                                유효범위는 다음과 같습니다 [0, 3]. Defaults to 0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.random_rotate90(image=image, factor=1)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "random_rotate90",
        }
        ```
    """
    return random_rotate90(image=image, factor=factor), None
color_jitter
color_jitter(image: ndarray, brightness: float = 1.0, contrast: float = 1.0, saturation: float = 1.0, hue: float = 0.0) -> Tuple[ndarray, None]

image의 밝기 (brightness), 대비 (contrast), 채도 (saturation), 색상 (hue)을 변경합니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • brightness (float, default: 1.0 ) –

    밝기를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [0.01, 10.00]. Defaults to 1.0.

  • contrast (float, default: 1.0 ) –

    대비를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [0.01, 10.00]. Defaults to 1.0.

  • saturation (float, default: 1.0 ) –

    채도를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [0.01, 10.00]. Defaults to 1.0.

  • hue (float, default: 0.0 ) –

    색상을 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [-0.50, 0.50]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.color_jitter(image=image,
                                                     brightness=0.5,
                                                     contrast=0.5,
                                                     saturation=0.5,
                                                     hue=0.1)  #  augmentation 적용
Trainer Config
{
    "_target_": "color_jitter",
    "brightness_limit": List[float],  # brightness 최소 최대 범위
    "contrast_limit": List[float],  # contrast 최소 최대 범위
    "saturation_limit": List[float],  # saturation 최소 최대 범위
    "hue_limit": List[float],  # hue 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def color_jitter(
    image: np.ndarray,
    brightness: float = 1.0,
    contrast: float = 1.0,
    saturation: float = 1.0,
    hue: float = 0.0,
) -> Tuple[np.ndarray, None]:
    """image의 밝기 (brightness), 대비 (contrast), 채도 (saturation), 색상 (hue)을 변경합니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        brightness (float, optional): 밝기를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [0.01, 10.00]. Defaults to 1.0.
        contrast (float, optional): 대비를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [0.01, 10.00]. Defaults to 1.0.
        saturation (float, optional): 채도를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [0.01, 10.00]. Defaults to 1.0.
        hue (float, optional): 색상을 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [-0.50, 0.50]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.color_jitter(image=image,
                                                             brightness=0.5,
                                                             contrast=0.5,
                                                             saturation=0.5,
                                                             hue=0.1)  #  augmentation 적용
        ```

    Trainer Config:
        ```python
        {
            "_target_": "color_jitter",
            "brightness_limit": List[float],  # brightness 최소 최대 범위
            "contrast_limit": List[float],  # contrast 최소 최대 범위
            "saturation_limit": List[float],  # saturation 최소 최대 범위
            "hue_limit": List[float],  # hue 최소 최대 범위
        }
        ```
    """
    return (
        color_jitter(
            image=image,
            brightness=brightness,
            contrast=contrast,
            saturation=saturation,
            hue=hue,
            order=[0, 1, 2, 3],
        ),
        None,
    )
blur
blur(image: ndarray, ksize: int = 1) -> Tuple[ndarray, None]

image에 averaging blur를 적용합니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • ksize (int, default: 1 ) –

    blur kernel의 크기 입니다. 유효 범위는 다음과 같습니다. [1, 100]. Defaults to 1.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.blur(image=image, ksize=3)
Trainer Config
{
    "_target_": "blur",
    "ksize_limit": List[int],  # ksize 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def blur(image: np.ndarray, ksize: int = 1) -> Tuple[np.ndarray, None]:
    """image에 averaging blur를 적용합니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        ksize (int, optional): blur kernel의 크기 입니다. 유효 범위는 다음과 같습니다. [1, 100]. Defaults to 1.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.blur(image=image, ksize=3)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "blur",
            "ksize_limit": List[int],  # ksize 최소 최대 범위
        }
        ```
    """
    return blur(image=image, ksize=ksize), None
gaussian_blur
gaussian_blur(image: ndarray, ksize: int = 1) -> Tuple[ndarray, None]

image에 gaussian blur를 적용합니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • ksize (int, default: 1 ) –

    blur kernel의 크기 입니다. 유효 범위는 다음과 같습니다. [1, 100]. Defaults to 1.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.gaussian_blur(image=image, ksize=3)
Trainer Config
{
    "_target_": "gaussian_blur",
    "ksize_limit": List[int],  # ksize 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def gaussian_blur(image: np.ndarray, ksize: int = 1) -> Tuple[np.ndarray, None]:
    """image에 gaussian blur를 적용합니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        ksize (int, optional): blur kernel의 크기 입니다. 유효 범위는 다음과 같습니다. [1, 100]. Defaults to 1.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.gaussian_blur(image=image, ksize=3)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "gaussian_blur",
            "ksize_limit": List[int],  # ksize 최소 최대 범위
        }
        ```
    """
    return gaussian_blur(image=image, ksize=ksize, sigma=0.0), None
adjust_brightness
adjust_brightness(image: ndarray, brightness: float = 0.0) -> Tuple[ndarray, None]

image의 밝기 (brightness)를 변경합니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • brightness (float, default: 0.0 ) –

    밝기를 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.adjust_brightness(image=image, brightness=0.3)
Trainer Config
{
    "_target_": "adjust_brightness",
    "brightness_limit": List[float],  # brightness 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def adjust_brightness(image: np.ndarray, brightness: float = 0.0) -> Tuple[np.ndarray, None]:
    """image의 밝기 (brightness)를 변경합니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        brightness (float, optional): 밝기를 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.adjust_brightness(image=image, brightness=0.3)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "adjust_brightness",
            "brightness_limit": List[float],  # brightness 최소 최대 범위
        }
        ```
    """
    return (
        adjust_brightness(image=image, brightness=brightness, brightness_by_max=True),
        None,
    )
adjust_contrast
adjust_contrast(image: ndarray, contrast: float = 0.0) -> Tuple[ndarray, None]

image의 대비 (contrast)를 변경합니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • contrast (float, default: 0.0 ) –

    대비 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.adjust_contrast(image=image, contrast=0.7)
Trainer Config
{
    "_target_": "adjust_contrast",
    "contrast_limit": List[float],  # contrast 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def adjust_contrast(image: np.ndarray, contrast: float = 0.0) -> Tuple[np.ndarray, None]:
    """image의 대비 (contrast)를 변경합니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        contrast (float, optional): 대비 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.adjust_contrast(image=image, contrast=0.7)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "adjust_contrast",
            "contrast_limit": List[float],  # contrast 최소 최대 범위
        }
        ```
    """
    return adjust_contrast(image=image, contrast=contrast), None
adjust_hue
adjust_hue(image: ndarray, hue: float = 0.0) -> Tuple[ndarray, None]

image의 색조 (hue)를 변경합니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • hue (float, default: 0.0 ) –

    색조 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.adjust_hue(image=image, hue=0.7)
Trainer Config
{
    "_target_": "adjust_hue",
    "hue_limit": List[float],  # hue 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def adjust_hue(image: np.ndarray, hue: float = 0.0) -> Tuple[np.ndarray, None]:
    """image의 색조 (hue)를 변경합니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        hue (float, optional): 색조 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.adjust_hue(image=image, hue=0.7)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "adjust_hue",
            "hue_limit": List[float],  # hue 최소 최대 범위
        }
        ```
    """
    return adjust_hue(image=image, hue=hue), None
adjust_saturation
adjust_saturation(image: ndarray, saturation: float = 0.0) -> Tuple[ndarray, None]

image의 채도 (saturation)를 변경합니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • saturation (float, default: 0.0 ) –

    채도 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.adjust_saturation(image=image, saturation=0.7)
Trainer Config
{
    "_target_": "adjust_saturation",
    "saturation_limit": List[float],  # saturation 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def adjust_saturation(image: np.ndarray, saturation: float = 0.0) -> Tuple[np.ndarray, None]:
    """image의 채도 (saturation)를 변경합니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        saturation (float, optional): 채도 변화 강도입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.adjust_saturation(image=image, saturation=0.7)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "adjust_saturation",
            "saturation_limit": List[float],  # saturation 최소 최대 범위
        }
        ```
    """
    return adjust_saturation(image=image, saturation=saturation), None
adjust_gamma
adjust_gamma(image: ndarray, gamma: float = 0.0) -> Tuple[ndarray, None]

image의 gamma를 조절하여 밝기를 변화시킵니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • gamma (float, default: 0.0 ) –

    조절할 gamma value 입니다. 유효 범위는 다음과 같습니다. [-1.0, 1.0]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.adjust_gamma(image=image, gamma=0.5)
Trainer Config
{
    "_target_": "adjust_gamma",
    "gamma_limit": List[float],  # gamma 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def adjust_gamma(image: np.ndarray, gamma: float = 0.0) -> Tuple[np.ndarray, None]:
    """image의 gamma를 조절하여 밝기를 변화시킵니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        gamma (float, optional): 조절할 gamma value 입니다. 유효 범위는 다음과 같습니다. [-1.0, 1.0]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.adjust_gamma(image=image, gamma=0.5)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "adjust_gamma",
            "gamma_limit": List[float],  # gamma 최소 최대 범위
        }
        ```
    """
    return adjust_gamma(image=image, gamma=gamma), None
adjust_brightness_contrast
adjust_brightness_contrast(image: ndarray, brightness: float = 0.0, contrast: float = 0.0) -> Tuple[ndarray, None]

image의 밝기 (brightness), 대비 (contrast)를 변경합니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • brightness (float, default: 0.0 ) –

    밝기를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

  • contrast (float, default: 0.0 ) –

    대비를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.adjust_brightness_contrast(image=image, brightness=0.3, contrast=0.7)
Trainer Config
{
    "_target_": "adjust_brightness_contrast",
    "brightness_limit": List[float],  # brightness 최소 최대 범위
    "contrast_limit": List[float],  # contrast 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def adjust_brightness_contrast(
    image: np.ndarray, brightness: float = 0.0, contrast: float = 0.0
) -> Tuple[np.ndarray, None]:
    """image의 밝기 (brightness), 대비 (contrast)를 변경합니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        brightness (float, optional): 밝기를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.
        contrast (float, optional): 대비를 담당하는 요소입니다. 유효 범위는 다음과 같습니다. [-1.00, 1.00]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.adjust_brightness_contrast(image=image, brightness=0.3, contrast=0.7)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "adjust_brightness_contrast",
            "brightness_limit": List[float],  # brightness 최소 최대 범위
            "contrast_limit": List[float],  # contrast 최소 최대 범위
        }
        ```
    """
    return (
        adjust_brightness_contrast(
            image=image, brightness=brightness, contrast=contrast, brightness_by_max=True
        ),
        None,
    )
iso_noise
iso_noise(image: ndarray, color_shift: float = 0.0, intensity: float = 0.0) -> Tuple[ndarray, None]

Apply camera sensor noise.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • color_shift (float, default: 0.0 ) –

    variance range for color hue change. Measured as a fraction of 360 degree Hue angle in HLS colorspace. 유효 범위는 다음과 같습니다. [0.00, 1.00]. Defaults to 0.0.

  • intensity (float, default: 0.0 ) –

    Multiplicative factor that control strength of color and luminace noise. 유효 범위는 다음과 같습니다. [0.00, 2.00]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.iso_noise(image=image, color_shift=0.2, intensity=0.2)
Trainer Config
{
    "_target_": "iso_noise",
    "color_shift_limit": List[float],  # color_shift 최소 최대 범위
    "intensity_limit": List[float],  # intensity 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def iso_noise(
    image: np.ndarray, color_shift: float = 0.0, intensity: float = 0.0
) -> Tuple[np.ndarray, None]:
    """Apply camera sensor noise.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        color_shift (float, optional): variance range for color hue change. Measured as a fraction of 360 degree Hue angle in HLS colorspace.
                                       유효 범위는 다음과 같습니다. [0.00, 1.00]. Defaults to 0.0.
        intensity (float, optional): Multiplicative factor that control strength of color and luminace noise.
                                     유효 범위는 다음과 같습니다. [0.00, 2.00]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.iso_noise(image=image, color_shift=0.2, intensity=0.2)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "iso_noise",
            "color_shift_limit": List[float],  # color_shift 최소 최대 범위
            "intensity_limit": List[float],  # intensity 최소 최대 범위
        }
        ```
    """
    return (
        iso_noise(image=image, color_shift=color_shift, intensity=intensity, random_state=0),
        None,
    )
ratio_jitter
ratio_jitter(image: ndarray, proportion: Optional[int] = 0, fixed_aug_params: Optional[Dict] = None) -> Tuple[ndarray, Dict]

image에 random하게 padding과 crop을 한 뒤, 원래 size로 resize 하는 과정을 통해 image의 가로 세로 비율을 변경합니다. NOTE: 프리뷰에서는 네변에 각각 [0, proportion] 범위에서 crop 혹은 padding한 예시를 보여줍니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • proportion (int, default: 0 ) –

    padding 혹은 crop을 할 비율(단위: 백분율)입니다. 유효 범위는 다음과 같습니다. [0, 50]. Defaults to 0. (fixed_aug_params=None일 때만 작동합니다.)

  • fixed_aug_params (Dict, default: None ) –

    각 변에 대해서 고정된 crop 혹은 padding을 직접 정해주고자 할 때 사용합니다.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • Dict ( Dict ) –

    각 변에 적용된 proportioin 비율(-50 ~ 50 사이의 실수, 양수이면 crop, 음수이면 pad)들입니다.

    {
        "proportion_left": float,
        "proportion_right": float,
        "proportion_top": float,
        "proportion_bottom": float,
    }
    

각 변에 대해 crop 혹은 padding할 비율을 직접 설정
error, augmented_image = ImageProcessor.ratio_jitter(
    image=image,
    proportion=None,
    fixed_aug_params={
        "proportion_left": 2.0,
        "proportion_right": 2.0,
        "proportion_top": 2.0,
        "proportion_bottom": 2.0,
    }
)
각 변에 [-proportion, proportion] 범위에서 랜덤하게 crop 혹은 padding 적용
error, augmented_image = ImageProcessor.ratio_jitter(image=image, proportion=2)
Trainer Config
{
    "_target_": "ratio_jitter",
    "proportion_limit": int,  # proportion 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def ratio_jitter(
    image: np.ndarray,
    proportion: Optional[int] = 0,
    fixed_aug_params: Optional[Dict] = None,
) -> Tuple[np.ndarray, Dict]:
    """image에 random하게 padding과 crop을 한 뒤, 원래 size로 resize 하는 과정을 통해 image의 가로 세로 비율을 변경합니다.
    NOTE: 프리뷰에서는 네변에 각각 [0, proportion] 범위에서 crop 혹은 padding한 예시를 보여줍니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        proportion (int, optional): padding 혹은 crop을 할 비율(단위: 백분율)입니다. 유효 범위는 다음과 같습니다. [0, 50]. Defaults to 0. (`fixed_aug_params=None`일 때만 작동합니다.)
        fixed_aug_params (Dict, optional): 각 변에 대해서 고정된 crop 혹은 padding을 직접 정해주고자 할 때 사용합니다.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        Dict: 각 변에 적용된 proportioin 비율(-50 ~ 50 사이의 실수, 양수이면 crop, 음수이면 pad)들입니다.
            ```python
            {
                "proportion_left": float,
                "proportion_right": float,
                "proportion_top": float,
                "proportion_bottom": float,
            }
            ```

    Example1: 각 변에 대해 crop 혹은 padding할 비율을 직접 설정
        ```python
        error, augmented_image = ImageProcessor.ratio_jitter(
            image=image,
            proportion=None,
            fixed_aug_params={
                "proportion_left": 2.0,
                "proportion_right": 2.0,
                "proportion_top": 2.0,
                "proportion_bottom": 2.0,
            }
        )
        ```

    Example2: 각 변에 [-proportion, proportion] 범위에서 랜덤하게 crop 혹은 padding 적용
        ```python
        error, augmented_image = ImageProcessor.ratio_jitter(image=image, proportion=2)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "ratio_jitter",
            "proportion_limit": int,  # proportion 최대 범위
        }
        ```
    """
    aug_param_keys = ["proportion_left", "proportion_right", "proportion_top", "proportion_bottom"]
    if fixed_aug_params is None:
        check_value(proportion, 0, 50)
        proportion_limit = [-proportion, proportion]
        fixed_aug_params = {k: random.uniform(*proportion_limit) for k in aug_param_keys}
    else:
        for k in aug_param_keys:
            check_value(fixed_aug_params[k], -50, 50)

    return (
        ratio_jitter(
            image=image,
            proportion_left=fixed_aug_params["proportion_left"] / 100,
            proportion_right=fixed_aug_params["proportion_right"] / 100,
            proportion_top=fixed_aug_params["proportion_top"] / 100,
            proportion_bottom=fixed_aug_params["proportion_bottom"] / 100,
            resampling="bilinear",
            border_mode=cv2.BORDER_CONSTANT,
            value=0,
        ),
        fixed_aug_params,
    )
zoom
zoom(image: ndarray, ratio: float = 1.0) -> Tuple[ndarray, None]

image에 zoom in/out 효과를 줍니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • ratio (float, default: 1.0 ) –

    zoom in/out 할 비율입니다. 1보다 크면 zoom in을 1보다 작으면 zoom out을 합니다. 유효 범위는 다음과 같습니다. [0.01, 100.00]. Defaults to 1.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.zoom(image=image, ratio=2.0)
Trainer Config
{
    "_target_": "zoom",
    "ratio_limit": List[float],  # ratio 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def zoom(image: np.ndarray, ratio: float = 1.0) -> Tuple[np.ndarray, None]:
    """image에 zoom in/out 효과를 줍니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        ratio (float, optional): zoom in/out 할 비율입니다. 1보다 크면 zoom in을 1보다 작으면 zoom out을 합니다.
                                 유효 범위는 다음과 같습니다. [0.01, 100.00]. Defaults to 1.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.zoom(image=image, ratio=2.0)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "zoom",
            "ratio_limit": List[float],  # ratio 최소 최대 범위
        }
        ```
    """
    return (
        zoom(
            image=image,
            ratio=ratio,
            h_start=0,
            w_start=0,
            resampling="bilinear",
            border_mode=cv2.BORDER_CONSTANT,
            value=0,
        ),
        None,
    )
random_resized_crop_and_pad
random_resized_crop_and_pad(image: ndarray, scale: float = 1.0, aspect_ratio: float = 1.0, height: Optional[int] = None, width: Optional[int] = None) -> Tuple[ndarray, None]

원본 image의 scale 비율의 면적을 가지면서 가로 세로 비가 aspect_ratio인 image를 random하게 crop 한 뒤, (crop image가 원본 image 보다 커지는 경우 padding을 통해 해결합니다.) 크기가 (height, width)가 되도록 resize를 합니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • scale (float, default: 1.0 ) –

    crop할 image의 면적을 나타내는 값입니다. 실제 면적은 [원본 이미지의 면적 * scale] 입니다. 유효 범위는 다음과 같습니다. [0.01, 1.00]. Defaults to 1.0.

  • aspect_ratio (float, default: 1.0 ) –

    crop할 image의 가로 세로 비를 나타내는 값입니다. 유효 범위는 다음과 같습니다. [0.10, 10.00]. Defaults to 1.0.

  • height (int, default: None ) –

    crop image를 resize할 height 입니다. None인 경우 입력 이미지의 원본 height를 사용합니다.

  • width (int, default: None ) –

    crop image를 resize할 width 입니다. None인 경우 입력 이미지의 원본 width를 사용합니다.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.random_resized_crop_and_pad(image=image,
                                                                    scale=0.5,
                                                                    aspect_ratio=2,
                                                                    height=256,
                                                                    width=256)
Trainer Config
{
    "_target_": "random_resized_crop_and_pad",
    "scale_limit": List[float],  # scale 최소 최대 범위
    "aspect_ratio_limit": List[float],  # aspect_ratio 최소 최대 범위
    "height": Optional[int],  # crop 후 resize할 이미지 height (None인 경우 원본 height 사용)
    "width": Optional[int],  # crop 후 resize할 이미지 width (None인 경우 원본 width 사용)
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def random_resized_crop_and_pad(
    image: np.ndarray,
    scale: float = 1.0,
    aspect_ratio: float = 1.0,
    height: Optional[int] = None,
    width: Optional[int] = None,
) -> Tuple[np.ndarray, None]:
    """원본 image의 scale 비율의 면적을 가지면서 가로 세로 비가 aspect_ratio인 image를 random하게 crop 한 뒤,
       (crop image가 원본 image 보다 커지는 경우 padding을 통해 해결합니다.)
       크기가 (height, width)가 되도록 resize를 합니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        scale (float, optional): crop할 image의 면적을 나타내는 값입니다. 실제 면적은 [원본 이미지의 면적 * scale] 입니다.
                                 유효 범위는 다음과 같습니다. [0.01, 1.00]. Defaults to 1.0.
        aspect_ratio (float, optional): crop할 image의 가로 세로 비를 나타내는 값입니다.
                                        유효 범위는 다음과 같습니다. [0.10, 10.00]. Defaults to 1.0.
        height (int): crop image를 resize할 height 입니다. None인 경우 입력 이미지의 원본 height를 사용합니다.
        width (int): crop image를 resize할 width 입니다. None인 경우 입력 이미지의 원본 width를 사용합니다.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.random_resized_crop_and_pad(image=image,
                                                                            scale=0.5,
                                                                            aspect_ratio=2,
                                                                            height=256,
                                                                            width=256)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "random_resized_crop_and_pad",
            "scale_limit": List[float],  # scale 최소 최대 범위
            "aspect_ratio_limit": List[float],  # aspect_ratio 최소 최대 범위
            "height": Optional[int],  # crop 후 resize할 이미지 height (None인 경우 원본 height 사용)
            "width": Optional[int],  # crop 후 resize할 이미지 width (None인 경우 원본 width 사용)
        }
        ```
    """
    return (
        random_resized_crop_and_pad(
            image=image,
            scale=scale,
            aspect_ratio=aspect_ratio,
            h_start=0,
            w_start=0,
            height=height,
            width=width,
            resampling="bilinear",
            border_mode=cv2.BORDER_CONSTANT,
            value=0,
        ),
        None,
    )
light_reflect
light_reflect(image: ndarray, radius: float = 0.0) -> Tuple[ndarray, None]

image에 원형 빛을 비춘 것 같은 효과를 줍니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • radius (float, default: 0.0 ) –

    원형 빛의 반지름 크기 입니다. 유효 범위는 다음과 같습니다. [0.00, 1.00]. Defaults to 0.0.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • NoneType ( None ) –

    None

Example
error, augmented_image = ImageProcessor.light_reflect(image=image, radius=0.30)
Trainer Config
{
    "_target_": "light_reflect",
    "radius_limit": List[float],  # radius 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def light_reflect(image: np.ndarray, radius: float = 0.0) -> Tuple[np.ndarray, None]:
    """image에 원형 빛을 비춘 것 같은 효과를 줍니다.

    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        radius (float, optional): 원형 빛의 반지름 크기 입니다. 유효 범위는 다음과 같습니다. [0.00, 1.00]. Defaults to 0.0.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        NoneType: None

    Example:
        ```python
        error, augmented_image = ImageProcessor.light_reflect(image=image, radius=0.30)
        ```

    Trainer Config:
        ```python
        {
            "_target_": "light_reflect",
            "radius_limit": List[float],  # radius 최소 최대 범위
        }
        ```
    """
    return (
        light_reflect(image=image, xc=0.5, yc=0.5, x_radius=radius, y_radius=radius, angle=0),
        None,
    )
perspective_transform
perspective_transform(image: ndarray, intensity: Optional[int] = 0, fixed_aug_params: Optional[Dict] = None) -> Tuple[ndarray, Dict]

이미지를 투영 변환(Perspective Transform)합니다. image를 다른 각도(시점)에서 바라본 형태로 변환합니다. Perspective Transform 을 위한 네개의 도착점의 좌표 (offset)은 다음과 같이 샘플링됩니다. offset_top_left: 원본 이미지의 좌측 상단 모서리를 얼마만큼 중심부로 이동시킬 지에 대한 실수 값이 들어있습니다. 즉, Perspective Transform 의 좌측 상단점의 도착점은 아래와 같이 계산할 수 있습니다.

```
x` = 0 + width * offset_top_left[0]
y` = 0 + height * offset_top_left[1]
point_dst = (x`, y`)
```
offset_bottom_right

offset_top_left 와 동일하되 우측 하단 점을 나타냅니다. Perspective Transform 의 우측 하단점의 도착점은 아래와 같이 계산할 수 있습니다.

x` = width - width * offset_bottom_right[0]
y` = height - height * offset_bottom_right[1]
point_dst = (x`, y`)

offset_top_right: offset_top_left 와 동일하되 우측 상단 점을 나타냅니다. offset_bottom_left: offset_top_left 와 동일하되 좌측 하단 점을 나타냅니다.

Parameters:

  • image (ndarray) –

    augmentation을 적용할 image 입니다.

    data type: uint8
    channel: H x W / H x W x 1  - Gray
             H x W x 3 - RGB
             H x W x 4 - RGBA
    

  • intensity (int, default: 0 ) –

    perspective transform 을 적용 강도(단위: 백분율)입니다. intensity 범위 내에서 랜덤한 값으로 샘플된 네개의 offset 을 이용해 perspective transform 을 수행합니다. 유효 범위는 [0, 49] 로, 각 도착지 점들은 이미지의 중간 선을 지나칠 수 없습니다. 이를 통해 이미지가 반전되는 정도의 왜곡을 방지합니다. Defaults to 0. (fixed_aug_params=None일 때만 작동합니다.)

  • fixed_aug_params (Dict, default: None ) –

    각 꼭짓점에 대해서 offset 비율을 직접 정해주고자 할 때 사용합니다.

Returns:

  • ndarray

    np.ndarray: augmentation이 적용된 image 입니다.

  • Dict ( Dict ) –

    각 꼭짓점에 적용된 offset들입니다.

    {
        "offset_top_left": Tuple[float, float],
        "offset_top_right": Tuple[float, float],
        "offset_bottom_right": Tuple[float, float],
        "offset_bottom_left": Tuple[float, float],
    }
    

각 꼭짓점의 offset 비율을 직접 설정
error, augmented_image = ImageProcessor.perspective_transform(
    image=image,
    fixed_aug_params={
        "offset_top_left": (25.0, 30.0),
        "offset_top_right": (10.0, 40.0),
        "offset_bottom_right": (0.0, 20.0),
        "offset_bottom_left": (20.0, 35.0),
    }
)
각 꼭짓점에 [0, intensity] 범위에서 랜덤하게 offset 비율을 적용
error, augmented_image = ImageProcessor.perspective_transform(
    image=image,
    intensity=10,
)
Trainer Config
{
    "_target_": "perspective_transform",
    "intensity_limit": List[float],  # intensity 최소 최대 범위
}
Source code in SaigeToolkit/data/transform/augmentation/api.py
def perspective_transform(
    image: np.ndarray,
    intensity: Optional[int] = 0,
    fixed_aug_params: Optional[Dict] = None,
) -> Tuple[np.ndarray, Dict]:
    """이미지를 투영 변환(Perspective Transform)합니다. image를 다른 각도(시점)에서 바라본 형태로 변환합니다.
    Perspective Transform 을 위한 네개의 도착점의 좌표 (offset)은 다음과 같이 샘플링됩니다.
    offset_top_left:
        원본 이미지의 좌측 상단 모서리를 얼마만큼 중심부로 이동시킬 지에 대한 실수 값이 들어있습니다.
        즉, Perspective Transform 의 좌측 상단점의 도착점은 아래와 같이 계산할 수 있습니다.

        ```
        x` = 0 + width * offset_top_left[0]
        y` = 0 + height * offset_top_left[1]
        point_dst = (x`, y`)
        ```

    offset_bottom_right:
        `offset_top_left` 와 동일하되 우측 하단 점을 나타냅니다.
        Perspective Transform 의 우측 하단점의 도착점은 아래와 같이 계산할 수 있습니다.

        ```
        x` = width - width * offset_bottom_right[0]
        y` = height - height * offset_bottom_right[1]
        point_dst = (x`, y`)
        ```

    offset_top_right: `offset_top_left` 와 동일하되 우측 상단 점을 나타냅니다.
    offset_bottom_left: `offset_top_left` 와 동일하되 좌측 하단 점을 나타냅니다.


    Args:
        image (np.ndarray): augmentation을 적용할 image 입니다.
            ```
            data type: uint8
            channel: H x W / H x W x 1  - Gray
                     H x W x 3 - RGB
                     H x W x 4 - RGBA
            ```
        intensity (int, optional): perspective transform 을 적용 강도(단위: 백분율)입니다.
            intensity 범위 내에서 랜덤한 값으로 샘플된 네개의 offset 을 이용해 perspective transform 을 수행합니다.
            유효 범위는 [0, 49] 로, 각 도착지 점들은 이미지의 중간 선을 지나칠 수 없습니다.
            이를 통해 이미지가 반전되는 정도의 왜곡을 방지합니다. Defaults to 0. (`fixed_aug_params=None`일 때만 작동합니다.)
        fixed_aug_params (Dict, optional): 각 꼭짓점에 대해서 offset 비율을 직접 정해주고자 할 때 사용합니다.

    Returns:
        np.ndarray: augmentation이 적용된 image 입니다.
        Dict: 각 꼭짓점에 적용된 offset들입니다.
            ```python
            {
                "offset_top_left": Tuple[float, float],
                "offset_top_right": Tuple[float, float],
                "offset_bottom_right": Tuple[float, float],
                "offset_bottom_left": Tuple[float, float],
            }
            ```

    Example1:  각 꼭짓점의 offset 비율을 직접 설정
        ```python
        error, augmented_image = ImageProcessor.perspective_transform(
            image=image,
            fixed_aug_params={
                "offset_top_left": (25.0, 30.0),
                "offset_top_right": (10.0, 40.0),
                "offset_bottom_right": (0.0, 20.0),
                "offset_bottom_left": (20.0, 35.0),
            }
        )
        ```

    Example2:  각 꼭짓점에 [0, intensity] 범위에서 랜덤하게 offset 비율을 적용
        ```python
        error, augmented_image = ImageProcessor.perspective_transform(
            image=image,
            intensity=10,
        )
        ```

    Trainer Config:
        ```python
        {
            "_target_": "perspective_transform",
            "intensity_limit": List[float],  # intensity 최소 최대 범위
        }
        ```
    """
    aug_param_keys = [
        "offset_top_left",
        "offset_top_right",
        "offset_bottom_right",
        "offset_bottom_left",
    ]
    if fixed_aug_params is None:
        check_value(intensity, 0, 49)
        fixed_aug_params = {
            k: tuple((random.uniform(0, intensity), random.uniform(0, intensity)))
            for k in aug_param_keys
        }
    else:
        for k in aug_param_keys:
            offset_x, offset_y = fixed_aug_params[k]
            check_value(offset_x, 0, 49)
            check_value(offset_y, 0, 49)

    return (
        perspective_transform(
            image=image,
            **fixed_aug_params,
        ),
        fixed_aug_params,
    )

augment_function

adjust_saturation
adjust_saturation(image: ImageType, saturation: float = 0.0) -> ImageType

adjust_saturation

Parameters:

  • image (ImageType) –

    입력 이미지

  • saturation (float, default: 0.0 ) –

    변형 강도, [-1.0, 1.0] 범위, Defaults to 0.0.

Returns:

  • ImageType ( ImageType ) –

    결과 이미지

Note

Ablumentation의 AF.shift_hsv()와 다른 알고리즘을 사용합니다. AF.shift_hsv()의 경우 색이 없는 픽셀을 붉은 색으로 변형합니다. 이 함수의 경우 색이 없는 픽셀은 변형하지 않습니다.

Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
@support_gray
@support_rgba
def adjust_saturation(image: ImageType, saturation: float = 0.0) -> ImageType:
    """adjust_saturation

    Args:
        image (ImageType): 입력 이미지
        saturation (float, optional): 변형 강도, [-1.0, 1.0] 범위, Defaults to 0.0.

    Returns:
        ImageType: 결과 이미지

    Note:
        Ablumentation의 AF.shift_hsv()와 다른 알고리즘을 사용합니다.
        AF.shift_hsv()의 경우 색이 없는 픽셀을 붉은 색으로 변형합니다.
        이 함수의 경우 색이 없는 픽셀은 변형하지 않습니다.

    """
    check_value(saturation, -1.00, 1.00)
    saturation = (saturation + 1) ** 2
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    result = image * saturation + gray[..., None] * (1 - saturation)

    dtype = image.dtype
    if dtype == np.uint8:
        result = np.clip(result, 0, 255)
    elif dtype == np.uint16:
        result = np.clip(result, 0, 65535)
    result = result.astype(dtype)

    return result
random_resized_crop
random_resized_crop(image: ImageType, h_scale: float = 1.0, w_scale: float = 1.0, h_start: float = 0.0, w_start: float = 0.0, resampling: str = 'bilinear') -> Union[ImageType, MaskType]

Crop the given image to given scale and then resize it to original size.

Parameters:

  • image (ImageType) –

    original image

  • h_scale (float, default: 1.0 ) –

    crop height scale. Defaults to 1.0.

  • w_scale (float, default: 1.0 ) –

    crop width scale. Defaults to 1.0.

  • h_start (float, default: 0.0 ) –

    crop height start ratio. Defaults to 0.0.

  • w_start (float, default: 0.0 ) –

    crop width start ratio. Defaults to 0.0.

  • resampling (str, default: 'bilinear' ) –

    interpolation method. Defaults to "bilinear".

Returns:

Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
def random_resized_crop(
    image: ImageType,
    h_scale: float = 1.0,
    w_scale: float = 1.0,
    h_start: float = 0.0,
    w_start: float = 0.0,
    resampling: str = "bilinear",
) -> Union[ImageType, MaskType]:
    """Crop the given image to given scale and then resize it to original size.

    Args:
        image (ImageType): original image
        h_scale (float, optional): crop height scale. Defaults to 1.0.
        w_scale (float, optional): crop width scale. Defaults to 1.0.
        h_start (float, optional): crop height start ratio. Defaults to 0.0.
        w_start (float, optional): crop width start ratio. Defaults to 0.0.
        resampling (str, optional): interpolation method. Defaults to "bilinear".

    Returns:
        Union[ImageType, MaskType]: augmented data
    """
    check_value(h_scale, 0.01, 1.00)
    check_value(w_scale, 0.01, 1.00)
    check_value(h_start, 0.00, 1.00)
    check_value(w_start, 0.00, 1.00)

    h_original, w_original = image.shape[:2]
    target_height = int(round(h_original * h_scale))
    target_width = int(round(w_original * w_scale))

    # crop
    image = AFCrops.random_crop(
        img=image,
        crop_height=target_height,
        crop_width=target_width,
        h_start=min(h_start, 1.0 - 1e-5),
        w_start=min(w_start, 1.0 - 1e-5),
    )

    # resize
    target_size = (w_original, h_original)
    image = resize_image(image, target_size, resampling)

    return image
calculate_transform_matrix
calculate_transform_matrix(width: int, height: int, offset_top_left: OffsetType, offset_top_right: OffsetType, offset_bottom_right: OffsetType, offset_bottom_left: OffsetType) -> ndarray

Calculates the perspective transformation matrix using the given width, height, and corner points of a rectangle.

Parameters:

  • width (int) –

    Width of the original image.

  • height (int) –

    Height of the original image.

  • offset_top_left (OffsetType) –

    The offset ratio of the top-left corner point. Represented by the coordinates (x, y) and has a range of [0, 49]. Calculate xand y according to the procedure below.

    x` = width * offset_top_left[0]
    y` = height * offset_top_left[1]
    
  • offset_bottom_right (OffsetType) –

    The offset ratio of the bottom-right corner point. Calculate xand y according to the procedure below.

    x` = width - width * offset_bottom_right[0]
    y` = hegiht - height * offset_bottom_right[1]
    
  • offset_top_right (OffsetType) –

    The offset ratio of the top-left corner point.

  • offset_bottom_left (OffsetType) –

    The offset ratio of the bottom-left corner point.

Returns:

  • ndarray

    np.ndarray: The 4x3 perspective transform matrix.

Source code in SaigeToolkit/data/transform/augmentation/augment_function.py
def calculate_transform_matrix(
    width: int,
    height: int,
    offset_top_left: OffsetType,
    offset_top_right: OffsetType,
    offset_bottom_right: OffsetType,
    offset_bottom_left: OffsetType,
) -> np.ndarray:
    """
    Calculates the perspective transformation matrix
    using the given width, height, and corner points of a rectangle.

    Parameters:
        width (int): Width of the original image.
        height (int): Height of the original image.
        offset_top_left (OffsetType):
            The offset ratio of the top-left corner point.
            Represented by the coordinates (x, y) and has a range of [0, 49].
            Calculate x` and y` according to the procedure below.

            ```
            x` = width * offset_top_left[0]
            y` = height * offset_top_left[1]
            ```

        offset_bottom_right (OffsetType):
            The offset ratio of the bottom-right corner point.
            Calculate x` and y` according to the procedure below.

            ```
            x` = width - width * offset_bottom_right[0]
            y` = hegiht - height * offset_bottom_right[1]
            ```

        offset_top_right (OffsetType): The offset ratio of the top-left corner point.
        offset_bottom_left (OffsetType): The offset ratio of the bottom-left corner point.

    Returns:
        np.ndarray: The 4x3 perspective transform matrix.

    """
    points_from = np.float32([[0, 0], [width, 0], [width, height], [0, height]])

    point_top_left: OffsetType = (
        (offset_top_left[0] / 100) * width,
        (offset_top_left[1] / 100) * height,
    )
    point_top_right: OffsetType = (
        width - (offset_top_right[0] / 100) * width,
        (offset_top_right[1] / 100) * height,
    )
    point_bottom_right: OffsetType = (
        width - (offset_bottom_right[0] / 100) * width,
        height - (offset_bottom_right[1] / 100) * height,
    )
    point_bottom_left: OffsetType = (
        (offset_bottom_left[0] / 100) * width,
        height - (offset_bottom_left[1] / 100) * height,
    )
    points_to = np.float32(
        [
            point_top_left,
            point_top_right,
            point_bottom_right,
            point_bottom_left,
        ]
    )
    transform_matrix = cv2.getPerspectiveTransform(points_from, points_to)

    return transform_matrix

augment_transform

Implement ImageTransform classes for image augmentation.

ImageTransform
ImageTransform(prob: float = 0.5)

Bases: BaseTransform

Image와 라벨에 적용되는 Transform 입니다.

Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
def __init__(self, prob: float = 0.5) -> None:
    self.prob = prob
    self._additional_targets = {}
RatioJitter
RatioJitter(proportion_limit: Optional[Union[List[float], int, float]] = None, resampling: str = 'bilinear', border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0, mask_value: Union[int, float] = 0, **kwargs)

Bases: ImageSizeParams, ImageTransform

crop, pad, and resize to original image size

Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
def __init__(
    self,
    proportion_limit: Optional[Union[List[float], int, float]] = None,
    resampling: str = "bilinear",
    border_mode: int = cv2.BORDER_CONSTANT,
    value: Union[int, float, List[int], List[float]] = 0,
    mask_value: Union[int, float] = 0,
    **kwargs,
) -> None:
    super().__init__(**kwargs)

    if proportion_limit is None:
        proportion_limit = [-0.10, 0.10]

    if isinstance(proportion_limit, int):
        # NOTE: int 입력은 백분율로 적용.
        proportion_limit = [-abs(proportion_limit) / 100, abs(proportion_limit) / 100]

    if isinstance(proportion_limit, float):
        # NOTE: float 입력은 0~1 스케일로 적용.
        proportion_limit = [-abs(proportion_limit), abs(proportion_limit)]

    check_range(proportion_limit, -0.50, 0.50)

    self.proportion_limit = proportion_limit
    self.resampling = resampling
    self.border_mode = border_mode
    self.value = value
    self.mask_value = mask_value
RandomResizedCrop
RandomResizedCrop(scale_limit: Optional[List[float]] = None, aspect_ratio_limit: Optional[List[float]] = None, resampling: str = 'bilinear', **kwargs)

Bases: ImageSizeParams, ImageTransform

Crop a random part of the input and rescale it to original size

Parameters:

  • scale_limit (Optional[List[float]], default: None ) –

    range of size of the origin size cropped. Defaults to [0.45, 1.00].

  • aspect_ratio_limit (Optional[List[float]], default: None ) –

    range of aspect ratio of the origin aspect ratio cropped. Defaults to [0.50, 2.00].

  • resampling (str, default: 'bilinear' ) –

    interpolation method. Defaults to "bilinear".

Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
def __init__(
    self,
    scale_limit: Optional[List[float]] = None,
    aspect_ratio_limit: Optional[List[float]] = None,
    resampling: str = "bilinear",
    **kwargs,
) -> None:
    """
    Args:
        scale_limit (Optional[List[float]], optional): range of size of the origin size cropped. Defaults to [0.45, 1.00].
        aspect_ratio_limit (Optional[List[float]], optional): range of aspect ratio of the origin aspect ratio cropped. Defaults to [0.50, 2.00].
        resampling (str, optional): interpolation method. Defaults to "bilinear".
    """
    super().__init__(**kwargs)

    if scale_limit is None:
        scale_limit = [0.45, 1.00]
    if aspect_ratio_limit is None:
        aspect_ratio_limit = [0.50, 2.00]

    check_range(scale_limit, 0.01, 1.00)
    check_range(aspect_ratio_limit, 0.10, 10.00)

    self.scale_limit = scale_limit
    self.aspect_ratio_limit = aspect_ratio_limit
    self.resampling = resampling
RandomResizedCropAndPad
RandomResizedCropAndPad(scale_limit: Optional[List[float]] = None, aspect_ratio_limit: Optional[List[float]] = None, height: Optional[int] = None, width: Optional[int] = None, resampling: str = 'bilinear', border_mode: int = cv2.BORDER_CONSTANT, value: Union[int, float, List[int], List[float]] = 0, mask_value: Union[int, float] = 0, **kwargs)

Bases: ImageSizeParams, ImageTransform

pad, crop and resize to original image size

Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
def __init__(
    self,
    scale_limit: Optional[List[float]] = None,
    aspect_ratio_limit: Optional[List[float]] = None,
    height: Optional[int] = None,
    width: Optional[int] = None,
    resampling: str = "bilinear",
    border_mode: int = cv2.BORDER_CONSTANT,
    value: Union[int, float, List[int], List[float]] = 0,
    mask_value: Union[int, float] = 0,
    **kwargs,
) -> None:
    super().__init__(**kwargs)

    if scale_limit is None:
        scale_limit = [0.45, 1.00]
    if aspect_ratio_limit is None:
        aspect_ratio_limit = [0.50, 2.00]

    check_range(scale_limit, 0.01, 1.00)
    check_range(aspect_ratio_limit, 0.10, 10.00)

    self.height = height
    self.width = width
    self.scale_limit = scale_limit
    self.aspect_ratio_limit = aspect_ratio_limit
    self.resampling = resampling
    self.border_mode = border_mode
    self.value = value
    self.mask_value = mask_value
RandomErasing
RandomErasing(scale: Tuple[float, float] = (0.02, 0.33), ratio: Tuple[float, float] = (0.2, 3.3), value: Union[int, Tuple[int, int, int], str] = 0, randomly_select_values: bool = False, **kwargs)

Bases: ImageTransform

Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
def __init__(
    self,
    scale: Tuple[float, float] = (0.02, 0.33),
    ratio: Tuple[float, float] = (0.2, 3.3),
    value: Union[int, Tuple[int, int, int], str] = 0,
    randomly_select_values: bool = False,
    **kwargs,
) -> None:
    super().__init__(**kwargs)
    self.scale = scale
    self.ratio = ratio
    self._value = value
    self.randomly_select_values = randomly_select_values
_get_random_erase_params
_get_random_erase_params()

This is modified version of get_params of random erasing see: https://pytorch.org/vision/main/_modules/torchvision/transforms/transforms.html#RandomErasing.forward

Source code in SaigeToolkit/data/transform/augmentation/augment_transform.py
def _get_random_erase_params(self):
    """
    This is modified version of get_params of random erasing
    see: https://pytorch.org/vision/main/_modules/torchvision/transforms/transforms.html#RandomErasing.forward
    """
    area = 1

    log_ratio = torch.log(torch.tensor(self.ratio))
    for _ in range(10):
        erase_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item()
        aspect_ratio = torch.exp(torch.empty(1).uniform_(log_ratio[0], log_ratio[1])).item()

        h_in_ratio = math.sqrt(erase_area * aspect_ratio)
        w_in_ratio = math.sqrt(erase_area / aspect_ratio)

        if not (h_in_ratio < 1 and w_in_ratio < 1):
            continue

        x_in_ratio = random.uniform(0, 1 - w_in_ratio)
        y_in_ratio = random.uniform(0, 1 - h_in_ratio)

        return x_in_ratio, y_in_ratio, h_in_ratio, w_in_ratio

    # Return Original Image
    return 0, 0, 1.0, 1.0

base_transform

Data augmentation을 위한 기본 Transform의 interface를 정의합니다.

BaseTransform
BaseTransform(prob: float = 0.5)

Transform의 기본 interface를 정의합니다.

Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
def __init__(self, prob: float = 0.5) -> None:
    self.prob = prob
    self._additional_targets = {}
get_params_from_data
get_params_from_data(data_for_params: ParamsType) -> ParamsType

이 함수는 input으로부터 parameter들을 뽑을 때 사용됩니다.

Parameters:

  • data_for_params (ParamsType) –

    params을 추출할 데이터를 입력으로 갖습니다.

Returns:

  • ParamsType ( ParamsType ) –

    params로 쓰일 데이터를 반환합니다.

Source code in SaigeToolkit/data/transform/augmentation/base_transform.py
def get_params_from_data(self, data_for_params: ParamsType) -> ParamsType:
    """이 함수는 input으로부터 parameter들을 뽑을 때 사용됩니다.

    Args:
        data_for_params (ParamsType): params을 추출할 데이터를 입력으로 갖습니다.

    Returns:
        ParamsType: params로 쓰일 데이터를 반환합니다.
    """
    return {}

builder

compose

여러 Data Transform들을 하나로 묶어서 관리해주는 기본 BaseCompose 클래스 및 Compose 구현을 제공합니다.

base_compose

Data augmentation을 위한 기본 Compose의 interface를 정의합니다.

BaseCompose
BaseCompose(transforms: Sequence[Union[BaseTransform, BaseCompose]], prob: float = 1.0)

여러 Data Transform들을 하나로 묶어서 관리해주는 Compose의 기본 interface를 정의합니다.

Source code in SaigeToolkit/data/transform/augmentation/compose/base_compose.py
def __init__(
    self, transforms: Sequence[Union[BaseTransform, BaseCompose]], prob: float = 1.0
) -> None:
    self.transforms = transforms
    self.prob = prob
builder
compose

box_function

preserve_coordinates

preserve_coordinates(func)

Box augmentation이 (left, top, right, bottom) coordinate system을 기반으로 구현 되어있기 때문에, input bboxes의 coordinate system을 확인하고 augmentation에 맞는 coordinate system으로 변환하고, augmentation이 끝나면 다시 기존 coordinate system으로 변경하여 출력합니다.

  • np.ndarray의 경우 coordinate system을 체크할 수 없기 때문에 (left, top, right, bottom) coordinate system이라고 가정합니다.

  • NumpyBBoxes의 경우 NumpyBBoxes 내부 변수 coordinate과 내부 함수 convert_coordinate를 활용하여 구현됩니다.

Source code in SaigeToolkit/data/transform/box_function.py
def preserve_coordinates(func):
    """
    Box augmentation이 (left, top, right, bottom) coordinate system을 기반으로 구현 되어있기 때문에,
    input bboxes의 coordinate system을 확인하고 augmentation에 맞는 coordinate system으로 변환하고,
    augmentation이 끝나면 다시 기존 coordinate system으로 변경하여 출력합니다.

    - np.ndarray의 경우
    coordinate system을 체크할 수 없기 때문에 (left, top, right, bottom) coordinate system이라고 가정합니다.

    - NumpyBBoxes의 경우
    NumpyBBoxes 내부 변수 coordinate과 내부 함수 convert_coordinate를 활용하여 구현됩니다.

    """
    _FUNCTIONAL_BBOX_COORDINATE = "xyxy"

    def wrapped_function_for_ndarray(bboxes: np.ndarray, *args, **kwargs) -> np.ndarray:
        new_bboxes = func(bboxes, *args, **kwargs)

        return new_bboxes

    def wrapped_function_for_numpyboxes(bboxes: NumpyBoxes, *args, **kwargs) -> NumpyBoxes:
        # original coordinate -> (left, top, right, bottom)
        original_coordinate = bboxes.coordinate  # record original coordinate
        bboxes = bboxes.convert_coordinate(_FUNCTIONAL_BBOX_COORDINATE)  # -> (left, top, right, bottom)

        # box augmentation
        new_bboxes = func(bboxes, *args, **kwargs)
        if not isinstance(new_bboxes, bboxes.__class__):
            new_bboxes = bboxes.__class__(new_bboxes, _FUNCTIONAL_BBOX_COORDINATE)

        # (left, top, right, bottom) -> original coordinate
        new_bboxes = new_bboxes.convert_coordinate(original_coordinate)

        return new_bboxes

    @wraps(func)
    def wrapped_function(bboxes: BBoxesType, *args, **kwargs) -> BBoxesType:
        # isinstance가 상속된 type도 true를 return 하기 때문에 여기서는 type(instance) == class로 체크
        if isinstance(bboxes, NumpyBoxes):
            new_bboxes = wrapped_function_for_numpyboxes(bboxes, *args, **kwargs)
        elif isinstance(bboxes, np.ndarray):
            new_bboxes = wrapped_function_for_ndarray(bboxes, *args, **kwargs)
        else:
            raise NotImplementedError

        return new_bboxes

    return wrapped_function

resize_box

resize_box(bboxes: BBoxesType, image_size: Tuple[int], tw: int, th: int) -> BBoxesType

bbox resize from (w, h) to (tw, th)

Source code in SaigeToolkit/data/transform/box_function.py
@preserve_coordinates
def resize_box(bboxes: BBoxesType, image_size: Tuple[int], tw: int, th: int) -> BBoxesType:
    """bbox resize from (w, h) to (tw, th)"""
    dtype = bboxes.dtype
    w, h = image_size
    if w == tw and h == th:
        return bboxes
    else:
        w_scale = tw / w
        h_scale = th / h
        return (bboxes * (w_scale, h_scale, w_scale, h_scale)).astype(dtype)

crop_box

crop_box(bboxes: BBoxesType, cropping_box: Union[ndarray, List[int]]) -> BBoxesType

bbox crop. An image is cropped at (new_left, new_top, new_right, new_bottom)

Source code in SaigeToolkit/data/transform/box_function.py
@preserve_coordinates
def crop_box(bboxes: BBoxesType, cropping_box: Union[np.ndarray, List[int]]) -> BBoxesType:
    """bbox crop. An image is cropped at (new_left, new_top, new_right, new_bottom)"""
    dtype = bboxes.dtype
    new_left, new_top, new_right, new_bottom = map(round, cropping_box)
    new_h = new_bottom - new_top
    new_bboxes = bboxes - (new_left, new_top, new_left, new_top)
    new_bboxes[:, [0, 1]] = np.maximum(new_bboxes[:, [0, 1]], 0)
    new_bboxes[:, [2, 3]] = np.minimum(new_bboxes[:, [2, 3]], (new_right - new_left, new_h))
    return new_bboxes.astype(dtype)

function_util

Define utility functions for data augmentation.

image_function

read_image_size

read_image_size(image: Union[Image, Tensor, ndarray]) -> ImageSizeType

image size: (W, H)

Source code in SaigeToolkit/data/transform/image_function.py
def read_image_size(image: Union[Image.Image, torch.Tensor, np.ndarray]) -> ImageSizeType:
    """image size: (W, H)"""
    if isinstance(image, Image.Image):
        return image.size
    elif isinstance(image, torch.Tensor) and image.ndim in (2, 3, 4):  # HW, CHW, BCHW
        return (image.shape[-1], image.shape[-2])
    elif isinstance(image, np.ndarray) and image.ndim in (2, 3):  # HW, HWC
        return (image.shape[1], image.shape[0])
    else:
        raise NotImplementedError

resize_image

resize_image(image: Union[Image, Tensor, ndarray], target_size: ImageSizeType, resampling: str = 'bilinear', use_cv2_for_numpy: bool = True) -> Union[Image, Tensor, ndarray]

이미지를 resize합니다.

Parameters:

  • image (Union[Image, Tensor, ndarray]) –

    image data

  • target_size (ImageSizeType) –

    [W, H]

  • resampling (str, default: 'bilinear' ) –

    resampling method. Defaults to "bilinear".

  • use_cv2_for_numpy (bool, default: True ) –

    use cv2 instead of PIL for faster numpy array image resizing. Defaults to True.

Returns:

  • Union[Image, Tensor, ndarray]

    Union[Image.Image, torch.Tensor, np.ndarray]: resized image

Source code in SaigeToolkit/data/transform/image_function.py
def resize_image(
    image: Union[Image.Image, torch.Tensor, np.ndarray],
    target_size: ImageSizeType,
    resampling: str = "bilinear",
    use_cv2_for_numpy: bool = True,
) -> Union[Image.Image, torch.Tensor, np.ndarray]:
    """이미지를 resize합니다.

    Args:
        image (Union[Image.Image, torch.Tensor, np.ndarray]): image data
        target_size (ImageSizeType): [W, H]
        resampling (str): resampling method. Defaults to "bilinear".
        use_cv2_for_numpy (bool): use cv2 instead of PIL for faster numpy array image resizing. Defaults to True.

    Returns:
        Union[Image.Image, torch.Tensor, np.ndarray]: resized image
    """
    if isinstance(image, Image.Image):
        image = image.resize(target_size, RESAMPLE_PIL[resampling])
    elif isinstance(image, torch.Tensor):  # CHW, BCHW
        is_three_dim = image.ndim == 3
        if is_three_dim:  # CHW -> 1CHW
            image = image.unsqueeze(0)
        image = torch.nn.functional.interpolate(
            image,
            size=(target_size[1], target_size[0]),
            mode=RESAMPLE_TORCH[resampling],
            antialias=None if resampling == "nearest" else True,
        )
        if is_three_dim:
            image = image.squeeze(0)
    elif isinstance(image, np.ndarray):  # HWC, HW
        if use_cv2_for_numpy:
            # NOTE: cv2 resize is different from PIL/torch (inaccurate but fast)
            image = cv2.resize(image, dsize=target_size, interpolation=RESAMPLE_CV2[resampling])
        else:
            is_single_channel = image.ndim == 3 and image.shape[-1] == 1
            if is_single_channel:
                image = image[:, :, 0]
            image = Image.fromarray(image)
            image = image.resize(target_size, RESAMPLE_PIL[resampling])
            image = np.array(image)
            if is_single_channel:
                image = image[:, :, np.newaxis]
    return image

resize_mask

resize_mask(mask: Union[Image, Tensor, ndarray], target_size: ImageSizeType) -> Union[Image, Tensor, ndarray]

mask 이미지를 resize합니다. (NEAREST resampling)

Parameters:

  • mask (Union[Image, Tensor, ndarray]) –

    mask image

  • target_size (ImageSizeType) –

    [W, H]

Returns:

  • Union[Image, Tensor, ndarray]

    Union[Image.Image, torch.Tensor, np.ndarray]: resized mask image

Source code in SaigeToolkit/data/transform/image_function.py
def resize_mask(
    mask: Union[Image.Image, torch.Tensor, np.ndarray],
    target_size: ImageSizeType,
) -> Union[Image.Image, torch.Tensor, np.ndarray]:
    """mask 이미지를 resize합니다. (NEAREST resampling)

    Args:
        mask (Union[Image.Image, torch.Tensor, np.ndarray]): mask image
        target_size (ImageSizeType): [W, H]

    Returns:
        Union[Image.Image, torch.Tensor, np.ndarray]: resized mask image
    """
    if isinstance(mask, Image.Image):
        mask = mask.resize(target_size, Image.Resampling.NEAREST)
    elif isinstance(mask, torch.Tensor):  # HW, BHW
        is_two_dim = mask.ndim == 2
        if is_two_dim:  # HW -> 1HW
            mask = mask.unsqueeze(0)
        mask = torch.nn.functional.interpolate(
            mask.unsqueeze(1),  # BHW -> B1HW
            size=(target_size[1], target_size[0]),
            mode="nearest-exact",
        ).squeeze(1)
        if is_two_dim:
            mask = mask.squeeze(0)
    elif isinstance(mask, np.ndarray):  # HW
        mask = Image.fromarray(mask)
        mask = mask.resize(target_size, Image.Resampling.NEAREST)
        mask = np.array(mask)
    return mask

resize_array

resize_array(array: Union[Tensor, ndarray], target_size: ImageSizeType, resampling: str = 'nearest') -> Union[Tensor, ndarray]

[HW, BHW]의 array를 resize합니다.

Parameters:

  • array (Union[Tensor, ndarray]) –

    array data [HW, BHW]

  • target_size (ImageSizeType) –

    [W, H]

  • resampling (str, default: 'nearest' ) –

    resampling method. Defaults to "nearest".

Returns:

  • Union[Tensor, ndarray]

    Union[torch.Tensor, np.ndarray]: resized array

Source code in SaigeToolkit/data/transform/image_function.py
def resize_array(
    array: Union[torch.Tensor, np.ndarray],
    target_size: ImageSizeType,
    resampling: str = "nearest",
) -> Union[torch.Tensor, np.ndarray]:
    """[HW, BHW]의 array를 resize합니다.

    Args:
        array (Union[torch.Tensor, np.ndarray]): array data [HW, BHW]
        target_size (ImageSizeType): [W, H]
        resampling (str, optional): resampling method. Defaults to "nearest".

    Returns:
        Union[torch.Tensor, np.ndarray]: resized array
    """
    is_np_array = isinstance(array, np.ndarray)
    if is_np_array:  # np.ndarray -> torch.Tensor
        array = torch.tensor(array)

    is_two_dim = array.ndim == 2
    if is_two_dim:  # HW -> 1HW
        array = array.unsqueeze(0)

    array = torch.nn.functional.interpolate(
        array.unsqueeze(1),  # BHW -> B1HW
        size=(target_size[1], target_size[0]),
        mode=RESAMPLE_TORCH[resampling],
        antialias=None if resampling == "nearest" else True,
    ).squeeze(1)

    if is_two_dim:  # 1HW -> HW
        array = array.squeeze(0)

    if is_np_array:  # torch.Tensor -> np.ndarray
        array = array.numpy()

    return array

crop

crop(image: Union[Image, Tensor, ndarray], coordinates: Union[List[int], Tuple[int, int, int, int]]) -> Union[Image, Tensor, ndarray]

이미지의 coordinates 좌표영역을 크롭합니다. coordinates가 이미지를 벗어나는 경우 zero padding 합니다.

Parameters:

  • image (Union[Image, Tensor, ndarray]) –

    image

  • coordinates (Union[List[int], Tuple[int, int, int, int]]) –

    [left, top, right, bottom]

Returns:

  • Union[Image, Tensor, ndarray]

    Union[Image.Image, torch.Tensor, np.ndarray]: cropped image

Source code in SaigeToolkit/data/transform/image_function.py
def crop(
    image: Union[Image.Image, torch.Tensor, np.ndarray],
    coordinates: Union[List[int], Tuple[int, int, int, int]],
) -> Union[Image.Image, torch.Tensor, np.ndarray]:
    """이미지의 coordinates 좌표영역을 크롭합니다. coordinates가 이미지를 벗어나는 경우 zero padding 합니다.

    Args:
        image (Union[Image.Image, torch.Tensor, np.ndarray]): image
        coordinates (Union[List[int], Tuple[int, int, int, int]]): [left, top, right, bottom]

    Returns:
        Union[Image.Image, torch.Tensor, np.ndarray]: cropped image
    """
    if isinstance(image, Image.Image):
        return image.crop(coordinates)
    else:
        left, top, right, bottom = coordinates
        image_w, image_h = read_image_size(image)
        cropped_shape = (bottom - top, right - left)
        if image.ndim == 3:
            cropped_shape = (*cropped_shape, image.shape[2])
        if isinstance(image, torch.Tensor):
            cropped_image = torch.zeros(*cropped_shape, dtype=image.dtype, device=image.device)
        else:
            cropped_image = np.zeros(cropped_shape, dtype=image.dtype)
        cropped_image[
            np.clip(0, top, bottom) - top : np.clip(image_h, top, bottom) - top,
            np.clip(0, left, right) - left : np.clip(image_w, left, right) - left,
        ] = image[
            np.clip(top, 0, image_h) : np.clip(bottom, 0, image_h),
            np.clip(left, 0, image_w) : np.clip(right, 0, image_w),
        ]
        return cropped_image

add_constant_margin

add_constant_margin(image: Union[Image, Tensor, ndarray], left: int, top: int, right: int, bottom: int, value: Union[float, int]) -> Union[Image, Tensor, ndarray]

image에 left, top, right, bottom 만큼 constant value로 padding 합니다.

Parameters:

  • image (Union[Image, Tensor, ndarray]) –

    image

  • left (int) –

    image의 왼쪽 padding size 입니다.

  • top (int) –

    image의 위쪽 padding size 입니다.

  • right (int) –

    image의 오른쪽 padding size 입니다.

  • bottom (int) –

    image의 아래쪽 padding size 입니다.

  • value (Union[float, int]) –

    padding된 영역에 들어갈 value 입니다.

Source code in SaigeToolkit/data/transform/image_function.py
def add_constant_margin(
    image: Union[Image.Image, torch.Tensor, np.ndarray],
    left: int,
    top: int,
    right: int,
    bottom: int,
    value: Union[float, int],
) -> Union[Image.Image, torch.Tensor, np.ndarray]:
    """image에 left, top, right, bottom 만큼 constant value로 padding 합니다.

    Args:
        image (Union[Image.Image, torch.Tensor, np.ndarray]): image
        left (int): image의 왼쪽 padding size 입니다.
        top (int): image의 위쪽 padding size 입니다.
        right (int): image의 오른쪽 padding size 입니다.
        bottom (int): image의 아래쪽 padding size 입니다.
        value (Union[float, int]): padding된 영역에 들어갈 value 입니다.
    """
    width, height = read_image_size(image)
    new_width = width + left + right
    new_height = height + top + bottom
    if isinstance(image, Image.Image):
        if image.mode == "RGB":
            value = [int(value)] * 3
        elif image.mode == "L":
            value = [int(value)]
        else:
            raise NotImplementedError
        result = Image.new(image.mode, (new_width, new_height), tuple(value))
        result.paste(image, (left, top))
    elif isinstance(image, np.ndarray):
        result = np.ones((new_height, new_width) + image.shape[2:]) * value
        result = result.astype(image.dtype)
        result[top : top + height, left : left + width] = image
    elif isinstance(image, torch.Tensor):
        result = torch.ones(image.shape[:-2] + (new_height, new_width), device=image.device) * value
        result = result.to(image.dtype)
        result[..., top : top + height, left : left + width] = image
    else:
        raise NotImplementedError

    return result

add_constant_margin_array

add_constant_margin_array(array: Union[Tensor, ndarray], left: int, top: int, right: int, bottom: int, value: Union[float, int]) -> Union[Tensor, ndarray]

array에 left, top, right, bottom 만큼 constant value로 padding 합니다.

Parameters:

  • array (Union[Tensor, ndarray]) –

    array data [HW, BHW]

  • left (int) –

    array의 왼쪽 padding size 입니다.

  • top (int) –

    array의 위쪽 padding size 입니다.

  • right (int) –

    array의 오른쪽 padding size 입니다.

  • bottom (int) –

    array의 아래쪽 padding size 입니다.

  • value (Union[float, int]) –

    padding된 영역에 들어갈 value 입니다.

Source code in SaigeToolkit/data/transform/image_function.py
def add_constant_margin_array(
    array: Union[torch.Tensor, np.ndarray],
    left: int,
    top: int,
    right: int,
    bottom: int,
    value: Union[float, int],
) -> Union[torch.Tensor, np.ndarray]:
    """array에 left, top, right, bottom 만큼 constant value로 padding 합니다.

    Args:
        array (Union[torch.Tensor, np.ndarray]): array data [HW, BHW]
        left (int): array의 왼쪽 padding size 입니다.
        top (int): array의 위쪽 padding size 입니다.
        right (int): array의 오른쪽 padding size 입니다.
        bottom (int): array의 아래쪽 padding size 입니다.
        value (Union[float, int]): padding된 영역에 들어갈 value 입니다.
    """
    if isinstance(array, np.ndarray):
        is_ndarray = True
        array = torch.from_numpy(array)
    else:
        is_ndarray = False

    result = torch.nn.functional.pad(array, (left, right, top, bottom), value=value)

    if is_ndarray:
        result = result.numpy(force=True)

    return result

fill_pixels_with_mask

fill_pixels_with_mask(image: Union[Image, ndarray], bool_mask: ndarray, value: Union[int, float] = 0) -> Union[Image, ndarray]

image 중 bool_mask=True인 픽셀들을 value로 채웁니다.

Parameters:

  • image (Union[Image, ndarray]) –

    image (HW or HWC)

  • bool_mask (ndarray) –

    boolean mask (HW)

  • value (Union[int, float], default: 0 ) –

    . Defaults to 0.

Returns:

  • Union[Image, ndarray]

    Union[Image.Image, np.ndarray]: 결과 이미지

Note
  • image가 Image.Image인 경우, 결과 이미지도 Image.Image로 반환합니다.
  • image의 값이 inplace로 변경됩니다. 값이 변경되지 않길 원한다면, copy를 해주세요.
Source code in SaigeToolkit/data/transform/image_function.py
def fill_pixels_with_mask(
    image: Union[Image.Image, np.ndarray],
    bool_mask: np.ndarray,
    value: Union[int, float] = 0,
) -> Union[Image.Image, np.ndarray]:
    """image 중 bool_mask=True인 픽셀들을 value로 채웁니다.

    Args:
        image (Union[Image.Image, np.ndarray]): image (HW or HWC)
        bool_mask (np.ndarray): boolean mask (HW)
        value (Union[int, float], optional): . Defaults to 0.

    Returns:
        Union[Image.Image, np.ndarray]: 결과 이미지

    Note:
        - image가 Image.Image인 경우, 결과 이미지도 Image.Image로 반환합니다.
        - image의 값이 inplace로 변경됩니다. 값이 변경되지 않길 원한다면, copy를 해주세요.
    """
    is_pil = isinstance(image, Image.Image)
    image = np.asarray(image)

    assert image.ndim in [2, 3] and image.shape[:2] == bool_mask.shape  # HW or HWC

    if image.ndim > bool_mask.ndim:  # max ndim difference is 1
        bool_mask = np.expand_dims(bool_mask, axis=-1)

    image = np.where(bool_mask, value, image)

    if is_pil:
        image = Image.fromarray(image)

    return image

convert_image_mode

convert_image_mode(image: Union[Image, ndarray], mode: str, copy: bool = False) -> Union[Image, ndarray]

convert image mode

Parameters:

  • image (Union[Image, ndarray]) –

    image

  • mode (str) –

    "RGB" or "L"

  • copy (bool, default: False ) –

    to copy data. Defaults to False.

Returns:

  • Union[Image, ndarray]

    Union[Image.Image, np.ndarray]: converted image

Note

RGB -> L 변환 시 Image.Image와 np.ndarray 연산 결과가 다를 수 있음. (PIL과 cv2 에서 변환식은 L = R * 299/1000 + G * 587/1000 + B * 114/1000 로 동일하나 소숫점 처리 방식이 다름)

Source code in SaigeToolkit/data/transform/image_function.py
def convert_image_mode(
    image: Union[Image.Image, np.ndarray], mode: str, copy: bool = False
) -> Union[Image.Image, np.ndarray]:
    """convert image mode

    Args:
        image (Union[Image.Image, np.ndarray]): image
        mode (str): "RGB" or "L"
        copy (bool, optional): to copy data. Defaults to False.

    Returns:
        Union[Image.Image, np.ndarray]: converted image

    Note:
        RGB -> L 변환 시 Image.Image와 np.ndarray 연산 결과가 다를 수 있음.
        (PIL과 cv2 에서 변환식은 L = R * 299/1000 + G * 587/1000 + B * 114/1000 로 동일하나 소숫점 처리 방식이 다름)
    """
    if mode not in IMAGE_MODES:
        raise NotImplementedError

    if isinstance(image, Image.Image):
        if image.mode != mode:
            image = image.convert(mode)
        elif copy:
            image = image.copy()
    elif isinstance(image, np.ndarray):
        # check original mode & regularize (RGB: HW3 / L: HW)
        if image.ndim == 3:
            if image.shape[2] == 3:
                original_mode = "RGB"
            elif image.shape[2] == 1:
                original_mode = "L"
                image = image[:, :, 0]  # HW1 -> HW (no copy)
            elif image.shape[2] == 4:
                original_mode = "RGB"
                image = image[:, :, :3]  # RGBA -> RGB (no copy)
            else:
                raise NotImplementedError
        elif image.ndim == 2:
            original_mode = "L"
        else:
            raise NotImplementedError
        # convert
        if original_mode == "RGB" and mode == "L":
            image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
        elif original_mode == "L" and mode == "RGB":
            image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
        elif copy:
            image = image.copy()
    else:
        raise NotImplementedError
    return image

image_load

ImageLoader

ImageLoader(image_mode: Union[str, List[str]] = 'RGB', to_numpy: bool = True)

여러 형태의 데이터를 입력으로 받아, 전처리 과정을 거쳐 PIL Image 혹은 np.ndarray 로 return 합니다. 현재 지원하는 데이터는 다음과 같습니다. - 데이터 타입: [image path, np.ndarray, PIL Image] - color: ["RGB", "Gray"] - bit: [8, 16]

입력으로 받은 데이터에 따른 출력값은 다음과 같습니다. | image path | np.ndarray | PIL | RGB; 8 | PIL(RGB;8) | PIL(RGB;8) | PIL(RGB;8) | RGB;16 | PIL(RGB;8) | PIL(RGB;8) | - | Gray; 8 | PIL(L;8) | PIL(L;8) | PIL(L;8) | Gray;16 | PIL(L;8) | PIL(L;8) | PIL(L;8) |

Note1

PIL은 RGB;16을 지원하지 않습니다. 따라서 PIL(RGB;16)은 입력으로 들어올 수 없습니다.

Note2

PIL은 "I;16" 모드로 Gray;16을 지원하지만, PIL 내부의 convert 함수를 써서 Gray;8로 변환시 값이 overflow 나는 issue가 있습니다.

Note3

이미지는 기본적으로 np.ndarray로 로드되며, PIL.Image.Image로 로드하려면 to_numpy=False를 세팅하세요.

Note4

image_mode는 "RGB", "L" 중 하나를 지원하며, multipage (이미지 리스트) 인 경우 각 페이지의 모드를 리스트로 입력하세요. 예시: 1, 3번째 페이지는 RGB 이고 2번째 페이지는 L 인 경우 image_mode = ["RGB", "L", "RGB"]

Source code in SaigeToolkit/data/transform/image_load.py
def __init__(self, image_mode: Union[str, List[str]] = "RGB", to_numpy: bool = True) -> None:
    if isinstance(image_mode, str):
        image_mode = [image_mode]
    elif not set(image_mode).issubset(set(IMAGE_MODES)):
        raise ValueError
    self.image_mode = image_mode
    self.to_numpy = to_numpy
call_method
call_method(image: Union[Image, ndarray, str, List], **data) -> Dict

make [PIL Image or np.ndarray] from PIL.Image, np.ndarray, or path string

Parameters:

  • image (Union[Image, ndarray, str, List]) –

    PIL.Image, array, path string or list of it.

Returns:

  • Dict ( Dict ) –

    { "image": Union[PIL.Image.Image, np.ndarray, List[PIL.Image.Image], List[np.ndarray]], **input_dict, }

Source code in SaigeToolkit/data/transform/image_load.py
def call_method(self, image: Union[Image.Image, np.ndarray, str, List], **data) -> Dict:
    """make [PIL Image or np.ndarray] from PIL.Image, np.ndarray, or path string

    Args:
        image (Union[Image.Image, np.ndarray, str, List]): PIL.Image, array, path string or list of it.

    Returns:
        Dict:
            {
                "image": Union[PIL.Image.Image, np.ndarray, List[PIL.Image.Image], List[np.ndarray]],
                **input_dict,
            }
    """
    multipage = isinstance(image, List)
    if not multipage:
        image = [image]

    if len(image) != len(self.image_mode):
        raise ValueError("number of images should match len(image_mode)")

    # 이미지들을 각자의 모드로 로드 (RGB 또는 L).
    loaded_images = []
    for image_i, image_mode_i in zip(image, self.image_mode):
        image_i = self.load(image_i)
        image_i = convert_image_mode(image=image_i, mode=image_mode_i, copy=False)
        loaded_images.append(image_i)

    if multipage:
        # multipage 이미지들의 사이즈가 모두 동일해야함.
        image_sizes = set(read_image_size(item) for item in loaded_images)
        if len(image_sizes) > 1:
            raise ValueError("sizef of images in multipage should be identical")
    else:
        loaded_images = loaded_images[0]

    data["image"] = loaded_images
    return data
load_from_path
load_from_path(path: str) -> Union[Image, ndarray]

Loading function using PIL.Image library. This function is introduced because {exif_transpose} must be processed. {exif_transpose} fix rotated image binary data using {EXIF} information. Without {exif_transpose}, network would accidently learn randomly rotated image data.

Parameters:

  • path (str) –

    path to image file

Returns:

  • Union[Image, ndarray]

    Union[Image.Image, np.ndarray]: image

Source code in SaigeToolkit/data/transform/image_load.py
def load_from_path(self, path: str) -> Union[Image.Image, np.ndarray]:
    """Loading function using PIL.Image library.
    This function is introduced because {exif_transpose} must be processed.
    {exif_transpose} fix rotated image binary data using {EXIF} information.
    Without {exif_transpose}, network would accidently learn randomly rotated image data.

    Args:
        path (str): path to image file

    Returns:
        Union[Image.Image, np.ndarray]: image
    """
    with open(path, "rb") as f:
        image = Image.open(f)
        image = ImageOps.exif_transpose(image)

    if self.to_numpy:
        image = np.array(image, dtype=np.uint16 if self._is_16bit(image) else np.uint8)

    if self._is_16bit(image):
        image = self._convert_16_to_8(image)

    return image
_convert_16_to_8 staticmethod
_convert_16_to_8(image: Union[Image, ndarray]) -> Union[Image, ndarray]

이미지 픽셀당 비트수를 16에서 8로 변화합니다. 입출력 데이터 타입이 같습니다. (pil로 받으면 pil을 ndarray로 받을 시 ndarray를 출력합니다.)

Source code in SaigeToolkit/data/transform/image_load.py
@staticmethod
def _convert_16_to_8(image: Union[Image.Image, np.ndarray]) -> Union[Image.Image, np.ndarray]:
    """
    이미지 픽셀당 비트수를 16에서 8로 변화합니다.
    입출력 데이터 타입이 같습니다. (pil로 받으면 pil을 ndarray로 받을 시 ndarray를 출력합니다.)
    """

    def _convert_16_to_8_np(array: np.ndarray) -> np.ndarray:
        return (array >> 8).astype(np.uint8)

    if isinstance(image, Image.Image):
        assert "I" in image.mode
        array_16bit = np.array(image, dtype=np.uint16)
        array_8bit = _convert_16_to_8_np(array_16bit)
        ret_image = Image.fromarray(array_8bit)
    elif isinstance(image, np.ndarray):
        assert image.dtype == np.uint16
        ret_image = _convert_16_to_8_np(image)
    else:
        raise NotImplementedError

    return ret_image

polygon_function

resize_polygon

resize_polygon(polygons: PolygonType, image_size: Tuple[int], tw: int, th: int) -> PolygonType

Resize polygon from (w, h) to (tw, th)

Source code in SaigeToolkit/data/transform/polygon_function.py
def resize_polygon(polygons: PolygonType, image_size: Tuple[int], tw: int, th: int) -> PolygonType:
    """Resize polygon from (w, h) to (tw, th)"""
    if len(polygons) == 0:
        return polygons

    w, h = image_size
    if w == tw and h == th:
        return polygons

    dtype = polygons[0].dtype

    w_scale = tw / w
    h_scale = th / h

    new_polygons = deepcopy(polygons)

    for polygon in new_polygons:
        polygon[:, 0] = polygon[:, 0] * w_scale
        polygon[:, 1] = polygon[:, 1] * h_scale
        polygon = polygon.astype(dtype)

    return new_polygons

translate_polygon

translate_polygon(polygons: PolygonType, offset: Tuple[int]) -> PolygonType

Translate polyfon from [(x1, y1), ... ] to [(x1 - x_offset), (y1 - y_offset), ...]

Source code in SaigeToolkit/data/transform/polygon_function.py
def translate_polygon(
    polygons: PolygonType,
    offset: Tuple[int],
) -> PolygonType:
    """Translate polyfon from [(x1, y1), ... ] to [(x1 - x_offset), (y1 - y_offset), ...]"""
    if len(polygons) == 0:
        return polygons

    if offset[0] == 0 and offset[1] == 0:
        return polygons

    dtype = polygons[0].dtype

    x_offset, y_offset = np.array(offset).astype(dtype)

    new_polygons = deepcopy(polygons)

    for polygon in new_polygons:
        polygon[:, 0] -= x_offset
        polygon[:, 1] -= y_offset

    return new_polygons

resize

Resizer

Resizer(size: Optional[Union[ImageSizeType, int]] = None, scale: Optional[Union[int, float]] = None, area_sqrt: Optional[Union[int, float]] = None, max_size: Optional[Union[ImageSizeType, int]] = None, round: Optional[int] = None, round_type: str = 'round', resampling: str = 'bilinear', image_only: bool = False, use_cv2_for_numpy: bool = True)

Module for resizing PIL, torch, numpy images Resizer의 작동 방식은 다음과 같습니다. 1. target size 계산 2. target size 미세 조정 3. 데이터에 resize 적용

Args에 따라 1, 2번의 작동 방식이 달라집니다. 1. target size 계산 - resize 될 target size를 계산합니다. - target size는 4개의 args에 영향을 받을 수 있습니다. (size, scale, area_sqrt, max_size) 하나의 Resizer는 4개중 하나의 args만 사용할 수 있으며, 2개 이상의 args가 None이 아닐시 error를 raise 합니다. 1-1. size: image를 size로 resize 합니다. aspect ratio가 변경될 수 있습니다. 1-2. scale: image를 scale배로 늘리거나 줄입니다. aspect ratio는 유지됩니다. 1-3. area_sqrt: image의 면적이 area_sqrt^2이 되도록 이미지를 늘리거나 줄입니다. aspect ratio는 유지됩니다. 1-4. max_size: image의 size가 max_size보다 클 경우 max_size로 resize 합니다. aspect ratio를 유지하기 위해, width/height중 더 많이 줄어야 하는 비율에 맞추어 전체를 resize합니다.

  1. target size 미세 조정
  2. resize된 이미지가 특정 값의 배수가 되도록 target size를 미세 조정 합니다. model의 입력으로 넣을 때, image size가 특정 값의 배수가 되어야 하기 때문에 필요합니다.
    1. target size 계산의 size parameter와 함께 사용할 수 없습니다. (고정 size이기 때문)
  3. target size 미세 조정은 총 2개의 args에 영향을 받을 수 있습니다. (round, round_type) round가 None이면 미세 조정을 하지 않습니다, round_type에 따라 다른 방식의 미세 조정을 적용합니다. 2-1. round: 미세 조정시 반올림합니다. (target size보다 작거나 크거나 같습니다.) 2-2. floor: 미세 조정시 내림합니다. (target size보다 작거나 같습니다.) 2-3. ceil: 미세 조정시 올림합니다. (target size보다 크거나 같습니다.)
  4. 미세 조정된 target_size의 width혹은 height가 0이 될 경우, round 값으로 변경해줍니다. (ex. size=(3, 3), round=8이면 round_type에 상관없이 size=(8, 8)이 됨.)

Parameters:

  • size (Optional[Union[ImageSizeType, int]], default: None ) –

    target image size. Defaults to None.

  • scale (Optional[Union[int, float]], default: None ) –

    target image scale. Defaults to None.

  • area_sqrt (Optional[Union[int, float]], default: None ) –

    target image sqrt area. Defaults to None.

  • max_size (Optional[Union[ImageSizeType, int]], default: None ) –

    target maximum image size. Defaults to None.

  • round (Optional[int], default: None ) –

    round image size. Defaults to None.

  • round_type (Optional[str], default: 'round' ) –

    type of round image. One of ["round", "floor", "ceil"]. Defaults to "round".

  • resampling (str, default: 'bilinear' ) –

    One of ["nearest", "bilinear", "bicubic"]. Defaults to "bilinear".

  • image_only (bool, default: False ) –

    to resize image only. Defaults to False.

  • use_cv2_for_numpy (bool, default: True ) –

    use cv2 instead of PIL for faster numpy array image resizing. Defaults to True.

Raises:

  • ResizerParameterValueError

    target size parameter가 2개 이상 들어오면 error를 raise 합니다. round_type이 ["round", "floor", "ceil"]안에 없으면 error를 raise 합니다. size와 미세조정 parameter가 함께 들어오면 error를 raise 합니다.

Source code in SaigeToolkit/data/transform/resize.py
def __init__(
    self,
    size: Optional[Union[ImageSizeType, int]] = None,
    scale: Optional[Union[int, float]] = None,
    area_sqrt: Optional[Union[int, float]] = None,
    max_size: Optional[Union[ImageSizeType, int]] = None,
    round: Optional[int] = None,
    round_type: str = "round",
    resampling: str = "bilinear",
    image_only: bool = False,
    use_cv2_for_numpy: bool = True,
) -> None:
    """Module for resizing PIL, torch, numpy images
    Resizer의 작동 방식은 다음과 같습니다.
    1. target size 계산
    2. target size 미세 조정
    3. 데이터에 resize 적용

    Args에 따라 1, 2번의 작동 방식이 달라집니다.
    1. target size 계산
    - resize 될 target size를 계산합니다.
    - target size는 4개의 args에 영향을 받을 수 있습니다. (size, scale, area_sqrt, max_size)
      하나의 Resizer는 4개중 하나의 args만 사용할 수 있으며, 2개 이상의 args가 None이 아닐시 error를 raise 합니다.
        1-1. size: image를 size로 resize 합니다. aspect ratio가 변경될 수 있습니다.
        1-2. scale: image를 scale배로 늘리거나 줄입니다. aspect ratio는 유지됩니다.
        1-3. area_sqrt: image의 면적이 area_sqrt^2이 되도록 이미지를 늘리거나 줄입니다. aspect ratio는 유지됩니다.
        1-4. max_size: image의 size가 max_size보다 클 경우 max_size로 resize 합니다.
                        aspect ratio를 유지하기 위해, width/height중 더 많이 줄어야 하는 비율에 맞추어 전체를 resize합니다.

    2. target size 미세 조정
    - resize된 이미지가 특정 값의 배수가 되도록 target size를 미세 조정 합니다.
      model의 입력으로 넣을 때, image size가 특정 값의 배수가 되어야 하기 때문에 필요합니다.
    - 1. target size 계산의 size parameter와 함께 사용할 수 없습니다. (고정 size이기 때문)
    - target size 미세 조정은 총 2개의 args에 영향을 받을 수 있습니다. (round, round_type)
      round가 None이면 미세 조정을 하지 않습니다, round_type에 따라 다른 방식의 미세 조정을 적용합니다.
        2-1. round: 미세 조정시 반올림합니다. (target size보다 작거나 크거나 같습니다.)
        2-2. floor: 미세 조정시 내림합니다. (target size보다 작거나 같습니다.)
        2-3. ceil: 미세 조정시 올림합니다. (target size보다 크거나 같습니다.)
    - 미세 조정된 target_size의 width혹은 height가 0이 될 경우, round 값으로 변경해줍니다.
      (ex. size=(3, 3), round=8이면 round_type에 상관없이 size=(8, 8)이 됨.)

    Args:
        size (Optional[Union[ImageSizeType, int]], optional): target image size. Defaults to None.
        scale (Optional[Union[int, float]], optional): target image scale. Defaults to None.
        area_sqrt (Optional[Union[int, float]], optional): target image sqrt area. Defaults to None.
        max_size (Optional[Union[ImageSizeType, int]], optional): target maximum image size. Defaults to None.
        round (Optional[int], optional): round image size. Defaults to None.
        round_type (Optional[str], optional): type of round image. One of ["round", "floor", "ceil"]. Defaults to "round".
        resampling (str): One of ["nearest", "bilinear", "bicubic"]. Defaults to "bilinear".
        image_only (bool): to resize image only. Defaults to False.
        use_cv2_for_numpy (bool): use cv2 instead of PIL for faster numpy array image resizing. Defaults to True.

    Raises:
        ResizerParameterValueError: target size parameter가 2개 이상 들어오면 error를 raise 합니다.
                                    round_type이 ["round", "floor", "ceil"]안에 없으면 error를 raise 합니다.
                                    size와 미세조정 parameter가 함께 들어오면 error를 raise 합니다.
    """

    self._check_parameter(
        size=size,
        scale=scale,
        area_sqrt=area_sqrt,
        max_size=max_size,
        round=round,
        round_type=round_type,
    )

    size = self._preprocess_size(size)
    max_size = self._preprocess_size(max_size)

    if scale == 1:
        scale = None

    self.size = size
    self.scale = scale
    self.area_sqrt = area_sqrt
    self.max_size = max_size
    self.round = round
    self.round_type = round_type

    if resampling not in RESAMPLE_PIL or resampling not in RESAMPLE_TORCH:
        raise ValueError
    self.resampling = resampling

    self.image_only = image_only
    self.use_cv2_for_numpy = use_cv2_for_numpy
compute_input_size staticmethod
compute_input_size(data: Dict) -> ImageSizeType

target size를 계산하기 위해 input size를 가져옵니다. Note: data에 image 혹은 mask data는 있다고 가정하며, 둘의 size는 같다고 가정합니다.

Source code in SaigeToolkit/data/transform/resize.py
@staticmethod
def compute_input_size(data: Dict) -> ImageSizeType:
    """target size를 계산하기 위해 input size를 가져옵니다.
    Note: data에 image 혹은 mask data는 있다고 가정하며, 둘의 size는 같다고 가정합니다.
    """
    if "image" in data:
        multipage = isinstance(data["image"], List)
        input_size = read_image_size(data["image"][0] if multipage else data["image"])
    elif "mask" in data:
        input_size = read_image_size(data["mask"])
    else:
        raise NotImplementedError

    return input_size
compute_target_size
compute_target_size(input_size: Union[ImageSizeType, ndarray]) -> ImageSizeType

compute resize target size from input image size

Parameters:

Returns:

Source code in SaigeToolkit/data/transform/resize.py
def compute_target_size(self, input_size: Union[ImageSizeType, np.ndarray]) -> ImageSizeType:
    """compute resize target size from input image size

    Args:
        input_size (Union[ImageSizeType, np.ndarray]): (width, height)

    Returns:
        ImageSizeType: (width, height)
    """
    return self._compute_target_size(
        input_size=input_size,
        size=self.size,
        scale=self.scale,
        area_sqrt=self.area_sqrt,
        max_size=self.max_size,
        round=self.round,
        round_type=self.round_type,
    )

InspectionSizeResizer

InspectionSizeResizer(inspection_size_wh: Optional[ImageSizeType] = None, resizer: Optional[Resizer] = None)

Bases: Resizer

원본 이미지가 inspection_size를 넘지 않도록 resize 했을 때의 image scale만큼 resize를 해주는 resizer를 생성하는 class 입니다.

inspection_size는 원본 이미지에 대해 적용하지만, 실제 연산은 ROI가 먼저 계산되기 때문에, 원본 이미지가 inspection_size를 넘지 않도록 resize 했을 때의 image scale을 미리 계산해두고, 해당 scale만큼 resize를 하는 resizer를 생성하여 계산합니다.

Source code in SaigeToolkit/data/transform/resize.py
def __init__(
    self,
    inspection_size_wh: Optional[ImageSizeType] = None,
    resizer: Optional[Resizer] = None,
) -> None:
    self._check_inspection_size_type(inspection_size_wh)
    self._check_inspection_size_value(inspection_size_wh)

    initial_params = {}
    if resizer is not None:
        initial_params["resampling"] = resizer.resampling
        initial_params["image_only"] = resizer.image_only

    super().__init__(**initial_params)

    self.inspection_size_wh = self._preprocess_size(inspection_size_wh)

StackedResizerHandler

StackedResizerHandler(resizer_list: List[Optional[Resizer]])

같은 image에 대해 여러번의 resize가 연속적으로 적용될 때, 여러개의 resize를 하나로 묶어서 최종 target size로 한번에 resize를 해주는 class입니다.

Source code in SaigeToolkit/data/transform/resize.py
def __init__(
    self,
    resizer_list: List[Optional[Resizer]],
) -> None:
    self.resizer_list = resizer_list
    self.is_empty = len(resizer_list) == 0 or all(x is None for x in resizer_list)

    if not self.is_empty:
        resampling = set()
        image_only = set()
        use_cv2_for_numpy = set()
        for resizer in resizer_list:
            if resizer is not None:
                resampling.add(resizer.resampling)
                image_only.add(resizer.image_only)
                use_cv2_for_numpy.add(resizer.use_cv2_for_numpy)

        if len(resampling) > 1 or len(image_only) > 1 or len(use_cv2_for_numpy) > 1:
            raise StackedResizerHandlerParameterValueError

        self.resampling = resampling.pop()
        self.image_only = image_only.pop()
        self.use_cv2_for_numpy = use_cv2_for_numpy.pop()

roi

ROI 좌표 계산 및 ROI 크롭, blind_mask 적용을 수행하는 ROIHandler 클래스를 제공합니다. Set-ROI 기능을 위한 API 클래스인 ROIHandlerAPI도 제공합니다.

api

ROIHandlerAPI
ROIHandlerAPI(**kwargs)

Set-ROI 기능을 위한 API입니다.

Usage
# 핸들러 빌드. 아래는 simple mode의 예제 config이며, 자세한 설명은 ROIHandlerAPI.set() 함수 참고.
config = {
    "mode": "simple",
    "left": 0.0,
    "top": 0.0,
    "right": 1.0,
    "bottom": 1.0,
    "blind_mask": None,
}
error, roi_hander = ROIHandlerAPI.build(config)

# image에 대한 roi 계산. 리턴 결과 설명은 ROIHandlerAPI.apply() 함수 참고.
image = np.zeros((100, 100, 3), dtype=np.unit8)
error, roi_results = roi_handler.apply(image)

# roi 파라미터 변경
config["left"] = 0.1
error, _  = roi_handler.set(config)

# 변경된 파라미터로 roi 다시 계산
error, roi_results = roi_handler.apply(image)
Source code in SaigeToolkit/data/transform/roi/api.py
def __init__(self, **kwargs) -> None:
    self.handler = ROIHandler(**kwargs)
build classmethod
build(config: Dict) -> ROIHandlerAPI

ROIHandlerAPI를 빌드합니다. Args: config (Dict): ROIHandlerAPI.set의 파라미터와 동일합니다.

Returns:

Source code in SaigeToolkit/data/transform/roi/api.py
@classmethod
@error_handler
def build(cls, config: Dict) -> ROIHandlerAPI:
    """ROIHandlerAPI를 빌드합니다.
    Args:
        config (Dict): ROIHandlerAPI.set의 파라미터와 동일합니다.

    Returns:
        ROIHandlerAPI: 빌드된 ROIHandlerAPI
    """
    return cls(**config)
set
set(config: Dict) -> None

ROI 파라미터를 변경합니다.

Parameters:

  • config (Dict) –

    ROI 파라미터의 dict입니다. mode에 따라 다른 파라미터를 가집니다.

    # simple mode:
    {
        "mode": "simple",  # Simple ROI 모드.
        "left": float,  # ROI의 왼쪽 경계. [0.0, 1.0) 범위의 실수.
        "top": float,  # ROI의 위쪽 경계. [0.0, 1.0) 범위의 실수.
        "right": float,  # ROI의 오른쪽 경계. (right, 1.0] 범위의 실수.
        "bottom": float,  # ROI의 아래쪽 경계. (top, 1.0] 범위의 실수.
        "blind_mask": Optional[np.ndarray],  # blind mask 이미지. None인 경우 blind 적용 안함.
                                             # np.ndarray인 경우 (dtype=uint8, shape=(H_roi, W_roi))이며 픽셀 값은 0 또는 1.
                                             # mask의 값이 1인 영역이 학습/검사 시 마스킹됩니다.
                                             # polygons에는 blind_mask가 적용되지 않습니다.
    }
    # advanced mode:
    {
        "mode": "advanced",  # Advanced ROI 모드.
        "intensity": List[int],  # 필터링할 [최소, 최대] 픽셀값 범위. 각 값은 [0, 255] 범위의 정수.
        "expansion": int,  # 필터링된 픽셀 영역에 대한 확장/축소 정도. [-10, 10] 범위의 정수.
        "inversion": bool,  # True인 경우 필터링된 픽셀 영역을 반전.
        "offset_left": float,  # ROI 박스의 왼쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기.
        "offset_right": float,  # ROI 박스의 오른쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기.
        "offset_top": float,  # ROI 박스의 위쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기.
        "offset_bottom": float,  # ROI 박스의 아래쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기.
        "blind_mask": Optional[np.ndarray],  # blind mask 이미지. None인 경우 blind 적용 안함.
                                             # np.ndarray인 경우 (dtype=uint8, shape=(H_roi, W_roi))이며 픽셀 값은 0 또는 1.
                                             # mask의 값이 1인 영역이 학습/검사 시 마스킹됩니다.
                                             # polygons에는 blind_mask가 적용되지 않습니다.
    }
    

Source code in SaigeToolkit/data/transform/roi/api.py
@error_handler
def set(self, config: Dict) -> None:
    """ROI 파라미터를 변경합니다.

    Args:
        config (Dict): ROI 파라미터의 dict입니다. mode에 따라 다른 파라미터를 가집니다.
            ```python
            # simple mode:
            {
                "mode": "simple",  # Simple ROI 모드.
                "left": float,  # ROI의 왼쪽 경계. [0.0, 1.0) 범위의 실수.
                "top": float,  # ROI의 위쪽 경계. [0.0, 1.0) 범위의 실수.
                "right": float,  # ROI의 오른쪽 경계. (right, 1.0] 범위의 실수.
                "bottom": float,  # ROI의 아래쪽 경계. (top, 1.0] 범위의 실수.
                "blind_mask": Optional[np.ndarray],  # blind mask 이미지. None인 경우 blind 적용 안함.
                                                     # np.ndarray인 경우 (dtype=uint8, shape=(H_roi, W_roi))이며 픽셀 값은 0 또는 1.
                                                     # mask의 값이 1인 영역이 학습/검사 시 마스킹됩니다.
                                                     # polygons에는 blind_mask가 적용되지 않습니다.
            }
            # advanced mode:
            {
                "mode": "advanced",  # Advanced ROI 모드.
                "intensity": List[int],  # 필터링할 [최소, 최대] 픽셀값 범위. 각 값은 [0, 255] 범위의 정수.
                "expansion": int,  # 필터링된 픽셀 영역에 대한 확장/축소 정도. [-10, 10] 범위의 정수.
                "inversion": bool,  # True인 경우 필터링된 픽셀 영역을 반전.
                "offset_left": float,  # ROI 박스의 왼쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기.
                "offset_right": float,  # ROI 박스의 오른쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기.
                "offset_top": float,  # ROI 박스의 위쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기.
                "offset_bottom": float,  # ROI 박스의 아래쪽 사이즈. [0.0, 2.0] 범위의 실수 이며, 1인 경우 기본 크기.
                "blind_mask": Optional[np.ndarray],  # blind mask 이미지. None인 경우 blind 적용 안함.
                                                     # np.ndarray인 경우 (dtype=uint8, shape=(H_roi, W_roi))이며 픽셀 값은 0 또는 1.
                                                     # mask의 값이 1인 영역이 학습/검사 시 마스킹됩니다.
                                                     # polygons에는 blind_mask가 적용되지 않습니다.
            }
            ```
    """
    self.handler.set(**config)
apply
apply(image: ndarray) -> Dict

image에 대한 ROI 좌표 및 기타 결과를 계산합니다.

Parameters:

  • image (ndarray) –

    ROI를 적용할 입력 이미지.

Returns:

  • Dict ( Dict ) –

    ROI 계산 결과 dict 입니다. mode에 따라 다른 결과 값들을 가집니다.

    # simple mode:
    {
        "roi_coordinates": List[int],  # [left, top, right, bottom].
    }
    # advanced mode:
    {
        "roi_coordinates": List[int],  # [left, top, right, bottom].
        "filtered_image": np.ndarray(uint8, shape=(H, W)),  # intensity, expansion, inversion이 적용된 중간 결과 이미지 입니다. (픽셀값: 0 or 1)
    }
    

Source code in SaigeToolkit/data/transform/roi/api.py
@error_handler
def apply(self, image: np.ndarray) -> Dict:
    """`image`에 대한 ROI 좌표 및 기타 결과를 계산합니다.

    Args:
        image (np.ndarray): ROI를 적용할 입력 이미지.

    Returns:
        Dict: ROI 계산 결과 dict 입니다. mode에 따라 다른 결과 값들을 가집니다.
            ```python
            # simple mode:
            {
                "roi_coordinates": List[int],  # [left, top, right, bottom].
            }
            # advanced mode:
            {
                "roi_coordinates": List[int],  # [left, top, right, bottom].
                "filtered_image": np.ndarray(uint8, shape=(H, W)),  # intensity, expansion, inversion이 적용된 중간 결과 이미지 입니다. (픽셀값: 0 or 1)
            }
            ```
    """
    return self.handler.roi_calculator(image=image, get_intermediate_results=True)

roi_calculator

ROICalculator

Bases: ABC

ROI 좌표 계산을 위한 추상 클래스입니다.

RelativeBoxROI
RelativeBoxROI(**kwargs)

Bases: ROICalculator

이미지 크기에 비례하는 상대좌표 박스로 ROI를 계산합니다.

Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
def __init__(self, **kwargs) -> None:
    self.set(**kwargs)
PixelIntensityROI
PixelIntensityROI(**kwargs)

Bases: ROICalculator

픽셀값이 intensity 범위에 들어오는 픽셀만 필터링한 뒤, 필터링 된 픽셀들의 컨투어를 찾고, 가장 면적이 큰 컨투어를 감싸는 최소 박스로 ROI를 계산합니다.

Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
def __init__(self, **kwargs) -> None:
    self.set(**kwargs)
AutoRelativeBoxROI
AutoRelativeBoxROI(padding: str = 'medium')

Bases: RelativeBoxROI

RelativeBoxROI class with automatic coordinate calculation.

Monostate pattern applied to prevent ROI coordinate mismatch between train ~ validation dataset.

Attributes:

  • left (float) –

    ROI coordinates.

  • top (float) –

    ROI coordinates.

  • right (float) –

    ROI coordinates.

  • bottom (float) –

    ROI coordinates.

  • is_ready (bol) –

    Whether auto ROI coordinates is set.

  • image_hw (Optional[List[int]]) –

    dataset image size.

  • discard_outer_polygons (bool) –

    Flag for discarding polygons outside of current ROI region.

  • expand_ratio

    Ratio for expanding ROI region. Larger value means more padding.

Example
in dataset building...

@property def files(self): return self._files

@files.setter def files(self, value): self._files = value

if isinstance(self.transform.roi_handler.roi_calculator, AutoRelativeBoxROI):
    self.transform.roi_handler.roi_calculator.autoupdate_roi_coordinate(self)
                                                                        self is dataset

```

Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
def __init__(self, padding: str = "medium"):
    self.__dict__ = self.__shared_state

    if padding not in self.REGION_EXPAND_RATIO.keys():
        raise AutoROIParameterValueError(f"AutoROI mode {padding} not available.")

    self.expand_ratio = self.REGION_EXPAND_RATIO[padding]
autoupdate_roi_coordinate
autoupdate_roi_coordinate(dataset: Dataset) -> bool

Automatically update ROI coordinate using dataset information.

Returns success flag.

Source code in SaigeToolkit/data/transform/roi/roi_calculator.py
def autoupdate_roi_coordinate(self, dataset: Dataset) -> bool:
    """Automatically update ROI coordinate using dataset information.

    Returns success flag.
    """

    # XXX: only called once
    if self.is_ready:
        logger.info("ROI coordinate already set. Update only once")
        return True

    marginal_label_region_xyxy = np.array([np.inf, np.inf, 0, 0])

    for data_idx in range(len(dataset)):
        file = dataset.files[data_idx]
        data_dict = dataset.load_image(file)
        data_dict.update(dataset.load_label(file))

        data_image: Union[Image.Image, np.ndarray] = data_dict["image"]
        current_img_hw = list(read_image_size(data_image))[::-1]

        if self.image_hw:
            if self.image_hw != current_img_hw:
                logger.warn("Variation in image size detected.. autoROI update aborted.")
                logger.warn(
                    f"Expected image size: {self.image_hw} / Given image size: {current_img_hw}"
                )
                return False

        self.image_hw = current_img_hw

        for polygon in data_dict["polygons"]:
            x_min, x_max = np.min(polygon[:, 0]), np.max(polygon[:, 0])
            y_min, y_max = np.min(polygon[:, 1]), np.max(polygon[:, 1])

            if x_min < marginal_label_region_xyxy[0]:
                marginal_label_region_xyxy[0] = x_min

            if y_min < marginal_label_region_xyxy[1]:
                marginal_label_region_xyxy[1] = y_min

            if x_max > marginal_label_region_xyxy[2]:
                marginal_label_region_xyxy[2] = x_max

            if y_max > marginal_label_region_xyxy[3]:
                marginal_label_region_xyxy[3] = y_max

    if not _check_region_xyxy_is_valid(marginal_label_region_xyxy):
        logger.warning(
            "AutoROI setting update failed. Needs at least one training data & valid polygon."
        )
        return False

    marginal_label_region_xyxy = _expand_region_xyxy(marginal_label_region_xyxy, self.expand_ratio)
    marginal_label_region_xyxy = _fit_region_into_img_size(
        marginal_label_region_xyxy,
        self.image_hw,
    )

    self.left = marginal_label_region_xyxy[0] / self.image_hw[1]
    self.top = marginal_label_region_xyxy[1] / self.image_hw[0]
    self.right = marginal_label_region_xyxy[2] / self.image_hw[1]
    self.bottom = marginal_label_region_xyxy[3] / self.image_hw[0]

    self.is_ready = True
    marginal_label_region_ratio = [self.left, self.top, self.right, self.bottom]
    logger.info(f"AutoROI setting success. ROI coordinates: {marginal_label_region_ratio}")

    return True

roi_handler

ROIHandler
ROIHandler(**kwargs)

ROI 기능을 수행합니다. 이미지에 대한 ROI 좌표를 계산해 크롭하고, 크롭된 이미지에 blind_mask를 적용해 마스크 영역의 픽셀 값을 0으로 치환합니다.

Source code in SaigeToolkit/data/transform/roi/roi_handler.py
def __init__(self, **kwargs) -> None:
    self.set(**kwargs)

transform

End-to-end 데이터 변환을 지원하는 모듈입니다.

Transform

Transform(image_mode: Union[str, List[str]] = 'RGB', inspection_size_wh: Optional[ImageSizeType] = None, roi: Optional[Dict] = None, resize: Optional[Dict] = None, augmentation: Optional[Dict] = None, roi_mask_first: bool = True)
Source code in SaigeToolkit/data/transform/transform.py
def __init__(
    self,
    image_mode: Union[str, List[str]] = "RGB",
    inspection_size_wh: Optional[ImageSizeType] = None,
    roi: Optional[Dict] = None,
    resize: Optional[Dict] = None,
    augmentation: Optional[Dict] = None,
    roi_mask_first: bool = True,  # 하위 호환성을 위해 roi_mask_first=True를 기본값으로 설정
):
    self.roi_mask_first = roi_mask_first
    self.image_loader = ImageLoader(image_mode=image_mode)
    self.roi_handler = ROIHandler(**roi) if roi is not None else None
    self.base_resizer = Resizer(**resize) if resize is not None else None

    # inspection_size_wh 설정 시 그 값에 따라 초기화
    self.inspection_size_resizer: Optional[InspectionSizeResizer] = None
    self.stacked_resizer_handler: StackedResizerHandler = None

    # inspection_size_wh setter에서 inspection_size_resizer와 stacked_resizer_handler 생성
    self.inspection_size_wh = inspection_size_wh

    if augmentation is None:
        self.augmentation = None
    elif "_target_" in augmentation:
        self.augmentation = build_augmentation(augmentation)
    else:
        raise NotImplementedError("Old version of augmentation config is not supported.")
__call__
__call__(data: Dict, warmup: bool = False) -> Dict

data Dict에 transform을 적용합니다.

Parameters:

  • data (Dict) –

    data Dictionary

  • warmup (bool, default: False ) –

    InferenceHandler warmup시에 사용하는 파라미터 입니다. True일 경우, 현재 transform을 적용했을 때 나올 수 있는 가장 큰 image size로 transform을 적용합니다. Transform operation 중 ROI의 경우 input image에 따라 output size가 매번 바뀔 수 있기 때문에 해당 옵션이 추가되었습니다. Defaults to False.

Returns:

  • Dict ( Dict ) –

    transform이 적용된 데이터 Dict입니다.

Source code in SaigeToolkit/data/transform/transform.py
def __call__(self, data: Dict, warmup: bool = False) -> Dict:
    """data Dict에 transform을 적용합니다.

    Args:
        data (Dict): data Dictionary
        warmup (bool, optional): InferenceHandler warmup시에 사용하는 파라미터 입니다. True일 경우,
                                    현재 transform을 적용했을 때 나올 수 있는 가장 큰 image size로
                                    transform을 적용합니다.
                                 Transform operation 중 ROI의 경우 input image에 따라 output size가
                                    매번 바뀔 수 있기 때문에 해당 옵션이 추가되었습니다.
                                 Defaults to False.

    Returns:
        Dict: transform이 적용된 데이터 Dict입니다.
    """
    # transform_params 설정
    if "transform_params" not in data:
        data["transform_params"] = {
            "operation_stack": [
                self.Operation.ROI,
                self.Operation.InspectionSize,
                self.Operation.Resize,
            ],
            "operation_params": {},
        }

    operation_params: Dict = data["transform_params"]["operation_params"]

    # load PIL Image
    data = self.image_loader(**data)

    # 원본 이미지가 inspection_size를 넘지 않도록 resize 했을 때의 image scale 계산
    if self.inspection_size_resizer is not None:
        self.inspection_size_resizer.set_scale_from_data(**data)

    # ROI crop 적용
    if self.roi_handler is not None:
        data, roi_revert_params = self.roi_handler.apply_crop(
            return_revert_params=True, warmup=warmup, **data
        )
        if self.roi_mask_first:
            data = self.roi_handler.apply_mask(**data)

        if self.Operation.ROI in operation_params:
            raise KeyError
        operation_params[self.Operation.ROI] = roi_revert_params

    # inspection_size와 resize_factor를 하나로 묶어서 resize
    data, revert_param_list = self.stacked_resizer_handler(return_revert_params=True, **data)
    inspection_size_revert_params, resizer_revert_params = revert_param_list

    if inspection_size_revert_params is not None:
        if self.Operation.InspectionSize in operation_params:
            raise KeyError
        operation_params[self.Operation.InspectionSize] = inspection_size_revert_params

    if resizer_revert_params is not None:
        if self.Operation.Resize in operation_params:
            raise KeyError
        operation_params[self.Operation.Resize] = resizer_revert_params

    # # ROI blind mask 적용
    if self.roi_handler is not None and not self.roi_mask_first:
        data = self.roi_handler.apply_mask(**data)

    # data augmentation
    if self.augmentation is not None:
        data = self.augmentation(**data)

    return data
get_resize_scale classmethod
get_resize_scale(transform_params: Dict) -> List[float]

before_transform_image_size -> after_transform_input_size가 되기 위한 scale을 구합니다. before_transform_image_size * scale = after_transform_input_size

Parameters:

  • transform_params (Dict) –

    transform시에 저장해둔 parameter 입니다.

Returns:

  • List[float]

    List[float]: before_transform_image_size * scale = after_transform_input_size인 scale scale: [scale_width, scale_height]

Source code in SaigeToolkit/data/transform/transform.py
@classmethod
def get_resize_scale(cls, transform_params: Dict) -> List[float]:
    """before_transform_image_size -> after_transform_input_size가 되기 위한 scale을 구합니다.
    before_transform_image_size * scale = after_transform_input_size

    Args:
        transform_params (Dict): transform시에 저장해둔 parameter 입니다.

    Returns:
        List[float]: before_transform_image_size * scale = after_transform_input_size인 scale
                     scale: [scale_width, scale_height]
    """
    operation_params: Dict = transform_params["operation_params"]
    inspection_size_revert_params = operation_params.get(cls.Operation.InspectionSize, None)
    resizer_revert_params = operation_params.get(cls.Operation.Resize, None)

    if inspection_size_revert_params is None and resizer_revert_params is None:
        resize_scale = [1.0, 1.0]
    else:
        if inspection_size_revert_params is None:
            image_size_before_resize = resizer_revert_params["image_size_before_resize"]
            image_size_after_resize = resizer_revert_params["image_size_after_resize"]
        elif resizer_revert_params is None:
            image_size_before_resize = inspection_size_revert_params["image_size_before_resize"]
            image_size_after_resize = inspection_size_revert_params["image_size_after_resize"]
        else:
            image_size_before_resize = inspection_size_revert_params["image_size_before_resize"]
            image_size_after_resize = resizer_revert_params["image_size_after_resize"]

        resize_scale = (
            np.array(image_size_after_resize) / np.array(image_size_before_resize)
        ).tolist()

    return resize_scale
_get_next_revert_operation staticmethod
_get_next_revert_operation(transform_params: Dict) -> Optional[Operation]

다음으로 할 revert operation을 가져옵니다. operation_stack에서 operation이 제거되지는 않습니다.

Parameters:

  • transform_params (Dict) –

    transform시에 저장해둔 parameter 입니다.

Returns:

  • Optional[Operation]

    Optional[Operation]: 남아있는 revert operation이 있으면 operation을 없으면 None을 반환합니다.

Source code in SaigeToolkit/data/transform/transform.py
@staticmethod
def _get_next_revert_operation(transform_params: Dict) -> Optional[Operation]:
    """다음으로 할 revert operation을 가져옵니다. operation_stack에서 operation이 제거되지는 않습니다.

    Args:
        transform_params (Dict): transform시에 저장해둔 parameter 입니다.

    Returns:
        Optional[Operation]: 남아있는 revert operation이 있으면 operation을 없으면 None을 반환합니다.
    """
    operation_stack: List = transform_params["operation_stack"]
    next_operation = None
    if len(operation_stack) > 0:
        next_operation = operation_stack[-1]

    return next_operation
revert classmethod
revert(data: Dict, transform_params: Dict, operation: Optional[Operation] = None) -> Dict

summary

Parameters:

  • data (Dict) –

    revert operation을 적용할 data dictionary입니다. data는 다음과 같은 구조를 지닙니다. { "key1": { "data" (Union[np.ndarray, torch.Tensor, List[Dict]]): 실제 data입니다. "data_type" (str): 해당 data의 type 입니다. 현재 ["array", "objects"]를 지원합니다. }, "key2": { "data" (Union[np.ndarray, torch.Tensor, List[Dict]]): 실제 data입니다. "data_type" (str): 해당 data의 type 입니다. 현재 ["array", "objects"]를 지원합니다. }, ... }

  • transform_params (Dict) –

    transform시에 저장해둔 parameter 입니다.

  • operation (Optional[Operation], default: None ) –

    transform에서 revert가 가능한 operation 입니다. Enum class인 Transform.Operation에 있는 항목들을 지원합니다. operation이 None이 아닐 시, 해당 operation 까지 revert를 적용하고, None일 시, 그 다음 revert operation을 적용합니다. Defaults to None.

Raises:

  • RevertOperationNotFoundError

    args로 넣은 operation이 남은 revert operation 중에 없을 때 에러를 발생합니다.

Returns:

  • Dict ( Dict ) –

    revert operation이 적용된 data dictionary 입니다. 구조는 Args의 data와 같습니다.

Source code in SaigeToolkit/data/transform/transform.py
@classmethod
def revert(
    cls,
    data: Dict,
    transform_params: Dict,
    operation: Optional[Operation] = None,
) -> Dict:
    """_summary_

    Args:
        data (Dict): revert operation을 적용할 data dictionary입니다. data는 다음과 같은 구조를 지닙니다.
            {
                "key1": {
                    "data" (Union[np.ndarray, torch.Tensor, List[Dict]]): 실제 data입니다.
                    "data_type" (str): 해당 data의 type 입니다. 현재 ["array", "objects"]를 지원합니다.
                },
                "key2": {
                    "data" (Union[np.ndarray, torch.Tensor, List[Dict]]): 실제 data입니다.
                    "data_type" (str): 해당 data의 type 입니다. 현재 ["array", "objects"]를 지원합니다.
                },
                ...
            }
        transform_params (Dict): transform시에 저장해둔 parameter 입니다.
        operation (Optional[Operation], optional): transform에서 revert가 가능한 operation 입니다.
                                                    Enum class인 Transform.Operation에 있는 항목들을 지원합니다.
                                                    operation이 None이 아닐 시, 해당 operation 까지 revert를 적용하고,
                                                    None일 시, 그 다음 revert operation을 적용합니다.
                                                    Defaults to None.

    Raises:
        RevertOperationNotFoundError: args로 넣은 operation이 남은 revert operation 중에 없을 때 에러를 발생합니다.

    Returns:
        Dict: revert operation이 적용된 data dictionary 입니다. 구조는 Args의 data와 같습니다.
    """
    # operation이 None인 경우 다음 revert operation 하나를 진행
    if operation is None:
        data = cls._revert(data=data, transform_params=transform_params)
    # operation이 None이 아닌 경우
    else:
        # 해당 operation이 operation_stack에 있는지 확인
        operation_stack: List = transform_params["operation_stack"]
        if operation not in operation_stack:
            raise RevertOperationNotFoundError
        # 해당 operation까지 revert를 적용
        while cls._get_next_revert_operation(transform_params=transform_params) != operation:
            data = cls._revert(data=data, transform_params=transform_params)
        data = cls._revert(data=data, transform_params=transform_params)

    return data
is_oversized staticmethod
is_oversized(transform_params: Optional[Dict]) -> bool

InspectionSize 연산에서 resize 되었는지 여부를 판단

Source code in SaigeToolkit/data/transform/transform.py
@staticmethod
def is_oversized(transform_params: Optional[Dict]) -> bool:
    """InspectionSize 연산에서 resize 되었는지 여부를 판단"""
    if transform_params is None:
        return False

    inspection_size_params = get_tree_node_with_default(
        transform_params, ["operation_params", Transform.Operation.InspectionSize], None
    )
    if inspection_size_params is None:
        return False

    size1 = tuple(inspection_size_params["image_size_before_resize"])
    size2 = tuple(inspection_size_params["image_size_after_resize"])

    if size1 != size2:
        return True
    else:
        return False

typevar