forked from jzbontar/mc-cnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocess_mb.py
executable file
·344 lines (279 loc) · 12.1 KB
/
preprocess_mb.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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#! /usr/bin/env python2
# wget -r -np -A png,pfm,pgm,txt http://vision.middlebury.edu/stereo/data/scenes2014/datasets/
# wget -r -np -A png,pfm,pgm,txt http://vision.middlebury.edu/stereo/data/scenes2006/FullSize/
import os
import re
import sys
import subprocess
import numpy as np
import cv2
def load_pfm(fname, downsample):
if downsample:
if not os.path.isfile(fname + '.H.pfm'):
x, scale = load_pfm(fname, False)
x = x / 2
x_ = np.zeros((x.shape[0] // 2, x.shape[1] // 2), dtype=np.float32)
for i in range(0, x.shape[0], 2):
for j in range(0, x.shape[1], 2):
tmp = x[i:i+2,j:j+2].ravel()
x_[i // 2,j // 2] = np.sort(tmp)[1]
save_pfm(fname + '.H.pfm', x_, scale)
return x_, scale
else:
fname += '.H.pfm'
color = None
width = None
height = None
scale = None
endian = None
file = open(fname)
header = file.readline().rstrip()
if header == 'PF':
color = True
elif header == 'Pf':
color = False
else:
raise Exception('Not a PFM file.')
dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline())
if dim_match:
width, height = map(int, dim_match.groups())
else:
raise Exception('Malformed PFM header.')
scale = float(file.readline().rstrip())
if scale < 0: # little-endian
endian = '<'
scale = -scale
else:
endian = '>' # big-endian
data = np.fromfile(file, endian + 'f')
shape = (height, width, 3) if color else (height, width)
return np.flipud(np.reshape(data, shape)), scale
def save_pfm(fname, image, scale=1):
file = open(fname, 'w')
color = None
if image.dtype.name != 'float32':
raise Exception('Image dtype must be float32.')
if len(image.shape) == 3 and image.shape[2] == 3: # color image
color = True
elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale
color = False
else:
raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')
file.write('PF\n' if color else 'Pf\n')
file.write('%d %d\n' % (image.shape[1], image.shape[0]))
endian = image.dtype.byteorder
if endian == '<' or endian == '=' and sys.byteorder == 'little':
scale = -scale
file.write('%f\n' % scale)
np.flipud(image).tofile(file)
def read_im(fname, downsample):
if downsample:
if not os.path.isfile(fname + '.H.png'):
subprocess.check_call('convert {} -resize 50% {}.H.png'.format(fname, fname).split())
fname += '.H.png'
x = cv2.imread(fname).astype(np.float32)
if color == 'rgb':
x = cv2.cvtColor(x, cv2.COLOR_BGR2RGB)
x = x.transpose(2, 0, 1)
else:
x = cv2.cvtColor(x, cv2.COLOR_BGR2GRAY)[None]
x = (x - x.mean()) / x.std()
return x[None]
def tofile(fname, x):
if x is None:
open(fname + '.dim', 'w').write('0\n')
open(fname, 'w')
else:
x.tofile(fname)
open(fname + '.type', 'w').write(str(x.dtype))
open(fname + '.dim', 'w').write('\n'.join(map(str, x.shape)))
rectification, color = sys.argv[1:]
assert(rectification in set(['perfect', 'imperfect']))
assert(color in set(['gray', 'rgb']))
output_dir = 'data.mb.{}_{}'.format(rectification, color)
assert(os.path.isdir(output_dir))
num_channels = 3 if color == 'rgb' else 1
X = []
dispnoc = []
meta = []
nnz_tr = []
nnz_te = []
te = np.arange(1, 11)
### 2014 dataset ###
base1 = 'data.mb/unzip/vision.middlebury.edu/stereo/data/scenes2014/datasets'
for dir in sorted(os.listdir(base1)):
if dir.endswith('imperfect'):
print(dir.split('-')[0])
base2_imperfect = os.path.join(base1, dir)
base2_perfect = base2_imperfect.replace('imperfect', 'perfect')
calib = open(os.path.join(base2_imperfect, 'calib.txt')).read()
ndisp = int(re.search('ndisp=(.*)', calib).group(1)) / 2
x0 = read_im(os.path.join(base2_imperfect, 'im0.png'), True)
x1 = read_im(os.path.join(base2_imperfect, 'im1.png'), True)
x1E = read_im(os.path.join(base2_imperfect, 'im1E.png'), True)
x1L = read_im(os.path.join(base2_imperfect, 'im1L.png'), True)
XX = [np.concatenate((x0, x1, x1E, x1L))]
base3 = os.path.join(base2_perfect if rectification == 'perfect' else base2_imperfect, 'ambient')
num_light = len(os.listdir(base3))
num_exp = [], []
for fname in os.listdir(base3 + '/L1'):
num_exp[int(fname[2])].append(int(fname[4]) + 1)
num_exp = min(max(num_exp[0]), max(num_exp[1]))
rng = {
8: [1, 3, 5],
7: [1, 3, 5],
6: [0, 2, 4],
5: [0, 2, 4],
3: [0, 1, 2],
2: [0, 1],
}
for light in range(num_light):
imgs = []
base4 = os.path.join(base3, 'L{}'.format(light + 1))
for exp in rng[num_exp]:
for cam in range(2):
im = read_im(base4 + '/im{}e{}.png'.format(cam, exp), True)
imgs.append(im)
_, _, height, width = imgs[0].shape
XX.append(np.concatenate(imgs).reshape(len(imgs) // 2, 2, num_channels, height, width))
disp0, scale0 = load_pfm(os.path.join(base2_imperfect, 'disp0.pfm'), True)
disp1, scale1 = load_pfm(os.path.join(base2_imperfect, 'disp1.pfm'), True)
disp0y, scale0y = load_pfm(os.path.join(base2_imperfect, 'disp0y.pfm'), True)
save_pfm('tmp/disp0.pfm', disp0, 1)
save_pfm('tmp/disp1.pfm', disp1, 1)
save_pfm('tmp/disp0y.pfm', disp0y, 1)
subprocess.check_output('computemask tmp/disp0.pfm tmp/disp0y.pfm tmp/disp1.pfm -1 tmp/mask.png'.split())
mask = cv2.imread('tmp/mask.png', 0)
disp0[mask != 255] = 0
y, x = np.nonzero(mask == 255)
X.append(XX)
nnz = nnz_te if len(X) in te else nnz_tr
nnz.append(np.column_stack((np.zeros_like(y) + len(X), y, x, disp0[y, x])).astype(np.float32))
dispnoc.append(disp0.astype(np.float32))
meta.append((x0.shape[2], x0.shape[3], ndisp))
print(np.vstack(nnz_tr).shape)
### 2006 & 2005 dataset ###
for year in (2006, 2005):
base1 = 'data.mb/unzip/vision.middlebury.edu/stereo/data/scenes{}/HalfSize'.format(year)
for dir in sorted(os.listdir(base1)):
base2 = os.path.join(base1, dir)
if not os.path.isfile(base2 + '/disp1.png'):
continue
print(dir)
XX = []
XX.append(None) # there are no test images for this dataset
for light in range(3):
imgs = []
for exp in (0, 1, 2):
base3 = os.path.join(base2, 'Illum{}/Exp{}'.format(light + 1, exp))
x0 = read_im(os.path.join(base3, 'view1.png'), False)
x1 = read_im(os.path.join(base3, 'view5.png'), False)
imgs.append(x0)
imgs.append(x1)
_, _, height, width = imgs[0].shape
XX.append(np.concatenate(imgs).reshape(len(imgs) // 2, 2, num_channels, height, width))
disp0 = cv2.imread(base2 + '/disp1.png', 0).astype(np.float32) / 2
disp1 = cv2.imread(base2 + '/disp5.png', 0).astype(np.float32) / 2
ndisp = int(np.ceil(disp0.max()))
disp0[disp0 == 0] = np.inf
disp1[disp1 == 0] = np.inf
save_pfm('tmp/disp0.pfm', disp0, 1)
save_pfm('tmp/disp1.pfm', disp1, 1)
subprocess.check_output('computemask tmp/disp0.pfm tmp/disp1.pfm -1 tmp/mask.png'.split())
mask = cv2.imread('tmp/mask.png', 0)
disp0[mask != 255] = 0
y, x = np.nonzero(mask == 255)
X.append(XX)
nnz_tr.append(np.column_stack((np.zeros_like(y) + len(X), y, x, disp0[y, x])).astype(np.float32))
dispnoc.append(disp0.astype(np.float32))
meta.append((x0.shape[2], x0.shape[3], ndisp))
print(np.vstack(nnz_tr).shape)
### 2003 dataset ###
for dir in ('conesH', 'teddyH'):
print(dir)
base1 = 'data.mb/unzip/vision.middlebury.edu/stereo/data/scenes2003/{}'.format(dir)
XX = []
XX.append(None)
x0 = read_im(base1 + '/im2.ppm', False)
x1 = read_im(base1 + '/im6.ppm', False)
_, _, height, width = x0.shape
XX.append(np.concatenate((x0, x1)).reshape(1, 2, num_channels, height, width))
disp0 = cv2.imread(base1 + '/disp2.pgm', 0).astype(np.float32) / 2
disp1 = cv2.imread(base1 + '/disp6.pgm', 0).astype(np.float32) / 2
ndisp = int(np.ceil(disp0.max()))
disp0[disp0 == 0] = np.inf
disp1[disp1 == 0] = np.inf
save_pfm('tmp/disp0.pfm', disp0, 1)
save_pfm('tmp/disp1.pfm', disp1, 1)
subprocess.check_output('computemask tmp/disp0.pfm tmp/disp1.pfm -1 tmp/mask.png'.split())
mask = cv2.imread('tmp/mask.png', 0)
disp0[mask != 255] = 0
y, x = np.nonzero(mask == 255)
X.append(XX)
nnz_tr.append(np.column_stack((np.zeros_like(y) + len(X), y, x, disp0[y, x])).astype(np.float32))
dispnoc.append(disp0.astype(np.float32))
meta.append((x0.shape[2], x0.shape[3], ndisp))
print(np.vstack(nnz_tr).shape)
### 2001 dataset ###
base1 = 'data.mb/unzip/vision.middlebury.edu/stereo/data/scenes2001/data'
for dir in sorted(os.listdir(base1)):
if dir == 'tsukuba':
fname_disp0, fname_disp1, fname_x0, fname_x1 = 'truedisp.row3.col3.pgm', '', 'scene1.row3.col3.ppm', 'scene1.row3.col4.ppm'
elif dir == 'map':
fname_disp0, fname_disp1, fname_x0, fname_x1 = 'disp0.pgm', 'disp1.pgm', 'im0.pgm', 'im1.pgm'
else:
fname_disp0, fname_disp1, fname_x0, fname_x1 = 'disp2.pgm', 'disp6.pgm', 'im2.ppm', 'im6.ppm'
base2 = os.path.join(base1, dir)
if os.path.isfile(os.path.join(base2, fname_disp0)):
print(dir)
XX = []
XX.append(None)
x0 = read_im(os.path.join(base2, fname_x0), False)
x1 = read_im(os.path.join(base2, fname_x1), False)
_, _, height, width = x0.shape
XX.append(np.concatenate((x0, x1)).reshape(1, 2, num_channels, height, width))
if dir == 'tsukuba':
disp0 = cv2.imread(os.path.join(base2, fname_disp0), 0).astype(np.float32) / 16
mask = cv2.imread(os.path.join(base2, 'nonocc.png'), 0)
else:
disp0 = cv2.imread(os.path.join(base2, fname_disp0), 0).astype(np.float32) / 8
disp1 = cv2.imread(os.path.join(base2, fname_disp1), 0).astype(np.float32) / 8
save_pfm('tmp/disp0.pfm', disp0, 1)
save_pfm('tmp/disp1.pfm', disp1, 1)
subprocess.check_output('computemask tmp/disp0.pfm tmp/disp1.pfm -1 tmp/mask.png'.split())
mask = cv2.imread('tmp/mask.png', 0)
disp0[mask != 255] = 0
y, x = np.nonzero(mask == 255)
X.append(XX)
nnz_tr.append(np.column_stack((np.zeros_like(y) + len(X), y, x, disp0[y, x])).astype(np.float32))
dispnoc.append(disp0.astype(np.float32))
meta.append((x0.shape[2], x0.shape[3], -1))
### test ###
fname_submit = []
base1 = 'data.mb/unzip/MiddEval3'
for dir1 in ['trainingH', 'testH']:
base2 = os.path.join(base1, dir1)
for dir2 in sorted(os.listdir(base2)):
base3 = os.path.join(base2, dir2)
print(os.path.join(dir1, dir2))
calib = open(os.path.join(base3, 'calib.txt')).read()
ndisp = int(re.search('ndisp=(.*)', calib).group(1))
x0 = read_im(os.path.join(base3, 'im0.png'), False)
x1 = read_im(os.path.join(base3, 'im1.png'), False)
X.append([np.concatenate((x0, x1)).astype(np.float32)])
meta.append((x0.shape[2], x0.shape[3], ndisp))
fname_submit.append(os.path.join(dir1, dir2))
meta = np.array(meta, dtype=np.int32)
nnz_tr = np.vstack(nnz_tr)
nnz_te = np.vstack(nnz_te)
subprocess.check_call('rm -f {}/*.{{bin,dim,txt,type}} tmp/*'.format(output_dir), shell=True)
for i in range(len(X)):
for j in range(len(X[i])):
tofile('{}/x_{}_{}.bin'.format(output_dir, i + 1, j + 1), X[i][j])
if i < len(dispnoc):
tofile('{}/dispnoc{}.bin'.format(output_dir, i + 1), dispnoc[i])
tofile('{}/meta.bin'.format(output_dir), meta)
tofile('{}/nnz_tr.bin'.format(output_dir), nnz_tr)
tofile('{}/nnz_te.bin'.format(output_dir), nnz_te)
tofile('{}/te.bin'.format(output_dir), te)
open('{}/fname_submit.txt'.format(output_dir), 'w').write('\n'.join(fname_submit))