-
Notifications
You must be signed in to change notification settings - Fork 3
/
base_dataset.py
48 lines (40 loc) · 1.46 KB
/
base_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
import torch.utils.data as data
from torchvision import transforms
from PIL import Image
import os
import numpy as np
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
def make_dataset(dir):
if os.path.isfile(dir):
images = [i for i in np.genfromtxt(dir, dtype=np.str, encoding='utf-8')]
else:
images = []
assert os.path.isdir(dir), '%s is not a valid directory' % dir
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if is_image_file(fname):
path = os.path.join(root, fname)
images.append(path)
return images
def pil_loader(path):
return Image.open(path).convert('RGB')
class BaseDataset(data.Dataset):
def __init__(self, data_root, image_size=[256, 256], loader=pil_loader):
self.imgs = make_dataset(data_root)
self.tfs = transforms.Compose([
transforms.Resize((image_size[0], image_size[1])),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
])
self.loader = loader
def __getitem__(self, index):
path = self.imgs[index]
img = self.tfs(self.loader(path))
return img
def __len__(self):
return len(self.imgs)