-
Notifications
You must be signed in to change notification settings - Fork 10
/
dataset.py
71 lines (58 loc) · 2.42 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
import torch.utils.data as data
from os import listdir
from os.path import join
from PIL import Image
import pickle
def is_image_file(filename):
return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg", ".JPEG"])
def load_img(filepath):
img = Image.open(filepath).convert('RGB')
return img
class DatasetFromFolder(data.Dataset):
def __init__(self, image_dir, input_transform=None, cache=True ):
super(DatasetFromFolder, self).__init__()
self.image_filenames = [join(image_dir, x) for x in listdir(image_dir) if is_image_file(x)]
self.image_filenames.sort()
self.input_transform = input_transform
self.cache = cache
if cache :
self.image_list = []
for image_file in self.image_filenames:
self.image_list.append(load_img(image_file))
print('load image finished')
def __getitem__(self, index):
if not self.cache:
input = load_img(self.image_filenames[index])
else:
input = self.image_list[index]
if self.input_transform:
input = self.input_transform(input)
return input, self.image_filenames[index]
def __len__(self):
return len(self.image_list) if self.cache else len(self.image_filenames)
class DatasetFromList(data.Dataset):
def __init__(self, list_path, input_transform=None, cache=True):
super(DatasetFromList, self).__init__()
with open(list_path) as f:
self.image_filenames = []
for line in f.readlines():
self.image_filenames.append(line.strip('\n'))
self.image_filenames = [x for x in self.image_filenames if is_image_file(x)]
self.image_filenames.sort()
self.input_transform = input_transform
self.cache = cache
if cache :
self.image_list = []
for image_file in self.image_filenames:
self.image_list.append(load_img(image_file))
print('load image finished')
def __getitem__(self, index):
if not self.cache:
input = load_img(self.image_filenames[index])
else:
input = self.image_list[index]
if self.input_transform:
input = self.input_transform(input)
return input, self.image_filenames[index]
def __len__(self):
return len(self.image_list) if self.cache else len(self.image_filenames)