-
Notifications
You must be signed in to change notification settings - Fork 12
/
postprocess.py
1348 lines (1111 loc) · 43 KB
/
postprocess.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 postprocessing functions.
It encompasses a High Resolution mask refinement and an N4 global bias field correction.
"""
import os
import sys
import platform
import json
import pkg_resources
from jinja2 import Environment, FileSystemLoader
from jinja2 import __version__ as __jinja2_version__
# Get pymialsrtk version
from pymialsrtk.info import __version__
from traits.api import *
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
import nibabel as nib
import numpy as np
import SimpleITK as sitk
import skimage.metrics
import pandas as pd
from pymialsrtk.utils import EXEC_PATH
import itertools
#######################
# Refinement HR mask
#######################
class MialsrtkRefineHRMaskByIntersectionInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the MialsrtkRefineHRMaskByIntersection interface."""
input_images = InputMultiPath(
File(mandatory=True), desc="Image filenames used in SR reconstruction"
)
input_masks = InputMultiPath(File(mandatory=True), desc="Mask filenames")
input_transforms = InputMultiPath(
File(mandatory=True), desc="Transformation filenames"
)
input_sr = File(desc="SR image filename", mandatory=True)
input_rad_dilatation = traits.Int(
1, desc="Radius of the structuring element (ball)", usedefault=True
)
in_use_staple = traits.Bool(
True,
desc="Use STAPLE for voting (default is True). If False, Majority voting is used instead",
usedefault=True,
)
out_lrmask_postfix = traits.Str(
"_LRmask",
desc="Suffix to be added to the Low resolution input_masks",
usedefault=True,
)
out_srmask_postfix = traits.Str(
"_srMask",
desc="Suffix to be added to the SR reconstruction filename to construct output SR mask filename",
usedefault=True,
)
verbose = traits.Bool(desc="Enable verbosity")
class MialsrtkRefineHRMaskByIntersectionOutputSpec(TraitedSpec):
"""Class used to represent outputs of the MialsrtkRefineHRMaskByIntersection interface."""
output_srmask = File(
desc="Output super-resolution reconstruction refined mask"
)
output_lrmasks = OutputMultiPath(
File(), desc="Output low-resolution reconstruction refined masks"
)
class MialsrtkRefineHRMaskByIntersection(BaseInterface):
"""Runs the MIALSRTK mask refinement module.
It uses the Simultaneous Truth And Performance Level Estimate (STAPLE) by Warfield et al. [1]_.
References
------------
.. [1] Warfield et al.; Medical Imaging, IEEE Transactions, 2004. `(link to paper) <https://www.ncbi.nlm.nih.gov/pmc/articles/PMC1283110/>`_
Example
----------
>>> from pymialsrtk.interfaces.postprocess import MialsrtkRefineHRMaskByIntersection
>>> refMask = MialsrtkRefineHRMaskByIntersection()
>>> refMask.inputs.input_images = ['sub-01_acq-haste_run-1_T2w.nii.gz','sub-01_acq-haste_run-2_T2w.nii.gz']
>>> refMask.inputs.input_masks = ['sub-01_acq-haste_run-1_mask.nii.gz','sub-01_acq-haste_run-2_mask.nii.gz']
>>> refMask.inputs.input_transforms = ['sub-01_acq-haste_run-1_transform.txt','sub-01_acq-haste_run-2_transform.nii.gz']
>>> refMask.inputs.input_sr = 'sr_image.nii.gz'
>>> refMask.run() # doctest: +SKIP
"""
input_spec = MialsrtkRefineHRMaskByIntersectionInputSpec
output_spec = MialsrtkRefineHRMaskByIntersectionOutputSpec
def _gen_filename(self, orig, name):
if name == "output_srmask":
_, name, ext = split_filename(orig)
run_id = (name.split("run-")[1]).split("_")[0]
name = name.replace("_run-" + run_id + "_", "_")
output = name + self.inputs.out_srmask_postfix + ext
return os.path.abspath(output)
elif name == "output_lrmasks":
_, name, ext = split_filename(orig)
output = name + self.inputs.out_lrmask_postfix + ext
return os.path.abspath(output)
return None
def _run_interface(self, runtime):
cmd = [f"{EXEC_PATH}mialsrtkRefineHRMaskByIntersection"]
cmd += ["--radius-dilation", str(self.inputs.input_rad_dilatation)]
if self.inputs.in_use_staple:
cmd += ["--use-staple"]
for in_file, in_mask, in_transform in zip(
self.inputs.input_images,
self.inputs.input_masks,
self.inputs.input_transforms,
):
cmd += ["-i", in_file]
cmd += ["-m", in_mask]
cmd += ["-t", in_transform]
out_file = self._gen_filename(in_file, "output_lrmasks")
cmd += ["-O", out_file]
out_file = self._gen_filename(
self.inputs.input_images[0], "output_srmask"
)
cmd += ["-r", self.inputs.input_sr]
cmd += ["-o", out_file]
if self.inputs.verbose:
cmd += ["--verbose"]
print("... cmd: {}".format(cmd))
cmd = " ".join(cmd)
run(cmd, env={})
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["output_srmask"] = self._gen_filename(
self.inputs.input_images[0], "output_srmask"
)
outputs["output_lrmasks"] = [
self._gen_filename(in_file, "output_lrmasks")
for in_file in self.inputs.input_images
]
return outputs
############################
# N4 Bias field correction
############################
class MialsrtkN4BiasFieldCorrectionInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the MialsrtkN4BiasFieldCorrection interface."""
input_image = File(
desc="Input image filename to be normalized", mandatory=True
)
input_mask = File(desc="Input mask filename", mandatory=False)
out_im_postfix = traits.Str("_gbcorr", usedefault=True)
out_fld_postfix = traits.Str("_gbcorrfield", usedefault=True)
verbose = traits.Bool(desc="Enable verbosity")
class MialsrtkN4BiasFieldCorrectionOutputSpec(TraitedSpec):
"""Class used to represent outputs of the MialsrtkN4BiasFieldCorrection interface."""
output_image = File(desc="Output corrected image")
output_field = File(desc="Output bias field extracted from input image")
class MialsrtkN4BiasFieldCorrection(BaseInterface):
"""
Runs the MIAL SRTK slice by slice N4 bias field correction module.
This tools implements the method proposed by Tustison et al. [1]_ slice by slice.
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.postprocess import MialsrtkSliceBySliceN4BiasFieldCorrection
>>> N4biasFieldCorr = MialsrtkSliceBySliceN4BiasFieldCorrection()
>>> N4biasFieldCorr.inputs.input_image = 'sub-01_acq-haste_run-1_SR.nii.gz'
>>> N4biasFieldCorr.inputs.input_mask = 'sub-01_acq-haste_run-1_mask.nii.gz'
>>> N4biasFieldCorr.run() # doctest: +SKIP
"""
input_spec = MialsrtkN4BiasFieldCorrectionInputSpec
output_spec = MialsrtkN4BiasFieldCorrectionOutputSpec
def _gen_filename(self, name):
if name == "output_image":
_, name, ext = split_filename(self.inputs.input_image)
output = name + self.inputs.out_im_postfix + ext
return os.path.abspath(output)
elif name == "output_field":
_, name, ext = split_filename(self.inputs.input_image)
output = name + self.inputs.out_fld_postfix + ext
return os.path.abspath(output)
return None
def _run_interface(self, runtime):
# _, name, ext = split_filename(os.path.abspath(
# self.inputs.input_image))
out_corr = self._gen_filename("output_image")
out_fld = self._gen_filename("output_field")
cmd = [
f"{EXEC_PATH}mialsrtkN4BiasFieldCorrection",
self.inputs.input_image,
self.inputs.input_mask,
out_corr,
out_fld,
]
if self.inputs.verbose:
cmd += [" verbose"]
print("... cmd: {}".format(cmd))
cmd = " ".join(cmd)
run(cmd, env={})
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["output_image"] = self._gen_filename("output_image")
outputs["output_field"] = self._gen_filename("output_field")
return outputs
############################
# Output filenames settings
############################
class FilenamesGenerationInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the FilenamesGeneration interface."""
sub_ses = traits.Str(
mandatory=True,
desc="Subject and session BIDS identifier to construct output filename.",
)
stacks_order = traits.List(
mandatory=True,
desc="List of stack run-id that specify the order of the stacks",
)
sr_id = traits.Int(mandatory=True, desc="Super-Resolution id")
run_type = traits.Str(mandatory=True, desc="Type of run (preproc or sr)")
use_manual_masks = traits.Bool(
mandatory=True,
desc="Whether masks were computed or manually performed.",
)
TV_params = traits.List(
mandatory=False, desc="List iterables TV parameters processed"
)
multi_parameters = traits.Bool(
mandatory=True, desc="Whether multiple SR were reconstructed."
)
class FilenamesGenerationOutputSpec(TraitedSpec):
"""Class used to represent outputs of the FilenamesGeneration interface."""
substitutions = traits.List(
desc="Output correspondance between old and new filenames."
)
class FilenamesGeneration(BaseInterface):
"""Generates final filenames from outputs of super-resolution reconstruction.
Example
----------
>>> from pymialsrtk.interfaces.postprocess import FilenamesGeneration
>>> filenamesGen = FilenamesGeneration()
>>> filenamesGen.inputs.sub_ses = 'sub-01'
>>> filenamesGen.inputs.stacks_order = [3,1,4]
>>> filenamesGen.inputs.sr_id = 3
>>> filenamesGen.inputs.use_manual_masks = False
>>> filenamesGen.run() # doctest: +SKIP
"""
input_spec = FilenamesGenerationInputSpec
output_spec = FilenamesGenerationOutputSpec
m_substitutions = []
def _run_interface(self, runtime):
run_type = self.inputs.run_type
max_stacks = max(self.inputs.stacks_order)
self.m_substitutions.append(
(
"_T2w_nlm_uni_bcorr_histnorm.nii.gz",
"_id-"
+ str(self.inputs.sr_id)
+ "_desc-preprocSDI_T2w.nii.gz",
)
)
if not self.inputs.use_manual_masks:
self.m_substitutions += [
(f"_brainExtraction{n}/", "") for n in range(max_stacks)
]
self.m_substitutions.append(
(
"_T2w_brainMask.nii.gz",
"_id-" + str(self.inputs.sr_id) + "_T2w_mask.nii.gz",
)
)
else:
self.m_substitutions.append(
(
"_T2w_mask.nii.gz",
"_id-" + str(self.inputs.sr_id) + "_T2w_mask.nii.gz",
)
)
self.m_substitutions.append(("_T2w_desc-brain_", "_desc-brain_"))
self.m_substitutions += [
(f"_srtkMaskImage01{n}/", "") for n in range(max_stacks)
]
self.m_substitutions += [
(f"_srtkMaskImage01_nlm{n}/", "") for n in range(max_stacks)
]
self.m_substitutions += [
(f"_reduceFOV{n}/", "") for n in range(max_stacks)
]
self.m_substitutions.append(
(
"_T2w_uni_bcorr_histnorm.nii.gz",
"_id-" + str(self.inputs.sr_id) + "_desc-preprocSR_T2w.nii.gz",
)
)
# Transforms if NLM was applied
self.m_substitutions.append(
(
"_T2w_nlm_uni_bcorr_histnorm_transform_"
+ str(len(self.inputs.stacks_order))
+ "V.txt",
"_id-"
+ str(self.inputs.sr_id)
+ "_mod-T2w_from-origin_to-SDI_"
+ "mode-image_xfm.txt",
)
)
# Transforms if NLM was not applied
self.m_substitutions.append(
(
"_T2w_uni_bcorr_histnorm_transform_"
+ str(len(self.inputs.stacks_order))
+ "V.txt",
"_id-"
+ str(self.inputs.sr_id)
+ "_mod-T2w_from-origin_to-SDI_"
+ "mode-image_xfm.txt",
)
)
for stack in self.inputs.stacks_order:
self.m_substitutions.append(
(
"_run-"
+ str(stack)
+ "_T2w_uni_"
+ "bcorr_histnorm_LRmask.nii.gz",
"_run-"
+ str(stack)
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w_mask.nii.gz",
)
)
self.m_substitutions.append(
(
"SDI_"
+ self.inputs.sub_ses
+ "_"
+ str(len(self.inputs.stacks_order))
+ "V_rad1.nii.gz",
self.inputs.sub_ses
+ f"_{run_type}-SDI"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w.nii.gz",
)
)
self.m_substitutions.append(
(
self.inputs.sub_ses + "_T2w_uni_bcorr_histnorm_srMask.nii.gz",
self.inputs.sub_ses
+ f"_{run_type}-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w_mask.nii.gz",
)
)
self.m_substitutions.append(
(
"SDI_"
+ self.inputs.sub_ses
+ "_"
+ str(len(self.inputs.stacks_order))
+ "V_rad1_srMask.nii.gz",
self.inputs.sub_ses
+ "_rec-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w_mask.nii.gz",
)
)
self.m_substitutions.append(
(
self.inputs.sub_ses + "_" + "HR_labelmap.nii.gz",
self.inputs.sub_ses
+ "_rec-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_labels.nii.gz",
)
)
self.m_substitutions.append(
(
"_motion_index_QC.png",
f"_{run_type}-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_desc-motion_stats.png",
)
)
self.m_substitutions.append(
(
"_motion_index_QC.tsv",
f"_{run_type}-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_desc-motion_stats.tsv",
)
)
# Metric CSV files
self.m_substitutions.append(
(
"SRTV_"
+ self.inputs.sub_ses
+ "_"
+ str(len(self.inputs.stacks_order))
+ "V_rad1_gbcorr_trans_csv.csv",
self.inputs.sub_ses
+ "_rec-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_desc-volume_metrics.csv",
)
)
self.m_substitutions.append(
(
"SRTV_"
+ self.inputs.sub_ses
+ "_"
+ str(len(self.inputs.stacks_order))
+ "V_rad1_gbcorr_trans_labels_csv.csv",
self.inputs.sub_ses
+ "_rec-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_desc-labels_metrics.csv",
)
)
#
# Management SR
input_sr_tv = "".join(
[
"SRTV_",
self.inputs.sub_ses,
"_",
str(len(self.inputs.stacks_order)),
"V_rad1_gbcorr.nii.gz",
]
)
input_sr_json = "".join(
[
"SRTV_",
self.inputs.sub_ses,
"_",
str(len(self.inputs.stacks_order)),
"V_rad1.json",
]
)
input_sr_png = "".join(
[
"SRTV_",
self.inputs.sub_ses,
"_",
str(len(self.inputs.stacks_order)),
"V_rad1.png",
]
)
sr_report = "".join(
[
"SRTV_",
self.inputs.sub_ses,
"_",
str(len(self.inputs.stacks_order)),
"V_rad1_gbcorr_report.html",
]
)
if self.inputs.multi_parameters:
tv_parameters_labels = [
"in_deltat",
"in_lambda",
"in_loop",
"in_bregman_loop",
"in_iter",
"in_step_scale",
"in_gamma",
]
tv_parameters_labels.sort()
tv_params_dict = dict(self.inputs.TV_params)
tv_params_dict = dict(
sorted(tv_params_dict.items(), key=lambda item: item[0])
)
list_of_sr_recon = list(
itertools.product(*tv_params_dict.values())
)
for i, recon in enumerate(list_of_sr_recon):
tv_dir = ""
for param_label, param_value in zip(
tv_parameters_labels, recon
):
tv_dir += "_" + param_label
tv_dir += "_" + str(param_value)
tv_identifier = "_tv-" + str(i)
self.m_substitutions.append(
(
os.path.join(tv_dir, input_sr_tv),
self.inputs.sub_ses
+ f"_{run_type}-SR"
+ tv_identifier
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w.nii.gz",
)
)
self.m_substitutions.append(
(
os.path.join(tv_dir, input_sr_json),
self.inputs.sub_ses
+ f"_{run_type}-SR"
+ tv_identifier
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w.json",
)
)
self.m_substitutions.append(
(
os.path.join(tv_dir, input_sr_png),
self.inputs.sub_ses
+ f"_{run_type}-SR"
+ tv_identifier
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w.png",
)
)
else:
self.m_substitutions.append(
(
input_sr_tv,
self.inputs.sub_ses
+ f"_{run_type}-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w.nii.gz",
)
)
self.m_substitutions.append(
(
input_sr_json,
self.inputs.sub_ses
+ f"_{run_type}-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w.json",
)
)
self.m_substitutions.append(
(
input_sr_png,
self.inputs.sub_ses
+ f"_{run_type}-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_T2w.png",
)
)
self.m_substitutions.append(
(
sr_report,
self.inputs.sub_ses
+ f"_{run_type}-SR"
+ "_id-"
+ str(self.inputs.sr_id)
+ "_desc-report_T2w.html",
)
)
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["substitutions"] = self.m_substitutions
return outputs
class BinarizeImageInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the BinarizeImage interface."""
input_image = File(
desc="Input image filename to be binarized", mandatory=True
)
class BinarizeImageOutputSpec(TraitedSpec):
"""Class used to represent outputs of the BinarizeImage interface."""
output_srmask = File(desc="Image mask (binarized input)")
class BinarizeImage(BaseInterface):
"""Runs the MIAL SRTK mask image module.
Example
=======
>>> from pymialsrtk.interfaces.postprocess import BinarizeImage
>>> maskImg = MialsrtkMaskImage()
>>> maskImg.inputs.input_image = 'input_image.nii.gz'
"""
input_spec = BinarizeImageInputSpec
output_spec = BinarizeImageOutputSpec
def _gen_filename(self, name):
if name == "output_srmask":
_, name, ext = split_filename(self.inputs.input_image)
output = name + "_srMask" + ext
return os.path.abspath(output)
return None
def _binarize_image(self, in_image):
image_nii = nib.load(in_image)
image = np.asanyarray(image_nii.dataobj)
out = nib.Nifti1Image(dataobj=1 * (image > 0), affine=image_nii.affine)
out._header = image_nii.header
nib.save(filename=self._gen_filename("output_srmask"), img=out)
return
def _run_interface(self, runtime):
self._binarize_image(self.inputs.input_image)
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["output_srmask"] = self._gen_filename("output_srmask")
return outputs
class ImageMetricsInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the QualityMetrics interface."""
input_image = File(desc="Input image filename", mandatory=True)
input_ref_image = File(
desc="Input reference image filename", mandatory=True
)
input_ref_mask = File(desc="Input reference mask filename", mandatory=True)
input_ref_labelmap = File(
desc="Input reference labelmap filename", mandatory=False
)
input_TV_parameters = traits.Dict(mandatory=True)
normalize_input = traits.Bool(
True,
desc="Whether the image and reference should be individually "
"normalized before passing them into the metrics",
usedefault=True,
)
mask_input = traits.Bool(
True,
desc="Whether the image and reference should be masked when "
"computing the metrics",
usedefault=True,
)
class ImageMetricsOutputSpec(TraitedSpec):
"""Class used to represent outputs of the QualityMetrics interface."""
output_metrics = File(desc="Output CSV")
output_metrics_labels = File(desc="Output per-label CSV")
class ImageMetrics(BaseInterface):
"""Compute various image metrics on a SR reconstructed image compared to a ground truth.
Example
----------
>>> from pymialsrtk.interfaces.postprocess import ImageMetrics
>>> compute_metrics = ImageMetrics()
>>> compute_metrics.inputs.input_image = 'sub-01_acq-haste_rec-SR_id-1_T2w.nii.gz'
>>> compute_metrics.inputs.input_ref_image = 'sub-01_acq-haste_desc-GT_T2w.nii.gz'
>>> compute_metrics.inputs.input_ref_mask = 'sub-01_acq-haste_desc-GT_T2w_mask.nii.gz'
>>> compute_metrics.inputs.input_TV_parameters = {'in_loop': '10', 'in_deltat': '0.01', 'in_lambda': '2.5', 'in_bregman_loop': '3', 'in_iter': '50', 'in_step_scale': '1', 'in_gamma': '1', 'in_inner_thresh': '1e-05', 'in_outer_thresh': '1e-06'}
>>> concat_metrics.run() # doctest: +SKIP
"""
input_spec = ImageMetricsInputSpec
output_spec = ImageMetricsOutputSpec
_image_array = None
_reference_array = None
_mask_array = None
_labelmap_array = None
_dict_metrics = None
_dict_metrics_labels = None
def _gen_filename(self, name):
if name == "output_metrics":
_, name, _ = split_filename(self.inputs.input_image)
output = name + "_csv" + ".csv"
return os.path.abspath(output)
if name == "output_metrics_labels":
_, name, _ = split_filename(self.inputs.input_image)
output = name + "_labels_csv" + ".csv"
return os.path.abspath(output)
return None
def _reset_class_members(self):
self._image_array = None
self._reference_array = None
self._labelmap_array = None
self._dict_metrics = {}
self._list_metrics_labels = []
def _load_image_arrays(self):
reader = sitk.ImageFileReader()
reader.SetFileName(self.inputs.input_ref_image)
self._reference_array = sitk.GetArrayFromImage(reader.Execute())
reader.SetFileName(self.inputs.input_ref_mask)
self._mask_array = sitk.GetArrayFromImage(reader.Execute())
reader.SetFileName(self.inputs.input_image)
self._image_array = sitk.GetArrayFromImage(reader.Execute())
if self.inputs.input_ref_labelmap is not None:
reader.SetFileName(self.inputs.input_ref_labelmap)
self._labelmap_array = sitk.GetArrayFromImage(reader.Execute())
def norm_data(self, data):
"""Normalize data into 0-1 range"""
return (data - data.min()) / (data.max() - data.min())
def _compute_metrics(self, mask=None):
dict_metrics = {}
im = self._image_array
ref = self._reference_array
if mask is None:
mask = self._mask_array
if self.inputs.normalize_input:
im = self.norm_data(im)
ref = self.norm_data(ref)
# Datarange will be 1. if normalize_input = True
datarange = int(np.amax(ref) - min(np.amin(im), np.amin(ref)))
im_in = im
ref_in = ref
if self.inputs.mask_input:
im_in = im[mask > 0]
ref_in = ref[mask > 0]
print("im_in", im_in.sum(), ref_in.sum())
# PSNR COMPUTATION
psnr = skimage.metrics.peak_signal_noise_ratio(
ref_in, im_in, data_range=datarange
)
dict_metrics["PSNR"] = psnr
# nRMSE
nrmse = skimage.metrics.normalized_root_mse(ref_in, im_in)
dict_metrics["nRMSE"] = nrmse
# RMSE
rmse = np.sqrt(skimage.metrics.mean_squared_error(ref_in, im_in))
dict_metrics["RMSE"] = rmse
# SSIM
ssim = skimage.metrics.structural_similarity(
ref,
im,
data_range=datarange,
full=True,
)
def pick_ssim(ssim):
"""Pick the SSIM output:
1- If masked input, take the full SSIM on the masked input
2- Else, return the average SSIM
"""
if self.inputs.mask_input:
return ssim[1][mask > 0].mean()
else:
return ssim[0]
dict_metrics["SSIM"] = pick_ssim(ssim)
# nSSIM
nssim = skimage.metrics.structural_similarity(
(ref - np.min(ref)) / np.ptp(ref),
(im - np.min(im)) / np.ptp(im),
data_range=1,
full=True,
)
dict_metrics["nSSIM"] = pick_ssim(nssim)
return dict_metrics
def _generate_csv(self):
TV_params = self.inputs.input_TV_parameters
data = []
data.append({**TV_params, **self._dict_metrics})
df_metrics = pd.DataFrame.from_records(data)
df_metrics.to_csv(
self._gen_filename("output_metrics"),
index=False,
header=True,
sep=",",
)
def _compute_metrics_labels(self):
label_ids = list(np.unique(self._labelmap_array).astype(int))
label_ids.remove(0)
for label in label_ids:
mask_label = self._labelmap_array == label
dict_label = self._compute_metrics(mask_label)
dict_label["Label"] = label
self._list_metrics_labels.append(dict_label)
def _generate_csv_labels(self):
TV_params = self.inputs.input_TV_parameters
data = []
for it in self._list_metrics_labels:
data.append({**TV_params, **it})
df_metrics = pd.DataFrame.from_records(data)
df_metrics.to_csv(
self._gen_filename("output_metrics_labels"),
index=False,
header=True,
sep=",",
)
def _run_interface(self, runtime):
self._reset_class_members()
self._load_image_arrays()
self._dict_metrics = self._compute_metrics()
self._generate_csv()
print("Computed and saved overall metrics!")
if self.inputs.input_ref_labelmap:
self._compute_metrics_labels()
self._generate_csv_labels()
print("Computed and saved per label metrics!")
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["output_metrics"] = self._gen_filename("output_metrics")
outputs["output_metrics_labels"] = self._gen_filename(
"output_metrics_labels"
)
return outputs
class ConcatenateImageMetricsInputSpec(BaseInterfaceInputSpec):
"""Class used to represent inputs of the ConcatenateImageMetrics interface."""
input_metrics = InputMultiPath(File(mandatory=True), desc="")
input_metrics_labels = InputMultiPath(File(mandatory=True), desc="")
class ConcatenateImageMetricsOutputSpec(TraitedSpec):
"""Class used to represent outputs of the ConcatenateImageMetrics interface."""
output_csv = File(desc="")
output_csv_labels = File(desc="")
class ConcatenateImageMetrics(BaseInterface):
"""Concatenate metrics CSV files with the metrics computed on each labelmap.
Example
----------
>>> from pymialsrtk.interfaces.postprocess import ConcatenateImageMetrics
>>> concat_metrics = ConcatenateImageMetrics()
>>> concat_metrics.inputs.input_metrics = ['sub-01_acq-haste_run-1_paramset_1_metrics.csv', 'sub-01_acq-haste_run-1_paramset2_metrics.csv']
concat_metrics.inputs.input_metrics_labels = ['sub-01_acq-haste_run-1_paramset_1_metrics_labels.csv', 'sub-01_acq-haste_run-1_paramset2_metrics_labels.csv']
>>> concat_metrics.run() # doctest: +SKIP
"""
input_spec = ConcatenateImageMetricsInputSpec
output_spec = ConcatenateImageMetricsOutputSpec
def _gen_filename(self, name):
if name == "output_csv":
return os.path.abspath(
os.path.basename(self.inputs.input_metrics[0])
)
if name == "output_csv_labels":
return os.path.abspath(
os.path.basename(self.inputs.input_metrics_labels[0])
)
return None
def _run_interface(self, runtime):
frames = [
pd.read_csv(s, index_col=False) for s in self.inputs.input_metrics