File size: 9,492 Bytes
01fdb75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# REFUGE2 Dataset for PixelGen Medical Image Generation
# Optic disc/cup segmentation: 1200 RGB fundus images with 3-class masks
# Mask values: 0=background, 128=optic cup, 255=optic disc

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

        # Collect files from specified splits
        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)
                # Mask may have different extension (.bmp or .png)
                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))

        # Optional: hold out a portion for validation
        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

        # Limit samples if specified
        if max_samples is not None and max_samples < len(self.pairs):
            random.seed(seed)
            self.pairs = random.sample(self.pairs, max_samples)

        # Normalization for images ([-1, 1] range)
        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')

        # Resize to target size (square)
        image = TF.resize(image, (self.resolution, self.resolution),
                         interpolation=transforms.InterpolationMode.BILINEAR)
        mask = TF.resize(mask, (self.resolution, self.resolution),
                        interpolation=transforms.InterpolationMode.NEAREST)

        # Data augmentation
        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)

            # Random color jitter for image only
            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)  # [3, H, W], range [0, 1]
        normalized_image = self.normalize(raw_image)

        # Normalize mask: 0->0.0, 128->0.5, 255->1.0
        mask_tensor = TF.to_tensor(mask)  # [1, H, W], range [0, 1]

        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

        # Collect all mask paths
        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