Newer
Older
TongueSegModel / src / tongue_seg_model / data / augment.py
"""データ拡張(SPEC_02「データ拡張」).

原本: `legacy/source/main.py` の「Params」の `transform_sample`(`ColorJitter`)と
`transform_both`(`TF.hflip` を確率 0.5).順序と乱数の使い方を原本と同じにしてある.

- 画像だけに色のゆらぎ(`torchvision.transforms.ColorJitter`.torch の乱数を使う)
- その後,`random.random() < hflip_prob` なら画像と正解マスクの両方を左右反転(Python の
  `random` を使う.同じ判定を両方に適用する)

乱数はグローバルな状態(torch・Python の `random`)を使う(原本どおり).再現性のための乱数の
固定は**学習の入口の 1 か所**(原本の `fix_rand` 相当)で行う前提であり,
本モジュールでは固定しない.
色のゆらぎは BGR の並びのまま掛ける(`ColorJitter` は RGB と見なすが,原本どおり並べ替えない).
"""

from __future__ import annotations

import random

import torch
import torchvision.transforms.functional as tf
from torchvision.transforms import ColorJitter

from tongue_seg_model.schema import AugmentConfig


class SegAugment:
    """画像と正解マスクの組に掛けるデータ拡張(学習・検証用).

    Args:
        config: データ拡張の設定(`augment`).
    """

    def __init__(self, config: AugmentConfig) -> None:
        jitter = config.color_jitter
        self._color_jitter = ColorJitter(
            brightness=jitter.brightness,
            contrast=jitter.contrast,
            saturation=jitter.saturation,
            hue=jitter.hue,
        )
        self._hflip_prob = config.hflip_prob

    def __call__(
        self, image: torch.Tensor, mask: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """色のゆらぎ(画像だけ)→ 左右反転(両方)を掛ける.

        Args:
            image: 画像(`(3, H, W)`, float32, BGR, 値域 0.0〜1.0).
            mask: 正解(`(2, H, W)`, float32, 0 か 1.チャンネル 0 が舌).

        Returns:
            拡張後の `(画像, 正解)`(形・型は入力と同じ.画像の値域は 0.0〜1.0 のまま).
        """
        image = self._color_jitter(image)
        # 原本はラベルを (3, H, W) のまま反転してから 2 チャンネルにしている.反転は画素の
        # 位置だけを動かすので,2 チャンネルにした後で反転しても結果は同じ.
        if random.random() < self._hflip_prob:
            image = tf.hflip(image)
            mask = tf.hflip(mask)
        return image, mask