"""`legacy/source/main.py` の `TongueSegDataset.__getitem__`(データ拡張あり)と「Params」の写し.
原本の写し.直さない.`legacy/` は import できない(`.claude/rules/legacy.md`)ため,
ここに書き写してある.原本との違いは次の点だけ:
- クラスではなく関数にし,画像とラベルのパスと変換を引数で受け取る(原本はフォルダを glob して
インデックスで選び,変換は `__init__` で受け取る).読み込み・変換・拡張の式と順序は原本のまま
- 「Params」の `transform_sample`・`transform_label`・`transform_both` を関数にした
(作るたびに同じものになる.値は原本のまま)
ruff の整形(引用符の種類)以外は原本どおり.
"""
import random
import cv2
import torch
import torchvision.transforms.functional as TF # noqa: N812
from torchvision import transforms
def original_params():
transform_sample = transforms.Compose(
[transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5)]
)
transform_label = transforms.Compose([])
transform_both = [(TF.hflip, 0.5)]
return transform_sample, transform_label, transform_both
def original_augmented_getitem(
path_sample, path_label, transform_sample=None, transform_label=None, transform_both=None
):
# Load sample
sample = torch.from_numpy(cv2.imread(path_sample, cv2.IMREAD_COLOR)) / 255.0
sample = sample.permute(2, 0, 1).float()
if transform_sample:
sample = transform_sample(sample)
# Load label
label = torch.from_numpy(cv2.imread(path_label, cv2.IMREAD_COLOR))
label[label <= 128] = 0.0
label[label > 128] = 1.0
label = label.permute(2, 0, 1).float()
if transform_label:
label = transform_label(label)
if transform_both:
for tf, p in transform_both:
if random.random() < p:
sample = tf(sample)
label = tf(label)
label_pos = label[0, :, :]
label_neg = torch.ones(label_pos.shape) - label[0, :, :]
label_pos = label_pos.unsqueeze(0)
label_neg = label_neg.unsqueeze(0)
label = torch.cat([label_pos, label_neg], axis=0)
return sample, label