-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathuspgs.py
1504 lines (1113 loc) · 53.8 KB
/
uspgs.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
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
import numpy as np
import scipy.ndimage
import scipy.interpolate
import time
import sys
import sklearn.decomposition
import statsmodels.api as sm
import angles
import cv2
import SimpleITK as sitk
import registration_callbacks as rc
import medpy.metric.image
import functools
from statsmodels.tsa.filters.hp_filter import hpfilter
from statsmodels.nonparametric.smoothers_lowess import lowess
sys.path.insert(0, 'pyLAR')
import core.ialm
class USPGS(object):
def __init__(self,
# noise suppression parameters
median_filter_size=1,
apply_lr_denoising = False,
lr_xy_downsampling=1,
lr_gamma_factor=1,
lr_conv_tol=1e-05,
# phase estimation
similarity_method='ncorr',
pca_n_components=0.99,
detrend_method='hp',
lowess_frac=0.3, lowess_mode='-',
hp_lamda=6400,
band_pass_bpm=None,
cardiac_bpass_bpm=[310, 840],
resp_lpass_bpm=230,
# respiratory gating
respiration_present=True, resp_phase_cutoff=0.2
):
"""
This class includes novel image-based methods for instantaneous
cardio-respiratory phase estimation, respiratory gating, and
temporal super-resolution.
Parameters
----------
median_filter_size : integer
kernel radius/half-width of the medial filter used to perform
some preliminary noise suppression. Default value 1.
apply_lr_denoising : bool
Set this to `True` if you want to perform denoising using low-rank
plus sparse decomposition. This is set to False by default as it
was not found to make a significant difference on phase estimation.
lr_xy_downsampling : double
A value in (0, 1] that specifies the amount by which the video
frames should be down-sampled, spatially, before applying low-rank
plus sparse decomposition. Down-sampling speeds up low-rank
decomposition. This parameter has an effect only if
`apply_lr_denoising` is set to `True`. Default value is 1 which
means no down-sampling.
lr_gamma_factor : double
This is used to determine the weight `gamma` of the sparsity term
in the low-rank + sparse decomposition. Specifically, the weight
`gamma = lr_gamma_factor * (1 / max(image_width, image_height))`.
This parameter has an effect only if `apply_lr_denoising` is set
to `True`. Default value is 1.
lr_conv_tol : double
The convergence tolerance for the low-rank + sparse decomposition
algorithm. Default value is `1e-05`.
similarity_method : 'pca' or 'ncorr'
Specifies the method used to compute the simarity between two images
while generating the inter-frame similarity matrix. Can be equal to
'ncorr' or 'pca'. Default value is 'ncorr'.
When set to `ncorr` it uses normalized correlation. When set to
'pca' it uses principal component analysis (PCA) to learn a low-dim
representation of video frames and measures similarity as the -ve
of the euclidean distance between the images in this reduced
dimensional space.
pca_n_components : double
A value between (0, 1] that specifies the amount variance that
needs to be covered when learning a low-dim space using principal
component analysis (PCA).
detrend_method : 'hp' or 'lowess'
Specifies the method used to decompose the frame similarity signal
into trend/respiration and residual/cardiac components. Can be
equal to 'hp' (for hodrick-prescott filter) or 'lowess' for
locally weighted regression. Default value is 'hp'.
lowess_frac : double
Must be between 0 and 1. Sepcifies the fraction of the data to be
used when estimating the value of the trend signal at each time
point. See `statsmodels.nonparametric.smoothers_lowess` for more
details. This parameter has an effect only if `detrend_method` is
set to `lowess`. Default value is 0.3.
lowess_mode : '-' or '/'
Specifies whether to subtract (when set to `-`) or divide (when set
to '/') the lowess trend/respiration signal to extract the
residual/cardiac component. This parameter has an effect only if
`detrend_method` is set to `lowess`.
hp_lamda : double
Sets the smoothing parameter of the hodrisk-prescott filter. See
`statsmodels.tsa.filters.hp_filter.hpfilter` for more details.
Default value is 6400 that was empirically found to work well for
separating the respiration and cardiac motions. We suggest trying
different values in powers of 2.
band_pass_bpm : None or array_like
Specifies the range of the band-pass filter (in beats/cycles per
min) to be applied to the frame similarity signal before decomposing
it into the trend/respiratory and residual/cardiac components. This
parameter can be used to suppress the effects of motions that
are outside the frequency band of cardio-respiratory motion.
cardiac_bpass_bpm : None or array_like
Specifies the frequency range (in beats per min) of cardiac motion
resp_lpass_bpm : None or double
Specified the upper frequency cutoff (in beats per min) of
respiratory motion
respiration_present : bool
Set to True if the video has respiratory motion. Default is True.
resp_phase_cutoff : double
Must be between 0 and 1. Frames whose phase distance from the
respiratory phase (equal to zero) is less than `resp_phase_cutoff`
are thrown out in the first step of respiratory gating method.
See paper for more details. Default value is 0.2.
"""
# noise suppression parameters
self.median_filter_size = median_filter_size
self.apply_lr_denoising = apply_lr_denoising
self.lr_gamma_factor = lr_gamma_factor
self.lr_conv_tol = lr_conv_tol
if not (lr_xy_downsampling > 0 and lr_xy_downsampling <= 1.0):
raise ValueError('lr_xy_downsampling should in (0, 1]')
self.lr_xy_downsampling = lr_xy_downsampling
# phase estimation parameters
if similarity_method not in ['ncorr', 'pca']:
raise ValueError("Invalid similarity method. Must be ncorr or pca")
self.similarity_method = similarity_method
self.pca_n_components = pca_n_components
if detrend_method not in ['lowess', 'hp']:
raise ValueError("Invalid detrend method. Must be lowess or hp")
self.detrend_method = detrend_method
if lowess_mode not in ['/', '-']:
raise ValueError("Invalid detrend mode. Must be '/' or '-'")
self.lowess_mode = lowess_mode
if not (lowess_frac > 0 and lowess_frac <= 1.0):
raise ValueError('lowess_frac should in (0, 1]')
self.lowess_frac = lowess_frac
self.hp_lamda = hp_lamda
if band_pass_bpm is not None and len(band_pass_bpm) != 2:
raise ValueError('band_pass_bpm must be an array of two elements')
self.band_pass_bpm = band_pass_bpm
if len(cardiac_bpass_bpm) != 2:
raise ValueError('cardiac_bpass_bpm must be an array of two '
'elements')
self.cardiac_bpass_bpm = cardiac_bpass_bpm
self.resp_lpass_bpm = resp_lpass_bpm
self.respiration_present = respiration_present
self.resp_phase_cutoff = resp_phase_cutoff
def set_input(self, imInput, fps, zero_phase_fid=None):
"""
Sets the input video to be analyzed
Parameters
----------
imInput : array_like
Input video to be analyzed
fps : double
Frame rate in frames per sec
"""
self.imInput_ = imInput
self.fps_ = fps
self.zero_phase_fid_ = zero_phase_fid
def process(self):
"""
Runs the phase estimation algorithm on the input video.
"""
tProcessing = time.time()
print 'Input video size: ', self.imInput_.shape
# Step-1: Suppress noise using low-rank plus sparse decomposition
print '\n>> Step-1: Suppressing noise ...\n'
tDenoising = time.time()
self._denoise(self.imInput_)
print '\nNoise suppression took %.2f seconds' % (time.time() -
tDenoising)
# Step-2: Estimate intra-period phase
print '\n>> Step-2: Estimating instantaneous phase ...\n'
tPhaseEstimation = time.time()
self._estimate_phase(self.imInputDenoised_)
print '\nPhase estimation took %.2f seconds' % (time.time() -
tPhaseEstimation)
# Done processing
print '\n>> Done processing ... took a total of %.2f seconds' % (
time.time() - tProcessing)
def get_frame_similarity_signal(self):
"""
Returns the inter-frame similarity signal
"""
return self.ts_
def get_cardiac_signal(self):
"""
Returns the residual/cardiac component of the inter-frame similarity
signal
"""
return self.ts_seasonal_
def get_respiration_signal(self):
"""
Returns the trend/respiration component of the inter-frame similarity
signal
"""
return self.ts_trend_
def get_cardiac_phase(self):
"""
Returns the instantaneous cardiac phase of each frame in the video
"""
return self.ts_instaphase_nmzd_
def get_respiratory_phase(self):
"""
Returns the instantaneous respiratory phase of each frame in the video
"""
return self.ts_trend_instaphase_nmzd_
def get_cardiac_cycle_duration(self):
"""
Returns the duration of the cardiac cycle in frames
"""
return self.period_
def generate_single_cycle_video(self, numOutFrames,
imInput=None, method=None):
"""
Reconstructs the video of a single cardiac cycle at a desired temporal
resolution.
Parameters
----------
numOutFrames : int
Number of frames in the output video. This parameter determines
the temporal resolution of the generated output video.
imInput : array_like
If you want to reconstruct the single cycle video from some
surrogate video (e.g. low-rank component) of the input, then
use this parameter to pass that video. Default is None which means
the single cycle video will be reconstructed from the input video.
method : dict or None
A dict specifying the name and associated parameters of the method
used to reconstruct the image at any phase.
The dict can obtained by calling one of these three function:
(i) `config_framegen_using_kernel_regression`,
(ii) `config_framegen_using_optical_flow`, or
(iii) `config_framegen_using_bspline_registration`
Take a look at these functions to know what this dict contains.
Default is None, which means it will internally call
`config_framegen_using_kernel_regression` to get this dict.
Returns
-------
imSingleCycleVideo : array_like
Reconstructured single cycle video.
"""
phaseRange = np.array([0, 1])
return self.generate_video_from_phase_range(numOutFrames, phaseRange,
imInput=imInput,
method=method)
def generate_video_from_phase_range(self, numOutFrames, phaseRange,
imInput=None, method=None):
"""
Reconstructs video within a given phase range at a desired temporal
resolution.
Parameters
----------
numOutFrames : int
Number of frames in the output video. This parameter determines
the temporal resolution of the generated output video.
phaseRange : tuple
A tuple of two phase values between which the video will be
generated.
imInput : array_like
If you want to reconstruct the single cycle video from some
surrogate video (e.g. low-rank component) of the input, then
use this parameter to pass that video. Default is None which means
the single cycle video will be reconstructed from the input video.
method : dict or None
A dict specifying the name and associated parameters of the method
used to reconstruct the image at any phase.
The dict can obtained by calling one of these three function:
(i) `config_framegen_using_kernel_regression`,
(ii) `config_framegen_using_optical_flow`, or
(iii) `config_framegen_using_bspline_registration`
Take a look at these functions to know what this dict contains.
Default is None, which means it will internally call
`config_framegen_using_kernel_regression` to get this dict.
Returns
-------
imOutputVideo : array_like
Reconstructured video within the given phase range.
"""
# validate phase argument
if not (len(phaseRange) == 2 and
np.all(phaseRange >= 0) and np.all(phaseRange <= 1) and
phaseRange[0] < phaseRange[1]):
raise ValueError('Invalid phase range')
# generate video
phaseVals = np.linspace(phaseRange[0], phaseRange[1], numOutFrames)
return self.generate_frames_from_phase_values(phaseVals,
imInput=imInput,
method=method)
def generate_frames_from_phase_values(self, phaseVals,
imInput=None, method=None,
exclude_frames=None,
show_progress=True):
"""
Reconstructs the images corresponding to a list of phase values.
Parameters
----------
phaseVals : list
A list of phase values for which images will be
reconstructs.
imInput : array_like
If you want to reconstruct the single cycle video from some
surrogate video (e.g. low-rank component) of the input, then
use this parameter to pass that video. Default is None which means
the single cycle video will be reconstructed from the input video.
method : dict or None
A dict specifying the name and associated parameters of the method
used to reconstruct the image at any phase.
The dict can obtained by calling one of these three function:
(i) `config_framegen_using_kernel_regression`,
(ii) `config_framegen_using_optical_flow`, or
(iii) `config_framegen_using_bspline_registration`
Take a look at these functions to know what this dict contains.
Default is None, which means it will internally call
`config_framegen_using_kernel_regression` to get this dict.
exclude_frames : list or None
A list of frames to exclude while performing the reconstruction
show_progress : bool
Prints computation progress
Returns
-------
imOutputVideo : array_like
Reconstructured video with frames corresponding to the
phase values in `phaseVals`.
"""
# validate phase vals
phaseVals = np.array(phaseVals)
if np.any(phaseVals < 0) or np.any(phaseVals > 1):
raise ValueError('Invalid phase values')
# set imInput
if imInput is None:
imInput = self.imInput_
# exclude the frames requested
if exclude_frames is not None:
fmask = np.ones(imInput.shape[2], dtype=bool)
fmask[exclude_frames] = False
imInput = imInput[:, :, fmask]
phaseRecorded = self.ts_instaphase_nmzd_[fmask]
simRecorded = self.ts_[fmask]
else:
phaseRecorded = self.ts_instaphase_nmzd_
simRecorded = self.ts_
# generate frames
numOutFrames = len(phaseVals)
imOutputVideo = np.zeros(imInput.shape[:2] + (numOutFrames, ))
if method is None:
method = config_framegen_using_kernel_regression()
if method['name'].startswith('kernel_regression'):
# compute sigmaPhase
kPhase = method['params']['sigmaPhaseFactor']
pdiff = phaseDiff(phaseRecorded)
pstd = sm.robust.scale.mad(pdiff, center=0)
sigmaPhase = kPhase * pstd
# print 'sigmaPhase = ', sigmaPhase
# compute sigmaSimilarity
kSim = method['params']['sigmaSimilarityFactor']
if kSim is not None:
if exclude_frames is None:
sim_lowess_reg = self.sim_lowess_reg_
else:
fmaskWoutResp = fmask
fmaskWoutResp[self.resp_ind_] = False
phaseWoutResp = self.ts_instaphase_nmzd_[fmaskWoutResp]
simWoutResp = self.ts_[fmaskWoutResp]
sim_lowess_reg = LowessRegression()
sim_lowess_reg.fit(phaseWoutResp, simWoutResp)
sigmaSim = kSim * sim_lowess_reg.residual_mad()
simLowess = sim_lowess_reg.predict(phaseVals)
X = np.reshape(imInput,
(np.prod(imInput.shape[:2]), imInput.shape[2])).T
prevPercent = 0
for fid in range(numOutFrames):
curPhase = phaseVals[fid]
if method['name'].startswith('kernel_regression'):
# generate frame by rbf interpolation
wPhase = gauss_phase_kernel(
phaseRecorded, curPhase, sigmaPhase).T
w = wPhase
if kSim is not None:
wSim = gauss_similarity_kernel(
simRecorded, simLowess[fid], sigmaSim).T
wSim[wSim < 1e-6] = 1e-6
w = wPhase * wSim
w /= w.sum()
if method['params']['stochastic']:
numRecordedFrames = X.shape[0]
numPixels = X.shape[1]
'''
imVote = np.zeros((256, numPixels))
for p in range(numPixels):
for f in range(numRecordedFrames):
imVote[X[f, p], p] += w[f]
d = np.zeros(numPixels)
for p in range(numPixels):
v = imVote[:, p]
v /= v.sum()
d[p] = np.random.choice(np.arange(256), size=1, p=v)
imCurFrame = np.reshape(d, imInput.shape[:2])
'''
# '''
fsel = np.random.choice(np.arange(numRecordedFrames),
size=numPixels, p=w)
d = np.zeros(X.shape[1])
for i in range(d.size):
d[i] = X[fsel[i], i]
imCurFrame = np.reshape(d, imInput.shape[:2])
# '''
imCurFrame = scipy.ndimage.filters.median_filter(
imCurFrame, (3, 3))
else:
imCurFrame = np.reshape(np.dot(w, X), imInput.shape[:2])
elif method['name'] in ['optical_flow', 'bspline_registration',
'linear_interpolation']:
# find closest prev and next frame
prevPhaseInd = np.argmin(
(curPhase - phaseRecorded) % 1)
prevPhase = phaseRecorded[prevPhaseInd]
nextPhaseInd = np.argmin(
(phaseRecorded - curPhase) % 1)
nextPhase = phaseRecorded[nextPhaseInd]
prevPhaseDist = phaseDist(prevPhase, curPhase)
nextPhaseDist = phaseDist(curPhase, nextPhase)
totalPhaseDist = prevPhaseDist + nextPhaseDist
alpha = prevPhaseDist / totalPhaseDist
imPrevFrame = imInput[:, :, prevPhaseInd]
imNextFrame = imInput[:, :, nextPhaseInd]
if method['name'] == 'optical_flow':
imCurFrame = frame_gen_optical_flow(
imPrevFrame, imNextFrame,
alpha, **(method['params']))
elif method['name'] == 'bspline_registration':
imCurFrame, _ = frame_gen_bspline_registration(
imPrevFrame, imNextFrame, alpha, **(method['params']))
elif method['name'] == 'linear_interpolation':
imCurFrame = (1-alpha) * imPrevFrame + alpha * imNextFrame
else:
raise ValueError('Invalid method - %s' % method['name'])
# add to video
imOutputVideo[:, :, fid] = imCurFrame
# update progress
if show_progress:
curPercent = np.floor(100.0*fid/numOutFrames)
if curPercent > prevPercent:
prevPercent = curPercent
print '%.2d%%' % curPercent,
if show_progress:
print '\n'
return imOutputVideo
def validate_frame_generation(self, k=1, rounds=10, method=None,
metric='ncorr', seed=1,
mi_bins=16, k_mad=None,
exclude_similar_phase_frames=False):
"""
Evaluates frame generation using Leave-k-out-cross-validation (LKOCV)
where k frames are left out, the phase estimation algorithm is run
on rest of the frames, the left out frames are reconstructed, and the
quality of the reconstructions are evaluated by computing their
similarity with the corresponding acquired frame using a specified
metric. Several rounds of LKOCV are performed and the performance
measures are averaged.
Parameters
----------
k : int
The value of k in LKOCV that represents the number of randomly
selected frames to leave out. The left out frames will be
reconstructed and the performance will be evaluated using the
method specified using the `metric` parameter.
rounds : int
Specifies the number of rounds of LKOCV.
method : dict or None
A dict specifying the name and associated parameters of the method
used to reconstruct the image at any phase.
The dict can obtained by calling one of these three function:
(i) `config_framegen_using_kernel_regression`,
(ii) `config_framegen_using_optical_flow`, or
(iii) `config_framegen_using_bspline_registration`
Take a look at these functions to know what this dict contains.
Default is None, which means it will internally call
`config_framegen_using_kernel_regression` to get this dict.
metric : string
Metric used to compute the similarity between the reconstructed
and actual/acquired frames. Can be 'ncorr', 'rmse', 'mad', or
'mutual_information'.
seed : int
seed used for the random number generate to get same results across
multiple runs.
mi_bins : int
Number of histogram bins for mutual information.
k_mad : double
Set this to drop frames whose value in the frame similarity signal
is farther than `k_mad` times the residual MAD of the lowess fit.
This can be used to leave out respiratory frames.
exclude_similar_phase_frames : bool
If set True, along with each randomly selected frame to leave-out,
the frames with the closest phase value from each cardiac cycle
will be dropped.
Returns
-------
mval : list
Returns the mean value of the similarity metric across all `k`
reconstructed frames for each round of LKOCV.
"""
'''
valid_ind = [fid for fid in range(self.imInput_.shape[2])
if (np.abs(self.ts_[fid] - self.ts_lowess_[fid]) <
2.0 * self.sim_lowess_reg_.residual_mad())]
'''
valid_ind = [fid for fid in range(self.imInput_.shape[2]) if fid not in self.resp_ind_]
mval = np.zeros(rounds)
np.random.seed(seed)
period = np.int(self.period_ + 0.5)
for r in range(rounds):
print r+1,
# choose k frames randomly
ksel_ind = np.random.choice(valid_ind, k, replace=False)
ph_ksel = self.ts_instaphase_nmzd_[ksel_ind]
# print '\t', zip(ksel_ind, ph_ksel)
# Find similar phase frames in each cycle to exclude if requested
sim_phase_ind = []
if exclude_similar_phase_frames:
for fid in ksel_ind:
prev_ind = np.arange(fid-period, 0, -period, dtype='int')
next_ind = np.arange(fid+period, self.imInput_.shape[2], period, dtype='int')
sim_phase_ind.extend(prev_ind)
sim_phase_ind.extend(next_ind)
sim_phase_ind = np.unique(sim_phase_ind)
# print '\t', zip(sim_phase_ind, self.ts_instaphase_nmzd_[sim_phase_ind])
imExclude = self.imInput_[:, :, ksel_ind].astype('float')
exclude_find = functools.reduce(np.union1d, (ksel_ind, sim_phase_ind))
imSynth = self.generate_frames_from_phase_values(
ph_ksel, method=method, show_progress=False,
exclude_frames=exclude_find)
cur_mval = 0.0
for i in range(len(ksel_ind)):
if metric == 'ncorr':
cur_mval += ncorr(imExclude[:, :, i], imSynth[:, :, i])
elif metric == 'rmse':
cur_mval += rmse(imExclude[:, :, i], imSynth[:, :, i])
elif metric == 'mad':
cur_mval += np.median(
np.abs(imExclude.ravel() - imSynth.ravel()))
elif metric == 'mutual_information':
cur_mval += medpy.metric.image.mutual_information(
imExclude, imSynth, bins=mi_bins
)
else:
raise ValueError('Invalid metric')
cur_mval /= len(ksel_ind)
mval[r] = cur_mval
print '\n', mval
return mval
def _denoise(self, imInput):
imInputDenoised = imInput
# denoise using median filter if requested
if self.median_filter_size > 0:
imInputDenoised = scipy.ndimage.filters.median_filter(
imInputDenoised,
(2 * self.median_filter_size + 1,
2 * self.median_filter_size + 1, 1)
)
if self.apply_lr_denoising:
# reduce xy size to speed up low-rank + sparse decomposition
if self.lr_xy_downsampling < 1:
imInputDenoised = scipy.ndimage.interpolation.zoom(
imInputDenoised,
(self.lr_xy_downsampling, self.lr_xy_downsampling, 1)
)
# create a matrix D where each column represents one video frame
D = np.reshape(imInputDenoised, (np.prod(imInputDenoised.shape[:2]),
imInputDenoised.shape[2]))
# perform low-rank plus sparse decomposition on D
tRPCA = time.time()
gamma = self.lr_gamma_factor / np.sqrt(np.max(D.shape))
res = core.ialm.recover(D, gamma, tol=self.lr_conv_tol)
D_lowRank = np.array( res[0] )
D_sparse = np.array( res[1] )
imD = np.reshape(D, imInputDenoised.shape)
imLowRank = np.reshape(D_lowRank, imInputDenoised.shape)
imSparse = np.reshape(D_sparse, imInputDenoised.shape)
if self.lr_xy_downsampling < 1:
# restore result to original size
zoomFactor = np.array(imInput.shape).astype('float') / \
np.array(imInputDenoised.shape)
imD = scipy.ndimage.interpolation.zoom(imD, zoomFactor)
imLowRank = scipy.ndimage.interpolation.zoom(imLowRank,
zoomFactor)
imSparse = scipy.ndimage.interpolation.zoom(imSparse,
zoomFactor)
print 'Low-rank plus sparse decomposition took {} seconds'.format(
time.time() - tRPCA)
imInputDenoised = imLowRank
# store results
self.imD_ = imD
self.imLowRank_ = imLowRank
self.imSparse_ = imSparse
self.imInputDenoised_ = imInputDenoised
def _compute_frame_similarity(self, imAnalyze):
# Compute similarity of each time point with all other time points
simMat = np.zeros((imAnalyze.shape[-1], imAnalyze.shape[-1]))
if self.similarity_method == 'ncorr':
print '\nComputing similarity using normalized correlation ... ',
tSimMat = time.time()
X = np.reshape(imAnalyze, (np.prod(imAnalyze.shape[:2]), imAnalyze.shape[-1])).T
# X = (X - X.mean(0)) / X.std(0)
# simMat = np.dot(X.T, X) / X.shape[0]
simMat = 1 - scipy.spatial.distance.cdist(X, X, 'correlation')
print 'took {} seconds'.format(time.time() - tSimMat)
elif self.similarity_method == 'pca':
# create a matrix where each row represents one frame
X = np.reshape(imAnalyze, (np.prod(imAnalyze.shape[:2]), imAnalyze.shape[-1])).T
# perform pca on X
print 'Reducing dimensionality using PCA ... ',
tPCA_Start = time.time()
pca = sklearn.decomposition.PCA(n_components = self.pca_n_components)
X_proj = pca.fit_transform(X)
tPCA_End = time.time()
numEigenVectors = pca.n_components_
print 'took {} seconds'.format(tPCA_End - tPCA_Start)
print '%d eigen vectors used to cover %.2f%% of variance' % (
numEigenVectors, self.pca_n_components * 100)
# Compute similarity of key frame with all the other frames
print '\nComputing similarity as -ve distance in pca space ... '
simMat = np.zeros((imAnalyze.shape[2], imAnalyze.shape[2]))
tSimMat = time.time()
for keyFrameId in range(imAnalyze.shape[2]):
for fid in range(keyFrameId, imAnalyze.shape[2]):
p2pVec = X_proj[fid, :numEigenVectors] - X_proj[keyFrameId, :numEigenVectors]
dist = np.sqrt(np.sum(p2pVec**2))
simMat[keyFrameId, fid] = -dist
simMat[fid, keyFrameId] = simMat[keyFrameId, fid]
print '%.3d' % keyFrameId,
print '\ntook {} seconds'.format(time.time() - tSimMat)
else:
raise ValueError('Invalid similarity method %s'
% self.similarity_method)
# store results
self.simMat_ = simMat
if self.similarity_method == 'pca':
self.pca_ = pca
self.X_proj_ = X_proj
# return results
return simMat
def _extract_cardio_respiratory_signals(self, imAnalyze):
# Step-1: compute inter-frame similarity matrix
simMat = self._compute_frame_similarity(imAnalyze)
# find the optimal key frame and use it to decompose
spectralEntropy = np.zeros((simMat.shape[0], 1))
simMat_Bpass = np.zeros_like(simMat)
simMat_Trend = np.zeros_like(simMat)
simMat_Seasonal = np.zeros_like(simMat)
for fid in range(simMat.shape[0]):
ts = simMat[fid,]
# perform band pass filtering if requested
if self.band_pass_bpm is not None:
ts_bpass = bpass_filter(ts, self.fps_, self.band_pass_bpm)
else:
ts_bpass = ts
# decompose into trend and seasonal parts
if self.detrend_method == 'lowess':
# lowess regression
ts_seasonal, ts_trend = detrend_lowess(ts_bpass,
frac=self.lowess_frac,
mode=self.lowess_mode)
else:
# hoedrick-prescott filter
ts_seasonal, ts_trend = hpfilter(ts_bpass, lamb=self.hp_lamda)
# compute periodogram entropy of the seasonal part
freq, power = scipy.signal.periodogram(ts_seasonal)
# store result
simMat_Bpass[fid,] = ts_bpass
simMat_Trend[fid,] = ts_trend
simMat_Seasonal[fid,] = ts_seasonal
spectralEntropy[fid] = scipy.stats.entropy(power)
if self.zero_phase_fid_ is None:
fid_best = np.argmin(spectralEntropy)
else:
fid_best = self.zero_phase_fid_
ts = simMat[fid_best, :]
ts_bpass = simMat_Bpass[fid_best, :]
ts_trend = simMat_Trend[fid_best, :]
ts_seasonal = simMat_Seasonal[fid_best, :]
# apply bpass/lpass filtering
ts_seasonal = bpass_filter(ts_seasonal,
self.fps_, self.cardiac_bpass_bpm)
ts_trend = lpass_filter(ts_trend, self.fps_, self.resp_lpass_bpm)
print "Chose frame %d as key frame" % fid_best
# estimate period from the periodogram
freq, power = scipy.signal.periodogram(ts_seasonal)
maxPowerLoc = np.argmax(power)
period = 1.0 / freq[maxPowerLoc]
print "Estimated period = %.2f frames" % period
print "Estimated number of periods = %.2f" % (ts_seasonal.size / period)
# store results
self.simMat_Bpass_ = simMat_Bpass
self.simMat_Trend_ = simMat_Trend
self.simMat_Seasonal_ = simMat_Seasonal
self.spectralEntropy_ = spectralEntropy
self.fid_best_ = fid_best
self.ts_ = ts
self.ts_bpass_ = ts_bpass
self.ts_trend_ = ts_trend
self.ts_seasonal_ = ts_seasonal
self.period_ = period
def _estimate_phase(self, imAnalyze):
self._extract_cardio_respiratory_signals(imAnalyze)
# compute analytic signal, instantaneous phase and amplitude
ts_analytic = scipy.signal.hilbert(
self.ts_seasonal_ - self.ts_seasonal_.mean())
ts_instaamp = np.abs(ts_analytic)
ts_instaphase = np.arctan2(np.imag(ts_analytic), np.real(ts_analytic))
ts_instaphase_nmzd = (ts_instaphase + np.pi) / (2 * np.pi)
# estimate instantaneous phase of trend component - breathing
ts_trend_analytic = scipy.signal.hilbert(
self.ts_trend_ - self.ts_trend_.mean())
ts_trend_instaamp = np.abs(ts_trend_analytic)
ts_trend_instaphase = np.arctan2(np.imag(ts_trend_analytic),
np.real(ts_trend_analytic))
ts_trend_instaphase_nmzd = (ts_trend_instaphase + np.pi) / (2 * np.pi)
# learn mapping from phase to similarity
resp_ind = []
if self.respiration_present: # is set to True when breathing is present
# identify frames with bad influence by respiration
w = self.resp_phase_cutoff
resp_ind = np.argwhere(
np.logical_or(ts_trend_instaphase_nmzd < w,
ts_trend_instaphase_nmzd > 1.0 - w)
).ravel()
print 'Frames with bad respiration influence = %.2f%%' % (
100.0 * len(resp_ind) / len(self.ts_))
# find similarity bounds at each phase using lowess
phaseord_est = np.argsort(ts_instaphase_nmzd)
phaseord_est_wout_resp = [fid for fid in phaseord_est
if fid not in resp_ind]