-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathiterativeN4_multispectral.sh
executable file
·1378 lines (1138 loc) · 71.7 KB
/
iterativeN4_multispectral.sh
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
#!/bin/bash
# Created by argbash-init v2.8.0
# Rearrange the order of options below according to what you would like to see in the help message.
# ARG_OPTIONAL_SINGLE([exclude],[e],[Mask file defining regions to exclude from classifcation, region is still corrected])
# ARG_OPTIONAL_SINGLE([config],[c],[Path to an alternative config file defining priors to use, use "auto" to use automatic template selection])
# ARG_OPTIONAL_SINGLE([logfile],[l],[Path to file to log all output])
# ARG_OPTIONAL_BOOLEAN([standalone],[s],[Script is run standalone so save all outputs])
# ARG_OPTIONAL_BOOLEAN([autocrop],[a],[Crop the final output to 10 mm around the head determined by headmask from modelspace])
# ARG_OPTIONAL_SINGLE([max-iterations],[],[Maximum number of iterations to run],[10])
# ARG_OPTIONAL_SINGLE([convergence-threshold],[],[Coeffcient of variation limit between two bias field estimates],[0.01])
# ARG_OPTIONAL_SINGLE([classification-prior-weight],[],[How much weight is given to prior classification proabilities during iteration],[0.25])
# ARG_OPTIONAL_BOOLEAN([debug],[],[Debug mode, increase verbosity further, don't cleanup])
# ARG_VERBOSE([v])
# ARG_POSITIONAL_SINGLE([input],[T1w scan to be corrected])
# ARG_POSITIONAL_SINGLE([output],[Output filename for corrected T1w (also used as basename for other outputs)])
# ARGBASH_SET_INDENT([ ])
# ARGBASH_SET_DELIM([ =])
# ARG_OPTION_STACKING([getopt])
# ARG_RESTRICT_VALUES([no-local-options])
# ARG_DEFAULTS_POS([])
# ARG_HELP([iterativeN4_multispectral.sh is script which performs iterative inhomogeneity (bias field) correction and classification on T1w (and optionally T2w/PDw) MRI scans])
# ARGBASH_GO()
# needed because of Argbash --> m4_ignore([
### START OF CODE GENERATED BY Argbash v2.8.1 one line above ###
# Argbash is a bash code generator used to get arguments parsing right.
# Argbash is FREE SOFTWARE, see https://argbash.io for more info
die()
{
local _ret=$2
test -n "$_ret" || _ret=1
test "$_PRINT_HELP" = yes && print_help >&2
echo "$1" >&2
exit ${_ret}
}
evaluate_strictness()
{
[[ "$2" =~ ^-(-(exclude|config|logfile|standalone|autocrop|max-iterations|convergence-threshold|classification-prior-weight|debug|verbose|input|output|help)$|[eclsavh]) ]] && die "You have passed '$2' as a value of argument '$1', which makes it look like that you have omitted the actual value, since '$2' is an option accepted by this script. This is considered a fatal error."
}
begins_with_short_option()
{
local first_option all_short_options='eclsavh'
first_option="${1:0:1}"
test "$all_short_options" = "${all_short_options/$first_option/}" && return 1 || return 0
}
# THE DEFAULTS INITIALIZATION - POSITIONALS
_positionals=()
_arg_input=
_arg_output=
# THE DEFAULTS INITIALIZATION - OPTIONALS
_arg_exclude=
_arg_config=
_arg_logfile=
_arg_standalone="off"
_arg_autocrop="off"
_arg_max_iterations="10"
_arg_convergence_threshold="0.01"
_arg_classification_prior_weight="0.25"
_arg_debug="off"
_arg_verbose=0
print_help()
{
printf '%s\n' "iterativeN4_multispectral.sh is script which performs iterative inhomogeneity (bias field) correction and classification on T1w (and optionally T2w/PDw) MRI scans"
printf 'Usage: %s [-e|--exclude <arg>] [-c|--config <arg>] [-l|--logfile <arg>] [-s|--(no-)standalone] [-a|--(no-)autocrop] [--max-iterations <arg>] [--convergence-threshold <arg>] [--classification-prior-weight <arg>] [--(no-)debug] [-v|--verbose] [-h|--help] <input> <output>\n' "$0"
printf '\t%s\n' "<input>: T1w scan to be corrected"
printf '\t%s\n' "<output>: Output filename for corrected T1w (also used as basename for other outputs)"
printf '\t%s\n' "-e, --exclude: Mask file defining regions to exclude from classifcation, region is still corrected (no default)"
printf '\t%s\n' "-c, --config: Path to an alternative config file defining priors to use, use \"auto\" to use automatic template selection (no default)"
printf '\t%s\n' "-l, --logfile: Path to file to log all output (no default)"
printf '\t%s\n' "-s, --standalone, --no-standalone: Script is run standalone so save all outputs (off by default)"
printf '\t%s\n' "-a, --autocrop, --no-autocrop: Crop the final output to 10 mm around the head determined by headmask from modelspace (off by default)"
printf '\t%s\n' "--max-iterations: Maximum number of iterations to run (default: '10')"
printf '\t%s\n' "--convergence-threshold: Coeffcient of variation limit between two bias field estimates (default: '0.01')"
printf '\t%s\n' "--classification-prior-weight: How much weight is given to prior classification proabilities during iteration (default: '0.25')"
printf '\t%s\n' "--debug, --no-debug: Debug mode, increase verbosity further, don't cleanup (off by default)"
printf '\t%s\n' "-v, --verbose: Set verbose output (can be specified multiple times to increase the effect)"
printf '\t%s\n' "-h, --help: Prints help"
}
parse_commandline()
{
_positionals_count=0
while test $# -gt 0
do
_key="$1"
case "$_key" in
-e|--exclude)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_exclude="$2"
shift
evaluate_strictness "$_key" "$_arg_exclude"
;;
--exclude=*)
_arg_exclude="${_key##--exclude=}"
evaluate_strictness "$_key" "$_arg_exclude"
;;
-e*)
_arg_exclude="${_key##-e}"
evaluate_strictness "$_key" "$_arg_exclude"
;;
-c|--config)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_config="$2"
shift
evaluate_strictness "$_key" "$_arg_config"
;;
--config=*)
_arg_config="${_key##--config=}"
evaluate_strictness "$_key" "$_arg_config"
;;
-c*)
_arg_config="${_key##-c}"
evaluate_strictness "$_key" "$_arg_config"
;;
-l|--logfile)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_logfile="$2"
shift
evaluate_strictness "$_key" "$_arg_logfile"
;;
--logfile=*)
_arg_logfile="${_key##--logfile=}"
evaluate_strictness "$_key" "$_arg_logfile"
;;
-l*)
_arg_logfile="${_key##-l}"
evaluate_strictness "$_key" "$_arg_logfile"
;;
-s|--no-standalone|--standalone)
_arg_standalone="on"
test "${1:0:5}" = "--no-" && _arg_standalone="off"
;;
-s*)
_arg_standalone="on"
_next="${_key##-s}"
if test -n "$_next" -a "$_next" != "$_key"
then
{ begins_with_short_option "$_next" && shift && set -- "-s" "-${_next}" "$@"; } || die "The short option '$_key' can't be decomposed to ${_key:0:2} and -${_key:2}, because ${_key:0:2} doesn't accept value and '-${_key:2:1}' doesn't correspond to a short option."
fi
;;
-a|--no-autocrop|--autocrop)
_arg_autocrop="on"
test "${1:0:5}" = "--no-" && _arg_autocrop="off"
;;
-a*)
_arg_autocrop="on"
_next="${_key##-a}"
if test -n "$_next" -a "$_next" != "$_key"
then
{ begins_with_short_option "$_next" && shift && set -- "-a" "-${_next}" "$@"; } || die "The short option '$_key' can't be decomposed to ${_key:0:2} and -${_key:2}, because ${_key:0:2} doesn't accept value and '-${_key:2:1}' doesn't correspond to a short option."
fi
;;
--max-iterations)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_max_iterations="$2"
shift
evaluate_strictness "$_key" "$_arg_max_iterations"
;;
--max-iterations=*)
_arg_max_iterations="${_key##--max-iterations=}"
evaluate_strictness "$_key" "$_arg_max_iterations"
;;
--convergence-threshold)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_convergence_threshold="$2"
shift
evaluate_strictness "$_key" "$_arg_convergence_threshold"
;;
--convergence-threshold=*)
_arg_convergence_threshold="${_key##--convergence-threshold=}"
evaluate_strictness "$_key" "$_arg_convergence_threshold"
;;
--classification-prior-weight)
test $# -lt 2 && die "Missing value for the optional argument '$_key'." 1
_arg_classification_prior_weight="$2"
shift
evaluate_strictness "$_key" "$_arg_classification_prior_weight"
;;
--classification-prior-weight=*)
_arg_classification_prior_weight="${_key##--classification-prior-weight=}"
evaluate_strictness "$_key" "$_arg_classification_prior_weight"
;;
--no-debug|--debug)
_arg_debug="on"
test "${1:0:5}" = "--no-" && _arg_debug="off"
;;
-v|--verbose)
_arg_verbose=$((_arg_verbose + 1))
;;
-v*)
_arg_verbose=$((_arg_verbose + 1))
_next="${_key##-v}"
if test -n "$_next" -a "$_next" != "$_key"
then
{ begins_with_short_option "$_next" && shift && set -- "-v" "-${_next}" "$@"; } || die "The short option '$_key' can't be decomposed to ${_key:0:2} and -${_key:2}, because ${_key:0:2} doesn't accept value and '-${_key:2:1}' doesn't correspond to a short option."
fi
;;
-h|--help)
print_help
exit 0
;;
-h*)
print_help
exit 0
;;
*)
_last_positional="$1"
_positionals+=("$_last_positional")
_positionals_count=$((_positionals_count + 1))
;;
esac
shift
done
}
handle_passed_args_count()
{
local _required_args_string="'input' and 'output'"
test "${_positionals_count}" -ge 2 || _PRINT_HELP=yes die "FATAL ERROR: Not enough positional arguments - we require exactly 2 (namely: $_required_args_string), but got only ${_positionals_count}." 1
test "${_positionals_count}" -le 2 || _PRINT_HELP=yes die "FATAL ERROR: There were spurious positional arguments --- we expect exactly 2 (namely: $_required_args_string), but got ${_positionals_count} (the last one was: '${_last_positional}')." 1
}
assign_positional_args()
{
local _positional_name _shift_for=$1
_positional_names="_arg_input _arg_output "
shift "$_shift_for"
for _positional_name in ${_positional_names}
do
test $# -gt 0 || break
eval "$_positional_name=\${1}" || die "Error during argument parsing, possibly an Argbash bug." 1
shift
done
}
parse_commandline "$@"
handle_passed_args_count
assign_positional_args 1 "${_positionals[@]}"
# OTHER STUFF GENERATED BY Argbash
### END OF CODE GENERATED BY Argbash (sortof) ### ])
# [ <-- needed because of Argbash
set -euoE pipefail
#Special trick to redirect all output within script into logfile
#https://unix.stackexchange.com/questions/145651/using-exec-and-tee-to-redirect-logs-to-stdout-and-a-log-file-in-the-same-time
if [[ -n ${_arg_logfile} ]]; then
exec > >(tee -ia ${_arg_logfile})
exec 2> >(tee -ia ${_arg_logfile} >&2)
fi
#If debug, print timestamps and every command run
if [[ ${_arg_debug} == "on" ]]; then
set -xT
set -o functrace
PS4='+\t '
fi
#If verbose (or debug) turn on verbose outputs for commands
if [[ ${_arg_verbose} -ge 1 || ${_arg_debug} == "on" ]]; then
N4_VERBOSE=1
fi
#Create temporary directory for work
tmpdir=$(mktemp -d)
#Setup exit trap for cleanup, don't do if debug
function finish() {
if [[ ${_arg_debug} == "off" ]]; then
rm -rf "${tmpdir}"
fi
}
trap finish EXIT
#Add handler for failure to show where things went wrong
failure() {
local lineno=$1
local msg=$2
echo "Failed at $lineno: $msg"
}
trap 'failure ${LINENO} "$BASH_COMMAND"' ERR
#Set local parallelism inherited from QBATCH
export ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS=${THREADS_PER_COMMAND:-$(nproc)}
export OMP_NUM_THREADS=${ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS}
### DEFAULT PRIORS ###
#BeAST configuration
BEASTLIBRARY_DIR="${QUARANTINE_PATH}/resources/BEaST_libraries/combined"
BEAST_CONFIG=${BEASTLIBRARY_DIR}/default.1mm.conf
#mni_icbm152_nlin_sym_09c priors as default
REGISTRATIONMODEL="${QUARANTINE_PATH}/resources/mni_icbm152_nlin_sym_09c_minc2/mni_icbm152_t1_tal_nlin_sym_09c.mnc"
REGISTRATIONBRAINMASK="${QUARANTINE_PATH}/resources/mni_icbm152_nlin_sym_09c_minc2/mni_icbm152_t1_tal_nlin_sym_09c_mask.mnc"
WMPRIOR="${QUARANTINE_PATH}/resources/mni_icbm152_nlin_sym_09c_minc2/mni_icbm152_wm_tal_nlin_sym_09c.mnc"
GMPRIOR="${QUARANTINE_PATH}/resources/mni_icbm152_nlin_sym_09c_minc2/mni_icbm152_gm_tal_nlin_sym_09c.mnc"
CSFPRIOR="${QUARANTINE_PATH}/resources/mni_icbm152_nlin_sym_09c_minc2/mni_icbm152_csf_tal_nlin_sym_09c.mnc"
#Files used to define MNI space
RESAMPLEMODEL="${QUARANTINE_PATH}/resources/mni_icbm152_nlin_sym_09c_minc2/mni_icbm152_t1_tal_nlin_sym_09c.mnc"
RESAMPLEMODELBRAINMASK="${QUARANTINE_PATH}/resources/mni_icbm152_nlin_sym_09c_minc2/mni_icbm152_t1_tal_nlin_sym_09c_mask.mnc"
# Check config files, eventually argbash will do this
if [[ -n ${_arg_config} && ${_arg_config} != "auto" ]]; then
if [[ -r ${_arg_config} ]]; then
source ${_arg_config}
else
echo "iterativeN4_multispectral.sh ERROR: config file does not exist or is not readable" && exit 2
fi
fi
if [[ ! -d ${BEASTLIBRARY_DIR} ]]; then
echo "iterativeN4_multispectral.sh ERROR: ${BEASTLIBRARY_DIR} does not exist"
fi
for prior in ${REGISTRATIONMODEL} ${REGISTRATIONBRAINMASK} ${WMPRIOR} ${GMPRIOR} ${CSFPRIOR} ${RESAMPLEMODEL} ${RESAMPLEMODELBRAINMASK} ${BEAST_CONFIG}; do
if [[ ! -s ${prior} ]]; then
echo "iterativeN4_multispectral.sh ERROR: File ${prior} does not exist or is zero size" && exit 3
fi
done
#Setup internal variables
output=${_arg_output}
originput=${_arg_input}
#Internal resampled input used for processing
input=${tmpdir}/t1.mnc
function outlier_mask() {
#Generate an outlier mask which combines the vessel segmentation >4.75 * MAD of WM
local outlier_input=$1
local outlier_mask=$2
local outlier_output=$3
local median
local mad
median=$(mincstats -quiet -median -mask ${outlier_mask} -mask_binvalue 1 ${outlier_input})
minccalc -quiet ${N4_VERBOSE:+-verbose} -clobber -expression "abs(A[0]-${median})" ${outlier_input} ${tmpdir}/${n}/madmap.mnc
mad=$(mincstats -quiet -median -mask ${outlier_mask} -mask_binvalue 1 ${tmpdir}/${n}/madmap.mnc)
minccalc -quiet ${N4_VERBOSE:+-verbose} -clobber -unsigned -byte -expression "(((0.6745*(A[0]-${median}))/${mad})<4.75)&&(A[1]<45)?1:0" \
${outlier_input} ${tmpdir}/vessels.mnc ${outlier_output}
}
function renorm() {
#Renormalize image 0.1%-(GM/WM mean)-99.9% to 0-32767-65535 using a classification mask
#Compute the percentiles using the GM/WM mask
#Achieved via solving a linear system to get a 2nd order polynomial remapping
#of the intensity values
local renorm_input=$1
local renorm_classification=$2
local usebrainmask="${3:-}"
local wmbinvalue
local gmbinvalue
if [[ -n ${usebrainmask} ]]; then
wmbinvalue=1
gmbinvalue=1
else
wmbinvalue=3
gmbinvalue=2
fi
#Compute the percentiles and median values of GM and WM
valuelow=$(mincstats -quiet -mask ${tmpdir}/headmask.mnc -mask_binvalue 1 -pctT 1 ${renorm_input})
valuewm=$(mincstats -quiet -median -mask ${renorm_classification} -mask_binvalue ${wmbinvalue} ${renorm_input})
valuegm=$(mincstats -quiet -median -mask ${renorm_classification} -mask_binvalue ${gmbinvalue} ${renorm_input})
valuehigh=$(mincstats -quiet -mask ${tmpdir}/headmask.mnc -mask_binvalue 1 -pctT 99 ${renorm_input})
#Solve the linear system of a quadratic polynomial mapping the input values to 0-32767-65535
mapping=($(python -c "import numpy as np; print(np.array2string(np.linalg.solve(np.array([[1, ${valuelow}, ${valuelow}**2], [1, ((${valuewm}+${valuegm})/2.0), ((${valuewm}+${valuegm})/2.0)**2], [1, ${valuehigh}, ${valuehigh}**2]]),np.array([0,32767,65535])),separator= ' ')[1:-1])"))
#Apply the mpapping
minccalc -quiet ${N4_VERBOSE:+-verbose} -short -unsigned -expression "clamp(A[0]^2*${mapping[2]} + A[0]*${mapping[1]} + ${mapping[0]},0,65535)" \
${renorm_input} $(dirname ${renorm_input})/$(basename ${renorm_input} .mnc).norm.mnc
mv -f $(dirname ${renorm_input})/$(basename ${renorm_input} .mnc).norm.mnc ${renorm_input}
}
#Function used to do bias field correction
function do_N4_correct() {
#input fov mask weight output bias shrink classifymask
local n4input=$1
local n4initmask=$2
local n4brainmask=$3
local n4weight=$4
local n4corrected=$5
local n4bias=$6
local n4shrink=$7
local n4classifymask=$8
#Estimate bias field
N4BiasFieldCorrection ${N4_VERBOSE:+--verbose} -d 3 -s ${n4shrink} -w ${n4weight} -x ${n4initmask} \
-b [ 200 ] -c [ 300x300x300x300,1e-5 ] --histogram-sharpening [ 0.05,0.01,200 ] \
-i ${tmpdir}/${n}/t1.mnc \
-o [ ${n4corrected},${tmpdir}/${n}/bias2.mnc ] -r 0
ImageMath 3 ${tmpdir}/${n}/bias2.mnc / ${tmpdir}/${n}/bias2.mnc $(mincstats -quiet -mean ${tmpdir}/${n}/bias2.mnc)
ImageMath 3 ${n4bias} m ${tmpdir}/prebias.mnc ${tmpdir}/${n}/bias2.mnc
ImageMath 3 ${n4bias} / ${n4bias} $(mincstats -quiet -mean ${n4bias})
ImageMath 3 ${n4corrected} / ${n4input} ${n4bias}
cp -f ${n4bias} ${tmpdir}/prebias.mnc
renorm ${n4corrected} ${n4classifymask}
}
function iterative_precorrect() {
local pctTlow
local pctThigh
#Foreground/background via multi-level otsu
ThresholdImage 3 ${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/weight1.mnc Otsu 4 ${tmpdir}/nonzero.mnc
ThresholdImage 3 ${tmpdir}/${n}/weight1.mnc ${tmpdir}/${n}/weight1.mnc 2 Inf 1 0
ImageMath 3 ${tmpdir}/${n}/weight1.mnc GetLargestComponent ${tmpdir}/${n}/weight1.mnc
iMath 3 ${tmpdir}/${n}/weight1.mnc MC ${tmpdir}/${n}/weight1.mnc 2 1 ball 1
ImageMath 3 ${tmpdir}/${n}/weight1.mnc FillHoles ${tmpdir}/${n}/weight1.mnc 2
cp -f ${tmpdir}/${n}/weight1.mnc ${tmpdir}/${n}/mask1.mnc
ImageMath 3 ${tmpdir}/${n}/weight1.mnc m ${tmpdir}/${n}/weight1.mnc ${tmpdir}/nonzero.mnc
ImageMath 3 ${tmpdir}/${n}/weight1.mnc GetLargestComponent ${tmpdir}/${n}/weight1.mnc
#Exclude Hotspots
minccalc -quiet ${N4_VERBOSE:+-verbose} \
-expression "A[0]<$(mincstats -quiet -mask ${tmpdir}/${n}/mask1.mnc -mask_binvalue 1 -pctT 99.9 ${tmpdir}/${n}/t1.mnc)?A[1]:0" \
${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/weight1.mnc ${tmpdir}/${n}/weighttemp.mnc
mv -f ${tmpdir}/${n}/weighttemp.mnc ${tmpdir}/${n}/weight1.mnc
#First round of correction
N4BiasFieldCorrection -d 3 -i ${tmpdir}/${n}/t1.mnc -b [ 200 ] -c [ 50x50x50x50,0 ] \
-w ${tmpdir}/${n}/weight1.mnc -o [ ${tmpdir}/${n}/t1.mnc,${tmpdir}/${n}/bias.mnc ] -s 4 --verbose \
--histogram-sharpening [ 0.15,0.01,200 ] -r 0 -x ${tmpdir}/initmask.mnc
ImageMath 3 ${tmpdir}/${n}/bias.mnc / ${tmpdir}/${n}/bias.mnc \
$(mincstats -quiet -mean ${tmpdir}/${n}/bias.mnc)
ImageMath 3 ${tmpdir}/${n}/t1.mnc / ${input} ${tmpdir}/${n}/bias.mnc
#Renormalize intensity
pctTlow=$(mincstats -quiet -mask ${tmpdir}/${n}/mask1.mnc -mask_binvalue 1 -pctT 0.1 ${tmpdir}/${n}/t1.mnc)
pctThigh=$(mincstats -quiet -mask ${tmpdir}/${n}/mask1.mnc -mask_binvalue 1 -pctT 99.9 ${tmpdir}/${n}/t1.mnc)
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} -expression "clamp(clamp(A[0]-${pctTlow},0,65535)/(${pctThigh}-${pctTlow})*65535,0,65535)" \
${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/t1.norm.mnc
mv -f ${tmpdir}/${n}/t1.norm.mnc ${tmpdir}/${n}/t1.mnc
#Second round Foreground/background via multi-level otsu
ThresholdImage 3 ${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/weight2.mnc Otsu 4 ${tmpdir}/nonzero.mnc
ThresholdImage 3 ${tmpdir}/${n}/weight2.mnc ${tmpdir}/${n}/weight2.mnc 2 Inf 1 0
ImageMath 3 ${tmpdir}/${n}/weight2.mnc GetLargestComponent ${tmpdir}/${n}/weight2.mnc
iMath 3 ${tmpdir}/${n}/weight2.mnc MC ${tmpdir}/${n}/weight2.mnc 3 1 ball 1
ImageMath 3 ${tmpdir}/${n}/weight2.mnc FillHoles ${tmpdir}/${n}/weight2.mnc 2
cp -f ${tmpdir}/${n}/weight2.mnc ${tmpdir}/${n}/mask2.mnc
cp -f ${tmpdir}/${n}/mask2.mnc ${tmpdir}/fgmask.mnc
ImageMath 3 ${tmpdir}/${n}/weight2.mnc m ${tmpdir}/${n}/weight2.mnc ${tmpdir}/nonzero.mnc
ImageMath 3 ${tmpdir}/${n}/weight2.mnc GetLargestComponent ${tmpdir}/${n}/weight2.mnc
pctTlow=$(mincstats -quiet -mask ${tmpdir}/${n}/mask2.mnc -mask_binvalue 1 -pctT 0.1 ${input})
pctThigh=$(mincstats -quiet -mask ${tmpdir}/${n}/mask2.mnc -mask_binvalue 1 -pctT 99.9 ${input})
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} -expression "clamp(clamp(A[0]-${pctTlow},0,65535)/(${pctThigh}-${pctTlow})*65535,0,65535)" \
${input} ${tmpdir}/${n}/t1.mnc
cp ${tmpdir}/${n}/t1.mnc ${tmpdir}/t1.renorm.mnc
input=${tmpdir}/t1.renorm.mnc
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} -unsigned -byte -expression 'A[0]>1.01?1:0' ${input} ${tmpdir}/nonzero.mnc
ImageMath 3 ${tmpdir}/${n}/weight2.mnc m ${tmpdir}/${n}/weight2.mnc ${tmpdir}/nonzero.mnc
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} \
-expression "A[0]<$(mincstats -quiet -mask ${tmpdir}/${n}/mask2.mnc -mask_binvalue 1 -pctT 99.5 ${tmpdir}/${n}/t1.mnc)?A[1]:0" \
${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/weight2.mnc ${tmpdir}/${n}/weighttemp.mnc
mv -f ${tmpdir}/${n}/weighttemp.mnc ${tmpdir}/${n}/weight2.mnc
N4BiasFieldCorrection -d 3 -i ${tmpdir}/${n}/t1.mnc -b [ 200 ] -c [ 50x50x50x50,0 ] \
-w ${tmpdir}/${n}/weight2.mnc -o [ ${tmpdir}/${n}/t1.mnc,${tmpdir}/${n}/bias.mnc ] -s 4 --verbose \
--histogram-sharpening [ 0.15,0.01,200 ] -r 0 -x ${tmpdir}/initmask.mnc
ImageMath 3 ${tmpdir}/${n}/bias.mnc / ${tmpdir}/${n}/bias.mnc \
$(mincstats -quiet -mean ${tmpdir}/${n}/bias.mnc)
ImageMath 3 ${tmpdir}/${n}/t1.mnc / ${input} ${tmpdir}/${n}/bias.mnc
pctTlow=$(mincstats -quiet -mask ${tmpdir}/${n}/mask2.mnc -mask_binvalue 1 -pctT 0.1 ${tmpdir}/${n}/t1.mnc)
pctThigh=$(mincstats -quiet -mask ${tmpdir}/${n}/mask2.mnc -mask_binvalue 1 -pctT 99.9 ${tmpdir}/${n}/t1.mnc)
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} -expression "clamp(clamp(A[0]-${pctTlow},0,65535)/(${pctThigh}-${pctTlow})*65535,0,65535)" \
${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/t1.norm.mnc
mv -f ${tmpdir}/${n}/t1.norm.mnc ${tmpdir}/${n}/t1.mnc
cp -f ${tmpdir}/${n}/bias.mnc ${tmpdir}/${n}/prebias.mnc
itk_vesselness --scales 8 --rescale ${tmpdir}/${n}/t1.mnc ${tmpdir}/vessels.mnc
i=0
#Iterative correction using tissue masking, some badly biased scans can't be
#corrected in one-shot
while true; do
ThresholdImage 3 ${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/otsu.mnc Otsu 4 ${tmpdir}/${n}/mask$((2 + i)).mnc
ThresholdImage 3 ${tmpdir}/${n}/otsu.mnc ${tmpdir}/${n}/otsu.mnc 2 Inf 1 0
ImageMath 3 ${tmpdir}/${n}/mask$((3 + i)).mnc GetLargestComponent ${tmpdir}/${n}/otsu.mnc
iMath 3 ${tmpdir}/${n}/mask$((3 + i)).mnc MC ${tmpdir}/${n}/mask$((3 + i)).mnc 8 1 ball 1
ImageMath 3 ${tmpdir}/${n}/mask$((3 + i)).mnc FillHoles ${tmpdir}/${n}/mask$((3 + i)).mnc 2
cp -f ${tmpdir}/${n}/mask$((3 + i)).mnc ${tmpdir}/fgmask.mnc
if [[ $i == 0 ]]; then
ImageMath 3 ${tmpdir}/${n}/weight$((3 + i)).mnc + ${tmpdir}/${n}/otsu.mnc ${tmpdir}/${n}/mask$((2 + i)).mnc
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} \
-expression "(A[0]<45)&&(A[1]<$(mincstats -quiet -mask ${tmpdir}/${n}/mask$((2 + i)).mnc -mask_binvalue 1 -pctT 99.5 ${tmpdir}/${n}/t1.mnc))?A[2]:0" \
${tmpdir}/vessels.mnc ${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/otsu.mnc ${tmpdir}/${n}/weight$((3 + i)).mnc
else
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} \
-expression "(A[0]<45)&&(A[1]<$(mincstats -quiet -mask ${tmpdir}/${n}/mask$((2 + i)).mnc -mask_binvalue 1 -pctT 99.5 ${tmpdir}/${n}/t1.mnc))?A[2]:0" \
${tmpdir}/vessels.mnc ${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/otsu.mnc ${tmpdir}/${n}/weight$((3 + i)).mnc
iMath 3 ${tmpdir}/${n}/weight$((3 + i)).mnc ME ${tmpdir}/${n}/otsu.mnc 1 1 ball 1
ImageMath 3 ${tmpdir}/${n}/weight$((3 + i)).mnc GetLargestComponent ${tmpdir}/${n}/weight$((3 + i)).mnc
iMath 3 ${tmpdir}/${n}/weight$((3 + i)).mnc MD ${tmpdir}/${n}/weight$((3 + i)).mnc 1 1 ball 1
fi
N4BiasFieldCorrection -d 3 -i ${tmpdir}/${n}/t1.mnc -b [ 200 ] -c [ 300x300x300x300,1e-4 ] \
-w ${tmpdir}/${n}/weight$((3 + i)).mnc -o [ ${tmpdir}/${n}/t1.mnc,${tmpdir}/${n}/bias.mnc ] -s 2 --verbose \
--histogram-sharpening [ 0.05,0.01,200 ] -r 0 -x ${tmpdir}/initmask.mnc
ImageMath 3 ${tmpdir}/${n}/bias.mnc / ${tmpdir}/${n}/bias.mnc $(mincstats -quiet -mean ${tmpdir}/${n}/bias.mnc)
ImageMath 3 ${tmpdir}/${n}/prebias.mnc m ${tmpdir}/${n}/prebias.mnc ${tmpdir}/${n}/bias.mnc
ImageMath 3 ${tmpdir}/${n}/prebias.mnc / ${tmpdir}/${n}/prebias.mnc $(mincstats -quiet -mean ${tmpdir}/${n}/prebias.mnc)
ImageMath 3 ${tmpdir}/${n}/t1.mnc / ${input} ${tmpdir}/${n}/prebias.mnc
((++i))
[[ ( ${i} -le 2 ) ]] || break
pctTlow=$(mincstats -quiet -mask ${tmpdir}/${n}/mask$((2 + i)).mnc -mask_binvalue 1 -pctT 0.1 ${tmpdir}/${n}/t1.mnc)
pctThigh=$(mincstats -quiet -mask ${tmpdir}/${n}/mask$((2 + i)).mnc -mask_binvalue 1 -pctT 99.9 ${tmpdir}/${n}/t1.mnc)
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} -expression "clamp(clamp(A[0]-${pctTlow},0,65535)/(${pctThigh}-${pctTlow})*65535,0,65535)" \
${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/t1.norm.mnc
mv -f ${tmpdir}/${n}/t1.norm.mnc ${tmpdir}/${n}/t1.mnc
done
pctThigh=$(mincstats -quiet -mask ${tmpdir}/${n}/mask5.mnc -mask_binvalue 1 -pctT 99.9 ${tmpdir}/${n}/t1.mnc)
pctTlow=$(mincstats -quiet -mask ${tmpdir}/${n}/mask5.mnc -mask_binvalue 1 -pctT 0.1 ${tmpdir}/${n}/t1.mnc)
minccalc -quiet ${N4_VERBOSE:+-verbose} -short -unsigned -expression "clamp(clamp(A[0]-${pctTlow},0,65535)/(${pctThigh}-${pctTlow})*65535,0,65535)" \
${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/corrected.mnc
minc_anlm ${N4_VERBOSE:+--verbose} --clobber --mt ${ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS} ${tmpdir}/${n}/corrected.mnc ${tmpdir}/${n}/t1.mnc
}
function classify_to_mask() {
#Convert classify image into a mask
#Mostly a clone of the supersteps of the antsBrainExtraction supersteps
ThresholdImage 3 ${tmpdir}/${n}/classify.mnc ${tmpdir}/${n}/gm.mnc 2 2 1 0
ThresholdImage 3 ${tmpdir}/${n}/classify.mnc ${tmpdir}/${n}/wm.mnc 3 3 1 0
ImageMath 3 ${tmpdir}/${n}/gm.mnc GetLargestComponent ${tmpdir}/${n}/gm.mnc
ImageMath 3 ${tmpdir}/${n}/wm.mnc GetLargestComponent ${tmpdir}/${n}/wm.mnc
ImageMath 3 ${tmpdir}/${n}/gm.mnc FillHoles ${tmpdir}/${n}/gm.mnc 2
ImageMath 3 ${tmpdir}/${n}/classifymask.mnc addtozero ${tmpdir}/${n}/gm.mnc ${tmpdir}/${n}/wm.mnc
iMath 3 ${tmpdir}/${n}/classifymask.mnc ME ${tmpdir}/${n}/classifymask.mnc 1 1 ball 1
ImageMath 3 ${tmpdir}/${n}/classifymask.mnc GetLargestComponent ${tmpdir}/${n}/classifymask.mnc
iMath 3 ${tmpdir}/${n}/classifymask.mnc MD ${tmpdir}/${n}/classifymask.mnc 2 1 ball 1
iMath 3 ${tmpdir}/bmask_E.mnc ME ${tmpdir}/masks/mnimask.mnc 10 1 ball 1
ImageMath 3 ${tmpdir}/${n}/classifymask.mnc addtozero ${tmpdir}/${n}/classifymask.mnc ${tmpdir}/bmask_E.mnc
ImageMath 3 ${tmpdir}/${n}/classifymask.mnc FillHoles ${tmpdir}/${n}/classifymask.mnc 2
}
function make_qc() {
#Generate a standardized view of the final correct brain in MNI space, with classification overlayed
#Create animated version if img2webp is available
mkdir -p ${tmpdir}/qc
#Resample into MNI space for all the inputs
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 ${MNI_XFM:+-t ${MNI_XFM}} -t ${tmpdir}/mni0_GenericAffine.xfm \
-i ${tmpdir}/${n}/classify.mnc -o ${tmpdir}/qc/classify.mnc -r ${RESAMPLEMODEL} -n GenericLabel
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 ${MNI_XFM:+-t ${MNI_XFM}} -t ${tmpdir}/mni0_GenericAffine.xfm \
-i ${tmpdir}/corrected.mnc -o ${tmpdir}/qc/corrected.mnc -r ${RESAMPLEMODEL} -n BSpline[5]
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 ${MNI_XFM:+-t ${MNI_XFM}} -t ${tmpdir}/mni0_GenericAffine.xfm \
-i ${tmpdir}/origqcref.mnc -o ${tmpdir}/qc/orig.mnc -r ${RESAMPLEMODEL} -n BSpline[5]
mincmath -clobber -quiet ${N4_VERBOSE:+-verbose} -clamp -const2 0 65535 ${tmpdir}/qc/corrected.mnc ${tmpdir}/qc/corrected.clamp.mnc
mv -f ${tmpdir}/qc/corrected.clamp.mnc ${tmpdir}/qc/corrected.mnc
mincmath -clobber -quiet ${N4_VERBOSE:+-verbose} -clamp -const2 0 65535 ${tmpdir}/qc/orig.mnc ${tmpdir}/qc/orig.clamp.mnc
mv -f ${tmpdir}/qc/orig.clamp.mnc ${tmpdir}/qc/orig.mnc
#Create the bounding box for create_verify_image
mincresample -clobber -quiet ${N4_VERBOSE:+-verbose} $(mincbbox -mincresample ${tmpdir}/qc/classify.mnc) ${tmpdir}/qc/classify.mnc ${tmpdir}/qc/label-crop.mnc
minccalc -quiet ${N4_VERBOSE:+-verbose} -unsigned -byte -expression '1' ${tmpdir}/qc/label-crop.mnc ${tmpdir}/qc/bounding.mnc
#Trasverse
create_verify_image -range_floor 0 ${tmpdir}/qc/trans_classify.rgb \
-width 1920 -autocols 10 -autocol_planes t \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/corrected.mnc color:gray:0:65535 \
volume_overlay:${tmpdir}/qc/classify.mnc:0.4
create_verify_image -range_floor 0 ${tmpdir}/qc/trans_corrected.rgb \
-width 1920 -autocols 10 -autocol_planes t \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/corrected.mnc color:spect:0:65535
create_verify_image -range_floor 0 ${tmpdir}/qc/trans_corrected_gray.rgb \
-width 1920 -autocols 10 -autocol_planes t \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/corrected.mnc color:gray:0:65535
create_verify_image -range_floor 0 ${tmpdir}/qc/trans_orig.rgb \
-width 1920 -autocols 10 -autocol_planes t \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/orig.mnc color:spect:0:65535
#Sagital
create_verify_image -range_floor 0 ${tmpdir}/qc/sag_classify.rgb \
-width 1920 -autocols 10 -autocol_planes s \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/corrected.mnc color:gray:0:65535 \
volume_overlay:${tmpdir}/qc/classify.mnc:0.4
create_verify_image -range_floor 0 ${tmpdir}/qc/sag_corrected.rgb \
-width 1920 -autocols 10 -autocol_planes s \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/corrected.mnc color:spect:0:65535
create_verify_image -range_floor 0 ${tmpdir}/qc/sag_corrected_gray.rgb \
-width 1920 -autocols 10 -autocol_planes s \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/corrected.mnc color:gray:0:65535
create_verify_image -range_floor 0 ${tmpdir}/qc/sag_orig.rgb \
-width 1920 -autocols 10 -autocol_planes s \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/orig.mnc color:spect:0:65535
#Coronal
create_verify_image -range_floor 0 ${tmpdir}/qc/cor_classify.rgb \
-width 1920 -autocols 10 -autocol_planes c \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/corrected.mnc color:gray:0:65535 \
volume_overlay:${tmpdir}/qc/classify.mnc:0.4
create_verify_image -range_floor 0 ${tmpdir}/qc/cor_corrected.rgb \
-width 1920 -autocols 10 -autocol_planes c \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/corrected.mnc color:spect:0:65535
create_verify_image -range_floor 0 ${tmpdir}/qc/cor_corrected_gray.rgb \
-width 1920 -autocols 10 -autocol_planes c \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/corrected.mnc color:gray:0:65535
create_verify_image -range_floor 0 ${tmpdir}/qc/cor_orig.rgb \
-width 1920 -autocols 10 -autocol_planes c \
-bounding_volume ${tmpdir}/qc/bounding.mnc \
-row ${tmpdir}/qc/orig.mnc color:spect:0:65535
convert -background black -strip -append \
${tmpdir}/qc/cor_corrected.rgb \
${tmpdir}/qc/cor_classify.rgb \
${tmpdir}/qc/sag_corrected.rgb \
${tmpdir}/qc/sag_classify.rgb \
${tmpdir}/qc/trans_corrected.rgb \
${tmpdir}/qc/trans_classify.rgb \
${tmpdir}/qc/corrected.mpc
convert -background black -strip -append \
${tmpdir}/qc/cor_orig.rgb \
${tmpdir}/qc/cor_corrected_gray.rgb \
${tmpdir}/qc/sag_orig.rgb \
${tmpdir}/qc/sag_corrected_gray.rgb \
${tmpdir}/qc/trans_orig.rgb \
${tmpdir}/qc/trans_corrected_gray.rgb \
${tmpdir}/qc/orig.mpc
#Save static QC jpg
convert -background black -strip -interlace Plane -sampling-factor 4:2:0 -quality "85%" \
${tmpdir}/qc/corrected.mpc $(dirname ${output})/$(basename ${output} .mnc).jpg
#If webp software is available animate a before/after image
if command -v img2webp; then
convert -background black ${tmpdir}/qc/corrected.mpc ${tmpdir}/qc/corrected.png
convert -background black ${tmpdir}/qc/orig.mpc ${tmpdir}/qc/orig.png
img2webp -d 750 -lossy -min_size ${tmpdir}/qc/corrected.png ${tmpdir}/qc/orig.png -o $(dirname ${output})/$(basename ${output} .mnc).webp || true
fi
}
function test_templates() {
#Automatic template selection for most similar template for use as prior
#Loop over the configs/auto config files and choose the best one based on ants CC
mkdir -p ${tmpdir}/test_templates
for configfile in $(dirname "$(readlink -f "$0")")/configs/auto/*cfg; do
source ${configfile}
antsRegistration ${N4_VERBOSE:+--verbose} -d 3 --float 1 --minc \
--output [ ${tmpdir}/test_templates/$(basename ${configfile} .cfg),${tmpdir}/test_templates/$(basename ${configfile} .cfg).mnc ] \
--use-histogram-matching 1 \
--initial-moving-transform [ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1 ] \
--transform Translation[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,32,None ] \
--convergence [ 500x500x500x500x500x500x500x500,1e-6,10 ] \
--shrink-factors 6x6x6x6x6x6x6x6 \
--smoothing-sigmas 6.35574237559x5.93006674681x5.50423435717x5.07820577132x4.65192708599x4.22532260674x3.79828256043x3.37064139994mm \
--masks [ NOMASK,NOMASK ] \
--transform Rigid[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,32,None ] \
--convergence [ 500x500x500x500x500x500x500,1e-6,10 ] \
--shrink-factors 6x6x6x6x6x6x5 \
--smoothing-sigmas 4.65192708599x4.22532260674x3.79828256043x3.37064139994x2.94213702015x2.51232776601x2.08040503813mm \
--masks [ NOMASK,NOMASK ] \
--transform Similarity[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,32,None ] \
--convergence [ 500x500x500x500x450x150,1e-6,10 ] \
--shrink-factors 6x6x5x4x3x2 \
--smoothing-sigmas 2.94213702015x2.51232776601x2.08040503813x1.64470459404x1.20112240879x0.735534255037mm \
--masks [ NOMASK,NOMASK ] \
--transform Similarity[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,32,None ] \
--convergence [ 500x500x500x500x450x150,1e-6,10 ] \
--shrink-factors 6x6x5x4x3x2 \
--smoothing-sigmas 2.94213702015x2.51232776601x2.08040503813x1.64470459404x1.20112240879x0.735534255037mm \
--masks [ ${REGISTRATIONBRAINMASK},NOMASK ] \
--transform Affine[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,64,None ] \
--convergence [ 500x450x150x50,1e-6,10 ] \
--shrink-factors 4x3x2x1 \
--smoothing-sigmas 1.64470459404x1.20112240879x0.735534255037x0.0mm \
--masks [ ${REGISTRATIONBRAINMASK},NOMASK ]
echo ${configfile},$(MeasureImageSimilarity -d 3 -m CC[${REGISTRATIONMODEL},${tmpdir}/test_templates/$(basename ${configfile} .cfg).mnc,1,4] \
-x ${REGISTRATIONBRAINMASK}) >> ${tmpdir}/test_templates/results.csv
done
#Prep and load winner template
unset MNI_XFM
echo "Choosing template $(sort -k2 -g -t, ${tmpdir}/test_templates/results.csv | cut -d"," -f 1 | head -1)"
source $(sort -k2 -g -t, ${tmpdir}/test_templates/results.csv | cut -d"," -f 1 | head -1)
#Store template registration for later use
cp -f ${tmpdir}/test_templates/$(basename $(sort -k2 -g -t, ${tmpdir}/test_templates/results.csv | cut -d"," -f 1 | head -1) .cfg)0_GenericAffine.xfm ${tmpdir}/template_bootstrap.xfm
if [[ ${_arg_debug} == "off" ]]; then
rm -rf ${tmpdir}/test_templates
fi
}
##########START OF SCRIPT#############
#Forceably convert to MINC2, and clamp range to avoid negative numbers, rescale to 0-65535
mincconvert -2 ${originput} ${tmpdir}/originput.mnc
#Rescale initial data into entirely positive range (fix for completely negative data)
ImageMath 3 ${tmpdir}/originput.mnc RescaleImage ${tmpdir}/originput.mnc 0 65535
#Very mild range clamp for very hot voxels
mincmath -quiet ${N4_VERBOSE:+-verbose} -clamp \
-const2 $(mincstats -quiet -floor 1e-12 -pctT 0.1 ${tmpdir}/originput.mnc) \
$(mincstats -quiet -floor 1e-12 -pctT 99.9 ${tmpdir}/originput.mnc) \
${tmpdir}/originput.mnc ${tmpdir}/originput.clamp.mnc
ImageMath 3 ${tmpdir}/originput.clamp.mnc RescaleImage ${tmpdir}/originput.clamp.mnc 0 65535
mincresample -quiet ${N4_VERBOSE:+-verbose} -like ${tmpdir}/originput.mnc -keep -unsigned -short \
${tmpdir}/originput.clamp.mnc ${tmpdir}/originput.clamp.resample.mnc
mv -f ${tmpdir}/originput.clamp.resample.mnc ${tmpdir}/originput.mnc
rm -f ${tmpdir}/originput.clamp.mnc
originput=${tmpdir}/originput.mnc
cp -f ${originput} ${tmpdir}/origqcref.mnc
#Isotropize, and normalize intensity range, this is the file that will be processed in the pipeline
#Need smoothing for downsampling to avoid aliasing
#Ideas stolen from https://discourse.itk.org/t/resampling-to-isotropic-signal-processing-theory/1403
isostep=1.0
inputres=$(python -c "print('\n'.join([str(abs(x)) for x in [float(x) for x in \"$(PrintHeader ${originput} 1)\".split(\"x\")]]))")
blurs=""
for dim in ${inputres}; do
if [[ $(python -c "print(${dim}>(${isostep}-1e-6))") == True ]]; then
blurs+=1e-12x
else
blurs+=$(python -c "import math; print(math.sqrt((${isostep}**2.0 - ${dim}**2.0)/(2.0*math.sqrt(2.0*math.log(2.0)))**2.0))")x
fi
done
SmoothImage 3 ${originput} "${blurs%?}" ${tmpdir}/smoothed.mnc 1 0
ResampleImage 3 ${tmpdir}/smoothed.mnc ${input} ${isostep}x${isostep}x${isostep} 0 4
mincmath -quiet ${N4_VERBOSE:+-verbose} -clamp -const2 0 $(mincstats -max -quiet ${input}) ${input} ${tmpdir}/input.clamp.mnc
ImageMath 3 ${input} RescaleImage ${tmpdir}/input.clamp.mnc 0 65535
rm -f ${tmpdir}/input.clamp.mnc
ImageMath 3 ${input} PadImage ${input} 20
#Generate a global nonzero mask to always exclude pure background
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} -unsigned -byte -expression 'A[0]>1.01?1:0' ${input} ${tmpdir}/nonzero.mnc
#If exclusion mask exists, negate it to produce a multiplicative exlcusion mask, resample to internal resolution
if [[ -n ${_arg_exclude} ]]; then
ImageMath 3 ${tmpdir}/exclude.mnc Neg ${_arg_exclude}
excludemask=${tmpdir}/exclude.mnc
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 -i ${excludemask} -r ${input} -n GenericLabel -o ${excludemask}
else
excludemask=""
fi
mkdir -p ${tmpdir}/masks
################################################################################
#Round 0
#Iterative estimation of a mask with multilevel otsu to find foreground-background
#Also found forground mask and use it combined to template FOV registration to
#trim the FOV to generate a headmask
################################################################################
n=0
mkdir -p ${tmpdir}/${n}
minc_anlm ${N4_VERBOSE:+--verbose} --mt ${ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS} ${input} ${tmpdir}/${n}/t1.mnc
iterative_precorrect
#If the "auto" template method is selected, do the registrations and CC
#estimate to find best matching model
if [[ ${_arg_config} == "auto" ]]; then
test_templates
fi
#Register to model to resample back a FOV mask
if [[ -s ${tmpdir}/template_bootstrap.xfm ]]; then
cp -f ${tmpdir}/template_bootstrap.xfm ${tmpdir}/${n}/mni0_GenericAffine.xfm
else
antsRegistration ${N4_VERBOSE:+--verbose} -d 3 --float 1 --minc \
--output [ ${tmpdir}/${n}/mni ] \
--use-histogram-matching 1 \
--initial-moving-transform [ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1 ] \
--transform Translation[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,32,None ] \
--convergence [ 500x500x500x500x500x500x500x500,1e-6,10 ] \
--shrink-factors 6x6x6x6x6x6x6x6 \
--smoothing-sigmas 6.35574237559x5.93006674681x5.50423435717x5.07820577132x4.65192708599x4.22532260674x3.79828256043x3.37064139994mm \
--masks [ NOMASK,NOMASK ] \
--transform Rigid[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,32,None ] \
--convergence [ 500x500x500x500x500x500x500,1e-6,10 ] \
--shrink-factors 6x6x6x6x6x6x5 \
--smoothing-sigmas 4.65192708599x4.22532260674x3.79828256043x3.37064139994x2.94213702015x2.51232776601x2.08040503813mm \
--masks [ NOMASK,NOMASK ] \
--transform Similarity[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,32,None ] \
--convergence [ 500x500x500x500x450x150,1e-6,10 ] \
--shrink-factors 6x6x5x4x3x2 \
--smoothing-sigmas 2.94213702015x2.51232776601x2.08040503813x1.64470459404x1.20112240879x0.735534255037mm \
--masks [ NOMASK,NOMASK ] \
--transform Similarity[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,32,None ] \
--convergence [ 500x500x500x500x450x150,1e-6,10 ] \
--shrink-factors 6x6x5x4x3x2 \
--smoothing-sigmas 2.94213702015x2.51232776601x2.08040503813x1.64470459404x1.20112240879x0.735534255037mm \
--masks [ ${REGISTRATIONBRAINMASK},NOMASK ] \
--transform Affine[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,64,None ] \
--convergence [ 500x450x150x0,1e-6,10 ] \
--shrink-factors 4x3x2x1 \
--smoothing-sigmas 1.64470459404x1.20112240879x0.735534255037x0.0mm \
--masks [ ${REGISTRATIONBRAINMASK},NOMASK ]
fi
#Make a fov mask from all 1's of the
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} -unsigned -byte -expression '1' ${REGISTRATIONMODEL} ${tmpdir}/modelfovmask.mnc
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 -i ${tmpdir}/modelfovmask.mnc \
-t [ ${tmpdir}/${n}/mni0_GenericAffine.xfm,1 ] -o ${tmpdir}/headmask.mnc -r ${tmpdir}/${n}/t1.mnc -n GenericLabel
#Headmask is intersection of filled otsu foreground mask and FOV from model
ImageMath 3 ${tmpdir}/headmask.mnc m ${tmpdir}/headmask.mnc ${tmpdir}/fgmask.mnc
cp -f ${tmpdir}/fgmask.mnc ${tmpdir}/fgmask_orig.mnc
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} \
-expression "(A[0]<45)&&(A[1]<$(mincstats -quiet -mask ${tmpdir}/headmask.mnc -mask_binvalue 1 -pctT 99.5 ${tmpdir}/${n}/t1.mnc))?A[2]:0" \
${tmpdir}/vessels.mnc ${tmpdir}/${n}/t1.mnc ${tmpdir}/headmask.mnc ${tmpdir}/${n}/otsu.mnc
ThresholdImage 3 ${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/otsu.mnc Otsu 4 ${tmpdir}/${n}/otsu.mnc
ThresholdImage 3 ${tmpdir}/${n}/otsu.mnc ${tmpdir}/${n}/weight6.mnc 2 Inf 1 0
ThresholdImage 3 ${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/otsu.mnc Otsu 4 ${tmpdir}/${n}/weight6.mnc
ThresholdImage 3 ${tmpdir}/${n}/otsu.mnc ${tmpdir}/${n}/weight6.mnc 2 Inf 1 0
iMath 3 ${tmpdir}/${n}/weight6.mnc ME ${tmpdir}/${n}/weight6.mnc 1 1 ball 1
ImageMath 3 ${tmpdir}/${n}/weight6.mnc GetLargestComponent ${tmpdir}/${n}/weight6.mnc
iMath 3 ${tmpdir}/${n}/weight6.mnc MD ${tmpdir}/${n}/weight6.mnc 1 1 ball 1
#Use exclude mask if provided
if [[ -n ${excludemask} ]]; then
ImageMath 3 ${tmpdir}/${n}/weight6.mnc m ${tmpdir}/${n}/weight6.mnc ${excludemask}
fi
N4BiasFieldCorrection -d 3 -i ${tmpdir}/${n}/t1.mnc -b [ 200 ] -c [ 300x300x300x300,1e-4 ] \
-w ${tmpdir}/${n}/weight6.mnc -o [ ${tmpdir}/${n}/t1.mnc,${tmpdir}/${n}/bias.mnc ] -s 2 --verbose \
--histogram-sharpening [ 0.05,0.01,200 ] -r 0
ImageMath 3 ${tmpdir}/${n}/bias.mnc / ${tmpdir}/${n}/bias.mnc $(mincstats -quiet -mean ${tmpdir}/${n}/bias.mnc)
ImageMath 3 ${tmpdir}/${n}/prebias.mnc m ${tmpdir}/${n}/prebias.mnc ${tmpdir}/${n}/bias.mnc
ImageMath 3 ${tmpdir}/${n}/prebias.mnc / ${tmpdir}/${n}/prebias.mnc $(mincstats -quiet -mean ${tmpdir}/${n}/prebias.mnc)
ImageMath 3 ${tmpdir}/${n}/t1.mnc / ${input} ${tmpdir}/${n}/prebias.mnc
renorm ${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/weight6.mnc usemask
cp ${tmpdir}/${n}/t1.mnc ${tmpdir}/${n}/corrected.mnc
#Resample headmask into subject space, zero background and recrop
ImageMath 3 ${input} PadImage ${input} 50
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 -i ${tmpdir}/headmask.mnc -o ${tmpdir}/headmask.mnc -r ${input} -n GenericLabel
ImageMath 3 ${input} m ${input} ${tmpdir}/headmask.mnc
ExtractRegionFromImageByMask 3 ${input} ${tmpdir}/input.crop.mnc ${tmpdir}/headmask.mnc 1 10
mv -f ${tmpdir}/input.crop.mnc ${input}
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 -i ${tmpdir}/headmask.mnc -o ${tmpdir}/headmask.mnc -r ${input} -n GenericLabel
minccalc -clobber -quiet ${N4_VERBOSE:+-verbose} -unsigned -byte -expression 'A[0]>1.01?1:0' ${input} ${tmpdir}/nonzero.mnc
#Backup the original bias field estimate, in case cropping is not done, so we can correct the neck tissues
cp -f ${tmpdir}/${n}/prebias.mnc ${tmpdir}/bias_orig.mnc
#Need to fill the bias field with 1's in case we're padding the image
mincresample -clobber -quiet ${N4_VERBOSE:+-verbose} -fill -fillvalue 1 -like ${input} ${tmpdir}/${n}/prebias.mnc ${tmpdir}/${n}/bias_resample.mnc
cp -f ${tmpdir}/${n}/prebias.mnc ${tmpdir}/prebias.mnc
mincresample -clobber -quiet ${N4_VERBOSE:+-verbose} -fill -fillvalue 1 -like ${input} ${tmpdir}/prebias.mnc ${tmpdir}/prebias_resample.mnc
mv -f ${tmpdir}/${n}/bias_resample.mnc ${tmpdir}/${n}/bias.mnc
mv -f ${tmpdir}/prebias_resample.mnc ${tmpdir}/prebias.mnc
#Resample the exlude mask into the new recropped space
if [[ -n ${_arg_exclude} ]]; then
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 -i ${excludemask} -r ${input} -n GenericLabel -o ${excludemask}
fi
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 -i ${tmpdir}/${n}/corrected.mnc -o ${tmpdir}/${n}/corrected.mnc -r ${input}
ImageMath 3 ${tmpdir}/${n}/corrected.mnc m ${tmpdir}/${n}/corrected.mnc ${tmpdir}/headmask.mnc
minccalc -quiet ${N4_VERBOSE:+-verbose} -clobber -unsigned -byte -expression '1' ${input} ${tmpdir}/initmask.mnc
################################################################################
#Round 1, N4 with estimate weight mask using affine registered GM/WM/CSF priors
################################################################################
((++n))
mkdir -p ${tmpdir}/${n}
minc_anlm ${N4_VERBOSE:+--verbose} --mt ${ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS} ${tmpdir}/$((n - 1))/corrected.mnc ${tmpdir}/${n}/t1.mnc
ThresholdImage 3 ${tmpdir}/${n}/t1.mnc ${tmpdir}/masks/tissuemask.mnc Otsu 4 ${tmpdir}/headmask.mnc
ThresholdImage 3 ${tmpdir}/masks/tissuemask.mnc ${tmpdir}/masks/tissuemask.mnc 2 Inf 1 0
itk_vesselness --clobber --scales 8 --rescale ${tmpdir}/${n}/t1.mnc ${tmpdir}/vessels.mnc
antsRegistration ${N4_VERBOSE:+--verbose} -d 3 --float 1 --minc \
--output [ ${tmpdir}/${n}/mni ] \
--use-histogram-matching 1 \
--initial-moving-transform ${tmpdir}/$((n - 1))/mni0_GenericAffine.xfm \
--transform Similarity[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,32,None ] \
--convergence [ 500x500x500x500x450x150,1e-6,10 ] \
--shrink-factors 6x6x5x4x3x2 \
--smoothing-sigmas 2.94213702015x2.51232776601x2.08040503813x1.64470459404x1.20112240879x0.735534255037mm \
--masks [ ${REGISTRATIONBRAINMASK},NOMASK ] \
--transform Affine[ 0.1 ] \
--metric Mattes[ ${REGISTRATIONMODEL},${tmpdir}/${n}/t1.mnc,1,64,None ] \
--convergence [ 500x450x150x50,1e-6,10 ] \
--shrink-factors 4x3x2x1 \
--smoothing-sigmas 1.64470459404x1.20112240879x0.735534255037x0.0mm \
--masks [ ${REGISTRATIONBRAINMASK},NOMASK ]
unset reg_initalization
#Make MNI-space copy of brain for BeAST
antsApplyTransforms ${N4_VERBOSE:+--verbose} -d 3 -i ${tmpdir}/${n}/t1.mnc \
${MNI_XFM:+-t ${MNI_XFM}} -t ${tmpdir}/${n}/mni0_GenericAffine.xfm -n BSpline[ 5 ] -o ${tmpdir}/${n}/mni.mnc -r ${RESAMPLEMODEL}
#BSpline[ 5 ] does weird things to intensity, clip back to positive range
mincmath -quiet ${N4_VERBOSE:+-verbose} -clamp -const2 0 65535 ${tmpdir}/${n}/mni.mnc ${tmpdir}/${n}/mni.clamp.mnc
mv -f ${tmpdir}/${n}/mni.clamp.mnc ${tmpdir}/${n}/mni.mnc
#Shrink the MNI mask for the first intensity matching
iMath 3 ${tmpdir}/${n}/shrinkmask.mnc ME ${RESAMPLEMODELBRAINMASK} 2 1 ball 1
#Intensity normalize
volume_pol ${N4_VERBOSE:+--verbose} --order 1 --min 0 --max 100 --noclamp \
--source_mask ${tmpdir}/${n}/shrinkmask.mnc --target_mask ${RESAMPLEMODELBRAINMASK} \
${tmpdir}/${n}/mni.mnc ${RESAMPLEMODEL} ${tmpdir}/${n}/mni.norm.mnc
#Run a quick beast to get a brain mask
mincbeast ${N4_VERBOSE:+-verbose} -sparse -v2 -double -fill -median -same_res -flip -conf ${BEAST_CONFIG} \
${BEASTLIBRARY_DIR} ${tmpdir}/${n}/mni.norm.mnc ${tmpdir}/${n}/beastmask.mnc
#Resample beast mask and MNI mask to native space