forked from z-bingo/kernel-prediction-networks-PyTorch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_prepare.py.orig
201 lines (167 loc) · 8.01 KB
/
data_prepare.py.orig
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#导入相关模块
from torch.utils.data import DataLoader,Dataset
from skimage import io,transform
import matplotlib.pyplot as plt
import os
import torch
from torchvision import transforms
import numpy as np
from PIL import Image, ImageOps
from skimage.color import rgb2xyz
import inspect
from utils.training_util import read_config
from data_generation.data_utils import *
import torch.nn.functional as F
class Random_Horizontal_Flip(object):
def __init__(self, p=0.5):
self.p = p
def __call__(self, tensor):
if np.random.rand() < self.p:
return torch.flip(tensor, dims=[-1])
return tensor
class Random_Vertical_Flip(object):
def __init__(self, p=0.5):
self.p = p
def __call__(self, tensor):
if np.random.rand() < self.p:
return torch.flip(tensor, dims=[-2])
return tensor
class Customized_dataset(Dataset): #继承Dataset
def __init__(self, config_file, train_dir, local_window_size, config_spec=None, color= False, train=True, transform=None, magnitude=1): #__init__是初始化该类的一些基础参数
if config_spec is None:
config_spec = self._configspec_path()
config = read_config(config_file, config_spec)
self.dataset_config = config['dataset_configs']
self.local_window_size = int(local_window_size)
self.dataset_dir = train_dir
self.train_dir = train_dir #文件目录
self.transform = transform #变换
self.input = os.listdir(self.train_dir)#目录里的所有文件
self.burst_size = self.dataset_config['burst_length']
self.patch_size = self.dataset_config['patch_size']
self.upscale = self.dataset_config['down_sample']
self.big_jitter = self.dataset_config['big_jitter']
self.small_jitter = self.dataset_config['small_jitter']
# 对应下采样之前图像的最大偏移量
self.jitter_upscale = self.big_jitter * self.upscale
# 对应下采样之前的图像的patch尺寸
self.size_upscale = self.patch_size * self.upscale + 2 * self.jitter_upscale
# 产生大jitter和小jitter之间的delta 在下采样之前的尺度上
self.delta_upscale = (self.big_jitter - self.small_jitter) * self.upscale
# 对应到原图的patch的尺寸
self.patch_size_upscale = self.patch_size * self.upscale
self.magnitude = magnitude
self.color = color
self.train = train
self.vertical_flip = Random_Vertical_Flip(p=0.5)
self.horizontal_flip = Random_Horizontal_Flip(p=0.5)
def __len__(self):#返回整个数据集的大小
return len(self.input)
@staticmethod
def _configspec_path():
current_dir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe()))
)
return os.path.join(current_dir,
'dataset_specs/data_configspec.conf')
@staticmethod
def crop_random(tensor, patch_size):
return random_crop(tensor, 1, patch_size)[0]
# def __getitem__(self,index):#根据索引index返回dataset[index]
# # print(index)
# image = Image.open(os.path.join(self.dataset_dir, self.input[index]))
# if not self.color:
# image = ImageOps.grayscale(image)
# else:
# raise Exception("Only gray scale is supported")
# # 先转换为Tensor进行degamma
# image = transforms.ToTensor()(image)
# image_crop = self.crop_random(image, self.size_upscale)
# # N*H*W 对应于较小jitter下
# image_crop_small = image_crop[:, self.delta_upscale:-self.delta_upscale,
# self.delta_upscale:-self.delta_upscale]
# # 进一步进行random_crop所需的transform
# # burst中的第一个不做偏移 后期作为target
# # output shape: N*3*H*W
# img_burst = []
# for i in range(self.burst_size+1):
# if i == 0:
# img_burst.append(
# image_crop[:, self.jitter_upscale:-self.jitter_upscale, self.jitter_upscale:-self.jitter_upscale]
# )
# else:
# if np.random.binomial(1, min(1.0, np.random.poisson(lam=1.5) / self.burst_size)) == 0:
# img_burst.append(
# self.crop_random(
# image_crop_small, self.patch_size_upscale
# )
# )
# else: #big
# img_burst.append(
# self.crop_random(image_crop, self.patch_size_upscale)
# )
# image_burst = torch.stack(img_burst, dim=0)
# image_burst = F.adaptive_avg_pool2d(image_burst, (self.patch_size, self.patch_size))
# # label为patch中burst的第一个
# if not self.color:
# # image_burst = 0.2989*image_burst[:, 0, ...] + 0.5870 * image_burst[:, 1, ...] + 0.1140*image_burst[:, 2, ...]
# image_burst = torch.clamp(image_burst, 0.0, 1.0)
# else:
# raise Exception("Only gray scale is supported")
# if self.train:
# # data augment
# image_burst = self.horizontal_flip(image_burst)
# image_burst = self.vertical_flip(image_burst)
# label = image_burst[0, ...]
# img = image_burst[1:, ...]
# #TODO: potentially add degamma and white level
# # generate the binary frames burst
# local_summation_window = 40 # 局部窗口大小
# img = torch.poisson(img.repeat(1,local_summation_window,1,1))
# img = (img > 0).float()
# img = torch.mean(img, dim=1)
# return img.squeeze(),label.squeeze() #返回该样本
# # version to handle moving scenes
# def __getitem__(self, index):
# image = np.load(os.path.join(self.dataset_dir, self.input[index]))
# image = torch.from_numpy(image)
# # over-sample the image between the frames
# oversample_rate = 1
# image = image.repeat(1,oversample_rate,1).reshape(image.shape[0]*oversample_rate, image.shape[1],image.shape[2])
# image = F.adaptive_avg_pool2d(image, (self.patch_size, self.patch_size))
# if image.shape[0] % 2 == 0:
# image = image[:-1, ...]
# label = image[image.shape[0]//2, ...]
# img = torch.cat([image[:image.shape[0]//2, ...], image[image.shape[0]//2+1:, ...]], dim=0)
# img = img.reshape(self.burst_size, -1, img.shape[1], img.shape[2])
# img = torch.poisson(img)
# img = (img > 0).float()
# img = torch.mean(img, dim=1)
# return img.squeeze(),label.squeeze() #返回该样本
def __getitem__(self,index):#根据索引index返回dataset[index]
# print(index)
image = Image.open(os.path.join(self.dataset_dir, self.input[index]))
if not self.color:
image = ImageOps.grayscale(image)
else:
raise Exception("Only gray scale is supported")
# 先转换为Tensor进行degamma
image = transforms.ToTensor()(image)
# output shape: N*1*H*W
image_burst = image.repeat(self.burst_size+1,1,1,1)
image_burst = F.adaptive_avg_pool2d(image_burst, (self.patch_size, self.patch_size))
# label为patch中burst的第一个
if not self.color:
# image_burst = 0.2989*image_burst[:, 0, ...] + 0.5870 * image_burst[:, 1, ...] + 0.1140*image_burst[:, 2, ...]
image_burst = torch.clamp(image_burst, 0.0, 1.0)
else:
raise Exception("Only gray scale is supported")
label = image_burst[0, ...]
img = image_burst[1:, ...]
#TODO: potentially add degamma and white level
# generate the binary frames burst
local_summation_window = self.local_window_size # 局部窗口大小
img = torch.poisson(img.repeat(1,local_summation_window,1,1))
img = (img > 0).float()
img = torch.mean(img, dim=1)
return img.squeeze(),label.squeeze() #返回该样本