File size: 26,084 Bytes
d4b77ac
 
 
 
 
 
2dbb619
d4b77ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import cv2
import copy
import numpy as np
import scipy.io as sio
from tool.utils.common_utils import interp, BFconsistCheck, \
    FBconsistCheck, consistCheck, get_KeySourceFrame_flowNN_gradient


def get_flowNN_gradient(args,
                        gradient_x,
                        gradient_y,
                        mask_RGB,
                        mask,
                        videoFlowF,
                        videoFlowB,
                        videoNonLocalFlowF,
                        videoNonLocalFlowB):

    # gradient_x:         imgH x (imgW - 1 + 1) x 3 x nFrame
    # gradient_y:         (imgH - 1 + 1) x imgW x 3 x nFrame
    # mask_RGB:           imgH x imgW x nFrame
    # mask:               imgH x imgW x nFrame
    # videoFlowF:         imgH x imgW x 2 x (nFrame - 1) | [u, v]
    # videoFlowB:         imgH x imgW x 2 x (nFrame - 1) | [u, v]
    # videoNonLocalFlowF: imgH x imgW x 2 x 3 x nFrame
    # videoNonLocalFlowB: imgH x imgW x 2 x 3 x nFrame

    if args.Nonlocal:
        num_candidate = 5
    else:
        num_candidate = 2
    imgH, imgW, nFrame = mask.shape
    numPix = np.sum(mask)

    # |--------------------|  |--------------------|
    # |       y            |  |       v            |
    # |   x   *            |  |   u   *            |
    # |                    |  |                    |
    # |--------------------|  |--------------------|

    # sub:            numPix * 3 | [y, x, t]
    # flowNN:         numPix * 3 * 2 | [y, x, t], [BN, FN]
    # HaveFlowNN:     imgH * imgW * nFrame * 2
    # numPixInd:      imgH * imgW * nFrame
    # consistencyMap: imgH * imgW * 5 * nFrame | [BN, FN, NL2, NL3, NL4]
    # consistency_uv: imgH * imgW * [BN, FN] * [u, v] * nFrame

    # sub: numPix * [y, x, t] | position of mising pixels
    sub = np.concatenate((np.where(mask == 1)[0].reshape(-1, 1),
                          np.where(mask == 1)[1].reshape(-1, 1),
                          np.where(mask == 1)[2].reshape(-1, 1)), axis=1)

    # flowNN: numPix * [y, x, t] * [BN, FN] | flow neighbors
    flowNN = np.ones((numPix, 3, 2)) * 99999   # * -1
    HaveFlowNN = np.ones((imgH, imgW, nFrame, 2)) * 99999
    HaveFlowNN[mask, :] = 0
    numPixInd = np.ones((imgH, imgW, nFrame)) * -1
    consistencyMap = np.zeros((imgH, imgW, num_candidate, nFrame))
    consistency_uv = np.zeros((imgH, imgW, 2, 2, nFrame))

    # numPixInd[y, x, t] gives the index of the missing pixel@[y, x, t] in sub,
    # i.e. which row. numPixInd[y, x, t] = idx; sub[idx, :] = [y, x, t]
    for idx in range(len(sub)):
        numPixInd[sub[idx, 0], sub[idx, 1], sub[idx, 2]] = idx

    # Initialization
    frameIndSetF = range(1, nFrame)
    frameIndSetB = range(nFrame - 2, -1, -1)

    # 1. Forward Pass (backward flow propagation)
    print('Forward Pass......')

    NN_idx = 0 # BN:0
    for indFrame in frameIndSetF:

        # Bool indicator of missing pixels at frame t
        holepixPosInd = (sub[:, 2] == indFrame)

        # Hole pixel location at frame t, i.e. [y, x, t]
        holepixPos = sub[holepixPosInd, :]

        # Calculate the backward flow neighbor. Should be located at frame t-1
        flowB_neighbor = copy.deepcopy(holepixPos)
        flowB_neighbor = flowB_neighbor.astype(np.float32)

        flowB_vertical = videoFlowB[:, :, 1, indFrame - 1]  # t --> t-1
        flowB_horizont = videoFlowB[:, :, 0, indFrame - 1]
        flowF_vertical = videoFlowF[:, :, 1, indFrame - 1]  # t-1 --> t
        flowF_horizont = videoFlowF[:, :, 0, indFrame - 1]

        flowB_neighbor[:, 0] += flowB_vertical[holepixPos[:, 0], holepixPos[:, 1]]
        flowB_neighbor[:, 1] += flowB_horizont[holepixPos[:, 0], holepixPos[:, 1]]
        flowB_neighbor[:, 2] -= 1

        # Round the backward flow neighbor location
        flow_neighbor_int = np.round(copy.deepcopy(flowB_neighbor)).astype(np.int32)

        # Chen: I should combine the following two operations together
        # Check the backward/forward consistency
        IsConsist, _ = BFconsistCheck(flowB_neighbor,
                                      flowF_vertical,
                                      flowF_horizont,
                                      holepixPos,
                                      args.consistencyThres)

        trueConsist = IsConsist[IsConsist == True]

        BFdiff, BF_uv = consistCheck(videoFlowF[:, :, :, indFrame - 1],
                                     videoFlowB[:, :, :, indFrame - 1])

        # Check out-of-boundary
        # Last column and last row does not have valid gradient
        ValidPos = np.logical_and(
            np.logical_and(flow_neighbor_int[:, 0] >= 0,
                           flow_neighbor_int[:, 0] < imgH - 1),
            np.logical_and(flow_neighbor_int[:, 1] >= 0,
                           flow_neighbor_int[:, 1] < imgW - 1))

        # Only work with pixels that are not out-of-boundary
        holepixPos = holepixPos[ValidPos, :]
        flowB_neighbor = flowB_neighbor[ValidPos, :]
        flow_neighbor_int = flow_neighbor_int[ValidPos, :]
        IsConsist = IsConsist[ValidPos]

        # For each missing pixel in holepixPos|[y, x, t],
        # we check its backward flow neighbor flowB_neighbor|[y', x', t-1].

        # Case 1: If mask[round(y'), round(x'), t-1] == 0,
        #         the backward flow neighbor of [y, x, t] is known.
        #         [y', x', t-1] is the backward flow neighbor.

        # KnownInd: Among all backward flow neighbors, which pixel is known.
        KnownInd = mask[flow_neighbor_int[:, 0],
                        flow_neighbor_int[:, 1],
                        indFrame - 1] == 0

        KnownIsConsist = np.logical_and(KnownInd, IsConsist)
        holepixPos_valid = holepixPos[KnownIsConsist]

        # We save backward flow neighbor flowB_neighbor in flowNN
        flowNN[numPixInd[holepixPos[KnownIsConsist, 0],
                         holepixPos[KnownIsConsist, 1],
                         indFrame].astype(np.int32), :, NN_idx] = \
                                                flowB_neighbor[KnownIsConsist, :]
        # flowNN[np.where(holepixPosInd == 1)[0][ValidPos][KnownIsConsist], :, 0] = \
        #                                         flowB_neighbor[KnownIsConsist, :]

        # We mark [y, x, t] in HaveFlowNN as 1
        HaveFlowNN[holepixPos[KnownIsConsist, 0],
                   holepixPos[KnownIsConsist, 1],
                   indFrame,
                   NN_idx] = 1

        # HaveFlowNN[:, :, :, 0]
        # 0: Backward flow neighbor can not be reached
        # 1: Backward flow neighbor can be reached
        # -1: Pixels that do not need to be completed

        consistency_uv[holepixPos[KnownIsConsist, 0], holepixPos[KnownIsConsist, 1], NN_idx, 0, indFrame] = np.abs(BF_uv[holepixPos[KnownIsConsist, 0], holepixPos[KnownIsConsist, 1], 0])
        consistency_uv[holepixPos[KnownIsConsist, 0], holepixPos[KnownIsConsist, 1], NN_idx, 1, indFrame] = np.abs(BF_uv[holepixPos[KnownIsConsist, 0], holepixPos[KnownIsConsist, 1], 1])

        # Case 2: If mask[round(y'), round(x'), t-1] == 1,
        #  the pixel@[round(y'), round(x'), t-1] is also occluded.
        #  We further check if we already assign a backward flow neighbor for the backward flow neighbor
        #  If HaveFlowNN[round(y'), round(x'), t-1] == 0,
        #   this is isolated pixel. Do nothing.
        #  If HaveFlowNN[round(y'), round(x'), t-1] == 1,
        #   we can borrow the value and refine it.

        UnknownInd = np.invert(KnownInd)

        # If we already assign a backward flow neighbor@[round(y'), round(x'), t-1]
        HaveNNInd = HaveFlowNN[flow_neighbor_int[:, 0],
                               flow_neighbor_int[:, 1],
                               indFrame - 1,
                               NN_idx] == 1

        # Unknown & IsConsist & HaveNNInd
        Valid_ = np.logical_and.reduce((UnknownInd, HaveNNInd, IsConsist))

        refineVec = np.concatenate((
            (flowB_neighbor[:, 0] - flow_neighbor_int[:, 0]).reshape(-1, 1),
            (flowB_neighbor[:, 1] - flow_neighbor_int[:, 1]).reshape(-1, 1),
            np.zeros((flowB_neighbor[:, 0].shape[0])).reshape(-1, 1)), 1)

        # Check if the transitive backward flow neighbor of [y, x, t] is known.
        # Sometimes after refinement, it is no longer known.
        flowNN_tmp = copy.deepcopy(flowNN[numPixInd[flow_neighbor_int[:, 0],
                                                    flow_neighbor_int[:, 1],
                                                    indFrame - 1].astype(np.int32), :, NN_idx] + refineVec[:, :])
        flowNN_tmp = np.round(flowNN_tmp).astype(np.int32)

        # Check out-of-boundary. flowNN_tmp may be out-of-boundary
        ValidPos_ = np.logical_and(
            np.logical_and(flowNN_tmp[:, 0] >= 0,
                           flowNN_tmp[:, 0] < imgH - 1),
            np.logical_and(flowNN_tmp[:, 1] >= 0,
                           flowNN_tmp[:, 1] < imgW - 1))

        # Change the out-of-boundary value to 0, in order to run mask[y,x,t]
        # in the next line. It won't affect anything as ValidPos_ is saved already
        flowNN_tmp[np.invert(ValidPos_), :] = 0
        ValidNN = mask[flowNN_tmp[:, 0],
                       flowNN_tmp[:, 1],
                       flowNN_tmp[:, 2]] == 0

        # Valid = np.logical_and.reduce((Valid_, ValidNN, ValidPos_))
        Valid = np.logical_and.reduce((Valid_, ValidPos_))

        # We save the transitive backward flow neighbor flowB_neighbor in flowNN
        flowNN[numPixInd[holepixPos[Valid, 0],
                         holepixPos[Valid, 1],
                         indFrame].astype(np.int32), :, NN_idx] = \
        flowNN[numPixInd[flow_neighbor_int[Valid, 0],
                         flow_neighbor_int[Valid, 1],
                         indFrame - 1].astype(np.int32), :, NN_idx] + refineVec[Valid, :]

        # We mark [y, x, t] in HaveFlowNN as 1
        HaveFlowNN[holepixPos[Valid, 0],
                   holepixPos[Valid, 1],
                   indFrame,
                   NN_idx] = 1

        consistency_uv[holepixPos[Valid, 0], holepixPos[Valid, 1], NN_idx, 0, indFrame] = np.maximum(np.abs(BF_uv[holepixPos[Valid, 0], holepixPos[Valid, 1], 0]), np.abs(consistency_uv[flow_neighbor_int[Valid, 0], flow_neighbor_int[Valid, 1], NN_idx, 0, indFrame - 1]))
        consistency_uv[holepixPos[Valid, 0], holepixPos[Valid, 1], NN_idx, 1, indFrame] = np.maximum(np.abs(BF_uv[holepixPos[Valid, 0], holepixPos[Valid, 1], 1]), np.abs(consistency_uv[flow_neighbor_int[Valid, 0], flow_neighbor_int[Valid, 1], NN_idx, 1, indFrame - 1]))

        consistencyMap[:, :, NN_idx, indFrame] = (consistency_uv[:, :, NN_idx, 0, indFrame] ** 2 + consistency_uv[:, :, NN_idx, 1, indFrame] ** 2) ** 0.5

        print("Frame {0:3d}: {1:8d} + {2:8d} = {3:8d}"
        .format(indFrame,
                np.sum(HaveFlowNN[:, :, indFrame, NN_idx] == 1),
                np.sum(HaveFlowNN[:, :, indFrame, NN_idx] == 0),
                np.sum(HaveFlowNN[:, :, indFrame, NN_idx] != 99999)))

    # 2. Backward Pass (forward flow propagation)
    print('Backward Pass......')

    NN_idx = 1 # FN:1
    for indFrame in frameIndSetB:

        # Bool indicator of missing pixels at frame t
        holepixPosInd = (sub[:, 2] == indFrame)

        # Hole pixel location at frame t, i.e. [y, x, t]
        holepixPos = sub[holepixPosInd, :]

        # Calculate the forward flow neighbor. Should be located at frame t+1
        flowF_neighbor = copy.deepcopy(holepixPos)
        flowF_neighbor = flowF_neighbor.astype(np.float32)

        flowF_vertical = videoFlowF[:, :, 1, indFrame]  # t --> t+1
        flowF_horizont = videoFlowF[:, :, 0, indFrame]
        flowB_vertical = videoFlowB[:, :, 1, indFrame]  # t+1 --> t
        flowB_horizont = videoFlowB[:, :, 0, indFrame]

        flowF_neighbor[:, 0] += flowF_vertical[holepixPos[:, 0], holepixPos[:, 1]]
        flowF_neighbor[:, 1] += flowF_horizont[holepixPos[:, 0], holepixPos[:, 1]]
        flowF_neighbor[:, 2] += 1

        # Round the forward flow neighbor location
        flow_neighbor_int = np.round(copy.deepcopy(flowF_neighbor)).astype(np.int32)

        # Check the forawrd/backward consistency
        IsConsist, _ = FBconsistCheck(flowF_neighbor,
                                      flowB_vertical,
                                      flowB_horizont,
                                      holepixPos,
                                      args.consistencyThres)

        FBdiff, FB_uv = consistCheck(videoFlowB[:, :, :, indFrame],
                                     videoFlowF[:, :, :, indFrame])

        # Check out-of-boundary
        # Last column and last row does not have valid gradient
        ValidPos = np.logical_and(
            np.logical_and(flow_neighbor_int[:, 0] >= 0,
                           flow_neighbor_int[:, 0] < imgH - 1),
            np.logical_and(flow_neighbor_int[:, 1] >= 0,
                           flow_neighbor_int[:, 1] < imgW - 1))

        # Only work with pixels that are not out-of-boundary
        holepixPos = holepixPos[ValidPos, :]
        flowF_neighbor = flowF_neighbor[ValidPos, :]
        flow_neighbor_int = flow_neighbor_int[ValidPos, :]
        IsConsist = IsConsist[ValidPos]

        # Case 1:
        KnownInd = mask[flow_neighbor_int[:, 0],
                        flow_neighbor_int[:, 1],
                        indFrame + 1] == 0

        KnownIsConsist = np.logical_and(KnownInd, IsConsist)
        flowNN[numPixInd[holepixPos[KnownIsConsist, 0],
                         holepixPos[KnownIsConsist, 1],
                         indFrame].astype(np.int32), :, NN_idx] = \
                                                flowF_neighbor[KnownIsConsist, :]

        HaveFlowNN[holepixPos[KnownIsConsist, 0],
                   holepixPos[KnownIsConsist, 1],
                   indFrame,
                   NN_idx] = 1

        consistency_uv[holepixPos[KnownIsConsist, 0], holepixPos[KnownIsConsist, 1], NN_idx, 0, indFrame] = np.abs(FB_uv[holepixPos[KnownIsConsist, 0], holepixPos[KnownIsConsist, 1], 0])
        consistency_uv[holepixPos[KnownIsConsist, 0], holepixPos[KnownIsConsist, 1], NN_idx, 1, indFrame] = np.abs(FB_uv[holepixPos[KnownIsConsist, 0], holepixPos[KnownIsConsist, 1], 1])

        # Case 2:
        UnknownInd = np.invert(KnownInd)
        HaveNNInd = HaveFlowNN[flow_neighbor_int[:, 0],
                               flow_neighbor_int[:, 1],
                               indFrame + 1,
                               NN_idx] == 1

        # Unknown & IsConsist & HaveNNInd
        Valid_ = np.logical_and.reduce((UnknownInd, HaveNNInd, IsConsist))

        refineVec = np.concatenate((
            (flowF_neighbor[:, 0] - flow_neighbor_int[:, 0]).reshape(-1, 1),
            (flowF_neighbor[:, 1] - flow_neighbor_int[:, 1]).reshape(-1, 1),
            np.zeros((flowF_neighbor[:, 0].shape[0])).reshape(-1, 1)), 1)

        # Check if the transitive backward flow neighbor of [y, x, t] is known.
        # Sometimes after refinement, it is no longer known.
        flowNN_tmp = copy.deepcopy(flowNN[numPixInd[flow_neighbor_int[:, 0],
                                                    flow_neighbor_int[:, 1],
                                                    indFrame + 1].astype(np.int32), :, NN_idx] + refineVec[:, :])
        flowNN_tmp = np.round(flowNN_tmp).astype(np.int32)

        # Check out-of-boundary. flowNN_tmp may be out-of-boundary
        ValidPos_ = np.logical_and(
            np.logical_and(flowNN_tmp[:, 0] >= 0,
                           flowNN_tmp[:, 0] < imgH - 1),
            np.logical_and(flowNN_tmp[:, 1] >= 0,
                           flowNN_tmp[:, 1] < imgW - 1))

        # Change the out-of-boundary value to 0, in order to run mask[y,x,t]
        # in the next line. It won't affect anything as ValidPos_ is saved already
        flowNN_tmp[np.invert(ValidPos_), :] = 0
        ValidNN = mask[flowNN_tmp[:, 0],
                       flowNN_tmp[:, 1],
                       flowNN_tmp[:, 2]] == 0

        # Valid = np.logical_and.reduce((Valid_, ValidNN, ValidPos_))
        Valid = np.logical_and.reduce((Valid_, ValidPos_))

        # We save the transitive backward flow neighbor flowB_neighbor in flowNN
        flowNN[numPixInd[holepixPos[Valid, 0],
                         holepixPos[Valid, 1],
                         indFrame].astype(np.int32), :, NN_idx] = \
        flowNN[numPixInd[flow_neighbor_int[Valid, 0],
                         flow_neighbor_int[Valid, 1],
                         indFrame + 1].astype(np.int32), :, NN_idx] + refineVec[Valid, :]

        # We mark [y, x, t] in HaveFlowNN as 1
        HaveFlowNN[holepixPos[Valid, 0],
                   holepixPos[Valid, 1],
                   indFrame,
                   NN_idx] = 1

        consistency_uv[holepixPos[Valid, 0], holepixPos[Valid, 1], NN_idx, 0, indFrame] = np.maximum(np.abs(FB_uv[holepixPos[Valid, 0], holepixPos[Valid, 1], 0]), np.abs(consistency_uv[flow_neighbor_int[Valid, 0], flow_neighbor_int[Valid, 1], NN_idx, 0, indFrame + 1]))
        consistency_uv[holepixPos[Valid, 0], holepixPos[Valid, 1], NN_idx, 1, indFrame] = np.maximum(np.abs(FB_uv[holepixPos[Valid, 0], holepixPos[Valid, 1], 1]), np.abs(consistency_uv[flow_neighbor_int[Valid, 0], flow_neighbor_int[Valid, 1], NN_idx, 1, indFrame + 1]))

        consistencyMap[:, :, NN_idx, indFrame] = (consistency_uv[:, :, NN_idx, 0, indFrame] ** 2 + consistency_uv[:, :, NN_idx, 1, indFrame] ** 2) ** 0.5

        print("Frame {0:3d}: {1:8d} + {2:8d} = {3:8d}"
        .format(indFrame,
                np.sum(HaveFlowNN[:, :, indFrame, NN_idx] == 1),
                np.sum(HaveFlowNN[:, :, indFrame, NN_idx] == 0),
                np.sum(HaveFlowNN[:, :, indFrame, NN_idx] != 99999)))

    # Interpolation
    gradient_x_BN = copy.deepcopy(gradient_x)
    gradient_y_BN = copy.deepcopy(gradient_y)
    gradient_x_FN = copy.deepcopy(gradient_x)
    gradient_y_FN = copy.deepcopy(gradient_y)

    for indFrame in range(nFrame):
        # Index of missing pixel whose backward flow neighbor is from frame indFrame
        SourceFmInd = np.where(flowNN[:, 2, 0] == indFrame)

        print("{0:8d} pixels are from source Frame {1:3d}"
                        .format(len(SourceFmInd[0]), indFrame))
        # The location of the missing pixel whose backward flow neighbor is
        # from frame indFrame flowNN[SourceFmInd, 0, 0], flowNN[SourceFmInd, 1, 0]

        if len(SourceFmInd[0]) != 0:

            # |--------------------|
            # |       y            |
            # |   x   *            |
            # |                    |
            # |--------------------|
            # sub: numPix x 3 [y, x, t]
            # img: [y, x]
            # interp(img, x, y)

            gradient_x_BN[sub[SourceFmInd[0], :][:, 0],
                    sub[SourceFmInd[0], :][:, 1],
                 :, sub[SourceFmInd[0], :][:, 2]] = \
                interp(gradient_x_BN[:, :, :, indFrame],
                        flowNN[SourceFmInd, 1, 0].reshape(-1),
                        flowNN[SourceFmInd, 0, 0].reshape(-1))

            gradient_y_BN[sub[SourceFmInd[0], :][:, 0],
                    sub[SourceFmInd[0], :][:, 1],
                 :, sub[SourceFmInd[0], :][:, 2]] = \
                interp(gradient_y_BN[:, :, :, indFrame],
                        flowNN[SourceFmInd, 1, 0].reshape(-1),
                        flowNN[SourceFmInd, 0, 0].reshape(-1))

            assert(((sub[SourceFmInd[0], :][:, 2] - indFrame) <= 0).sum() == 0)

    for indFrame in range(nFrame - 1, -1, -1):
        # Index of missing pixel whose forward flow neighbor is from frame indFrame
        SourceFmInd = np.where(flowNN[:, 2, 1] == indFrame)
        print("{0:8d} pixels are from source Frame {1:3d}"
                        .format(len(SourceFmInd[0]), indFrame))
        if len(SourceFmInd[0]) != 0:

            gradient_x_FN[sub[SourceFmInd[0], :][:, 0],
                          sub[SourceFmInd[0], :][:, 1],
                       :, sub[SourceFmInd[0], :][:, 2]] = \
                interp(gradient_x_FN[:, :, :, indFrame],
                         flowNN[SourceFmInd, 1, 1].reshape(-1),
                         flowNN[SourceFmInd, 0, 1].reshape(-1))

            gradient_y_FN[sub[SourceFmInd[0], :][:, 0],
                    sub[SourceFmInd[0], :][:, 1],
                 :, sub[SourceFmInd[0], :][:, 2]] = \
                interp(gradient_y_FN[:, :, :, indFrame],
                         flowNN[SourceFmInd, 1, 1].reshape(-1),
                         flowNN[SourceFmInd, 0, 1].reshape(-1))

            assert(((indFrame - sub[SourceFmInd[0], :][:, 2]) <= 0).sum() == 0)

    # New mask
    mask_tofill = np.zeros((imgH, imgW, nFrame)).astype(np.bool)

    for indFrame in range(nFrame):
        if args.Nonlocal:
            consistencyMap[:, :, 2, indFrame], _ = consistCheck(
                videoNonLocalFlowB[:, :, :, 0, indFrame],
                videoNonLocalFlowF[:, :, :, 0, indFrame])
            consistencyMap[:, :, 3, indFrame], _ = consistCheck(
                videoNonLocalFlowB[:, :, :, 1, indFrame],
                videoNonLocalFlowF[:, :, :, 1, indFrame])
            consistencyMap[:, :, 4, indFrame], _ = consistCheck(
                videoNonLocalFlowB[:, :, :, 2, indFrame],
                videoNonLocalFlowF[:, :, :, 2, indFrame])

        HaveNN = np.zeros((imgH, imgW, num_candidate))

        if args.Nonlocal:
            HaveKeySourceFrameFlowNN, gradient_x_KeySourceFrameFlowNN, gradient_y_KeySourceFrameFlowNN = \
                get_KeySourceFrame_flowNN_gradient(sub,
                                                  indFrame,
                                                  mask,
                                                  videoNonLocalFlowB,
                                                  videoNonLocalFlowF,
                                                  gradient_x,
                                                  gradient_y,
                                                  args.consistencyThres)

            HaveNN[:, :, 2] = HaveKeySourceFrameFlowNN[:, :, 0] == 1
            HaveNN[:, :, 3] = HaveKeySourceFrameFlowNN[:, :, 1] == 1
            HaveNN[:, :, 4] = HaveKeySourceFrameFlowNN[:, :, 2] == 1

        HaveNN[:, :, 0] = HaveFlowNN[:, :, indFrame, 0] == 1
        HaveNN[:, :, 1] = HaveFlowNN[:, :, indFrame, 1] == 1

        NotHaveNN = np.logical_and(np.invert(HaveNN.astype(np.bool)),
                np.repeat(np.expand_dims((mask[:, :, indFrame]), 2), num_candidate, axis=2))

        if args.Nonlocal:
            HaveNN_sum = np.logical_or.reduce((HaveNN[:, :, 0],
                                               HaveNN[:, :, 1],
                                               HaveNN[:, :, 2],
                                               HaveNN[:, :, 3],
                                               HaveNN[:, :, 4]))
        else:
            HaveNN_sum = np.logical_or.reduce((HaveNN[:, :, 0],
                                               HaveNN[:, :, 1]))

        gradient_x_Candidate = np.zeros((imgH, imgW, 3, num_candidate))
        gradient_y_Candidate = np.zeros((imgH, imgW, 3, num_candidate))

        gradient_x_Candidate[:, :, :, 0] = gradient_x_BN[:, :, :, indFrame]
        gradient_y_Candidate[:, :, :, 0] = gradient_y_BN[:, :, :, indFrame]
        gradient_x_Candidate[:, :, :, 1] = gradient_x_FN[:, :, :, indFrame]
        gradient_y_Candidate[:, :, :, 1] = gradient_y_FN[:, :, :, indFrame]

        if args.Nonlocal:
            gradient_x_Candidate[:, :, :, 2] = gradient_x_KeySourceFrameFlowNN[:, :, :, 0]
            gradient_y_Candidate[:, :, :, 2] = gradient_y_KeySourceFrameFlowNN[:, :, :, 0]
            gradient_x_Candidate[:, :, :, 3] = gradient_x_KeySourceFrameFlowNN[:, :, :, 1]
            gradient_y_Candidate[:, :, :, 3] = gradient_y_KeySourceFrameFlowNN[:, :, :, 1]
            gradient_x_Candidate[:, :, :, 4] = gradient_x_KeySourceFrameFlowNN[:, :, :, 2]
            gradient_y_Candidate[:, :, :, 4] = gradient_y_KeySourceFrameFlowNN[:, :, :, 2]

        consistencyMap[:, :, :, indFrame] = np.exp( - consistencyMap[:, :, :, indFrame] / args.alpha)

        consistencyMap[NotHaveNN[:, :, 0], 0, indFrame] = 0
        consistencyMap[NotHaveNN[:, :, 1], 1, indFrame] = 0

        if args.Nonlocal:
            consistencyMap[NotHaveNN[:, :, 2], 2, indFrame] = 0
            consistencyMap[NotHaveNN[:, :, 3], 3, indFrame] = 0
            consistencyMap[NotHaveNN[:, :, 4], 4, indFrame] = 0

        weights = (consistencyMap[HaveNN_sum, :, indFrame] * HaveNN[HaveNN_sum, :]) / ((consistencyMap[HaveNN_sum, :, indFrame] * HaveNN[HaveNN_sum, :]).sum(axis=1, keepdims=True))

        # Fix the numerical issue. 0 / 0
        fix = np.where((consistencyMap[HaveNN_sum, :, indFrame] * HaveNN[HaveNN_sum, :]).sum(axis=1, keepdims=True) == 0)[0]
        weights[fix, :] = HaveNN[HaveNN_sum, :][fix, :] / HaveNN[HaveNN_sum, :][fix, :].sum(axis=1, keepdims=True)

        # Fuse RGB channel independently
        gradient_x[HaveNN_sum, 0, indFrame] = \
            np.sum(np.multiply(gradient_x_Candidate[HaveNN_sum, 0, :], weights), axis=1)
        gradient_x[HaveNN_sum, 1, indFrame] = \
            np.sum(np.multiply(gradient_x_Candidate[HaveNN_sum, 1, :], weights), axis=1)
        gradient_x[HaveNN_sum, 2, indFrame] = \
            np.sum(np.multiply(gradient_x_Candidate[HaveNN_sum, 2, :], weights), axis=1)

        gradient_y[HaveNN_sum, 0, indFrame] = \
            np.sum(np.multiply(gradient_y_Candidate[HaveNN_sum, 0, :], weights), axis=1)
        gradient_y[HaveNN_sum, 1, indFrame] = \
            np.sum(np.multiply(gradient_y_Candidate[HaveNN_sum, 1, :], weights), axis=1)
        gradient_y[HaveNN_sum, 2, indFrame] = \
            np.sum(np.multiply(gradient_y_Candidate[HaveNN_sum, 2, :], weights), axis=1)

        mask_tofill[np.logical_and(np.invert(HaveNN_sum), mask[:, :, indFrame]), indFrame] = True

    return gradient_x, gradient_y, mask_tofill