forked from sniklaus/pytorch-pwc
-
Notifications
You must be signed in to change notification settings - Fork 1
/
runbatch.py
375 lines (286 loc) · 17.2 KB
/
runbatch.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python
import torch
import argparse
import getopt
import math
import numpy
import os
import PIL
import PIL.Image
import sys
from glob import glob
import os.path as osp
import time
import pandas as pd
try:
from correlation import correlation # the custom cost volume layer
except:
sys.path.insert(0, './correlation'); import correlation # you should consider upgrading python
# end
##########################################################
assert(int(str('').join(torch.__version__.split('.')[0:3])) >= 40) # requires at least pytorch version 0.4.0
torch.set_grad_enabled(False) # make sure to not compute gradients for computational performance
torch.cuda.device(1) # change this if you have a multiple graphics cards and you want to utilize them
torch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance
##########################################################
Backward_tensorGrid = {}
Backward_tensorPartial = {}
def Backward(tensorInput, tensorFlow):
if str(tensorFlow.size()) not in Backward_tensorGrid:
tensorHorizontal = torch.linspace(-1.0, 1.0, tensorFlow.size(3)).view(1, 1, 1, tensorFlow.size(3)).expand(tensorFlow.size(0), -1, tensorFlow.size(2), -1)
tensorVertical = torch.linspace(-1.0, 1.0, tensorFlow.size(2)).view(1, 1, tensorFlow.size(2), 1).expand(tensorFlow.size(0), -1, -1, tensorFlow.size(3))
Backward_tensorGrid[str(tensorFlow.size())] = torch.cat([ tensorHorizontal, tensorVertical ], 1).cuda()
# end
if str(tensorFlow.size()) not in Backward_tensorPartial:
Backward_tensorPartial[str(tensorFlow.size())] = tensorFlow.new_ones([ tensorFlow.size(0), 1, tensorFlow.size(2), tensorFlow.size(3) ])
# end
tensorFlow = torch.cat([ tensorFlow[:, 0:1, :, :] / ((tensorInput.size(3) - 1.0) / 2.0), tensorFlow[:, 1:2, :, :] / ((tensorInput.size(2) - 1.0) / 2.0) ], 1)
tensorInput = torch.cat([ tensorInput, Backward_tensorPartial[str(tensorFlow.size())] ], 1)
tensorOutput = torch.nn.functional.grid_sample(input=tensorInput, grid=(Backward_tensorGrid[str(tensorFlow.size())] + tensorFlow).permute(0, 2, 3, 1), mode='bilinear', padding_mode='zeros')
tensorMask = tensorOutput[:, -1:, :, :]; tensorMask[tensorMask > 0.999] = 1.0; tensorMask[tensorMask < 1.0] = 0.0
return tensorOutput[:, :-1, :, :] * tensorMask
##########################################################
class Network(torch.nn.Module):
def __init__(self, model_name):
super(Network, self).__init__()
class Extractor(torch.nn.Module):
def __init__(self):
super(Extractor, self).__init__()
self.moduleOne = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=2, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleTwo = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=2, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleThr = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleFou = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleFiv = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleSix = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=128, out_channels=196, kernel_size=3, stride=2, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
# end
def forward(self, tensorInput):
tensorOne = self.moduleOne(tensorInput)
tensorTwo = self.moduleTwo(tensorOne)
tensorThr = self.moduleThr(tensorTwo)
tensorFou = self.moduleFou(tensorThr)
tensorFiv = self.moduleFiv(tensorFou)
tensorSix = self.moduleSix(tensorFiv)
return [ tensorOne, tensorTwo, tensorThr, tensorFou, tensorFiv, tensorSix ]
class Decoder(torch.nn.Module):
def __init__(self, intLevel):
super(Decoder, self).__init__()
intPrevious = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 1]
intCurrent = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 0]
if intLevel < 6: self.moduleUpflow = torch.nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)
if intLevel < 6: self.moduleUpfeat = torch.nn.ConvTranspose2d(in_channels=intPrevious + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=4, stride=2, padding=1)
if intLevel < 6: self.dblBackward = [ None, None, None, 5.0, 2.5, 1.25, 0.625, None ][intLevel + 1]
self.moduleOne = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=intCurrent, out_channels=128, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleTwo = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=intCurrent + 128, out_channels=128, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleThr = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=intCurrent + 128 + 128, out_channels=96, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleFou = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96, out_channels=64, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleFiv = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64, out_channels=32, kernel_size=3, stride=1, padding=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
)
self.moduleSix = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=3, stride=1, padding=1)
)
def forward(self, tensorFirst, tensorSecond, objectPrevious):
tensorFlow = None
tensorFeat = None
if objectPrevious is None:
tensorFlow = None
tensorFeat = None
tensorVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tensorFirst=tensorFirst, tensorSecond=tensorSecond), negative_slope=0.1, inplace=False)
tensorFeat = torch.cat([ tensorVolume ], 1)
elif objectPrevious is not None:
tensorFlow = self.moduleUpflow(objectPrevious['tensorFlow'])
tensorFeat = self.moduleUpfeat(objectPrevious['tensorFeat'])
tensorVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tensorFirst=tensorFirst, tensorSecond=Backward(tensorInput=tensorSecond, tensorFlow=tensorFlow * self.dblBackward)), negative_slope=0.1, inplace=False)
tensorFeat = torch.cat([ tensorVolume, tensorFirst, tensorFlow, tensorFeat ], 1)
# end
tensorFeat = torch.cat([ self.moduleOne(tensorFeat), tensorFeat ], 1)
tensorFeat = torch.cat([ self.moduleTwo(tensorFeat), tensorFeat ], 1)
tensorFeat = torch.cat([ self.moduleThr(tensorFeat), tensorFeat ], 1)
tensorFeat = torch.cat([ self.moduleFou(tensorFeat), tensorFeat ], 1)
tensorFeat = torch.cat([ self.moduleFiv(tensorFeat), tensorFeat ], 1)
tensorFlow = self.moduleSix(tensorFeat)
return {
'tensorFlow': tensorFlow,
'tensorFeat': tensorFeat
}
class Refiner(torch.nn.Module):
def __init__(self):
super(Refiner, self).__init__()
self.moduleMain = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=81 + 32 + 2 + 2 + 128 + 128 + 96 + 64 + 32, out_channels=128, kernel_size=3, stride=1, padding=1, dilation=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=2, dilation=2),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=4, dilation=4),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=128, out_channels=96, kernel_size=3, stride=1, padding=8, dilation=8),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=96, out_channels=64, kernel_size=3, stride=1, padding=16, dilation=16),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1, dilation=1),
torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
torch.nn.Conv2d(in_channels=32, out_channels=2, kernel_size=3, stride=1, padding=1, dilation=1)
)
def forward(self, tensorInput):
return self.moduleMain(tensorInput)
self.moduleExtractor = Extractor()
self.moduleTwo = Decoder(2)
self.moduleThr = Decoder(3)
self.moduleFou = Decoder(4)
self.moduleFiv = Decoder(5)
self.moduleSix = Decoder(6)
self.moduleRefiner = Refiner()
self.load_state_dict(torch.load('./network-' + model_name + '.pytorch'))
def forward(self, tensorFirst, tensorSecond):
tensorFirst = self.moduleExtractor(tensorFirst)
tensorSecond = self.moduleExtractor(tensorSecond)
objectEstimate = self.moduleSix(tensorFirst[-1], tensorSecond[-1], None)
objectEstimate = self.moduleFiv(tensorFirst[-2], tensorSecond[-2], objectEstimate)
objectEstimate = self.moduleFou(tensorFirst[-3], tensorSecond[-3], objectEstimate)
objectEstimate = self.moduleThr(tensorFirst[-4], tensorSecond[-4], objectEstimate)
objectEstimate = self.moduleTwo(tensorFirst[-5], tensorSecond[-5], objectEstimate)
return objectEstimate['tensorFlow'] + self.moduleRefiner(objectEstimate['tensorFeat'])
##########################################################
def estimate(moduleNetwork, tensorFirst, tensorSecond):
tensorOutput = torch.FloatTensor()
assert(tensorFirst.size(1) == tensorSecond.size(1))
assert(tensorFirst.size(2) == tensorSecond.size(2))
intWidth = tensorFirst.size(2)
intHeight = tensorFirst.size(1)
# There is no guarantee for correctness if the input size is not the same when training the model
# comment this line out if you acknowledge this and want to continue
#assert(intWidth == 1024)
#assert(intHeight == 436)
tensorFirst = tensorFirst.cuda()
tensorSecond = tensorSecond.cuda()
tensorOutput = tensorOutput.cuda()
tensorPreprocessedFirst = tensorFirst.view(1, 3, intHeight, intWidth)
tensorPreprocessedSecond = tensorSecond.view(1, 3, intHeight, intWidth)
intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0))
intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0))
tensorPreprocessedFirst = torch.nn.functional.interpolate(input=tensorPreprocessedFirst, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
tensorPreprocessedSecond = torch.nn.functional.interpolate(input=tensorPreprocessedSecond, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
tensorFlow = 20.0 * torch.nn.functional.interpolate(input=moduleNetwork(tensorPreprocessedFirst, tensorPreprocessedSecond), size=(intHeight, intWidth), mode='bilinear', align_corners=False)
tensorFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)
tensorFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)
tensorOutput.resize_(2, intHeight, intWidth).copy_(tensorFlow[0, :, :, :])
tensorOutput = tensorOutput.cpu()
return tensorOutput
##########################################################
def profile_dir_processing(strModel, strInputDir, strFramesExt, strOutputDir):
total_start_time = time.time()
moduleNetwork = Network(strModel).cuda().eval()
listFramesPath = sorted(glob(osp.join(strInputDir, '*%s'%strFramesExt)))
processing_start_time = time.time()
for intIndex, strFirst, strSecond in zip(range(len(listFramesPath)-1), listFramesPath[:-1], listFramesPath[1:]):
tensorFirst = torch.FloatTensor(
numpy.array(PIL.Image.open(strFirst))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (
1.0 / 255.0))
tensorSecond = torch.FloatTensor(
numpy.array(PIL.Image.open(strSecond))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (
1.0 / 255.0))
tensorOutput = estimate(moduleNetwork, tensorFirst, tensorSecond)
fileOutput = open(osp.join(strOutputDir, '%05d.flo'%(intIndex)), 'wb')
numpy.array([80, 73, 69, 72], numpy.uint8).tofile(fileOutput)
numpy.array([tensorOutput.size(2), tensorOutput.size(1)], numpy.int32).tofile(fileOutput)
numpy.array(tensorOutput.numpy().transpose(1, 2, 0), numpy.float32).tofile(fileOutput)
fileOutput.close()
return time.time() - total_start_time, time.time() - processing_start_time
def process_dir(moduleNetwork, strInputDir, strOutputDir, strFramesExt='.jpg', bound=20):
listFramesPath = sorted(glob(osp.join(strInputDir, '*%s' % strFramesExt)))
os.makedirs(strOutputDir, exist_ok=True)
for intIndex, strFirst, strSecond in zip(range(len(listFramesPath)-1), listFramesPath[:-1], listFramesPath[1:]):
tensorFirst = torch.FloatTensor(
numpy.array(PIL.Image.open(strFirst))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (
1.0 / 255.0))
tensorSecond = torch.FloatTensor(
numpy.array(PIL.Image.open(strSecond))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (
1.0 / 255.0))
tensorOutput = estimate(moduleNetwork, tensorFirst, tensorSecond)
fileOutput = open(osp.join(strOutputDir, '%05d.flo'%(intIndex)), 'wb')
numpy.array([80, 73, 69, 72], numpy.uint8).tofile(fileOutput)
numpy.array([tensorOutput.size(2), tensorOutput.size(1)], numpy.int32).tofile(fileOutput)
arrayOutput = numpy.array(tensorOutput.numpy().transpose(1, 2, 0), numpy.float32)
arrayOutput.tofile(fileOutput)
fileOutput.close()
arrayOutput = ((arrayOutput + bound) / (2 * bound)) * 255.
arrayOutput[arrayOutput < 0.] = 0.
arrayOutput[arrayOutput > 255.] = 255.
flow_x, flow_y = arrayOutput[..., 0], arrayOutput[..., 1]
PIL.Image.fromarray(flow_x.astype(numpy.uint8), mode='L').save(
osp.join(strOutputDir, 'flow_x_%05d.jpg' % intIndex))
PIL.Image.fromarray(flow_y.astype(numpy.uint8), mode='L').save(
osp.join(strOutputDir, 'flow_y_%05d.jpg' % intIndex))
torch.cuda.empty_cache()
def process_batch(strModel, strSourceDir, strTargetDir, strFramesExt):
listSourceDirs = sorted(glob(osp.join(strSourceDir, '*/')))
listTargetDirs = [osp.join(strTargetDir, osp.basename(osp.normpath(sd))) for sd in listSourceDirs]
intDirsTotal = len(listSourceDirs)
moduleNetwork = Network(strModel).cuda().eval()
intStartIndex = 0
for intIndex, source_dir, target_dir in zip(list(range(1, len(listSourceDirs)+1))[intStartIndex:], listSourceDirs[intStartIndex:], listTargetDirs[intStartIndex:]):
print('[{}/{}]Processing: {}'.format(intIndex, intDirsTotal, osp.basename(osp.normpath(source_dir))))
process_dir(moduleNetwork, source_dir, target_dir)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Calculates PWC-Net optical flow')
parser.add_argument('--model', dest='strModel', type=str, default='default', help="Model's name")
parser.add_argument('--sourceDir', dest='strSourceDir', type=str, help='Path to directory with video directories')
parser.add_argument('--targetDir', dest='strTargetDir', type=str, help='Path where optical flow will be saved')
parser.add_argument('--framesExt', dest='strFramesExt', type=str, default='.jpg', help='Frames file extension')
args = parser.parse_args()
process_batch(args.strModel, args.strSourceDir, args.strTargetDir, args.strFramesExt)