File size: 6,119 Bytes
e99a83c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from pathlib import Path

import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from PIL import Image


class FIVESDataset(Dataset):
    """
    PyTorch Dataset for FIVES retinal vessel segmentation.

    Expected structure:
        FIVES_dataset/
        β”œβ”€β”€ train/
        β”‚   β”œβ”€β”€ Original/
        β”‚   └── Ground truth/
        └── test/
            β”œβ”€β”€ Original/
            └── Ground truth/

    Each image in Original/ should have a matching vessel mask
    with the same filename in Ground truth/.

    Output sample:
        {
            "image": Tensor [3, H, W],
            "label": Tensor [1, H, W],
            "case_id": str,
            "image_path": str,
            "label_path": str,
        }

    If transform is provided, it should be an Albumentations transform.
    """

    def __init__(
        self,
        root,
        split="train",
        transform=None,
        image_dir_name="Original",
        label_dir_name="Ground truth",
    ):
        self.root = Path(root)
        self.split = split
        self.transform = transform

        if split not in ["train", "test"]:
            raise ValueError("split must be either 'train' or 'test'")

        self.split_dir = self.root / split
        self.image_dir = self.split_dir / image_dir_name
        self.label_dir = self.split_dir / label_dir_name

        if not self.image_dir.exists():
            raise FileNotFoundError(f"Image directory not found: {self.image_dir}")

        if not self.label_dir.exists():
            raise FileNotFoundError(f"Label directory not found: {self.label_dir}")

        self.image_paths = sorted(
            [
                p for p in self.image_dir.glob("*.png")
                if not p.name.startswith(".") and p.name.lower() != "thumbs.db"
            ]
        )

        if len(self.image_paths) == 0:
            raise RuntimeError(f"No PNG images found in {self.image_dir}")

        self.samples = []

        for image_path in self.image_paths:
            label_path = self.label_dir / image_path.name

            if not label_path.exists():
                raise FileNotFoundError(
                    f"Missing label for image:\n"
                    f"image: {image_path}\n"
                    f"label: {label_path}"
                )

            self.samples.append(
                {
                    "image_path": image_path,
                    "label_path": label_path,
                    "case_id": image_path.stem,
                }
            )

    def __len__(self):
        return len(self.samples)

    def _load_image(self, path):
        image = Image.open(path).convert("RGB")
        return np.array(image)

    def _load_mask(self, path):
        mask = Image.open(path).convert("L")
        return np.array(mask)

    def __getitem__(self, idx):
        sample_info = self.samples[idx]

        image_path = sample_info["image_path"]
        label_path = sample_info["label_path"]
        case_id = sample_info["case_id"]

        image = self._load_image(image_path)
        label = self._load_mask(label_path)

        if self.transform is not None:
            transformed = self.transform(
                image=image,
                mask=label,
            )

            image = transformed["image"]
            label = transformed["mask"]

            # Albumentations ToTensorV2 converts image to [3, H, W],
            # but mask remains [H, W], so add channel dimension.
            if isinstance(label, torch.Tensor):
                label = label.float().unsqueeze(0)
            else:
                label = torch.from_numpy(label).float().unsqueeze(0)

        else:
            image = torch.from_numpy(image).permute(2, 0, 1).float() / 255.0
            label = torch.from_numpy(label).float().unsqueeze(0)

        # Convert vessel mask to binary {0, 1}
        label = (label > 0).float()

        return {
            "image": image,
            "label": label,
            "case_id": case_id,
            "image_path": str(image_path),
            "label_path": str(label_path),
        }


if __name__ == "__main__":
    import matplotlib.pyplot as plt

    try:
        from augmentations import get_train_transforms, get_val_transforms
    except ImportError:
        import sys

        project_root = Path(__file__).resolve().parents[1]
        sys.path.append(str(project_root))

        from augmentations import get_train_transforms, get_val_transforms

    root = "/data/MIDS/datasets/retina/FIVES_dataset"
    image_size = 512

    dataset = FIVESDataset(
        root=root,
        split="train",
        transform=get_train_transforms(image_size=image_size),
    )

    loader = DataLoader(
        dataset,
        batch_size=4,
        shuffle=True,
        num_workers=0,
    )

    batch = next(iter(loader))

    print("Number of samples:", len(dataset))
    print("Batch keys:", batch.keys())
    print("Image shape:", batch["image"].shape)
    print("Label shape:", batch["label"].shape)
    print("Label min/max:", batch["label"].min().item(), batch["label"].max().item())
    print("Case IDs:", batch["case_id"])

    # -------------------------
    # Matplotlib visualization
    # -------------------------
    image = batch["image"][0]
    label = batch["label"][0, 0]

    # Undo ImageNet normalization for visualization.
    mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
    std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)

    image_vis = image.cpu() * std + mean
    image_vis = image_vis.clamp(0, 1)
    image_vis = image_vis.permute(1, 2, 0).numpy()

    label_vis = label.cpu().numpy()

    fig, axes = plt.subplots(1, 3, figsize=(12, 4))

    axes[0].imshow(image_vis)
    axes[0].set_title("Image")
    axes[0].axis("off")

    axes[1].imshow(label_vis, cmap="gray")
    axes[1].set_title("Vessel Label")
    axes[1].axis("off")

    axes[2].imshow(image_vis)
    axes[2].imshow(label_vis, cmap="Reds", alpha=0.45)
    axes[2].set_title("Overlay")
    axes[2].axis("off")

    plt.tight_layout()
    plt.show()