-
Notifications
You must be signed in to change notification settings - Fork 12
/
preprocess.py
2712 lines (2187 loc) · 90.8 KB
/
preprocess.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
# Copyright © 2016-2023 Medical Image Analysis Laboratory, University Hospital Center and University of Lausanne (UNIL-CHUV), Switzerland
#
# This software is distributed under the open-source license Modified BSD.
"""PyMIALSRTK preprocessing functions.
It includes BTK Non-local-mean denoising, slice intensity correction
slice N4 bias field correction, slice-by-slice correct bias field, intensity standardization,
histogram normalization and both manual or deep learning based automatic brain extraction.
"""
from decimal import DivisionByZero
import os
import pathlib
from skimage.morphology import binary_opening, binary_closing
import numpy as np
from traits.api import *
# Reorientation
import nsol.principal_component_analysis as pca
from nipype.algorithms.metrics import Similarity
import nibabel as nib
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import skimage.measure
from scipy.signal import argrelextrema
import scipy.ndimage as snd
import pandas as pd
import cv2
from copy import deepcopy
from nipype.utils.filemanip import split_filename
from nipype.interfaces.base import (
traits,
TraitedSpec,
File,
InputMultiPath,
OutputMultiPath,
BaseInterface,
BaseInterfaceInputSpec,
)
from pymialsrtk.interfaces.utils import run
from pymialsrtk.utils import EXEC_PATH
###############
# NLM denoising
###############
class BtkNLMDenoisingInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the BtkNLMDenoising interface."""
in_file = File(desc="Input image filename", mandatory=True)
in_mask = File(desc="Input mask filename", mandatory=False)
out_postfix = traits.Str(
"_nlm",
desc="Suffix to be added to input image filename to construst denoised output filename",
usedefault=True,
)
weight = traits.Float(
0.1,
desc="NLM smoothing parameter (high beta produces smoother result)",
usedefault=True,
)
verbose = traits.Bool(desc="Enable verbosity")
class BtkNLMDenoisingOutputSpec(TraitedSpec):
"""Class used to represent outputs of the BtkNLMDenoising interface."""
out_file = File(desc="Output denoised image file")
class BtkNLMDenoising(BaseInterface):
"""Runs the non-local mean denoising module.
It calls the Baby toolkit implementation by Rousseau et al. [1]_ of the method proposed by Coupé et al. [2]_.
References
-----------
.. [1] Rousseau et al.; Computer Methods and Programs in Biomedicine, 2013. `(link to paper) <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3508300>`_
.. [2] Coupé et al.; IEEE Transactions on Medical Imaging, 2008. `(link to paper) <https://doi.org/10.1109/tmi.2007.906087>`_
Example
---------
>>> from pymialsrtk.interfaces.preprocess import BtkNLMDenoising
>>> nlmDenoise = BtkNLMDenoising()
>>> nlmDenoise.inputs.in_file = 'sub-01_acq-haste_run-1_T2w.nii.gz'
>>> nlmDenoise.inputs.in_mask = 'sub-01_acq-haste_run-1_mask.nii.gz'
>>> nlmDenoise.inputs.weight = 0.2
>>> nlmDenoise.run() # doctest: +SKIP
"""
input_spec = BtkNLMDenoisingInputSpec
output_spec = BtkNLMDenoisingOutputSpec
def _gen_filename(self, name):
if name == "out_file":
_, name, ext = split_filename(self.inputs.in_file)
output = name + self.inputs.out_postfix + ext
return os.path.abspath(output)
return None
def _run_interface(self, runtime):
_, name, ext = split_filename(os.path.abspath(self.inputs.in_file))
out_file = self._gen_filename("out_file")
if self.inputs.in_mask:
cmd = (
f'{EXEC_PATH}btkNLMDenoising -i "{self.inputs.in_file}" '
f'-m "{self.inputs.in_mask}" -o "{out_file}" '
f"-b {self.inputs.weight}"
)
else:
cmd = (
f'{EXEC_PATH}btkNLMDenoising -i "{self.inputs.in_file}" '
f'-o "{out_file}" -b {self.inputs.weight}'
)
if self.inputs.verbose:
cmd += " --verbose"
print("... cmd: {}".format(cmd))
run(cmd, env={})
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["out_file"] = self._gen_filename("out_file")
return outputs
#############################
# Slice intensity correction
#############################
class MialsrtkCorrectSliceIntensityInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the MialsrtkCorrectSliceIntensity interface."""
in_file = File(desc="Input image filename", mandatory=True)
in_mask = File(desc="Input mask filename", mandatory=False)
out_postfix = traits.Str(
"",
desc="Suffix to be added to input image file to construct corrected output filename",
usedefault=True,
)
verbose = traits.Bool(desc="Enable verbosity")
class MialsrtkCorrectSliceIntensityOutputSpec(TraitedSpec):
"""Class used to represent outputs of the MialsrtkCorrectSliceIntensity interface."""
out_file = File(desc="Output image with corrected slice intensities")
class MialsrtkCorrectSliceIntensity(BaseInterface):
"""Runs the MIAL SRTK mean slice intensity correction module.
Example
=======
>>> from pymialsrtk.interfaces.preprocess import MialsrtkCorrectSliceIntensity
>>> sliceIntensityCorr = MialsrtkCorrectSliceIntensity()
>>> sliceIntensityCorr.inputs.in_file = 'sub-01_acq-haste_run-1_T2w.nii.gz'
>>> sliceIntensityCorr.inputs.in_mask = 'sub-01_acq-haste_run-1_mask.nii.gz'
>>> sliceIntensityCorr.run() # doctest: +SKIP
"""
input_spec = MialsrtkCorrectSliceIntensityInputSpec
output_spec = MialsrtkCorrectSliceIntensityOutputSpec
def _gen_filename(self, name):
if name == "out_file":
_, name, ext = split_filename(self.inputs.in_file)
output = name + self.inputs.out_postfix + ext
return os.path.abspath(output)
return None
def _run_interface(self, runtime):
_, name, ext = split_filename(os.path.abspath(self.inputs.in_file))
out_file = self._gen_filename("out_file")
cmd = (
f"{EXEC_PATH}mialsrtkCorrectSliceIntensity "
f'"{self.inputs.in_file}" "{self.inputs.in_mask}" "{out_file}"'
)
if self.inputs.verbose:
cmd += " verbose"
print("... cmd: {}".format(cmd))
env_cpp = os.environ.copy()
env_cpp["LD_PRELOAD"] = ""
run(cmd, env=env_cpp)
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["out_file"] = self._gen_filename("out_file")
return outputs
##########################################
# Slice by slice N4 bias field correction
##########################################
class MialsrtkSliceBySliceN4BiasFieldCorrectionInputSpec(
BaseInterfaceInputSpec
):
"""Class used to represent inputs of the MialsrtkSliceBySliceN4BiasFieldCorrection interface."""
in_file = File(desc="Input image", mandatory=True)
in_mask = File(desc="Input mask", mandatory=True)
out_im_postfix = traits.Str(
"_bcorr",
desc="Suffix to be added to input image filename to construct corrected output filename",
usedefault=True,
)
out_fld_postfix = traits.Str(
"_n4bias",
desc="Suffix to be added to input image filename to construct output bias field filename",
usedefault=True,
)
verbose = traits.Bool(desc="Enable verbosity")
class MialsrtkSliceBySliceN4BiasFieldCorrectionOutputSpec(TraitedSpec):
"""Class used to represent outputs of the MialsrtkSliceBySliceN4BiasFieldCorrection interface."""
out_im_file = File(
desc="Filename of corrected output image from N4 bias field (slice by slice)."
)
out_fld_file = File(
desc="Filename bias field extracted slice by slice from input image."
)
class MialsrtkSliceBySliceN4BiasFieldCorrection(BaseInterface):
"""Runs the MIAL SRTK slice by slice N4 bias field correction module.
This module implements the method proposed by Tustison et al. [1]_.
References
------------
.. [1] Tustison et al.; Medical Imaging, IEEE Transactions, 2010. `(link to paper) <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3071855>`_
Example
----------
>>> from pymialsrtk.interfaces.preprocess import MialsrtkSliceBySliceN4BiasFieldCorrection
>>> N4biasFieldCorr = MialsrtkSliceBySliceN4BiasFieldCorrection()
>>> N4biasFieldCorr.inputs.in_file = 'sub-01_acq-haste_run-1_T2w.nii.gz'
>>> N4biasFieldCorr.inputs.in_mask = 'sub-01_acq-haste_run-1_mask.nii.gz'
>>> N4biasFieldCorr.run() # doctest: +SKIP
"""
input_spec = MialsrtkSliceBySliceN4BiasFieldCorrectionInputSpec
output_spec = MialsrtkSliceBySliceN4BiasFieldCorrectionOutputSpec
def _gen_filename(self, name):
if name == "out_im_file":
_, name, ext = split_filename(self.inputs.in_file)
output = name + self.inputs.out_im_postfix + ext
return os.path.abspath(output)
elif name == "out_fld_file":
_, name, ext = split_filename(self.inputs.in_file)
output = name + self.inputs.out_fld_postfix + ext
if "_uni" in output:
output.replace("_uni", "")
return os.path.abspath(output)
return None
def _run_interface(self, runtime):
_, name, ext = split_filename(os.path.abspath(self.inputs.in_file))
out_im_file = self._gen_filename("out_im_file")
out_fld_file = self._gen_filename("out_fld_file")
cmd = (
f"{EXEC_PATH}mialsrtkSliceBySliceN4BiasFieldCorrection "
f'"{self.inputs.in_file}" "{self.inputs.in_mask}" '
f'"{out_im_file}" "{out_fld_file}"'
)
if self.inputs.verbose:
cmd += " verbose"
print("... cmd: {}".format(cmd))
run(cmd, env={})
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["out_im_file"] = self._gen_filename("out_im_file")
outputs["out_fld_file"] = self._gen_filename("out_fld_file")
return outputs
#####################################
# slice by slice correct bias field
#####################################
class MialsrtkSliceBySliceCorrectBiasFieldInputSpec(BaseInterfaceInputSpec):
"""Class used to represent outputs of the MialsrtkSliceBySliceCorrectBiasField interface."""
in_file = File(desc="Input image file", mandatory=True)
in_mask = File(desc="Input mask file", mandatory=True)
in_field = File(desc="Input bias field file", mandatory=True)
out_im_postfix = traits.Str(
"_bcorr",
desc="Suffix to be added to bias field corrected `in_file`",
usedefault=True,
)
verbose = traits.Bool(desc="Enable verbosity")
class MialsrtkSliceBySliceCorrectBiasFieldOutputSpec(TraitedSpec):
"""Class used to represent outputs of the MialsrtkSliceBySliceCorrectBiasField interface."""
out_im_file = File(desc="Bias field corrected image")
class MialsrtkSliceBySliceCorrectBiasField(BaseInterface):
"""Runs the MIAL SRTK independant slice by slice bias field correction module.
Example
=======
>>> from pymialsrtk.interfaces.preprocess import MialsrtkSliceBySliceCorrectBiasField
>>> biasFieldCorr = MialsrtkSliceBySliceCorrectBiasField()
>>> biasFieldCorr.inputs.in_file = 'sub-01_acq-haste_run-1_T2w.nii.gz'
>>> biasFieldCorr.inputs.in_mask = 'sub-01_acq-haste_run-1_mask.nii.gz'
>>> biasFieldCorr.inputs.in_field = 'sub-01_acq-haste_run-1_field.nii.gz'
>>> biasFieldCorr.run() # doctest: +SKIP
"""
input_spec = MialsrtkSliceBySliceCorrectBiasFieldInputSpec
output_spec = MialsrtkSliceBySliceCorrectBiasFieldOutputSpec
def _gen_filename(self, name):
if name == "out_im_file":
_, name, ext = split_filename(self.inputs.in_file)
output = name + self.inputs.out_im_postfix + ext
return os.path.abspath(output)
return None
def _run_interface(self, runtime):
_, name, ext = split_filename(os.path.abspath(self.inputs.in_file))
out_im_file = self._gen_filename("out_im_file")
cmd = (
f"{EXEC_PATH}mialsrtkSliceBySliceCorrectBiasField "
f'"{self.inputs.in_file}" "{self.inputs.in_mask}" '
f'"{self.inputs.in_field}" "{out_im_file}"'
)
if self.inputs.verbose:
cmd += " verbose"
print("... cmd: {}".format(cmd))
run(cmd, env={})
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["out_im_file"] = self._gen_filename("out_im_file")
return outputs
#############################
# Intensity standardization
#############################
class MialsrtkIntensityStandardizationInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the MialsrtkIntensityStandardization interface."""
input_images = InputMultiPath(
File(mandatory=True), desc="Files to be corrected for intensity"
)
out_postfix = traits.Str(
"",
desc="Suffix to be added to intensity corrected input_images",
usedefault=True,
)
in_max = traits.Float(desc="Maximal intensity", usedefault=False)
stacks_order = traits.List(
desc="Order of images index. To ensure images are processed with their correct corresponding mask",
mandatory=False,
) # ToDo: Can be removed -> Also in pymialsrtk.pipelines.anatomical.srr.AnatomicalPipeline !!!
verbose = traits.Bool(desc="Enable verbosity")
class MialsrtkIntensityStandardizationOutputSpec(TraitedSpec):
"""Class used to represent outputs of the MialsrtkIntensityStandardization interface."""
output_images = OutputMultiPath(
File(), desc="Intensity-standardized images"
)
class MialsrtkIntensityStandardization(BaseInterface):
"""Runs the MIAL SRTK intensity standardization module.
This module rescales image intensity by linear transformation
Example
=======
>>> from pymialsrtk.interfaces.preprocess import MialsrtkIntensityStandardization
>>> intensityStandardization= MialsrtkIntensityStandardization()
>>> intensityStandardization.inputs.input_images = ['sub-01_acq-haste_run-1_T2w.nii.gz','sub-01_acq-haste_run-2_T2w.nii.gz']
>>> intensityStandardization.run() # doctest: +SKIP
"""
input_spec = MialsrtkIntensityStandardizationInputSpec
output_spec = MialsrtkIntensityStandardizationOutputSpec
def _gen_filename(self, orig, name):
if name == "output_images":
_, name, ext = split_filename(orig)
output = name + self.inputs.out_postfix + ext
return os.path.abspath(output)
return None
def _run_interface(self, runtime):
cmd = f"{EXEC_PATH}mialsrtkIntensityStandardization"
for input_image in self.inputs.input_images:
out_file = self._gen_filename(input_image, "output_images")
cmd = cmd + ' --input "{}" --output "{}"'.format(
input_image, out_file
)
if self.inputs.in_max:
cmd = cmd + ' --max "{}"'.format(self.inputs.in_max)
if self.inputs.verbose:
cmd = cmd + " --verbose"
print("... cmd: {}".format(cmd))
run(cmd, env={})
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["output_images"] = [
self._gen_filename(input_image, "output_images")
for input_image in self.inputs.input_images
]
return outputs
###########################
# Histogram normalization
###########################
class MialsrtkHistogramNormalizationInputSpec(BaseInterfaceInputSpec):
"""Class used to represent outputs of the MialsrtkHistogramNormalization interface."""
input_images = InputMultiPath(
File(mandatory=True), desc="Input image filenames to be normalized"
)
input_masks = InputMultiPath(
File(mandatory=False), desc="Input mask filenames"
)
out_postfix = traits.Str(
"_histnorm",
desc="Suffix to be added to normalized input image filenames to construct ouptut normalized image filenames",
usedefault=True,
)
verbose = traits.Bool(desc="Enable verbosity")
class MialsrtkHistogramNormalizationOutputSpec(TraitedSpec):
"""Class used to represent outputs of the MialsrtkHistogramNormalization interface."""
output_images = OutputMultiPath(File(), desc="Histogram-normalized images")
class MialsrtkHistogramNormalization(BaseInterface):
"""Runs the MIAL SRTK histogram normalizaton module.
This module implements the method proposed by Nyúl et al. [1]_.
References
------------
.. [1] Nyúl et al.; Medical Imaging, IEEE Transactions, 2000. `(link to paper) <https://ieeexplore.ieee.org/document/836373>`_
Example
----------
>>> from pymialsrtk.interfaces.preprocess import MialsrtkHistogramNormalization
>>> histNorm = MialsrtkHistogramNormalization()
>>> histNorm.inputs.input_images = ['sub-01_acq-haste_run-1_T2w.nii.gz','sub-01_acq-haste_run-2_T2w.nii.gz']
>>> histNorm.inputs.input_masks = ['sub-01_acq-haste_run-1_mask.nii.gz','sub-01_acq-haste_run-2_mask.nii.gz']
>>> histNorm.run() # doctest: +SKIP
"""
input_spec = MialsrtkHistogramNormalizationInputSpec
output_spec = MialsrtkHistogramNormalizationOutputSpec
def _gen_filename(self, orig, name):
if name == "output_images":
_, name, ext = split_filename(orig)
output = name + self.inputs.out_postfix + ext
return os.path.abspath(output)
return None
def _run_interface(self, runtime, verbose=False):
cmd = "python /usr/local/bin/mialsrtkHistogramNormalization.py "
if len(self.inputs.input_masks) > 0:
for in_file, in_mask in zip(
self.inputs.input_images, self.inputs.input_masks
):
out_file = self._gen_filename(in_file, "output_images")
cmd = cmd + ' -i "{}" -o "{}" -m "{}" '.format(
in_file, out_file, in_mask
)
else:
for in_file in self.inputs.input_images:
out_file = self._gen_filename(in_file, "output_images")
cmd = cmd + ' -i "{}" -o "{}" '.format(in_file, out_file)
if self.inputs.verbose:
cmd += " -v"
print("... cmd: {}".format(cmd))
run(cmd, env={})
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["output_images"] = [
self._gen_filename(in_file, "output_images")
for in_file in self.inputs.input_images
]
return outputs
##############
# Mask Image
##############
class MialsrtkMaskImageInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the MialsrtkMaskImage interface."""
in_file = File(desc="Input image filename to be masked", mandatory=True)
in_mask = File(desc="Input mask filename", mandatory=True)
out_im_postfix = traits.Str(
"", desc="Suffix to be added to masked in_file", usedefault=True
)
verbose = traits.Bool(desc="Enable verbosity")
class MialsrtkMaskImageOutputSpec(TraitedSpec):
"""Class used to represent outputs of the MialsrtkMaskImage interface."""
out_im_file = File(desc="Masked image")
class MialsrtkMaskImage(BaseInterface):
"""Runs the MIAL SRTK mask image module.
Example
=======
>>> from pymialsrtk.interfaces.preprocess import MialsrtkMaskImage
>>> maskImg = MialsrtkMaskImage()
>>> maskImg.inputs.in_file = 'sub-01_acq-haste_run-1_T2w.nii.gz'
>>> maskImg.inputs.in_mask = 'sub-01_acq-haste_run-1_mask.nii.gz'
>>> maskImg.inputs.out_im_postfix = '_masked'
>>> maskImg.run() # doctest: +SKIP
"""
input_spec = MialsrtkMaskImageInputSpec
output_spec = MialsrtkMaskImageOutputSpec
def _gen_filename(self, name):
if name == "out_im_file":
_, name, ext = split_filename(self.inputs.in_file)
output = name + self.inputs.out_im_postfix + ext
return os.path.abspath(output)
return None
def _run_interface(self, runtime):
out_im_file = self._gen_filename("out_im_file")
cmd = (
f'{EXEC_PATH}mialsrtkMaskImage -i "{self.inputs.in_file}" '
f'-m "{self.inputs.in_mask}" -o "{out_im_file}"'
)
if self.inputs.verbose:
cmd += " --verbose"
print("... cmd: {}".format(cmd))
run(cmd, env={})
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["out_im_file"] = self._gen_filename("out_im_file")
return outputs
###############################
# Stacks ordering and filtering
###############################
class CheckAndFilterInputStacksInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the FilterInputStacks interface."""
input_images = InputMultiPath(File(mandatory=True), desc="Input images")
input_masks = InputMultiPath(File(None), desc="Input masks")
input_labels = InputMultiPath(File(None), desc="Input label maps")
stacks_id = traits.List(desc="List of stacks id to be kept")
class CheckAndFilterInputStacksOutputSpec(TraitedSpec):
"""Class used to represent outputs of the FilterInputStacks interface."""
output_stacks = traits.List(desc="Filtered list of stack files")
output_images = traits.List(
traits.Str, desc="Filtered list of image files"
)
output_masks = traits.List(desc="Filtered list of mask files")
output_labels = traits.List(desc="Filtered list of label files")
class CheckAndFilterInputStacks(BaseInterface):
"""Runs a filtering and a check on the input files.
This module filters the input files matching the specified run-ids.
Other files are discarded.
Examples
--------
>>> from pymialsrtk.interfaces.preprocess import CheckAndFilterInputStacks
>>> stacksFiltering = CheckAndFilterInputStacks()
>>> stacksFiltering.inputs.input_masks = ['sub-01_run-1_mask.nii.gz', 'sub-01_run-4_mask.nii.gz', 'sub-01_run-2_mask.nii.gz']
>>> stacksFiltering.inputs.stacks_id = [1,2]
>>> stacksFiltering.run() # doctest: +SKIP
"""
input_spec = CheckAndFilterInputStacksInputSpec
output_spec = CheckAndFilterInputStacksOutputSpec
m_output_stacks = []
m_output_images = []
m_output_masks = []
m_output_labels = []
def _run_interface(self, runtime):
self.m_output_stacks, out_files = self._filter_by_runid(
self.inputs.input_images,
self.inputs.input_masks,
self.inputs.input_labels,
self.inputs.stacks_id,
)
self.m_output_images = out_files.pop(0)
if self.inputs.input_masks:
self.m_output_masks = out_files.pop(0)
if self.inputs.input_labels:
self.m_output_labels = out_files.pop(0)
return runtime
def _filter_by_runid(
self, input_images, input_masks, input_labels, p_stacks_id
):
input_checks = [input_images]
if input_masks:
input_checks.append(input_masks)
if input_labels:
input_checks.append(input_labels)
if p_stacks_id:
assert len(p_stacks_id) > 1, (
f"Only a single stack (# {p_stacks_id[0]}) "
"was given. MialSRTK needs at least two stacks to run."
)
else:
# If stacks aren't given, take as stack the runs found in the images.
# 1. Check that there is at least two scans in the input folder.
assert len(input_images) > 1, (
f"Only a single input file ({input_images[0]}) "
"was found. MialSRTK needs at least two stacks to run.\n"
"It is however recommended to use at least *three* orthogonal stacks."
)
p_stacks_id = [
int(f.split("run-")[1].split("_")[0]) for f in input_images
]
# Check consistency between files, i.e. that for a given p_stacks_id
# the file exists for each inputs.
output_files = []
for input_files in input_checks:
stacks = deepcopy(p_stacks_id)
output_list = []
for f in input_files:
f_id = int(f.split("_run-")[1].split("_")[0])
if f_id in p_stacks_id:
output_list.append(f)
stacks.remove(f_id)
output_files.append(output_list)
if len(stacks) > 0:
raise RuntimeError(
f"Stacks with id {stacks} not found in {os.path.dirname(f)}."
)
return p_stacks_id, output_files
def _list_outputs(self):
outputs = self._outputs().get()
outputs["output_stacks"] = self.m_output_stacks
outputs["output_images"] = self.m_output_images
outputs["output_masks"] = self.m_output_masks
outputs["output_labels"] = self.m_output_labels
return outputs
class StacksOrderingInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the StacksOrdering interface."""
input_masks = InputMultiPath(
File(mandatory=True),
desc="Input brain masks on which motion is computed",
)
sub_ses = traits.Str(
desc=("Subject and session BIDS identifier"), mandatory=True
)
verbose = traits.Bool(desc="Enable verbosity")
class StacksOrderingOutputSpec(TraitedSpec):
"""Class used to represent outputs of the StacksOrdering interface."""
stacks_order = traits.List(
desc="Order of image `run-id` to be used for reconstruction"
)
motion_tsv = File(
desc="Output TSV file with results used to create `report_image`"
)
report_image = File(desc="Output PNG image for report")
class StacksOrdering(BaseInterface):
"""Runs the automatic ordering of stacks.
This module is based on the tracking of the brain mask centroid slice by slice.
Examples
--------
>>> from pymialsrtk.interfaces.preprocess import StacksOrdering
>>> stacksOrdering = StacksOrdering()
>>> stacksOrdering.inputs.input_masks = ['sub-01_run-1_mask.nii.gz',
>>> 'sub-01_run-4_mask.nii.gz',
>>> 'sub-01_run-2_mask.nii.gz']
>>> stacksOrdering.run() # doctest: +SKIP
.. note:: In the case of discontinuous brain masks, the centroid coordinates of
the slices excluded from the mask are set to `numpy.nan` and are not
anymore considered in the motion index computation since `v2.0.2` release.
Prior to this release, the centroids of these slices were set to zero
that has shown to drastically increase the motion index with respect
to the real motion during acquisition. However the motion in the remaining
slices that were actually used for SR reconstruction might not correspond
to the high value of this index.
"""
input_spec = StacksOrderingInputSpec
output_spec = StacksOrderingOutputSpec
m_stack_order = []
def _gen_filename(self, name):
if name == "report_image":
output = self.inputs.sub_ses + "_motion_index_QC.png"
return os.path.abspath(output)
elif name == "motion_tsv":
output = self.inputs.sub_ses + "_motion_index_QC.tsv"
return os.path.abspath(output)
return None
def _run_interface(self, runtime):
self.m_stack_order = self._compute_stack_order()
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["stacks_order"] = self.m_stack_order
outputs["report_image"] = self._gen_filename("report_image")
outputs["motion_tsv"] = self._gen_filename("motion_tsv")
return outputs
def _compute_motion_index(self, in_file):
"""Function to compute the motion index.
The motion index is computed from the inter-slice displacement of
the centroid of the brain mask.
"""
central_third = True
img = nib.load(in_file)
data = img.get_fdata()
# To compute centroid displacement as a distance
# instead of a number of voxel
sx, sy, sz = img.header.get_zooms()
z = np.where(data)[2]
data = data[..., int(min(z)) : int(max(z) + 1)]
if central_third:
num_z = data.shape[2]
center_z = int(num_z / 2.0)
data = data[
..., int(center_z - num_z / 6.0) : int(center_z + num_z / 6.0)
]
centroid_coord = np.zeros((data.shape[2], 2))
for i in range(data.shape[2]):
moments = skimage.measure.moments(data[..., i])
try:
centroid_coordx = moments[0, 1] / moments[0, 0]
centroid_coordy = moments[1, 0] / moments[0, 0]
# This happens in the case of discontinuous brain masks
except ZeroDivisionError:
centroid_coordx = np.nan
centroid_coordy = np.nan
centroid_coord[i, :] = [centroid_coordx, centroid_coordy]
nb_of_notnans = np.count_nonzero(~np.isnan(centroid_coord))
nb_of_nans = np.count_nonzero(np.isnan(centroid_coord))
if nb_of_nans > 0:
print(f" Info: File {in_file} - Number of NaNs = {nb_of_nans}")
if nb_of_nans + nb_of_notnans == 0:
import re
run_id = re.findall(r"run-(\d+)_", in_file)[-1]
raise DivisionByZero(
f"The mask of run-{run_id} is empty on the range "
"considered. The stack should be excluded."
)
prop_of_nans = nb_of_nans / (nb_of_nans + nb_of_notnans)
centroid_coord = centroid_coord[~np.isnan(centroid_coord)]
centroid_coord = np.reshape(
centroid_coord, (int(centroid_coord.shape[0] / 2), 2)
)
# Zero-centering
centroid_coord[:, 0] -= np.mean(centroid_coord[:, 0])
centroid_coord[:, 1] -= np.mean(centroid_coord[:, 1])
# Convert from "number of voxels" to "mm" based on the voxel size
centroid_coord[:, 0] *= sx
centroid_coord[:, 1] *= sy
nb_slices = centroid_coord.shape[0]
score = (
np.var(centroid_coord[:, 0]) + np.var(centroid_coord[:, 1])
) / (nb_slices * sz)
return score, prop_of_nans, centroid_coord[:, 0], centroid_coord[:, 1]
def _create_report_image(
self, score, prop_of_nans, centroid_coordx, centroid_coordy
):
# Output report image basename
image_basename = "motion_index_QC"
if self.inputs.verbose:
print("\t>> Create report image...")
# Visualization setup
matplotlib.use("agg")
sns.set_style("whitegrid")
sns.set(font_scale=1)
# Compute mean centroid coordinates for each image
mean_centroid_coordx = {}
mean_centroid_coordy = {}
for f in self.inputs.input_masks:
mean_centroid_coordx[f] = np.nanmean(centroid_coordx[f])
mean_centroid_coordy[f] = np.nanmean(centroid_coordy[f])
# Format data and create a Pandas DataFrame
if self.inputs.verbose:
print("\t\t\t - Format data...")
df_files = []
df_slices = []
df_motion_ind = []
df_prop_of_nans = []
df_centroid_coordx = []
df_centroid_coordy = []
df_centroid_displ = []
for f in self.inputs.input_masks:
# Extract only filename with extension from the absolute path
path = pathlib.Path(f)
# Extract the "run-xx" part in the filename
fname = path.stem.split("_T2w_")[0].split("_")[1]
for i, (coordx, coordy) in enumerate(
zip(centroid_coordx[f], centroid_coordy[f])
):
df_files.append(fname)
df_slices.append(i)
df_motion_ind.append(score[f])
df_prop_of_nans.append(prop_of_nans[f])
df_centroid_coordx.append(coordx)
df_centroid_coordy.append(coordy)
if not np.isnan(coordx) and not np.isnan(coordy):
df_centroid_displ.append(
np.sqrt(coordx * coordx + coordy * coordy)
)
else:
df_centroid_displ.append(np.nan)
# Create a dataframe to facilitate handling with the results
if self.inputs.verbose:
print("\t\t\t - Create DataFrame...")
df = pd.DataFrame(
{
"Scan": df_files,
"Slice": df_files,
"Motion Index": df_motion_ind,
"Proportion of NaNs (%)": df_prop_of_nans,
"X (mm)": df_centroid_coordx,
"Y (mm)": df_centroid_coordy,
"Displacement Magnitude (mm)": df_centroid_displ,
}
)
df = df.sort_values(by=["Motion Index", "Scan", "Slice"])
# Save the results in a TSV file
tsv_file = self._gen_filename("motion_tsv")
if self.inputs.verbose:
print(f"\t\t\t - Save motion results to {tsv_file}...")
df.to_csv(tsv_file, sep="\t")
# Make multiple figures with seaborn,
# Saved in temporary png image and
# combined in a final report image
if self.inputs.verbose:
print("\t\t\t - Create figures...")
# Show the zero-centered positions of the centroids
sf0 = sns.jointplot(
data=df,
x="X (mm)",
y="Y (mm)",
hue="Scan",
height=6,
)
# Save the temporary report image
image_filename = os.path.abspath(image_basename + "_0.png")
if self.inputs.verbose:
print(f"\t\t\t - Save report image 0 as {image_filename}...")
sf0.savefig(image_filename, dpi=150)
plt.close(sf0.fig)
# Show the scan motion index
sf1 = sns.catplot(data=df, y="Scan", x="Motion Index", kind="bar")
sf1.ax.set_yticklabels(sf1.ax.get_yticklabels(), rotation=0)
sf1.fig.set_size_inches(6, 2)
# Save the temporary report image
image_filename = os.path.abspath(image_basename + "_1.png")
if self.inputs.verbose:
print(f"\t\t\t - Save report image 1 as {image_filename}...")
sf1.savefig(image_filename, dpi=150)
plt.close(sf1.fig)
# Show the displacement magnitude of the centroids
sf2 = sns.catplot(
data=df,
y="Scan",
x="Displacement Magnitude (mm)",
kind="violin",
inner="stick",
)
sf2.ax.set_yticklabels(sf2.ax.get_yticklabels(), rotation=0)
sf2.fig.set_size_inches(6, 2)
# Save the temporary report image