forked from MMathisLab/stylize-datasets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
44 lines (36 loc) · 1.17 KB
/
utils.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
import torch
from torch.utils.data import Dataset
from torchvision.datasets.folder import default_loader
from torch.utils.data.dataloader import default_collate
class ImageFolderWithPaths(Dataset):
"""
Custom dataset that includes image file paths.
"""
def __init__(self, root, paths, loader=default_loader, transform=None):
if len(paths) == 0:
raise (RuntimeError("Found 0 files in " + root))
self.root = root
self.loader = loader
self.samples = paths
self.transform = transform
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (sample, path)
"""
path = self.samples[index]
sample = self.loader(path)
if self.transform is not None:
sample = self.transform(sample)
return sample, path
def __len__(self):
return len(self.samples)
def collate(batch):
if isinstance(batch[0], torch.Tensor):
return default_collate(batch)
elif isinstance(batch[0], tuple):
transposed = zip(*batch)
return [collate(samples) for samples in transposed]
return batch