-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
59 lines (46 loc) · 2.13 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
from os import listdir
from os.path import join
import random
from PIL import Image
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from utils import is_image_file, load_img
class DatasetFromFolder(data.Dataset):
def __init__(self, image_dir, direction):
super(DatasetFromFolder, self).__init__()
self.direction = direction
self.a_path = join(image_dir, "a")
self.b_path = join(image_dir, "b")
self.image_filenames = [x for x in listdir(self.a_path) if is_image_file(x)]
transform_list = [transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
self.transform = transforms.Compose(transform_list)
def __getitem__(self, index):
a = Image.open(join(self.a_path, self.image_filenames[index])).convert('RGB')
b = Image.open(join(self.b_path, self.image_filenames[index])).convert('RGB')
#三次样条插值
a = a.resize((286, 286), Image.BICUBIC)
b = b.resize((286, 286), Image.BICUBIC)
a = transforms.ToTensor()(a) # range [0, 255] -> [0.0,1.0]
b = transforms.ToTensor()(b) # range [0, 255] -> [0.0,1.0]
#图像增广处理
w_offset = random.randint(0, max(0, 286 - 256 - 1))
h_offset = random.randint(0, max(0, 286 - 256 - 1))
#torch.Size([3, 286, 286]) -->torch.Size([3, 256, 256])
a = a[:, h_offset:h_offset + 256, w_offset:w_offset + 256]
b = b[:, h_offset:h_offset + 256, w_offset:w_offset + 256]
a = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(a) # range [0.0, 1.0] -> [-1.0,1.0]
b = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(b) # range [0.0, 1.0] -> [-1.0,1.0]
#一半的图像翻转
if random.random() < 0.5:
idx = [i for i in range(a.size(2) - 1, -1, -1)]
idx = torch.LongTensor(idx)
a = a.index_select(2, idx)
b = b.index_select(2, idx)
if self.direction == "a2b":
return a, b
else:
return b, a
def __len__(self):
return len(self.image_filenames)