-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataloader.py
38 lines (31 loc) · 1.3 KB
/
dataloader.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
import os
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from PIL import Image
class ProstateDataset(Dataset):
def __init__(self, img_dir, mask_dir, transform=None):
"""
Args:
img_dir (string): Directory with all the images.
mask_dir (string): Directory with all the masks.
transform (callable, optional): Optional transform to be applied on a sample.
"""
self.img_dir = img_dir
self.mask_dir = mask_dir
self.transform = transform
self.images = sorted([os.path.join(img_dir, file) for file in os.listdir(img_dir) if file.endswith('.png')])
self.masks = sorted([os.path.join(mask_dir, file) for file in os.listdir(mask_dir) if file.endswith('.png')])
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
img_path = self.images[idx]
mask_path = self.masks[idx]
image = Image.open(img_path).convert('L') # Convert to grayscale
mask = Image.open(mask_path).convert('L') # Convert to grayscale (binary mask)
sample = {'image': image, 'mask': mask}
if self.transform:
sample = self.transform(sample)
return sample