| |
| |
| |
|
|
| import os |
| import torch |
| import random |
| import numpy as np |
| from torch.utils.data import Dataset |
| from PIL import Image |
| import torchvision.transforms as transforms |
| import torchvision.transforms.functional as TF |
| from torchvision.transforms import Normalize |
|
|
|
|
| class REFUGE2Dataset(Dataset): |
| """ |
| REFUGE2 dataset for mask-conditional image generation. |
| |
| Data format: |
| - Images: RGB fundus photographs (varying sizes ~1600-2100px) |
| - Masks: 3-class segmentation (0=background, 128=optic cup, 255=optic disc) |
| - 400 images per split (train/val/test) |
| - Mask files: train/test=.bmp, val=.png |
| |
| Returns format compatible with PixelGen: |
| - normalized_image: [3, H, W] in range [-1, 1] |
| - label: class label (0 for all) |
| - metadata: dict with 'raw_image', 'mask', 'class' |
| """ |
|
|
| def __init__(self, data_root, resolution=256, splits=('train', 'val'), |
| augment=True, seed=42, max_samples=None, random_flip=True, |
| val_ratio=0.0): |
| super().__init__() |
| self.data_root = data_root |
| self.resolution = resolution |
| self.augment = augment |
| self.random_flip = random_flip |
|
|
| |
| all_pairs = [] |
| for split in splits: |
| img_dir = os.path.join(data_root, split, 'images') |
| mask_dir = os.path.join(data_root, split, 'mask') |
|
|
| img_files = sorted([f for f in os.listdir(img_dir) |
| if f.endswith(('.jpg', '.png', '.jpeg'))]) |
|
|
| for img_f in img_files: |
| img_path = os.path.join(img_dir, img_f) |
| |
| base_name = os.path.splitext(img_f)[0] |
| mask_path = None |
| for ext in ['.bmp', '.png', '.jpg']: |
| candidate = os.path.join(mask_dir, base_name + ext) |
| if os.path.exists(candidate): |
| mask_path = candidate |
| break |
| if mask_path is not None: |
| all_pairs.append((img_path, mask_path)) |
|
|
| |
| if val_ratio > 0: |
| random.seed(seed) |
| random.shuffle(all_pairs) |
| split_idx = int(len(all_pairs) * (1 - val_ratio)) |
| self.pairs = all_pairs[:split_idx] |
| else: |
| self.pairs = all_pairs |
|
|
| |
| if max_samples is not None and max_samples < len(self.pairs): |
| random.seed(seed) |
| self.pairs = random.sample(self.pairs, max_samples) |
|
|
| |
| self.normalize = Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) |
|
|
| print(f"[REFUGE2Dataset] splits={splits}: {len(self.pairs)} image pairs") |
|
|
| def __len__(self): |
| return len(self.pairs) |
|
|
| def _load_and_process(self, idx): |
| """Load and process a single sample.""" |
| img_path, mask_path = self.pairs[idx] |
|
|
| image = Image.open(img_path).convert('RGB') |
| mask = Image.open(mask_path).convert('L') |
|
|
| |
| image = TF.resize(image, (self.resolution, self.resolution), |
| interpolation=transforms.InterpolationMode.BILINEAR) |
| mask = TF.resize(mask, (self.resolution, self.resolution), |
| interpolation=transforms.InterpolationMode.NEAREST) |
|
|
| |
| if self.augment: |
| if self.random_flip and random.random() > 0.5: |
| image = TF.hflip(image) |
| mask = TF.hflip(mask) |
|
|
| if self.random_flip and random.random() > 0.5: |
| image = TF.vflip(image) |
| mask = TF.vflip(mask) |
|
|
| |
| if random.random() > 0.5: |
| brightness_factor = random.uniform(0.85, 1.15) |
| image = TF.adjust_brightness(image, brightness_factor) |
| contrast_factor = random.uniform(0.85, 1.15) |
| image = TF.adjust_contrast(image, contrast_factor) |
| saturation_factor = random.uniform(0.85, 1.15) |
| image = TF.adjust_saturation(image, saturation_factor) |
|
|
| return image, mask |
|
|
| def __getitem__(self, idx): |
| max_retries = 10 |
| for retry in range(max_retries): |
| try: |
| actual_idx = (idx + retry) % len(self.pairs) |
| image, mask = self._load_and_process(actual_idx) |
| break |
| except Exception as e: |
| if retry == max_retries - 1: |
| raise RuntimeError(f"Failed to load image after {max_retries} retries: {e}") |
| continue |
|
|
| raw_image = TF.to_tensor(image) |
| normalized_image = self.normalize(raw_image) |
|
|
| |
| mask_tensor = TF.to_tensor(mask) |
|
|
| label = 0 |
| metadata = { |
| "raw_image": raw_image, |
| "mask": mask_tensor, |
| "class": label, |
| } |
|
|
| return normalized_image, label, metadata |
|
|
|
|
| class REFUGE2ValDataset(Dataset): |
| """Validation subset from REFUGE2 (held-out from training splits).""" |
|
|
| def __init__(self, data_root, resolution=256, splits=('train', 'val'), |
| val_ratio=0.1, seed=42): |
| super().__init__() |
| self.resolution = resolution |
| self.normalize = Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) |
|
|
| all_pairs = [] |
| for split in splits: |
| img_dir = os.path.join(data_root, split, 'images') |
| mask_dir = os.path.join(data_root, split, 'mask') |
| img_files = sorted([f for f in os.listdir(img_dir) |
| if f.endswith(('.jpg', '.png', '.jpeg'))]) |
| for img_f in img_files: |
| base_name = os.path.splitext(img_f)[0] |
| img_path = os.path.join(img_dir, img_f) |
| mask_path = None |
| for ext in ['.bmp', '.png', '.jpg']: |
| candidate = os.path.join(mask_dir, base_name + ext) |
| if os.path.exists(candidate): |
| mask_path = candidate |
| break |
| if mask_path is not None: |
| all_pairs.append((img_path, mask_path)) |
|
|
| random.seed(seed) |
| random.shuffle(all_pairs) |
| split_idx = int(len(all_pairs) * (1 - val_ratio)) |
| self.pairs = all_pairs[split_idx:] |
|
|
| print(f"[REFUGE2ValDataset] {len(self.pairs)} val samples") |
|
|
| def __len__(self): |
| return len(self.pairs) |
|
|
| def __getitem__(self, idx): |
| img_path, mask_path = self.pairs[idx] |
| image = Image.open(img_path).convert('RGB') |
| mask = Image.open(mask_path).convert('L') |
| image = TF.resize(image, (self.resolution, self.resolution), |
| interpolation=transforms.InterpolationMode.BILINEAR) |
| mask = TF.resize(mask, (self.resolution, self.resolution), |
| interpolation=transforms.InterpolationMode.NEAREST) |
|
|
| raw_image = TF.to_tensor(image) |
| normalized_image = self.normalize(raw_image) |
| mask_tensor = TF.to_tensor(mask) |
|
|
| label = 0 |
| metadata = { |
| "raw_image": raw_image, |
| "mask": mask_tensor, |
| "class": label, |
| } |
| return normalized_image, label, metadata |
|
|
|
|
| class REFUGE2RandnDataset(Dataset): |
| """Random noise dataset for evaluation/prediction with REFUGE2 masks.""" |
|
|
| def __init__(self, data_root, resolution=256, max_num_instances=1000, |
| noise_scale=1.0, seed=42, splits=('train', 'val', 'test')): |
| super().__init__() |
| self.resolution = resolution |
| self.noise_scale = noise_scale |
|
|
| |
| all_masks = [] |
| for split in splits: |
| mask_dir = os.path.join(data_root, split, 'mask') |
| if not os.path.exists(mask_dir): |
| continue |
| mask_files = sorted([f for f in os.listdir(mask_dir) |
| if f.endswith(('.bmp', '.png', '.jpg'))]) |
| for mf in mask_files: |
| all_masks.append(os.path.join(mask_dir, mf)) |
|
|
| random.seed(seed) |
| if max_num_instances <= len(all_masks): |
| self.mask_paths = random.sample(all_masks, max_num_instances) |
| else: |
| self.mask_paths = all_masks * (max_num_instances // len(all_masks) + 1) |
| self.mask_paths = self.mask_paths[:max_num_instances] |
|
|
| print(f"[REFUGE2RandnDataset] {len(self.mask_paths)} samples for generation") |
|
|
| def __len__(self): |
| return len(self.mask_paths) |
|
|
| def __getitem__(self, idx): |
| xT = self.noise_scale * torch.randn(3, self.resolution, self.resolution) |
|
|
| mask = Image.open(self.mask_paths[idx]).convert('L') |
| mask = TF.resize(mask, (self.resolution, self.resolution), |
| interpolation=transforms.InterpolationMode.NEAREST) |
| mask_tensor = TF.to_tensor(mask) |
|
|
| label = 0 |
| metadata = { |
| "mask": mask_tensor, |
| "class": label, |
| } |
| return xT, label, metadata |
|
|