/
segmentation.py
1795 lines (1647 loc) · 67.8 KB
/
segmentation.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
"""Wrappers for segmentation utilities within ANTs."""
import os
from glob import glob
from ...external.due import BibTeX
from ...utils.filemanip import split_filename, copyfile, which, fname_presuffix
from ..base import TraitedSpec, File, traits, InputMultiPath, OutputMultiPath, isdefined
from ..mixins import CopyHeaderInterface
from .base import ANTSCommand, ANTSCommandInputSpec
class AtroposInputSpec(ANTSCommandInputSpec):
dimension = traits.Enum(
3,
2,
4,
argstr="--image-dimensionality %d",
usedefault=True,
desc="image dimension (2, 3, or 4)",
)
intensity_images = InputMultiPath(
File(exists=True), argstr="--intensity-image %s...", mandatory=True
)
mask_image = File(exists=True, argstr="--mask-image %s", mandatory=True)
initialization = traits.Enum(
"Random",
"Otsu",
"KMeans",
"PriorProbabilityImages",
"PriorLabelImage",
argstr="%s",
requires=["number_of_tissue_classes"],
mandatory=True,
)
kmeans_init_centers = traits.List(traits.Either(traits.Int, traits.Float), minlen=1)
prior_image = traits.Either(
File(exists=True),
traits.Str,
desc="either a string pattern (e.g., 'prior%02d.nii') or an existing vector-image file.",
)
number_of_tissue_classes = traits.Int(mandatory=True)
prior_weighting = traits.Float()
prior_probability_threshold = traits.Float(requires=["prior_weighting"])
likelihood_model = traits.Str(argstr="--likelihood-model %s")
mrf_smoothing_factor = traits.Float(argstr="%s")
mrf_radius = traits.List(traits.Int(), requires=["mrf_smoothing_factor"])
icm_use_synchronous_update = traits.Bool(argstr="%s")
maximum_number_of_icm_terations = traits.Int(
requires=["icm_use_synchronous_update"]
)
n_iterations = traits.Int(argstr="%s")
convergence_threshold = traits.Float(requires=["n_iterations"])
posterior_formulation = traits.Str(argstr="%s")
use_random_seed = traits.Bool(
True,
argstr="--use-random-seed %d",
desc="use random seed value over constant",
usedefault=True,
)
use_mixture_model_proportions = traits.Bool(requires=["posterior_formulation"])
out_classified_image_name = File(argstr="%s", genfile=True, hash_files=False)
save_posteriors = traits.Bool()
output_posteriors_name_template = traits.Str(
"POSTERIOR_%02d.nii.gz", usedefault=True
)
class AtroposOutputSpec(TraitedSpec):
classified_image = File(exists=True)
posteriors = OutputMultiPath(File(exist=True))
class Atropos(ANTSCommand):
"""
A multivariate n-class segmentation algorithm.
A finite mixture modeling (FMM) segmentation approach with possibilities for
specifying prior constraints. These prior constraints include the specification
of a prior label image, prior probability images (one for each class), and/or an
MRF prior to enforce spatial smoothing of the labels. Similar algorithms include
FAST and SPM.
Examples
--------
>>> from nipype.interfaces.ants import Atropos
>>> at = Atropos(
... dimension=3, intensity_images='structural.nii', mask_image='mask.nii',
... number_of_tissue_classes=2, likelihood_model='Gaussian', save_posteriors=True,
... mrf_smoothing_factor=0.2, mrf_radius=[1, 1, 1], icm_use_synchronous_update=True,
... maximum_number_of_icm_terations=1, n_iterations=5, convergence_threshold=0.000001,
... posterior_formulation='Socrates', use_mixture_model_proportions=True)
>>> at.inputs.initialization = 'Random'
>>> at.cmdline
'Atropos --image-dimensionality 3 --icm [1,1]
--initialization Random[2] --intensity-image structural.nii
--likelihood-model Gaussian --mask-image mask.nii --mrf [0.2,1x1x1] --convergence [5,1e-06]
--output [structural_labeled.nii,POSTERIOR_%02d.nii.gz] --posterior-formulation Socrates[1]
--use-random-seed 1'
>>> at = Atropos(
... dimension=3, intensity_images='structural.nii', mask_image='mask.nii',
... number_of_tissue_classes=2, likelihood_model='Gaussian', save_posteriors=True,
... mrf_smoothing_factor=0.2, mrf_radius=[1, 1, 1], icm_use_synchronous_update=True,
... maximum_number_of_icm_terations=1, n_iterations=5, convergence_threshold=0.000001,
... posterior_formulation='Socrates', use_mixture_model_proportions=True)
>>> at.inputs.initialization = 'KMeans'
>>> at.inputs.kmeans_init_centers = [100, 200]
>>> at.cmdline
'Atropos --image-dimensionality 3 --icm [1,1]
--initialization KMeans[2,100,200] --intensity-image structural.nii
--likelihood-model Gaussian --mask-image mask.nii --mrf [0.2,1x1x1] --convergence [5,1e-06]
--output [structural_labeled.nii,POSTERIOR_%02d.nii.gz] --posterior-formulation Socrates[1]
--use-random-seed 1'
>>> at = Atropos(
... dimension=3, intensity_images='structural.nii', mask_image='mask.nii',
... number_of_tissue_classes=2, likelihood_model='Gaussian', save_posteriors=True,
... mrf_smoothing_factor=0.2, mrf_radius=[1, 1, 1], icm_use_synchronous_update=True,
... maximum_number_of_icm_terations=1, n_iterations=5, convergence_threshold=0.000001,
... posterior_formulation='Socrates', use_mixture_model_proportions=True)
>>> at.inputs.initialization = 'PriorProbabilityImages'
>>> at.inputs.prior_image = 'BrainSegmentationPrior%02d.nii.gz'
>>> at.inputs.prior_weighting = 0.8
>>> at.inputs.prior_probability_threshold = 0.0000001
>>> at.cmdline
'Atropos --image-dimensionality 3 --icm [1,1]
--initialization PriorProbabilityImages[2,BrainSegmentationPrior%02d.nii.gz,0.8,1e-07]
--intensity-image structural.nii --likelihood-model Gaussian --mask-image mask.nii
--mrf [0.2,1x1x1] --convergence [5,1e-06]
--output [structural_labeled.nii,POSTERIOR_%02d.nii.gz]
--posterior-formulation Socrates[1] --use-random-seed 1'
>>> at = Atropos(
... dimension=3, intensity_images='structural.nii', mask_image='mask.nii',
... number_of_tissue_classes=2, likelihood_model='Gaussian', save_posteriors=True,
... mrf_smoothing_factor=0.2, mrf_radius=[1, 1, 1], icm_use_synchronous_update=True,
... maximum_number_of_icm_terations=1, n_iterations=5, convergence_threshold=0.000001,
... posterior_formulation='Socrates', use_mixture_model_proportions=True)
>>> at.inputs.initialization = 'PriorLabelImage'
>>> at.inputs.prior_image = 'segmentation0.nii.gz'
>>> at.inputs.number_of_tissue_classes = 2
>>> at.inputs.prior_weighting = 0.8
>>> at.cmdline
'Atropos --image-dimensionality 3 --icm [1,1]
--initialization PriorLabelImage[2,segmentation0.nii.gz,0.8] --intensity-image structural.nii
--likelihood-model Gaussian --mask-image mask.nii --mrf [0.2,1x1x1] --convergence [5,1e-06]
--output [structural_labeled.nii,POSTERIOR_%02d.nii.gz] --posterior-formulation Socrates[1]
--use-random-seed 1'
"""
input_spec = AtroposInputSpec
output_spec = AtroposOutputSpec
_cmd = "Atropos"
def _format_arg(self, opt, spec, val):
if opt == "initialization":
n_classes = self.inputs.number_of_tissue_classes
brackets = ["%d" % n_classes]
if val == "KMeans" and isdefined(self.inputs.kmeans_init_centers):
centers = sorted(set(self.inputs.kmeans_init_centers))
if len(centers) != n_classes:
raise ValueError(
"KMeans initialization with initial cluster centers requires "
"the number of centers to match number_of_tissue_classes"
)
brackets += ["%g" % c for c in centers]
if val in ("PriorProbabilityImages", "PriorLabelImage"):
if not isdefined(self.inputs.prior_image) or not isdefined(
self.inputs.prior_weighting
):
raise ValueError(
"'%s' initialization requires setting "
"prior_image and prior_weighting" % val
)
priors_paths = [self.inputs.prior_image]
if "%02d" in priors_paths[0]:
if val == "PriorLabelImage":
raise ValueError(
"'PriorLabelImage' initialization does not "
"accept patterns for prior_image."
)
priors_paths = [
priors_paths[0] % i for i in range(1, n_classes + 1)
]
if not all([os.path.exists(p) for p in priors_paths]):
raise FileNotFoundError(
"One or more prior images do not exist: "
"%s." % ", ".join(priors_paths)
)
brackets += [
self.inputs.prior_image,
"%g" % self.inputs.prior_weighting,
]
if val == "PriorProbabilityImages" and isdefined(
self.inputs.prior_probability_threshold
):
brackets.append("%g" % self.inputs.prior_probability_threshold)
return "--initialization %s[%s]" % (val, ",".join(brackets))
if opt == "mrf_smoothing_factor":
retval = "--mrf [%g" % val
if isdefined(self.inputs.mrf_radius):
retval += ",%s" % self._format_xarray(
[str(s) for s in self.inputs.mrf_radius]
)
return retval + "]"
if opt == "icm_use_synchronous_update":
retval = "--icm [%d" % val
if isdefined(self.inputs.maximum_number_of_icm_terations):
retval += ",%g" % self.inputs.maximum_number_of_icm_terations
return retval + "]"
if opt == "n_iterations":
retval = "--convergence [%d" % val
if isdefined(self.inputs.convergence_threshold):
retval += ",%g" % self.inputs.convergence_threshold
return retval + "]"
if opt == "posterior_formulation":
retval = "--posterior-formulation %s" % val
if isdefined(self.inputs.use_mixture_model_proportions):
retval += "[%d]" % self.inputs.use_mixture_model_proportions
return retval
if opt == "out_classified_image_name":
retval = "--output [%s" % val
if isdefined(self.inputs.save_posteriors):
retval += ",%s" % self.inputs.output_posteriors_name_template
return retval + "]"
return super(Atropos, self)._format_arg(opt, spec, val)
def _gen_filename(self, name):
if name == "out_classified_image_name":
output = self.inputs.out_classified_image_name
if not isdefined(output):
_, name, ext = split_filename(self.inputs.intensity_images[0])
output = name + "_labeled" + ext
return output
def _list_outputs(self):
outputs = self._outputs().get()
outputs["classified_image"] = os.path.abspath(
self._gen_filename("out_classified_image_name")
)
if isdefined(self.inputs.save_posteriors) and self.inputs.save_posteriors:
outputs["posteriors"] = []
for i in range(self.inputs.number_of_tissue_classes):
outputs["posteriors"].append(
os.path.abspath(
self.inputs.output_posteriors_name_template % (i + 1)
)
)
return outputs
class LaplacianThicknessInputSpec(ANTSCommandInputSpec):
input_wm = File(
argstr="%s",
mandatory=True,
copyfile=True,
desc="white matter segmentation image",
position=1,
)
input_gm = File(
argstr="%s",
mandatory=True,
copyfile=True,
desc="gray matter segmentation image",
position=2,
)
output_image = File(
desc="name of output file",
argstr="%s",
position=3,
name_source=["input_wm"],
name_template="%s_thickness",
keep_extension=True,
hash_files=False,
)
smooth_param = traits.Float(
argstr="%s",
desc="Sigma of the Laplacian Recursive Image Filter (defaults to 1)",
position=4,
)
prior_thickness = traits.Float(
argstr="%s",
desc="Prior thickness (defaults to 500)",
requires=["smooth_param"],
position=5,
)
dT = traits.Float(
argstr="%s",
desc="Time delta used during integration (defaults to 0.01)",
requires=["prior_thickness"],
position=6,
)
sulcus_prior = traits.Float(
argstr="%s",
desc="Positive floating point number for sulcus prior. "
"Authors said that 0.15 might be a reasonable value",
requires=["dT"],
position=7,
)
tolerance = traits.Float(
argstr="%s",
desc="Tolerance to reach during optimization (defaults to 0.001)",
requires=["sulcus_prior"],
position=8,
)
class LaplacianThicknessOutputSpec(TraitedSpec):
output_image = File(exists=True, desc="Cortical thickness")
class LaplacianThickness(ANTSCommand):
"""Calculates the cortical thickness from an anatomical image
Examples
--------
>>> from nipype.interfaces.ants import LaplacianThickness
>>> cort_thick = LaplacianThickness()
>>> cort_thick.inputs.input_wm = 'white_matter.nii.gz'
>>> cort_thick.inputs.input_gm = 'gray_matter.nii.gz'
>>> cort_thick.cmdline
'LaplacianThickness white_matter.nii.gz gray_matter.nii.gz white_matter_thickness.nii.gz'
>>> cort_thick.inputs.output_image = 'output_thickness.nii.gz'
>>> cort_thick.cmdline
'LaplacianThickness white_matter.nii.gz gray_matter.nii.gz output_thickness.nii.gz'
"""
_cmd = "LaplacianThickness"
input_spec = LaplacianThicknessInputSpec
output_spec = LaplacianThicknessOutputSpec
class N4BiasFieldCorrectionInputSpec(ANTSCommandInputSpec):
dimension = traits.Enum(
3, 2, 4, argstr="-d %d", usedefault=True, desc="image dimension (2, 3 or 4)"
)
input_image = File(
argstr="--input-image %s",
mandatory=True,
desc=(
"input for bias correction. Negative values or values close to "
"zero should be processed prior to correction"
),
)
mask_image = File(
argstr="--mask-image %s",
desc=("image to specify region to perform final bias correction in"),
)
weight_image = File(
argstr="--weight-image %s",
desc=(
"image for relative weighting (e.g. probability map of the white "
"matter) of voxels during the B-spline fitting. "
),
)
output_image = traits.Str(
argstr="--output %s",
desc="output file name",
name_source=["input_image"],
name_template="%s_corrected",
keep_extension=True,
hash_files=False,
)
bspline_fitting_distance = traits.Float(argstr="--bspline-fitting %s")
bspline_order = traits.Int(requires=["bspline_fitting_distance"])
shrink_factor = traits.Int(argstr="--shrink-factor %d")
n_iterations = traits.List(traits.Int(), argstr="--convergence %s")
convergence_threshold = traits.Float(requires=["n_iterations"])
save_bias = traits.Bool(
False,
mandatory=True,
usedefault=True,
desc=("True if the estimated bias should be saved to file."),
xor=["bias_image"],
)
bias_image = File(desc="Filename for the estimated bias.", hash_files=False)
copy_header = traits.Bool(
False,
mandatory=True,
usedefault=True,
desc="copy headers of the original image into the output (corrected) file",
)
rescale_intensities = traits.Bool(
False,
usedefault=True,
argstr="-r",
min_ver="2.1.0",
desc="""\
[NOTE: Only ANTs>=2.1.0]
At each iteration, a new intensity mapping is calculated and applied but there
is nothing which constrains the new intensity range to be within certain values.
The result is that the range can "drift" from the original at each iteration.
This option rescales to the [min,max] range of the original image intensities
within the user-specified mask.""",
)
histogram_sharpening = traits.Tuple(
(0.15, 0.01, 200),
traits.Float,
traits.Float,
traits.Int,
argstr="--histogram-sharpening [%g,%g,%d]",
desc="""\
Three-values tuple of histogram sharpening parameters \
(FWHM, wienerNose, numberOfHistogramBins).
These options describe the histogram sharpening parameters, i.e. the \
deconvolution step parameters described in the original N3 algorithm.
The default values have been shown to work fairly well.""",
)
class N4BiasFieldCorrectionOutputSpec(TraitedSpec):
output_image = File(exists=True, desc="Warped image")
bias_image = File(exists=True, desc="Estimated bias")
class N4BiasFieldCorrection(ANTSCommand, CopyHeaderInterface):
"""
Bias field correction.
N4 is a variant of the popular N3 (nonparameteric nonuniform normalization)
retrospective bias correction algorithm. Based on the assumption that the
corruption of the low frequency bias field can be modeled as a convolution of
the intensity histogram by a Gaussian, the basic algorithmic protocol is to
iterate between deconvolving the intensity histogram by a Gaussian, remapping
the intensities, and then spatially smoothing this result by a B-spline modeling
of the bias field itself. The modifications from and improvements obtained over
the original N3 algorithm are described in [Tustison2010]_.
.. [Tustison2010] N. Tustison et al.,
N4ITK: Improved N3 Bias Correction, IEEE Transactions on Medical Imaging,
29(6):1310-1320, June 2010.
Examples
--------
>>> import copy
>>> from nipype.interfaces.ants import N4BiasFieldCorrection
>>> n4 = N4BiasFieldCorrection()
>>> n4.inputs.dimension = 3
>>> n4.inputs.input_image = 'structural.nii'
>>> n4.inputs.bspline_fitting_distance = 300
>>> n4.inputs.shrink_factor = 3
>>> n4.inputs.n_iterations = [50,50,30,20]
>>> n4.cmdline
'N4BiasFieldCorrection --bspline-fitting [ 300 ]
-d 3 --input-image structural.nii
--convergence [ 50x50x30x20 ] --output structural_corrected.nii
--shrink-factor 3'
>>> n4_2 = copy.deepcopy(n4)
>>> n4_2.inputs.convergence_threshold = 1e-6
>>> n4_2.cmdline
'N4BiasFieldCorrection --bspline-fitting [ 300 ]
-d 3 --input-image structural.nii
--convergence [ 50x50x30x20, 1e-06 ] --output structural_corrected.nii
--shrink-factor 3'
>>> n4_3 = copy.deepcopy(n4_2)
>>> n4_3.inputs.bspline_order = 5
>>> n4_3.cmdline
'N4BiasFieldCorrection --bspline-fitting [ 300, 5 ]
-d 3 --input-image structural.nii
--convergence [ 50x50x30x20, 1e-06 ] --output structural_corrected.nii
--shrink-factor 3'
>>> n4_4 = N4BiasFieldCorrection()
>>> n4_4.inputs.input_image = 'structural.nii'
>>> n4_4.inputs.save_bias = True
>>> n4_4.inputs.dimension = 3
>>> n4_4.cmdline
'N4BiasFieldCorrection -d 3 --input-image structural.nii
--output [ structural_corrected.nii, structural_bias.nii ]'
>>> n4_5 = N4BiasFieldCorrection()
>>> n4_5.inputs.input_image = 'structural.nii'
>>> n4_5.inputs.dimension = 3
>>> n4_5.inputs.histogram_sharpening = (0.12, 0.02, 200)
>>> n4_5.cmdline
'N4BiasFieldCorrection -d 3 --histogram-sharpening [0.12,0.02,200]
--input-image structural.nii --output structural_corrected.nii'
"""
_cmd = "N4BiasFieldCorrection"
input_spec = N4BiasFieldCorrectionInputSpec
output_spec = N4BiasFieldCorrectionOutputSpec
_copy_header_map = {
"output_image": ("input_image", False),
"bias_image": ("input_image", True),
}
def __init__(self, *args, **kwargs):
"""Instantiate the N4BiasFieldCorrection interface."""
self._out_bias_file = None
super(N4BiasFieldCorrection, self).__init__(*args, **kwargs)
def _format_arg(self, name, trait_spec, value):
if name == "output_image" and self._out_bias_file:
newval = "[ %s, %s ]" % (value, self._out_bias_file)
return trait_spec.argstr % newval
if name == "bspline_fitting_distance":
if isdefined(self.inputs.bspline_order):
newval = "[ %g, %d ]" % (value, self.inputs.bspline_order)
else:
newval = "[ %g ]" % value
return trait_spec.argstr % newval
if name == "n_iterations":
if isdefined(self.inputs.convergence_threshold):
newval = "[ %s, %g ]" % (
self._format_xarray([str(elt) for elt in value]),
self.inputs.convergence_threshold,
)
else:
newval = "[ %s ]" % self._format_xarray([str(elt) for elt in value])
return trait_spec.argstr % newval
return super(N4BiasFieldCorrection, self)._format_arg(name, trait_spec, value)
def _parse_inputs(self, skip=None):
skip = (skip or []) + ["save_bias", "bias_image"]
self._out_bias_file = None
if self.inputs.save_bias or isdefined(self.inputs.bias_image):
bias_image = self.inputs.bias_image
if not isdefined(bias_image):
bias_image = fname_presuffix(
os.path.basename(self.inputs.input_image), suffix="_bias"
)
self._out_bias_file = bias_image
return super(N4BiasFieldCorrection, self)._parse_inputs(skip=skip)
def _list_outputs(self):
outputs = super(N4BiasFieldCorrection, self)._list_outputs()
if self._out_bias_file:
outputs["bias_image"] = os.path.abspath(self._out_bias_file)
return outputs
class CorticalThicknessInputSpec(ANTSCommandInputSpec):
dimension = traits.Enum(
3, 2, argstr="-d %d", usedefault=True, desc="image dimension (2 or 3)"
)
anatomical_image = File(
exists=True,
argstr="-a %s",
desc=(
"Structural *intensity* image, typically T1."
" If more than one anatomical image is specified,"
" subsequently specified images are used during the"
" segmentation process. However, only the first"
" image is used in the registration of priors."
" Our suggestion would be to specify the T1"
" as the first image."
),
mandatory=True,
)
brain_template = File(
exists=True,
argstr="-e %s",
desc=(
"Anatomical *intensity* template (possibly created using a"
" population data set with buildtemplateparallel.sh in ANTs)."
" This template is *not* skull-stripped."
),
mandatory=True,
)
brain_probability_mask = File(
exists=True,
argstr="-m %s",
desc="brain probability mask in template space",
copyfile=False,
mandatory=True,
)
segmentation_priors = InputMultiPath(
File(exists=True), argstr="-p %s", mandatory=True
)
out_prefix = traits.Str(
"antsCT_",
argstr="-o %s",
usedefault=True,
desc=("Prefix that is prepended to all output files"),
)
image_suffix = traits.Str(
"nii.gz",
desc=("any of standard ITK formats, nii.gz is default"),
argstr="-s %s",
usedefault=True,
)
t1_registration_template = File(
exists=True,
desc=(
"Anatomical *intensity* template"
" (assumed to be skull-stripped). A common"
" case would be where this would be the same"
" template as specified in the -e option which"
" is not skull stripped."
),
argstr="-t %s",
mandatory=True,
)
extraction_registration_mask = File(
exists=True,
argstr="-f %s",
desc=(
"Mask (defined in the template space) used during"
" registration for brain extraction."
),
)
keep_temporary_files = traits.Int(
argstr="-k %d",
desc="Keep brain extraction/segmentation warps, etc (default = 0).",
)
max_iterations = traits.Int(
argstr="-i %d",
desc=("ANTS registration max iterations (default = 100x100x70x20)"),
)
prior_segmentation_weight = traits.Float(
argstr="-w %f",
desc=("Atropos spatial prior *probability* weight for the segmentation"),
)
segmentation_iterations = traits.Int(
argstr="-n %d",
desc=("N4 -> Atropos -> N4 iterations during segmentation (default = 3)"),
)
posterior_formulation = traits.Str(
argstr="-b %s",
desc=(
"Atropos posterior formulation and whether or not"
" to use mixture model proportions."
""" e.g 'Socrates[1]' (default) or 'Aristotle[1]'."""
" Choose the latter if you"
" want use the distance priors (see also the -l option"
" for label propagation control)."
),
)
use_floatingpoint_precision = traits.Enum(
0,
1,
argstr="-j %d",
desc=("Use floating point precision in registrations (default = 0)"),
)
use_random_seeding = traits.Enum(
0,
1,
argstr="-u %d",
desc=("Use random number generated from system clock in Atropos (default = 1)"),
)
b_spline_smoothing = traits.Bool(
argstr="-v",
desc=(
"Use B-spline SyN for registrations and B-spline"
" exponential mapping in DiReCT."
),
)
cortical_label_image = File(
exists=True, desc="Cortical ROI labels to use as a prior for ATITH."
)
label_propagation = traits.Str(
argstr="-l %s",
desc=(
"Incorporate a distance prior one the posterior formulation. Should be"
""" of the form 'label[lambda,boundaryProbability]' where label"""
" is a value of 1,2,3,... denoting label ID. The label"
" probability for anything outside the current label"
" = boundaryProbability * exp( -lambda * distanceFromBoundary )"
" Intuitively, smaller lambda values will increase the spatial capture"
" range of the distance prior. To apply to all label values, simply omit"
" specifying the label, i.e. -l [lambda,boundaryProbability]."
),
)
quick_registration = traits.Bool(
argstr="-q 1",
desc=(
"If = 1, use antsRegistrationSyNQuick.sh as the basis for registration"
" during brain extraction, brain segmentation, and"
" (optional) normalization to a template."
" Otherwise use antsRegistrationSyN.sh (default = 0)."
),
)
debug = traits.Bool(
argstr="-z 1",
desc=(
"If > 0, runs a faster version of the script."
" Only for testing. Implies -u 0."
" Requires single thread computation for complete reproducibility."
),
)
class CorticalThicknessOutputSpec(TraitedSpec):
BrainExtractionMask = File(exists=True, desc="brain extraction mask")
ExtractedBrainN4 = File(exists=True, desc="extracted brain from N4 image")
BrainSegmentation = File(exists=True, desc="brain segmentaion image")
BrainSegmentationN4 = File(exists=True, desc="N4 corrected image")
BrainSegmentationPosteriors = OutputMultiPath(
File(exists=True), desc="Posterior probability images"
)
CorticalThickness = File(exists=True, desc="cortical thickness file")
TemplateToSubject1GenericAffine = File(
exists=True, desc="Template to subject affine"
)
TemplateToSubject0Warp = File(exists=True, desc="Template to subject warp")
SubjectToTemplate1Warp = File(exists=True, desc="Template to subject inverse warp")
SubjectToTemplate0GenericAffine = File(
exists=True, desc="Template to subject inverse affine"
)
SubjectToTemplateLogJacobian = File(
exists=True, desc="Template to subject log jacobian"
)
CorticalThicknessNormedToTemplate = File(
exists=True, desc="Normalized cortical thickness"
)
BrainVolumes = File(exists=True, desc="Brain volumes as text")
class CorticalThickness(ANTSCommand):
"""
Examples
--------
>>> from nipype.interfaces.ants.segmentation import CorticalThickness
>>> corticalthickness = CorticalThickness()
>>> corticalthickness.inputs.dimension = 3
>>> corticalthickness.inputs.anatomical_image ='T1.nii.gz'
>>> corticalthickness.inputs.brain_template = 'study_template.nii.gz'
>>> corticalthickness.inputs.brain_probability_mask ='ProbabilityMaskOfStudyTemplate.nii.gz'
>>> corticalthickness.inputs.segmentation_priors = ['BrainSegmentationPrior01.nii.gz',
... 'BrainSegmentationPrior02.nii.gz',
... 'BrainSegmentationPrior03.nii.gz',
... 'BrainSegmentationPrior04.nii.gz']
>>> corticalthickness.inputs.t1_registration_template = 'brain_study_template.nii.gz'
>>> corticalthickness.cmdline
'antsCorticalThickness.sh -a T1.nii.gz -m ProbabilityMaskOfStudyTemplate.nii.gz
-e study_template.nii.gz -d 3 -s nii.gz -o antsCT_
-p nipype_priors/BrainSegmentationPrior%02d.nii.gz -t brain_study_template.nii.gz'
"""
input_spec = CorticalThicknessInputSpec
output_spec = CorticalThicknessOutputSpec
_cmd = "antsCorticalThickness.sh"
def _format_arg(self, opt, spec, val):
if opt == "anatomical_image":
retval = "-a %s" % val
return retval
if opt == "brain_template":
retval = "-e %s" % val
return retval
if opt == "brain_probability_mask":
retval = "-m %s" % val
return retval
if opt == "out_prefix":
retval = "-o %s" % val
return retval
if opt == "t1_registration_template":
retval = "-t %s" % val
return retval
if opt == "segmentation_priors":
_, _, ext = split_filename(self.inputs.segmentation_priors[0])
retval = "-p nipype_priors/BrainSegmentationPrior%02d" + ext
return retval
return super(CorticalThickness, self)._format_arg(opt, spec, val)
def _run_interface(self, runtime, correct_return_codes=[0]):
priors_directory = os.path.join(os.getcwd(), "nipype_priors")
if not os.path.exists(priors_directory):
os.makedirs(priors_directory)
_, _, ext = split_filename(self.inputs.segmentation_priors[0])
for i, f in enumerate(self.inputs.segmentation_priors):
target = os.path.join(
priors_directory, "BrainSegmentationPrior%02d" % (i + 1) + ext
)
if not (
os.path.exists(target)
and os.path.realpath(target) == os.path.abspath(f)
):
copyfile(os.path.abspath(f), target)
runtime = super(CorticalThickness, self)._run_interface(runtime)
return runtime
def _list_outputs(self):
outputs = self._outputs().get()
outputs["BrainExtractionMask"] = os.path.join(
os.getcwd(),
self.inputs.out_prefix + "BrainExtractionMask." + self.inputs.image_suffix,
)
outputs["ExtractedBrainN4"] = os.path.join(
os.getcwd(),
self.inputs.out_prefix + "ExtractedBrain0N4." + self.inputs.image_suffix,
)
outputs["BrainSegmentation"] = os.path.join(
os.getcwd(),
self.inputs.out_prefix + "BrainSegmentation." + self.inputs.image_suffix,
)
outputs["BrainSegmentationN4"] = os.path.join(
os.getcwd(),
self.inputs.out_prefix + "BrainSegmentation0N4." + self.inputs.image_suffix,
)
posteriors = []
for i in range(len(self.inputs.segmentation_priors)):
posteriors.append(
os.path.join(
os.getcwd(),
self.inputs.out_prefix
+ "BrainSegmentationPosteriors%02d." % (i + 1)
+ self.inputs.image_suffix,
)
)
outputs["BrainSegmentationPosteriors"] = posteriors
outputs["CorticalThickness"] = os.path.join(
os.getcwd(),
self.inputs.out_prefix + "CorticalThickness." + self.inputs.image_suffix,
)
outputs["TemplateToSubject1GenericAffine"] = os.path.join(
os.getcwd(), self.inputs.out_prefix + "TemplateToSubject1GenericAffine.mat"
)
outputs["TemplateToSubject0Warp"] = os.path.join(
os.getcwd(),
self.inputs.out_prefix
+ "TemplateToSubject0Warp."
+ self.inputs.image_suffix,
)
outputs["SubjectToTemplate1Warp"] = os.path.join(
os.getcwd(),
self.inputs.out_prefix
+ "SubjectToTemplate1Warp."
+ self.inputs.image_suffix,
)
outputs["SubjectToTemplate0GenericAffine"] = os.path.join(
os.getcwd(), self.inputs.out_prefix + "SubjectToTemplate0GenericAffine.mat"
)
outputs["SubjectToTemplateLogJacobian"] = os.path.join(
os.getcwd(),
self.inputs.out_prefix
+ "SubjectToTemplateLogJacobian."
+ self.inputs.image_suffix,
)
outputs["CorticalThicknessNormedToTemplate"] = os.path.join(
os.getcwd(),
self.inputs.out_prefix + "CorticalThickness." + self.inputs.image_suffix,
)
outputs["BrainVolumes"] = os.path.join(
os.getcwd(), self.inputs.out_prefix + "brainvols.csv"
)
return outputs
class BrainExtractionInputSpec(ANTSCommandInputSpec):
dimension = traits.Enum(
3, 2, argstr="-d %d", usedefault=True, desc="image dimension (2 or 3)"
)
anatomical_image = File(
exists=True,
argstr="-a %s",
desc=(
"Structural image, typically T1. If more than one"
" anatomical image is specified, subsequently specified"
" images are used during the segmentation process. However,"
" only the first image is used in the registration of priors."
" Our suggestion would be to specify the T1 as the first image."
" Anatomical template created using e.g. LPBA40 data set with"
" buildtemplateparallel.sh in ANTs."
),
mandatory=True,
)
brain_template = File(
exists=True,
argstr="-e %s",
desc=(
"Anatomical template created using e.g. LPBA40 data set with"
" buildtemplateparallel.sh in ANTs."
),
mandatory=True,
)
brain_probability_mask = File(
exists=True,
argstr="-m %s",
desc=(
"Brain probability mask created using e.g. LPBA40 data set which"
" have brain masks defined, and warped to anatomical template and"
" averaged resulting in a probability image."
),
copyfile=False,
mandatory=True,
)
out_prefix = traits.Str(
"highres001_",
argstr="-o %s",
usedefault=True,
desc=("Prefix that is prepended to all output files"),
)
extraction_registration_mask = File(
exists=True,
argstr="-f %s",
desc=(
"Mask (defined in the template space) used during"
" registration for brain extraction."
" To limit the metric computation to a specific region."
),
)
image_suffix = traits.Str(
"nii.gz",
desc=("any of standard ITK formats, nii.gz is default"),
argstr="-s %s",
usedefault=True,
)
use_random_seeding = traits.Enum(
0,
1,
argstr="-u %d",
desc=("Use random number generated from system clock in Atropos (default = 1)"),
)
keep_temporary_files = traits.Int(
argstr="-k %d",
desc="Keep brain extraction/segmentation warps, etc (default = 0).",
)
use_floatingpoint_precision = traits.Enum(
0,
1,
argstr="-q %d",
desc=("Use floating point precision in registrations (default = 0)"),
)
debug = traits.Bool(
argstr="-z 1",
desc=(
"If > 0, runs a faster version of the script."
" Only for testing. Implies -u 0."
" Requires single thread computation for complete reproducibility."
),
)
class BrainExtractionOutputSpec(TraitedSpec):
BrainExtractionMask = File(exists=True, desc="brain extraction mask")
BrainExtractionBrain = File(exists=True, desc="brain extraction image")
BrainExtractionCSF = File(exists=True, desc="segmentation mask with only CSF")
BrainExtractionGM = File(
exists=True, desc="segmentation mask with only grey matter"
)
BrainExtractionInitialAffine = File(exists=True, desc="")
BrainExtractionInitialAffineFixed = File(exists=True, desc="")
BrainExtractionInitialAffineMoving = File(exists=True, desc="")
BrainExtractionLaplacian = File(exists=True, desc="")
BrainExtractionPrior0GenericAffine = File(exists=True, desc="")
BrainExtractionPrior1InverseWarp = File(exists=True, desc="")
BrainExtractionPrior1Warp = File(exists=True, desc="")
BrainExtractionPriorWarped = File(exists=True, desc="")
BrainExtractionSegmentation = File(
exists=True, desc="segmentation mask with CSF, GM, and WM"
)
BrainExtractionTemplateLaplacian = File(exists=True, desc="")
BrainExtractionTmp = File(exists=True, desc="")
BrainExtractionWM = File(
exists=True, desc="segmenration mask with only white matter"
)
N4Corrected0 = File(exists=True, desc="N4 bias field corrected image")
N4Truncated0 = File(exists=True, desc="")
class BrainExtraction(ANTSCommand):
"""
Atlas-based brain extraction.
Examples
--------
>>> from nipype.interfaces.ants.segmentation import BrainExtraction
>>> brainextraction = BrainExtraction()
>>> brainextraction.inputs.dimension = 3
>>> brainextraction.inputs.anatomical_image ='T1.nii.gz'
>>> brainextraction.inputs.brain_template = 'study_template.nii.gz'
>>> brainextraction.inputs.brain_probability_mask ='ProbabilityMaskOfStudyTemplate.nii.gz'
>>> brainextraction.cmdline
'antsBrainExtraction.sh -a T1.nii.gz -m ProbabilityMaskOfStudyTemplate.nii.gz
-e study_template.nii.gz -d 3 -s nii.gz -o highres001_'
"""
input_spec = BrainExtractionInputSpec
output_spec = BrainExtractionOutputSpec
_cmd = "antsBrainExtraction.sh"
def _run_interface(self, runtime, correct_return_codes=(0,)):
# antsBrainExtraction.sh requires ANTSPATH to be defined
out_environ = self._get_environ()
ants_path = out_environ.get("ANTSPATH", None) or os.getenv("ANTSPATH", None)
if ants_path is None:
# Check for antsRegistration, which is under bin/ (the $ANTSPATH) instead of
# checking for antsBrainExtraction.sh which is under script/
cmd_path = which("antsRegistration", env=runtime.environ)
if not cmd_path:
raise RuntimeError(