/
process.pyx
1323 lines (1060 loc) · 53.4 KB
/
process.pyx
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""This module is dedicated to advanced algorithms for PIV image analysis."""
from __future__ import division
import numpy as np
import numpy.ma as ma
from numpy.fft import rfft2,irfft2,fftshift
from math import log
from scipy.signal import convolve
import time
import openpiv
import warnings
from progressbar import *
cimport numpy as np
cimport cython
DTYPEi = np.int32
ctypedef np.int32_t DTYPEi_t
DTYPEf = np.float64
ctypedef np.float64_t DTYPEf_t
def extended_search_area_piv( np.ndarray[DTYPEi_t, ndim=2] frame_a,
np.ndarray[DTYPEi_t, ndim=2] frame_b,
int window_size,
int overlap=0,
float dt=1.0,
int search_area_size=0,
str subpixel_method='gaussian',
sig2noise_method=None,
int width=2,
nfftx=None,
nffty=None):
"""
The implementation of the one-step direct correlation with different
size of the interrogation window and the search area. The increased
size of the search areas cope with the problem of loss of pairs due
to in-plane motion, allowing for a smaller interrogation window size,
without increasing the number of outlier vectors.
See:
Particle-Imaging Techniques for Experimental Fluid Mechanics
Annual Review of Fluid Mechanics
Vol. 23: 261-304 (Volume publication date January 1991)
DOI: 10.1146/annurev.fl.23.010191.001401
Parameters
----------
frame_a : 2d np.ndarray, dtype=np.int32
an two dimensions array of integers containing grey levels of
the first frame.
frame_b : 2d np.ndarray, dtype=np.int32
an two dimensions array of integers containing grey levels of
the second frame.
window_size : int
the size of the (square) interrogation window.
overlap : int
the number of pixels by which two adjacent windows overlap.
dt : float
the time delay separating the two frames.
search_area_size : int
the size of the (square) interrogation window from the second frame
subpixel_method : string
one of the following methods to estimate subpixel location of the peak:
'centroid' [replaces default if correlation map is negative],
'gaussian' [default if correlation map is positive],
'parabolic'.
sig2noise_method : string
defines the method of signal-to-noise-ratio measure,
('peak2peak' or 'peak2mean'. If None, no measure is performed.)
width : int
the half size of the region around the first
correlation peak to ignore for finding the second
peak. [default: 2]. Only used if ``sig2noise_method==peak2peak``.
nfftx : int
the size of the 2D FFT in x-direction,
[default: 2 x windows_a.shape[0] is recommended]
nffty : int
the size of the 2D FFT in y-direction,
[default: 2 x windows_a.shape[1] is recommended]
Returns
-------
u : 2d np.ndarray
a two dimensional array containing the u velocity component,
in pixels/seconds.
v : 2d np.ndarray
a two dimensional array containing the v velocity component,
in pixels/seconds.
sig2noise : 2d np.ndarray, optional
a two dimensional array containing the signal to noise ratio
from the cross correlation function. This array is returned if
sig2noise_method is not None.
Examples
--------
>>> u, v = openpiv.process.extended_search_area_piv( frame_a, frame_b, window_size=16, overlap=8, search_area_size=48, dt=0.1)
"""
# check the inputs for validity
if search_area_size == 0:
search_area_size = window_size
if overlap >= window_size:
raise ValueError('Overlap has to be smaller than the window_size')
if search_area_size < window_size:
raise ValueError('Search size cannot be smaller than the window_size')
if (window_size > frame_a.shape[0]) or (window_size > frame_a.shape[1]):
raise ValueError('window size cannot be larger than the image')
cdef int i, j, k, l, I, J
# subpixel peak location
cdef float i_peak, j_peak
# signal to noise ratio
cdef float s2n
# shape of the resulting flow field
cdef int n_cols, n_rows
# get field shape
n_rows, n_cols = get_field_shape( (frame_a.shape[0], frame_a.shape[1]), window_size, overlap )
# define arrays
cdef np.ndarray[DTYPEi_t, ndim=2] window_a = np.zeros([window_size, window_size], dtype=DTYPEi)
cdef np.ndarray[DTYPEi_t, ndim=2] search_area = np.zeros([search_area_size, search_area_size], dtype=DTYPEi)
cdef np.ndarray[DTYPEf_t, ndim=2] corr = np.zeros([search_area_size, search_area_size], dtype=DTYPEf)
cdef np.ndarray[DTYPEf_t, ndim=2] u = np.zeros([n_rows, n_cols], dtype=DTYPEf)
cdef np.ndarray[DTYPEf_t, ndim=2] v = np.zeros([n_rows, n_cols], dtype=DTYPEf)
cdef np.ndarray[DTYPEf_t, ndim=2] sig2noise = np.zeros([n_rows, n_cols], dtype=DTYPEf)
# loop over the interrogation windows
# i, j are the row, column indices of the top left corner
I = 0
for i in range( 0, frame_a.shape[0]-window_size+1, window_size-overlap ):
J = 0
for j in range( 0, frame_a.shape[1]-window_size+1, window_size-overlap ):
# get interrogation window matrix from frame a
for k in range( window_size ):
for l in range( window_size ):
window_a[k,l] = frame_a[i+k, j+l]
# get search area using frame b
for k in range( search_area_size ):
for l in range( search_area_size ):
# fill with zeros if we are out of the borders
if i+window_size/2-search_area_size//2+k < 0 or \
i+window_size//2-search_area_size//2+k >= frame_b.shape[0]:
search_area[k,l] = 0
elif j+window_size//2-search_area_size//2+l < 0 or \
j+window_size//2-search_area_size//2+l >= frame_b.shape[1]:
search_area[k,l] = 0
else:
search_area[k,l] = frame_b[ i+window_size//2-search_area_size//2+k,
j+window_size//2-search_area_size//2+l ]
# compute correlation map
if any(window_a.flatten()):
corr = correlate_windows( search_area, window_a, nfftx=nfftx, nffty=nffty )
c = CorrelationFunction( corr )
# find subpixel approximation of the peak center
i_peak, j_peak = c.subpixel_peak_position( subpixel_method )
# velocities
v[I,J] = -( (i_peak - corr.shape[0]/2) - (search_area_size-window_size)/2 ) / dt
u[I,J] = ( (j_peak - corr.shape[0]/2) - (search_area_size-window_size)/2 ) / dt
# compute signal to noise ratio
if sig2noise_method:
sig2noise[I,J] = c.sig2noise_ratio( sig2noise_method, width )
else:
v[I,J] = 0.0
u[I,J] = 0.0
# compute signal to noise ratio
if sig2noise_method:
sig2noise[I,J] = np.inf
# go to next vector
J = J + 1
# go to next vector
I = I + 1
if sig2noise_method:
return u, v, sig2noise
else:
return u, v
class CorrelationFunction( ):
def __init__ ( self, corr ):
"""A class representing a cross correlation function.
Parameters
----------
corr : 2d np.ndarray
the correlation function array
"""
self.data = corr
self.shape = self.data.shape
# get first peak
self.peak1, self.corr_max1 = self._find_peak( self.data )
def _find_peak ( self, array ):
"""Find row and column indices of the highest peak in an array."""
ind = array.argmax()
s = array.shape[1]
i = ind // s
j = ind % s
return (i, j), array.max()
def _find_second_peak ( self, width ):
"""
Find the value of the second largest peak.
The second largest peak is the height of the peak in
the region outside a ``width * width`` submatrix around
the first correlation peak.
Parameters
----------
width : int
the half size of the region around the first correlation
peak to ignore for finding the second peak.
Returns
-------
i, j : two elements tuple
the row, column index of the second correlation peak.
corr_max2 : int
the value of the second correlation peak.
"""
# create a masked view of the self.data array
tmp = self.data.view(ma.MaskedArray)
# set width x width square submatrix around the first correlation peak as masked.
# Before check if we are not too close to the boundaries, otherwise we have negative indices
iini = max(0, self.peak1[0]-width)
ifin = min(self.peak1[0]+width+1, self.data.shape[0])
jini = max(0, self.peak1[1]-width)
jfin = min(self.peak1[1]+width+1, self.data.shape[1])
tmp[ iini:ifin, jini:jfin ] = ma.masked
peak, corr_max2 = self._find_peak( tmp )
return peak, corr_max2
def subpixel_peak_position( self, method='gaussian' ):
"""
Find subpixel approximation of the correlation peak.
This function returns a subpixels approximation of the correlation
peak by using one of the several methods available.
Parameters
----------
method : string
one of the following methods to estimate subpixel location of the peak:
'centroid' [replaces default if correlation map is negative],
'gaussian' [default if correlation map is positive],
'parabolic'.
Returns
-------
subp_peak_position : two elements tuple
the fractional row and column indices for the sub-pixel
approximation of the correlation peak.
"""
# the peak and its neighbours: left, right, down, up
try:
c = self.data[self.peak1[0] , self.peak1[1] ]
cl = self.data[self.peak1[0]-1, self.peak1[1] ]
cr = self.data[self.peak1[0]+1, self.peak1[1] ]
cd = self.data[self.peak1[0] , self.peak1[1]-1]
cu = self.data[self.peak1[0] , self.peak1[1]+1]
except IndexError:
# if the peak is near the border do not
# do subpixel approximation
return self.peak1
# if all zero or some is NaN, don't do sub-pixel search:
tmp = np.array([c,cl,cr,cd,cu])
if np.any( np.isnan(tmp) ) or np.all ( tmp == 0 ):
return self.peak1
# if correlation is negative near the peak, fall back
# to a centroid approximation
if np.any ( tmp < 0 ) and method == 'gaussian':
method = 'centroid'
# choose method
if method == 'centroid':
subp_peak_position = (((self.peak1[0]-1)*cl+self.peak1[0]*c+(self.peak1[0]+1)*cr)/(cl+c+cr),
((self.peak1[1]-1)*cd+self.peak1[1]*c+(self.peak1[1]+1)*cu)/(cd+c+cu))
elif method == 'gaussian':
subp_peak_position = (self.peak1[0] + ( (np.log(cl)-np.log(cr) )/( 2*np.log(cl) - 4*np.log(c) + 2*np.log(cr) )),
self.peak1[1] + ( (np.log(cd)-np.log(cu) )/( 2*np.log(cd) - 4*np.log(c) + 2*np.log(cu) )))
elif method == 'parabolic':
subp_peak_position = (self.peak1[0] + (cl-cr)/(2*cl-4*c+2*cr),
self.peak1[1] + (cd-cu)/(2*cd-4*c+2*cu))
else:
raise ValueError( "method not understood. Can be 'gaussian', 'centroid', 'parabolic'." )
return subp_peak_position
def sig2noise_ratio( self, method='peak2peak', width=2 ):
"""Computes the signal to noise ratio.
The signal to noise ratio is computed from the correlation map with
one of two available method. It is a measure of the quality of the
matching between two interogation windows.
Parameters
----------
sig2noise_method: string
the method for evaluating the signal to noise ratio value from
the correlation map. Can be `peak2peak`, `peak2mean` or None
if no evaluation should be made.
width : int, optional
the half size of the region around the first
correlation peak to ignore for finding the second
peak. [default: 2]. Only used if ``sig2noise_method==peak2peak``.
Returns
-------
sig2noise : float
the signal to noise ratio from the correlation map.
"""
# if the image is lacking particles, totally black it will correlate to very low value, but not zero
# return zero, since we have no signal.
if self.corr_max1 < 1e-3:
return 0.0
# if the first peak is on the borders, the correlation map is wrong
# return zero, since we have no signal.
if ( 0 in self.peak1 or self.data.shape[0] in self.peak1 or self.data.shape[1] in self.peak1):
return 0.0
# now compute signal to noise ratio
if method == 'peak2peak':
# find second peak height
peak2, corr_max2 = self._find_second_peak( width=width )
elif method == 'peak2mean':
# find mean of the correlation map
corr_max2 = self.data.mean()
else:
raise ValueError('wrong sig2noise_method')
# avoid dividing by zero
try:
sig2noise = self.corr_max1/corr_max2
except ValueError:
sig2noise = np.inf
return sig2noise
def get_coordinates( image_size, window_size, overlap ):
"""Compute the x, y coordinates of the centers of the interrogation windows.
Parameters
----------
image_size: two elements tuple
a two dimensional tuple for the pixel size of the image
first element is number of rows, second element is
the number of columns.
window_size: int
the size of the interrogation windows.
overlap: int
the number of pixel by which two adjacent interrogation
windows overlap.
Returns
-------
x : 2d np.ndarray
a two dimensional array containing the x coordinates of the
interrogation window centers, in pixels.
y : 2d np.ndarray
a two dimensional array containing the y coordinates of the
interrogation window centers, in pixels.
"""
# get shape of the resulting flow field
field_shape = get_field_shape( image_size, window_size, overlap )
# compute grid coordinates of the interrogation window centers
x = np.arange( field_shape[1] )*(window_size-overlap) + window_size/2.0
y = np.arange( field_shape[0] )*(window_size-overlap) + window_size/2.0
return np.meshgrid(x,y[::-1])
def get_field_shape ( image_size, window_size, overlap ):
"""Compute the shape of the resulting flow field.
Given the image size, the interrogation window size and
the overlap size, it is possible to calculate the number
of rows and columns of the resulting flow field.
Parameters
----------
image_size: two elements tuple
a two dimensional tuple for the pixel size of the image
first element is number of rows, second element is
the number of columns.
window_size: int
the size of the interrogation window.
overlap: int
the number of pixel by which two adjacent interrogation
windows overlap.
Returns
-------
field_shape : two elements tuple
the shape of the resulting flow field
"""
return ( (image_size[0] - window_size)//(window_size-overlap)+1,
(image_size[1] - window_size)//(window_size-overlap)+1 )
def correlate_windows( window_a, window_b, corr_method = 'fft', nfftx = None, nffty = None ):
"""Compute correlation function between two interrogation windows.
The correlation function can be computed by using the correlation
theorem to speed up the computation.
Parameters
----------
window_a : 2d np.ndarray
a two dimensions array for the first interrogation window.
window_b : 2d np.ndarray
a two dimensions array for the second interrogation window.
corr_method : string
one of the two methods currently implemented: 'fft' or 'direct'.
Default is 'fft', which is much faster.
nfftx : int
the size of the 2D FFT in x-direction,
[default: 2 x windows_a.shape[0] is recommended].
nffty : int
the size of the 2D FFT in y-direction,
[default: 2 x windows_a.shape[1] is recommended].
Returns
-------
corr : 2d np.ndarray
a two dimensions array for the correlation function.
"""
if corr_method == 'fft':
if nfftx is None:
nfftx = 2*window_a.shape[0]
if nffty is None:
nffty = 2*window_a.shape[1]
return fftshift(irfft2(rfft2(normalize_intensity(window_a),\
s=(nfftx,nffty))*np.conj(rfft2(normalize_intensity(window_b),\
s=(nfftx,nffty)))).real, axes=(0,1) )
elif corr_method == 'direct':
return convolve(normalize_intensity(window_a), normalize_intensity(window_b[::-1,::-1]), 'full')
else:
raise ValueError('method is not implemented')
def normalize_intensity( window ):
"""Normalize interrogation window by removing the mean value.
Parameters
----------
window : 2d np.ndarray
the interrogation window array
Returns
-------
window : 2d np.ndarray
the interrogation window array, with mean value equal to zero.
"""
return window - window.mean()
##################################################################
def WiDIM( np.ndarray[DTYPEi_t, ndim=2] frame_a,
np.ndarray[DTYPEi_t, ndim=2] frame_b,
np.ndarray[DTYPEi_t, ndim=2] mark,
int min_window_size,
float overlap_ratio,
int coarse_factor,
float dt,
str validation_method='mean_velocity',
int trust_1st_iter=1,
int validation_iter = 1,
float tolerance = 1.5,
int nb_iter_max=3,
str subpixel_method='gaussian',
str sig2noise_method='peak2peak',
int width=2,
nfftx=None,
nffty=None):
"""
Implementation of the WiDIM algorithm (Window Displacement Iterative Method).
This is an iterative method to cope with the lost of pairs due to particles
motion and get rid of the limitation in velocity range due to the window size.
The possibility of window size coarsening is implemented.
Example : minimum window size of 16*16 pixels and coarse_level of 2 gives a 1st
iteration with a window size of 64*64 pixels, then 32*32 then 16*16.
----Algorithm : At each step, a predictor of the displacement (dp) is applied based on the results of the previous iteration.
Each window is correlated with a shifted window.
The displacement obtained from this correlation is the residual displacement (dc)
The new displacement (d) is obtained with dx = dpx + dcx and dy = dpy + dcy
The velocity field is validated and wrong vectors are replaced by mean value of surrounding vectors from the previous iteration (or by bilinear interpolation if the window size of previous iteration was different)
The new predictor is obtained by bilinear interpolation of the displacements of the previous iteration:
dpx_k+1 = dx_k
Reference:
F. Scarano & M. L. Riethmuller, Iterative multigrid approach in PIV image processing with discrete window offset, Experiments in Fluids 26 (1999) 513-523
Parameters
----------
frame_a : 2d np.ndarray, dtype=np.int32
an two dimensions array of integers containing grey levels of
the first frame.
frame_b : 2d np.ndarray, dtype=np.int32
an two dimensions array of integers containing grey levels of
the second frame.
mark : 2d np.ndarray, dtype=np.int32
an two dimensions array of integers with values 0 for the background, 1 for the flow-field. If the center of a window is on a 0 value the velocity is set to 0.
min_window_size : int
the size of the minimum (final) (square) interrogation window.
overlap_ratio : float
the ratio of overlap between two windows (between 0 and 1).
dt : float
the time delay separating the two frames.
validation_method : string
the method used for validation (in addition to the sig2noise method). Only the mean velocity method is implemented now
trust_1st_iter : int = 0 or 1
0 if the first iteration need to be validated. With a first window size following the 1/4 rule, the 1st iteration can be trusted and the value should be 1 (Default value)
validation_iter : int
number of iterations per validation cycle.
tolerance : float
the threshold for the validation method chosen. This does not concern the sig2noise for which the threshold is 1.5; [nb: this could change in the future]
nb_iter_max : int
global number of iterations.
subpixel_method : string
one of the following methods to estimate subpixel location of the peak:
'centroid' [replaces default if correlation map is negative],
'gaussian' [default if correlation map is positive],
'parabolic'.
sig2noise_method : string
defines the method of signal-to-noise-ratio measure,
('peak2peak' or 'peak2mean'. If None, no measure is performed.)
width : int
the half size of the region around the first
correlation peak to ignore for finding the second
peak. [default: 2]. Only used if ``sig2noise_method==peak2peak``.
nfftx : int
the size of the 2D FFT in x-direction,
[default: 2 x windows_a.shape[0] is recommended]
nffty : int
the size of the 2D FFT in y-direction,
[default: 2 x windows_a.shape[1] is recommended]
Returns
-------
x : 2d np.ndarray
a two dimensional array containing the x-axis component of the interpolations locations.
y : 2d np.ndarray
a two dimensional array containing the y-axis component of the interpolations locations.
u : 2d np.ndarray
a two dimensional array containing the u velocity component,
in pixels/seconds.
v : 2d np.ndarray
a two dimensional array containing the v velocity component,
in pixels/seconds.
mask : 2d np.ndarray
a two dimensional array containing the boolean values (True for vectors interpolated from previous iteration)
Example
--------
>>> x,y,u,v, mask = openpiv.process.WiDIM( frame_a, frame_b, mark, min_window_size=16, overlap_ratio=0.25, coarse_factor=2, dt=0.02, validation_method='mean_velocity', trust_1st_iter=1, validation_iter=2, tolerance=0.7, nb_iter_max=4, sig2noise_method='peak2peak')
--------------------------------------
Method of implementation : to improve the speed of the programm,
all data have been placed in the same huge 4-dimensions 'F' array.
(this prevent the definition of a new array for each iteration)
However, during the coarsening process a large part of the array is not used.
Structure of array F:
--The 1st index is the main iteration (K) --> length is nb_iter_max
-- 2nd index (I) is row (of the map of the interpolations locations of iteration K) --> length (effectively used) is Nrow[K]
--3rd index (J) is column --> length (effectively used) is Ncol[K]
--4th index represent the type of data stored at this point:
| 0 --> x |
| 1 --> y |
| 2 --> xb |
| 3 --> yb |
| 4 --> dx |
| 5 --> dy |
| 6 --> dpx |
| 7 --> dpy |
| 8 --> dcx |
| 9 --> dcy |
| 10 --> u |
| 11 --> v |
| 12 --> si2noise |
Storage of data with indices is not good for comprehension so its very important to comment on each single operation.
A python dictionary type could have been used (and would be much more intuitive)
but its equivalent in c language (type map) is very slow compared to a numpy ndarray.
"""
#initializations
# warnings.warn("deprecated", RuntimeWarning)
if nb_iter_max <= coarse_factor:
raise ValueError( "Please provide a nb_iter_max that is greater than the coarse_level" )
cdef int K #main iteration index
cdef int I, J #interrogation locations indices
cdef int L, M #inside window indices
cdef int O, P #frame indices corresponding to I and J
cdef int i, j #dumb indices for various works
cdef float i_peak, j_peak, mean_u, mean_v, rms_u, rms_v, residual_0
cdef int residual, nbwind
cdef np.ndarray[DTYPEi_t, ndim=1] Nrow = np.zeros(nb_iter_max, dtype=DTYPEi)
cdef np.ndarray[DTYPEi_t, ndim=1] Ncol = np.zeros(nb_iter_max, dtype=DTYPEi)
cdef np.ndarray[DTYPEi_t, ndim=1] W = np.zeros(nb_iter_max, dtype=DTYPEi)
cdef np.ndarray[DTYPEi_t, ndim=1] Overlap = np.zeros(nb_iter_max, dtype=DTYPEi)
pic_size=frame_a.shape
#window sizes list initialization
for K in range(coarse_factor+1):
W[K]=np.power(2,coarse_factor-K)*min_window_size
for K in range(coarse_factor+1,nb_iter_max):
W[K]=W[K-1]
#overlap init
for K in range(nb_iter_max):
Overlap[K]=int(np.floor(overlap_ratio*W[K]))
#Ncol and Nrow init
for K in range(nb_iter_max):
Nrow[K]=((pic_size[0]-W[K])//(W[K]-Overlap[K]))+1
Ncol[K]=((pic_size[1]-W[K])//(W[K]-Overlap[K]))+1
#writting the parameters to the screen
if validation_iter==0:
validation_method='None'
cdef float startTime = launch(method='WiDIM', names=['Size of image', 'total number of iterations', 'overlap ratio', 'coarse factor', 'time step', 'validation method', 'number of validation iterations', 'subpixel_method','Nrow', 'Ncol', 'Window sizes', 'overlaps'], arg=[[pic_size[0], pic_size[1]], nb_iter_max, overlap_ratio, coarse_factor, dt, validation_method, validation_iter, subpixel_method, Nrow, Ncol, W, Overlap])
#define the main array F that contains all the data
cdef np.ndarray[DTYPEf_t, ndim=4] F = np.zeros([nb_iter_max, Nrow[nb_iter_max-1], Ncol[nb_iter_max-1], 14], dtype=DTYPEf)
#define mask - bool array don't exist in cython so we go to lower level with cast
#you can access mask with (<object>mask)[I,J]
cdef np.ndarray[np.uint8_t, ndim=2, cast=True] mask = np.empty([Nrow[nb_iter_max-1], Ncol[nb_iter_max-1]], dtype=np.bool)
#define u,v, x,y fields (only used as outputs of this programm)
cdef np.ndarray[DTYPEf_t, ndim=2] u = np.zeros([Nrow[nb_iter_max-1], Ncol[nb_iter_max-1]], dtype=DTYPEf)
cdef np.ndarray[DTYPEf_t, ndim=2] v = np.zeros([Nrow[nb_iter_max-1], Ncol[nb_iter_max-1]], dtype=DTYPEf)
cdef np.ndarray[DTYPEf_t, ndim=2] x = np.zeros([Nrow[nb_iter_max-1], Ncol[nb_iter_max-1]], dtype=DTYPEf)
cdef np.ndarray[DTYPEf_t, ndim=2] y = np.zeros([Nrow[nb_iter_max-1], Ncol[nb_iter_max-1]], dtype=DTYPEf)
#define two small arrays used for the validation process
cdef np.ndarray[DTYPEf_t, ndim=3] neighbours = np.zeros([2,3,3], dtype=DTYPEf)
cdef np.ndarray[DTYPEi_t, ndim=2] neighbours_present = np.zeros([3,3], dtype=DTYPEi)
#initialize x and y values
for K in range(nb_iter_max):
for I in range(Nrow[K]):
for J in range(Ncol[K]):
#x unit vector corresponds to rows
#y unit vector corresponds to columns
if I==0:
F[K,I,J,0]=W[K]/2 #init x on 1st row
else:
F[K,I,J,0]=F[K,I-1,J,0] + W[K] - Overlap[K] #init x
if J==0:
F[K,I,J,1]=W[K]/2 #init y on first column
else:
F[K,I,J,1]=F[K,I,J-1,1] + W[K] - Overlap[K] #init y
#end of the initializations
####################################################
#main loop
for K in range(nb_iter_max):
print("ITERATION # ", K)
window_a, window_b = define_windows(W[K])
#a simple progress bar
# widgets = ['Computing the displacements : ', Percentage(), ' ', Bar(marker='-',left='[',right=']'),
# ' ', ETA(), ' ', FileTransferSpeed()]
# pbar = ProgressBar(widgets=widgets, maxval=100)
# pbar.start()
residual = 0
for I in range(Nrow[K]):#run through interpolations locations
# pbar.update(100*I/Nrow[K])#progress update
for J in range(Ncol[K]):
#compute xb, yb:
F[K,I,J,2]=np.floor(F[K,I,J,0]+F[K,I,J,6])#xb=xa+dpx
F[K,I,J,3]=np.floor(F[K,I,J,1]+F[K,I,J,7])#yb=yb+dpy
#look for corrupted window (ie. going outside of the picture) and relocate them with 0 displacement:
if F[K,I,J,2] + W[K]/2 > pic_size[0]-1 or F[K,I,J,2] - W[K]/2 < 0: #if corrupted on x-axis do:
F[K,I,J,2]=F[K,I,J,0]#xb=x
F[K,I,J,3]=F[K,I,J,1]#yb=y
F[K,I,J,6]=0.0#dpx=0
F[K,I,J,7]=0.0#dpy=0
elif F[K,I,J,3] + W[K]/2 > pic_size[1]-1 or F[K,I,J,3] - W[K]/2 < 0: #if corrupted on y-axis do the same
F[K,I,J,2]=F[K,I,J,0]#xb=x
F[K,I,J,3]=F[K,I,J,1]#yb=y
F[K,I,J,6]=0.0#dpx=0
F[K,I,J,7]=0.0#dpy=0
#fill windows a and b
for L in range(W[K]):
for M in range(W[K]):
window_a[L,M]=frame_a[np.int(F[K,I,J,0] - W[K]/2 + L), \
np.int(F[K,I,J,1] - W[K]/2 + M)]
window_b[L,M]=frame_b[np.int(F[K,I,J,2] - W[K]/2 + L), \
np.int(F[K,I,J,3] - W[K]/2 + M)]
#perform correlation of the two windows
corr = correlate_windows( window_b, window_a, nfftx=nfftx, nffty=nffty )
c = CorrelationFunction( corr )
F[K,I,J,12] = c.sig2noise_ratio( sig2noise_method, width )#compute sig2noise
i_peak, j_peak = c.subpixel_peak_position( subpixel_method )#get peak position
if np.any(np.isnan((i_peak, j_peak))) or mark[np.int(F[K,I,J,0]), np.int(F[K,I,J,1])] == 0:#prevent 'Not a Number' peak location
#if np.any(np.isnan((i_peak, j_peak))):
F[K,I,J,8]=0.0
F[K,I,J,9]=0.0
else:
#find residual displacement dcx and dcy
F[K,I,J,8]=i_peak - corr.shape[0]/2#dcx
F[K,I,J,9]=j_peak - corr.shape[1]/2#dcy
residual = residual + np.sqrt(F[K,I,J,8]*F[K,I,J,8]+F[K,I,J,9]*F[K,I,J,9])
#get new displacement prediction
F[K,I,J,4]=F[K,I,J,6]+F[K,I,J,8]#dx=dpx+dcx
F[K,I,J,5]=F[K,I,J,7]+F[K,I,J,9]#dy=dpy+dcy
#get new velocity vectors
F[K,I,J,10]=F[K,I,J,5] / dt #u=dy/dt
F[K,I,J,11]=-F[K,I,J,4] / dt #v=-dx/dt
# pbar.finish()#close progress bar
print("..[DONE]")
if K==0:
residual_0 = residual/np.float(Nrow[K]*Ncol[K])
print(" --residual : ", (residual/np.float(Nrow[K]*Ncol[K]))/residual_0)
#####################################################
#validation of the velocity vectors with 3*3 filtering
if K==0 and trust_1st_iter:#1st iteration can generally be trust if it follows the 1/4 rule
print("no validation : trusting 1st iteration")
else:
print("Starting validation..")
for I in range(Nrow[nb_iter_max-1]):#init mask to False
for J in range(Ncol[nb_iter_max-1]):
(<object>mask)[I,J]=False
for i in range(validation_iter):#real validation starts
print("Validation, iteration number ",i)
print(" ")
# widgets = ['Validation : ', Percentage(), ' ', Bar(marker='-',left='[',right=']'),
# ' ', ETA(), ' ', FileTransferSpeed()]
# pbar = ProgressBar(widgets=widgets, maxval=100)
# pbar.start()
for I in range(Nrow[K]):#run through locations
# pbar.update(100*I/Nrow[K])
for J in range(Ncol[K]):
neighbours_present = find_neighbours(I, J, Nrow[K]-1, Ncol[K]-1)#get a map of the neighbouring locations
for L in range(3):#get the velocity of the neighbours in a 2*3*3 array
for M in range(3):
if neighbours_present[L,M]:
neighbours[0,L,M]=F[K,I+L-1,J+M-1,10]#u
neighbours[1,L,M]=F[K,I+L-1,J+M-1,11]#v
else:
neighbours[0,L,M]=0
neighbours[1,L,M]=0
if np.sum(neighbours_present) !=0 and mark[np.int(F[K,I,J,0]), np.int(F[K,I,J,1])] == 1:
#if np.sum(neighbours_present):
mean_u = np.sum(neighbours[0])/np.float(np.sum(neighbours_present))#computing the mean velocity
mean_v = np.sum(neighbours[1])/np.float(np.sum(neighbours_present))
if F[K,I,J,12] < 1.5:#validation with the sig2noise ratio, 1.5 is a recommended minimum value
if K==0:#if in 1st iteration, no interpolation is needed so just replace by the mean
F[K,I,J,10] = mean_u
F[K,I,J,11] = mean_v
(<object>mask)[I,J]=True
F[K,I,J,4] = -F[K,I,J,11]*dt#recompute displacement from velocity
F[K,I,J,5] = F[K,I,J,10]*dt
elif K>0 and (Nrow[K] != Nrow[K-1] or Ncol[K] != Ncol[K-1]):#perform interpolation using previous iteration (which is supposed to be already validated -> this prevents error propagation)
F[K,I,J,10] = interpolate_surroundings(F,Nrow,Ncol,K-1,I,J, 10)
F[K,I,J,11] = interpolate_surroundings(F,Nrow,Ncol,K-1,I,J, 11)
if validation_method=='mean_velocity':#add a validation with the mean and rms values
rms_u = np.sqrt(sumsquare_array(neighbours[0])/np.float(np.sum(neighbours_present)))#get rms of u
rms_v = np.sqrt(sumsquare_array(neighbours[1])/np.float(np.sum(neighbours_present)))
if rms_u==0 or rms_v==0:
F[K,I,J,10] = mean_u
F[K,I,J,11] = mean_v
elif ((F[K,I,J,10] - mean_u)/rms_u) > tolerance or ((F[K,I,J,11] - mean_v)/rms_v) > tolerance:
if K==0:
F[K,I,J,10] = mean_u
F[K,I,J,11] = mean_v
(<object>mask)[I,J]=True
F[K,I,J,4] = -F[K,I,J,11]*dt
F[K,I,J,5] = F[K,I,J,10]*dt
elif K>0 and (Nrow[K] != Nrow[K-1] or Ncol[K] != Ncol[K-1]):#case if different dimensions : interpolation using previous iteration
F[K,I,J,10] = interpolate_surroundings(F,Nrow,Ncol,K-1,I,J, 10)
F[K,I,J,11] = interpolate_surroundings(F,Nrow,Ncol,K-1,I,J, 11)
(<object>mask)[I,J]=True
F[K,I,J,4] = -F[K,I,J,11]*dt
F[K,I,J,5] = F[K,I,J,10]*dt
elif K>0 and (Nrow[K] == Nrow[K-1] or Ncol[K] == Ncol[K-1]):#case if same dimensions
for L in range(3):
for M in range(3):
if neighbours_present[L,M]:
neighbours[0,L,M]=F[K-1,I+L-1,J+M-1,10]#u
neighbours[1,L,M]=F[K-1,I+L-1,J+M-1,11]#v
else:
neighbours[0,L,M]=0
neighbours[1,L,M]=0
if np.sum(neighbours_present) !=0:
mean_u = np.sum(neighbours[0])/np.float(np.sum(neighbours_present))
mean_v = np.sum(neighbours[1])/np.float(np.sum(neighbours_present))
F[K,I,J,10] = mean_u
F[K,I,J,11] = mean_v
(<object>mask)[I,J]=True
F[K,I,J,4] = -F[K,I,J,11]*dt
F[K,I,J,5] = F[K,I,J,10]*dt
# pbar.finish()
print("..[DONE]")
print(" ")
#end of validation
##############################################################################
#stop process if this is the last iteration
if K==nb_iter_max-1:
print("//////////////////////////////////////////////////////////////////")
print("end of iterative process.. Re-arranging vector fields..")
for I in range(Nrow[K]):#assembling the u,v and x,y fields for outputs
for J in range(Ncol[K]):
x[I,J]=F[K,I,J,1]
y[I,J]=F[K,Nrow[K]-I-1,J,0]
u[I,J]=F[K,I,J,10]
v[I,J]=F[K,I,J,11]
print("...[DONE]")
end(startTime)
return x, y, u, v, (<object>mask)
#############################################################################
#go to next iteration : compute the predictors dpx and dpy from the current displacements
print("going to next iteration.. ")
print("performing interpolation of the displacement field")
print(" ")
# widgets = ['Performing interpolations : ', Percentage(), ' ', Bar(marker='-',left='[',right=']'),
# ' ', ETA(), ' ', FileTransferSpeed()]
# pbar = ProgressBar(widgets=widgets, maxval=100)
# pbar.start()
for I in range(Nrow[K+1]):
# pbar.update(100*I/Nrow[K+1])
for J in range(Ncol[K+1]):
if Nrow[K+1]==Nrow[K] and Ncol[K+1]==Ncol[K]:
F[K+1,I,J,6] = F[K,I,J,4]#dpx_k+1 = dx_k
F[K+1,I,J,7] = F[K,I,J,5]#dpy_k+1 = dy_k
else:#interpolate if dimensions do not agree
F[K+1,I,J,6] = interpolate_surroundings(F,Nrow,Ncol,K,I,J, 4)
F[K+1,I,J,7] = interpolate_surroundings(F,Nrow,Ncol,K,I,J, 5)
# pbar.finish()
print("..[DONE] -----> going to iteration ",K+1)
print(" ")
def interpolate_surroundings(np.ndarray[DTYPEf_t, ndim=4] F,
np.ndarray[DTYPEi_t, ndim=1] Nrow,
np.ndarray[DTYPEi_t, ndim=1] Ncol,
int K,
int I,
int J,
int dat):
"""Perform interpolation of between to iterations of the F 4d-array for a specific location I,J and the data type dat.
Parameters
----------
F : 4d np.ndarray
The main array of the WIDIM algorithm.
Nrow : 1d np.ndarray
list of the numbers of row for each iteration K
Ncol : 1d np.ndarray
list of the numbers of column for each iteration K
K : int
the iteration that contains the valid data. K+1 will be the iteration at which the interpolation is needed.
I,J : int
indices of the point that need interpolation (in iteration K+1)
dat : int
the index of the data to interpolate.
Returns
-------
the interpolated data (type float)
"""
#interpolate data dat from previous iteration
cdef float lower_lim_previous_x = F[K,0,0,0]
cdef float lower_lim_previous_y = F[K,0,0,1]
cdef float upper_lim_previous_x = F[K,Nrow[K]-1,Ncol[K]-1,0]
cdef float upper_lim_previous_y = F[K,Nrow[K]-1,Ncol[K]-1,1]
cdef float pos_now_x = F[K+1,I,J,0]
cdef float pos_now_y = F[K+1,I,J,1]
cdef np.ndarray[DTYPEi_t, ndim=1] Q1 = np.zeros(2, dtype=DTYPEi)
cdef np.ndarray[DTYPEi_t, ndim=1] Q4 = np.zeros(2, dtype=DTYPEi)
if pos_now_x < lower_lim_previous_x:#top row
if pos_now_y < lower_lim_previous_y:#top left corner
return F[K,0,0,dat]
elif pos_now_y > upper_lim_previous_y:#top right corner
return F[K,0,Ncol[K]-1,dat]
else:#top row no corners
low_y, high_y = F_dichotomy(F,K,Ncol,'y_axis',pos_now_y)
if low_y == high_y:
return F[K,0,low_y,dat]
else:
return linear_interpolation(F[K,0,low_y,1], F[K,0,high_y,1], pos_now_y, F[K,0,low_y,dat], F[K,0,high_y,dat])
elif pos_now_x > upper_lim_previous_x:#bottom row
if pos_now_y < lower_lim_previous_y:#bottom left corner
return F[K,Nrow[K]-1,0,dat]
elif pos_now_y > upper_lim_previous_y:#bottom right corner
return F[K,Nrow[K]-1,Ncol[K]-1,dat]
else:#bottom row no corners
low_y, high_y = F_dichotomy(F,K,Ncol,'y_axis',pos_now_y)
#print low_y, high_y
if low_y == high_y:
return F[K,Nrow[K]-1,low_y,dat]
else:
return linear_interpolation(F[K,0,low_y,1], F[K,0,high_y,1], pos_now_y, F[K,Nrow[K]-1,low_y,dat], F[K,Nrow[K]-1,high_y,dat])
elif pos_now_y < lower_lim_previous_y:#left column no corners
low_x, high_x = F_dichotomy(F,K,Nrow,'x_axis',pos_now_x)
if low_x == high_x:
return F[K,low_x,0,dat]
else:
return linear_interpolation(F[K,low_x,0,0], F[K,high_x,0,0], pos_now_x, F[K,low_x,0,dat], F[K,high_x,0,dat])
elif pos_now_y > upper_lim_previous_y:#right column no corners
low_x, high_x = F_dichotomy(F,K,Nrow,'x_axis',pos_now_x)
if low_x == high_x: