-
Notifications
You must be signed in to change notification settings - Fork 1
/
dataset.py
150 lines (116 loc) · 4.98 KB
/
dataset.py
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
import os
import numpy as np
import albumentations as A
from typing import Any
from glob import glob
from PIL import Image
from albumentations.pytorch import ToTensorV2
from torch.utils.data import Dataset, DataLoader
class CustomDataset(Dataset):
def __init__(
self,
data_dir: str = None,
transformations: A.Compose = None,
pre_split: bool = False,
split: str = "train",
test_ratio: int = 0.2,
) -> None:
if not os.path.exists(data_dir):
raise ValueError(f'Provided data_dir: "{data_dir}" does not exist.')
np.random.seed(42)
self.data_dir = data_dir
self.image_dir = os.path.join(data_dir, "Image")
self.mask_dir = os.path.join(data_dir, "Mask")
self.image_filenames = sorted(glob(os.path.join(self.image_dir, "*.png")))
self.mask_filenames = sorted(glob(os.path.join(self.mask_dir, "*.png")))
self.transformations = transformations
self.split = split
self.pre_split = pre_split
self.test_ratio = test_ratio
num_samples = len(self.image_filenames)
indices = list(range(num_samples))
if not self.pre_split:
np.random.shuffle(indices)
num_test_samples = int(self.test_ratio * num_samples)
if self.split == "train":
self.indices = indices[:-num_test_samples]
elif self.split == "test":
self.indices = indices[-num_test_samples:]
else:
raise ValueError("Invalid split value. Use 'train' or 'test'.")
else:
self.indices = indices
def __len__(self) -> int:
return len(self.indices)
def __getitem__(self, idx: Any) -> Any:
img_idx = self.indices[idx]
img_name = self.image_filenames[img_idx]
mask_name = self.mask_filenames[img_idx]
image = np.array(Image.open(img_name).convert("RGB"), dtype=np.float32)
mask = np.array(Image.open(mask_name).convert("L"), dtype=np.float32)
image = image / 255.0
mask = mask / 255.0
if self.transformations is not None:
augmentations = self.transformations(image=image, mask=mask)
image = augmentations["image"]
mask = augmentations["mask"]
mask = np.expand_dims(mask, axis=0)
return image, mask
class EvalDataset(Dataset):
def __init__(self, data_dir: str, transformations: A.Compose = None) -> None:
if not os.path.exists(data_dir):
return ValueError(f'Provided data_dir: "{data_dir}" does not exist.')
self.data_dir = data_dir
self.image_dir = os.path.join(data_dir, "Image")
self.mask_dir = os.path.join(data_dir, "Mask")
self.image_filenames = sorted(glob(os.path.join(self.image_dir, "*.png")))
self.mask_filenames = sorted(glob(os.path.join(self.mask_dir, "*.png")))
self.transformations = transformations
def __len__(self) -> int:
return len(self.image_filenames)
def __getitem__(self, idx: Any) -> Any:
img_name = self.image_filenames[idx]
mask_name = self.mask_filenames[idx]
image = np.array(Image.open(img_name).convert("RGB"), dtype=np.float32)
mask = np.array(Image.open(mask_name).convert("L"), dtype=np.float32)
image = image / 255.0
mask = mask / 255.0
if self.transformations is not None:
augmentations = self.transformations(image=image, mask=mask)
image = augmentations["image"]
mask = augmentations["mask"]
mask = np.expand_dims(mask, axis=0)
return image, mask
if __name__ == "__main__":
data_dir = "./data_ews"
input_size = (256, 256)
train_transform = A.Compose(
[
A.Resize(input_size[0], input_size[1]),
ToTensorV2(),
]
)
test_transform = A.Compose(
[
A.Resize(input_size[0], input_size[1]),
ToTensorV2(),
]
)
# Train dataset with defining split
train_dataset = CustomDataset(data_dir, transformations=train_transform, split="train")
train_dataloader = DataLoader(train_dataset, batch_size=4, shuffle=True)
# Test dataset with defining split
test_dataset = CustomDataset(data_dir, transformations=test_transform, split="test")
test_dataloader = DataLoader(test_dataset, batch_size=4, shuffle=False)
# for images, masks in train_dataloader:
# # Use the train data here for training
# print(f"Image: {images.shape}")
# print(f"Mask: {masks.shape}")
# Train dataset with pre-split
split_train = CustomDataset(data_dir="./augmented_data_ews/Train", pre_split=True)
split_train_loader = DataLoader(split_train, batch_size=4, shuffle=False)
# Test dataset with pre-split
split_test = CustomDataset(data_dir="./augmented_data_ews/Test", pre_split=True)
split_test_loader = DataLoader(split_train, batch_size=4, shuffle=False)
print(split_train.__len__())
print(split_test.__len__())