-
Notifications
You must be signed in to change notification settings - Fork 18
/
whiteMatterHyperintensitySegmentation.R
786 lines (694 loc) · 26.1 KB
/
whiteMatterHyperintensitySegmentation.R
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
#' White matter hyperintensity segmentation
#'
#' Perform WMH segmentation using the winning submission in the MICCAI
#' 2017 challenge by the sysu_media team using FLAIR or T1/FLAIR. The
#' MICCAI challenge is discussed in
#'
#' \url{https://pubmed.ncbi.nlm.nih.gov/30908194/}
#'
#' with the sysu_media's team entry is discussed in
#'
#' \url{https://pubmed.ncbi.nlm.nih.gov/30125711/}
#'
#' with the original implementation available here:
#'
#' \url{https://github.com/hongweilibran/wmh_ibbmTum}
#'
#' The original implementation used global thresholding as a quick
#' brain extraction approach. Due to possible generalization difficulties,
#' we leave such post-processing steps to the user. For brain or white
#' matter masking see functions brainExtraction or deepAtropos,
#' respectively.
#'
#' @param flair input 3-D FLAIR brain image.
#' @param t1 input 3-D T1-weighted brain image (assumed to be aligned to
#' the flair, if specified).
#' @param useEnsemble boolean to check whether to use all 3 sets of weights.
#' @param antsxnetCacheDirectory destination directory for storing the downloaded
#' template and model weights. Since these can be resused, if
#' \code{is.null(antsxnetCacheDirectory)}, these data will be downloaded to the
#' inst/extdata/ subfolder of the ANTsRNet package.
#' @param verbose print progress.
#' @return WMH segmentation probability image
#' @author Tustison NJ
#' @examples
#' \dontrun{
#' library( ANTsRNet )
#' library( keras )
#'
#' image <- antsImageRead( "flair.nii.gz" )
#' probabilityMask <-sysuMediaWmhSegmentation( image )
#' }
#' @export
sysuMediaWmhSegmentation <- function( flair, t1 = NULL,
useEnsemble = TRUE, antsxnetCacheDirectory = NULL, verbose = FALSE )
{
if( flair@dimension != 3 )
{
stop( "Input image dimension must be 3." )
}
imageSize <- c( 200, 200 )
################################
#
# Preprocess images
#
################################
flairPreprocessed <- flair
numberOfChannels <- 1
if( ! is.null( t1 ) )
{
t1Preprocessed <- t1
numberOfChannels <- 2
}
referenceImage <- makeImage( c( 170, 256, 256 ),
voxval = 1,
spacing = c( 1, 1, 1 ),
origin = c( 0, 0, 0 ),
direction = diag( 3 ) )
centerOfMassReference <- getCenterOfMass( referenceImage )
centerOfMassImage <- getCenterOfMass( flair )
xfrm <- createAntsrTransform( type = "Euler3DTransform",
center = centerOfMassReference,
translation = centerOfMassImage - centerOfMassReference )
flairPreprocessedWarped <- applyAntsrTransformToImage( xfrm, flairPreprocessed, referenceImage )
if( ! is.null( t1 ) )
{
t1PreprocessedWarped <- applyAntsrTransformToImage( xfrm, t1Preprocessed, referenceImage )
}
################################
#
# Gaussian normalize intensity based on brain mask
#
################################
meanFlair <- mean( flairPreprocessedWarped, na.rm = TRUE )
sdFlair <- sd( flairPreprocessedWarped, na.rm = TRUE )
flairPreprocessedWarped <- ( flairPreprocessedWarped - meanFlair ) / sdFlair
if( numberOfChannels == 2 )
{
meanT1 <- mean( t1PreprocessedWarped, na.rm = TRUE )
sdT1 <- sd( t1PreprocessedWarped, na.rm = TRUE )
t1PreprocessedWarped <- ( t1PreprocessedWarped - meanT1 ) / sdT1
}
################################
#
# Build models and load weights
#
################################
numberOfModels <- 1
if( useEnsemble )
{
numberOfModels <- 3
}
if( verbose )
{
cat( "White matter hyperintensity: retrieving model weights.\n" )
}
unetModels <- list()
for( i in seq.int( numberOfModels ) )
{
weightsFileName <- ''
if( numberOfChannels == 1 )
{
weightsFileName <- getPretrainedNetwork( paste0( "sysuMediaWmhFlairOnlyModel", i - 1 ),
antsxnetCacheDirectory = antsxnetCacheDirectory )
} else {
weightsFileName <- getPretrainedNetwork( paste0( "sysuMediaWmhFlairT1Model", i - 1 ),
antsxnetCacheDirectory = antsxnetCacheDirectory )
}
unetModels[[i]] <- createSysuMediaUnetModel2D( c( imageSize, numberOfChannels ), anatomy = "wmh" )
unetModels[[i]]$load_weights( weightsFileName )
}
################################
#
# Extract slices
#
################################
rotate <- function( x ) t( apply( x, 2, rev ) )
rotateReverse <- function( x ) apply( t( x ), 2, rev )
dimensionsToPredict <- c( 3 )
batchX <- array( data = 0,
c( sum( dim( flairPreprocessedWarped )[dimensionsToPredict]), imageSize, numberOfChannels ) )
sliceCount <- 1
for( d in seq.int( length( dimensionsToPredict ) ) )
{
numberOfSlices <- dim( flairPreprocessedWarped )[dimensionsToPredict[d]]
if( verbose )
{
cat( "Extracting slices for dimension", dimensionsToPredict[d], "\n" )
pb <- txtProgressBar( min = 1, max = numberOfSlices, style = 3 )
}
for( i in seq.int( numberOfSlices ) )
{
if( verbose )
{
setTxtProgressBar( pb, i )
}
flairSlice <- padOrCropImageToSize( extractSlice( flairPreprocessedWarped, i, dimensionsToPredict[d] ), imageSize )
batchX[sliceCount,,,1] <- rotateReverse( as.array( flairSlice ) )
if( numberOfChannels == 2 )
{
t1Slice <- padOrCropImageToSize( extractSlice( t1PreprocessedWarped, i, dimensionsToPredict[d] ), imageSize )
batchX[sliceCount,,,2] <- rotateReverse( as.array( t1Slice ) )
}
sliceCount <- sliceCount + 1
}
if( verbose )
{
cat( "\n" )
}
}
################################
#
# Do prediction and then restack into the image
#
################################
if( verbose )
{
cat( "Prediction.\n" )
}
prediction <- predict( unetModels[[1]], batchX, verbose = verbose )
if( numberOfModels > 1 )
{
for( i in seq.int( from = 2, to = numberOfModels ) )
{
prediction <- prediction + predict( unetModels[[i]], batchX, verbose = verbose )
}
}
prediction <- prediction / numberOfModels
for( i in seq.int( dim( flairPreprocessedWarped )[3] ) )
{
prediction[i,,,1] <- rotate( prediction[i,,,1] )
}
permutations <- list()
permutations[[1]] <- c( 1, 2, 3 )
permutations[[2]] <- c( 2, 1, 3 )
permutations[[3]] <- c( 2, 3, 1 )
predictionImageAverage <- antsImageClone( flairPreprocessedWarped ) * 0
currentStartSlice <- 1
for( d in seq.int( length( dimensionsToPredict ) ) )
{
currentEndSlice <- currentStartSlice - 1 + dim( flairPreprocessedWarped )[dimensionsToPredict[d]]
whichBatchSlices <- currentStartSlice:currentEndSlice
predictionPerDimension <- prediction[whichBatchSlices,,,]
predictionArray <- aperm( drop( predictionPerDimension ), permutations[[dimensionsToPredict[d]]] )
predictionImage <- antsCopyImageInfo( flairPreprocessedWarped,
padOrCropImageToSize( as.antsImage( predictionArray ), dim( flairPreprocessedWarped ) ) )
predictionImageAverage <- predictionImageAverage + ( predictionImage - predictionImageAverage ) / d
currentStartSlice <- currentEndSlice + 1
}
probabilityImage <- applyAntsrTransformToImage( invertAntsrTransform( xfrm ),
predictionImageAverage, flair )
return( probabilityImage )
}
#' hyperMapp3rSegmentation
#'
#' Perform HyperMapp3r (white matter hyperintensity) segmentation described in
#'
#' https://pubmed.ncbi.nlm.nih.gov/35088930/
#'
#' with models and architecture ported from
#'
#' https://github.com/AICONSlab/HyperMapp3r
#'
#' Additional documentation and attribution resources found at
#'
#' https://hypermapp3r.readthedocs.io/en/latest/
#'
#' Preprocessing consists of:
#' * n4 bias correction and
#' * brain extraction.
#' The input T1 should undergo the same steps. If the input T1 is the raw
#' T1, these steps can be performed by the internal preprocessing, i.e. set
#' \code{doPreprocessing = TRUE}
#'
#' @param t1 input 3-D t1-weighted MR image. Assumed to be aligned with the flair.
#' @param flair input 3-D flair MR image. Assumed to be aligned with the t1.
#' @param doPreprocessing perform preprocessing. See description above.
#' @param antsxnetCacheDirectory destination directory for storing the downloaded
#' template and model weights. Since these can be resused, if
#' \code{is.null(antsxnetCacheDirectory)}, these data will be downloaded to the
#' subdirectory ~/.keras/ANTsXNet/.
#' @param verbose print progress.
#' @return white matter hyperintensity probability mask
#' @author Tustison NJ
#' @examples
#' \dontrun{
#' library( ANTsRNet )
#' library( keras )
#'
#' wmh <- hyperMapp3rSegmentation( image, verbose = TRUE )
#' }
#' @export
hyperMapp3rSegmentation <- function( t1, flair, doPreprocessing = TRUE,
numberOfMonteCarloIterations = 30, antsxnetCacheDirectory = NULL, verbose = FALSE )
{
if( t1@dimension != 3 )
{
stop( "Image dimension must be 3." )
}
#########################################
#
# Perform preprocessing
#
if( verbose )
{
cat( "************* Preprocessing ***************\n" )
cat( "\n" )
}
t1Preprocessed <- t1
brainMask <- NULL
if( doPreprocessing )
{
t1Preprocessing <- preprocessBrainImage( t1,
truncateIntensity = c( 0.01, 0.99 ),
brainExtractionModality = "t1",
template = NULL,
doBiasCorrection = TRUE,
doDenoising = FALSE,
antsxnetCacheDirectory = antsxnetCacheDirectory,
verbose = verbose )
brainMask <- t1Preprocessing$brainMask
t1Preprocessed <- t1Preprocessing$preprocessedImage * brainMask
} else {
# If we don't generate the mask from the preprocessing, we assume that we
# can extract the brain directly from the foreground of the t1 image.
brainMask <- thresholdImage( t1, 0, 0, 0, 1 )
}
t1PreprocessedMean <- mean( t1Preprocessed[brainMask > 0] )
t1PreprocessedSd <- sd( t1Preprocessed[brainMask > 0] )
t1Preprocessed[brainMask > 0] <- ( t1Preprocessed[brainMask > 0] - t1PreprocessedMean ) / t1PreprocessedSd
flairPreprocessed <- flair
if( doPreprocessing )
{
flairPreprocessing <- preprocessBrainImage( flair,
truncateIntensity = c( 0.01, 0.99 ),
brainExtractionModality = "flair",
template = NULL,
doBiasCorrection = TRUE,
doDenoising = FALSE,
antsxnetCacheDirectory = antsxnetCacheDirectory,
verbose = verbose )
flairPreprocessed <- flairPreprocessing$preprocessedImage * brainMask
}
flairPreprocessedMean <- mean( flairPreprocessed[brainMask > 0] )
flairPreprocessedSd <- sd( flairPreprocessed[brainMask > 0] )
flairPreprocessed[brainMask > 0] <- ( flairPreprocessed[brainMask > 0] - flairPreprocessedMean ) / flairPreprocessedSd
# Reorient to hypermapp3r space
if( verbose )
{
cat( " HyperMapp3r: reorient input images.\n" )
}
channelSize <- 2
inputImageSize <- c( 224, 224, 224 )
templateArray <- array( data = 1, dim = inputImageSize )
templateDirection <- diag( 3 )
reorientTemplate <- as.antsImage( templateArray, origin = c( 0, 0, 0 ),
spacing = c( 1, 1, 1 ), direction = templateDirection )
centerOfMassTemplate <- getCenterOfMass( reorientTemplate )
centerOfMassImage <- getCenterOfMass( brainMask )
xfrm <- createAntsrTransform( type = "Euler3DTransform",
center = centerOfMassTemplate,
translation = centerOfMassImage - centerOfMassTemplate )
batchX <- array( data = 0, dim = c( 1, inputImageSize, channelSize ) )
t1PreprocessedWarped <- applyAntsrTransformToImage( xfrm, t1Preprocessed, reorientTemplate )
batchX[1,,,,1] <- as.array( t1PreprocessedWarped )
flairPreprocessedWarped <- applyAntsrTransformToImage( xfrm, flairPreprocessed, reorientTemplate )
batchX[1,,,,2] <- as.array( flairPreprocessedWarped )
if( verbose )
{
cat( " HyperMapp3r: generate network and load weights.\n" )
}
model <- createHyperMapp3rUnetModel3D( c( inputImageSize, 2 ) )
weightsFileName <- getPretrainedNetwork( "hyperMapp3r",
antsxnetCacheDirectory = antsxnetCacheDirectory )
model$load_weights( weightsFileName )
if( verbose )
{
cat( " HyperMapp3r: prediction.\n" )
}
if( verbose )
{
cat( " HyperMapp3r: do Monte Carlo iterations (SpatialDropout).\n" )
}
predictionArray <- array( data = 0, dim = c( inputImageSize ) )
for( i in seq_len( numberOfMonteCarloIterations ) )
{
if( verbose )
{
cat( " Monte Carlo iteration", i, "out of", numberOfMonteCarloIterations, "\n" )
}
predictionArray <- ( model$predict( batchX, verbose = verbose )[1,,,,1] +
( i - 1 ) * predictionArray ) / i
}
predictionImage <- as.antsImage( predictionArray, origin = antsGetOrigin( reorientTemplate ),
spacing = antsGetSpacing( reorientTemplate ), direction = antsGetDirection( reorientTemplate ) )
xfrmInv <- invertAntsrTransform( xfrm )
probabilityImage <- applyAntsrTransformToImage( xfrmInv, predictionImage, t1 )
return( probabilityImage )
}
#' White matter hyperintensity probabilistic segmentation
#'
#' Perform white matter hyperintensity probabilistic segmentation
#' using deep learning
#'
#' @param flair input 3-D FLAIR brain image.
#' @param t1 input 3-D T1-weighted brain image (assumed to be aligned to
#' the flair).
#' @param whiteMatterMask input white matter mask for patch extraction. If None,
#' calculated using deepAtropos (labels 3 and 4).
#' @param useCombinedModel Original or combined.
#' @param predictionBatchSize Control memory usage for prediction. More consequential
#' for GPU-usage.
#' @param patchStrideLength 3-D vector or int. Dictates the stride length for
#' accumulating predicting patches.
#' @param doPreprocessing perform n4 bias correction, intensity truncation, brain
#' extraction.
#' @param antsxnetCacheDirectory destination directory for storing the downloaded
#' template and model weights. Since these can be resused, if
#' \code{is.null(antsxnetCacheDirectory)}, these data will be downloaded to the
#' inst/extdata/ subfolder of the ANTsRNet package.
#' @param verbose print progress.
#' @return probabilistic image.
#' @author Tustison NJ
#' @examples
#' \dontrun{
#' library( ANTsRNet )
#' library( keras )
#'
#' t1 <- antsImageRead( "t1.nii.gz" )
#' flair <- antsImageRead( "flair.nii.gz" )
#' results <- wmhSegmentation( t1, flair )
#' }
#' @export
wmhSegmentation <- function( flair, t1, whiteMatterMask = NULL,
useCombinedModel = TRUE, predictionBatchSize = 16,
patchStrideLength = 32,
doPreprocessing = TRUE, antsxnetCacheDirectory = NULL, verbose = FALSE )
{
if( any( dim( t1 ) < c( 64, 64, 64 ) ) )
{
stop( "Images must be > 64 voxels per dimension." )
}
################################
#
# Preprocess images
#
################################
if( is.null( whiteMatterMask ) )
{
if( verbose )
{
message( "Calculate white matter mask.\n" )
atropos <- deepAtropos( t1, doPreprocessing = TRUE, verbose = verbose )
whiteMatterMask <- thresholdImage( atropos$segmentationImage, 3, 4, 1, 0 )
}
}
t1Preprocessed <- NULL
flairPreprocessed <- NULL
if( doPreprocessing )
{
if( verbose )
{
message( "Preprocess T1 and FLAIR images.\n" )
}
t1Preprocessing <- preprocessBrainImage( t1,
truncateIntensity = c( 0.001, 0.995 ),
brainExtractionModality = "t1",
doBiasCorrection = TRUE,
doDenoising = FALSE,
antsxnetCacheDirectory = antsxnetCacheDirectory,
verbose = verbose )
brainMask <- thresholdImage( t1Preprocessing$brainMask, 0.5, 1, 1, 0 )
t1Preprocessed <- t1Preprocessing$preprocessedImage * brainMask
flairPreprocessing <- preprocessBrainImage( flair,
truncateIntensity = NULL,
brainExtractionModality = NULL,
doBiasCorrection = TRUE,
doDenoising = FALSE,
antsxnetCacheDirectory = antsxnetCacheDirectory,
verbose = verbose )
flairPreprocessed <- flairPreprocessing$preprocessedImage * brainMask
} else {
t1Preprocessed <- antsImageClone( t1 )
flairPreprocessed <- antsImageClone( flair )
}
t1PreprocessedMin <- min( t1Preprocessed[whiteMatterMask > 0] )
t1PreprocessedMax <- max( t1Preprocessed[whiteMatterMask > 0] )
flairPreprocessedMin <- min( flairPreprocessed[whiteMatterMask > 0] )
flairPreprocessedMax <- max( flairPreprocessed[whiteMatterMask > 0] )
t1Preprocessed <- ( t1Preprocessed - t1PreprocessedMin ) / ( t1PreprocessedMax - t1PreprocessedMin )
flairPreprocessed <- ( flairPreprocessed - flairPreprocessedMin ) / ( flairPreprocessedMax - flairPreprocessedMin )
################################
#
# Build model and load weights
#
################################
if( verbose )
{
message( "Load model and weights.\n" )
}
patchSize <- c( 64L, 64L, 64L )
strideLength <- c( 32L, 32L, 32L )
numberOfFilters <- c( 64, 96, 128, 256, 512 )
channelSize <- 2
model <- createSysuMediaUnetModel3D( c( patchSize, channelSize ),
numberOfFilters = numberOfFilters )
weightsFileName <- ""
if( useCombinedModel )
{
weightsFileName <- getPretrainedNetwork( "antsxnetWmhOr",
antsxnetCacheDirectory = antsxnetCacheDirectory )
} else {
weightsFileName <- getPretrainedNetwork( "antsxnetWmh",
antsxnetCacheDirectory = antsxnetCacheDirectory )
}
load_model_weights_hdf5( model, filepath = weightsFileName )
################################
#
# Extract patches
#
################################
if( verbose )
{
message( "Extract patches." )
}
t1Patches <- extractImagePatches( t1Preprocessed,
patchSize = patchSize,
maxNumberOfPatches = "all",
strideLength = strideLength,
maskImage = whiteMatterMask,
randomSeed = NULL,
returnAsArray = TRUE )
flairPatches <- extractImagePatches( flairPreprocessed,
patchSize = patchSize,
maxNumberOfPatches = "all",
strideLength = strideLength,
maskImage = whiteMatterMask,
randomSeed = NULL,
returnAsArray = TRUE )
totalNumberOfPatches <- dim( t1Patches )[1]
################################
#
# Do prediction and then restock into the image
#
################################
numberOfBatches <- floor( totalNumberOfPatches / predictionBatchSize )
residualNumberOfPatches <- totalNumberOfPatches - numberOfBatches * predictionBatchSize
if( residualNumberOfPatches > 0 )
{
numberOfBatches <- numberOfBatches + 1
}
if( verbose )
{
message( "Total number of patches: ", totalNumberOfPatches )
message( "Prediction batch size: ", predictionBatchSize )
message( "Number of batches: ", numberOfFullBatches )
}
prediction <- array( data = 0, dim = c( totalNumberOfPatches, patchSize, 1 ) )
for( b in seq.int( numberOfBatches ) )
{
batchX <- NULL
if( b < numberOfFullBatches || residualNumberOfPatches == 0 )
{
batchX <- array( data = 0, dim = c( predictionBatchSize, patchSize, channelSize ) )
} else {
batchX <- array( data = 0, dim = c( residualNumberOfPatches, patchSize, channelSize ) )
}
indices <- ( ( b - 1 ) * predictionBatchSize + 1):( ( b - 1 ) * predictionBatchSize + dim( batchX )[1] )
batchX[,,,,1] <- flairPatches[indices,,,]
batchX[,,,,2] <- t1Patches[indices,,,]
if( verbose )
{
message( "Predicting batch ", b, " of ", numberOfBatches )
}
prediction[indices,,,,] <- model %>% predict( batchX, verbose = verbose )
}
wmhProbabilityImage <- reconstructImageFromPatches( drop( prediction ),
strideLength = strideLength,
domainImage = whiteMatterMask,
domainImageIsMask = TRUE )
}
#' PVS/VRS segmentation.
#'
#' Perform segmentation of perivascular (PVS) or Vircho-Robin spaces (VRS).
#' \url{https://pubmed.ncbi.nlm.nih.gov/34262443/}
#' with the original implementation available here:
#' https://github.com/pboutinaud/SHIVA_PVS
#'
#' @param t1 input 3-D T1-weighted brain image.
#' @param flair (Optional) input 3-D FLAIR brain image (aligned to T1 image).
#' @param whichModel integer or string. Several models were trained for the
#' case of T1-only or T1/FLAIR image pairs. One can use a specific single
#' trained model or the average of the entire ensemble. I.e., options are:
#' * For T1-only: 0, 1, 2, 3, 4, 5.
#' * For T1/FLAIR: 0, 1, 2, 3, 4.
#' * Or "all" for using the entire ensemble.
#' @param doPreprocessing perform n4 bias correction, intensity truncation, brain
#' extraction.
#' @param antsxnetCacheDirectory destination directory for storing the downloaded
#' template and model weights. Since these can be resused, if
#' \code{is.null(antsxnetCacheDirectory)}, these data will be downloaded to the
#' inst/extdata/ subfolder of the ANTsRNet package.
#' @param verbose print progress.
#' @return probabilistic image.
#' @author Tustison NJ
#' @examples
#' \dontrun{
#' library( ANTsRNet )
#' library( keras )
#'
#' t1 <- antsImageRead( "t1.nii.gz" )
#' flair <- antsImageRead( "flair.nii.gz" )
#' results <- wmhSegmentation( t1, flair )
#' }
#' @export
shivaPvsSegmentation <- function( t1, flair = NULL,
whichModel = "all", doPreprocessing = TRUE,
antsxnetCacheDirectory = NULL, verbose = FALSE )
{
################################
#
# Preprocess images
#
################################
t1Preprocessed <- NULL
flairPreprocessed <- NULL
brainMask <- NULL
if( doPreprocessing )
{
if( verbose )
{
message( "Preprocess image(s).\n" )
}
t1Preprocessing <- preprocessBrainImage( t1,
truncateIntensity = c( 0.0, 0.99 ),
brainExtractionModality = "t1",
doBiasCorrection = TRUE,
doDenoising = FALSE,
intensityNormalizationType = "01",
antsxnetCacheDirectory = antsxnetCacheDirectory,
verbose = verbose )
brainMask <- thresholdImage( t1Preprocessing$brainMask, 0.5, 1, 1, 0 )
t1Preprocessed <- t1Preprocessing$preprocessedImage * brainMask
if( ! is.null( flair ) )
{
flairPreprocessing <- preprocessBrainImage( flair,
truncateIntensity = c( 0.0, 0.99 ),
brainExtractionModality = NULL,
doBiasCorrection = TRUE,
doDenoising = FALSE,
intensityNormalizationType = "01",
antsxnetCacheDirectory = antsxnetCacheDirectory,
verbose = verbose )
flairPreprocessed <- flairPreprocessing$preprocessedImage * brainMask
}
} else {
t1Preprocessed <- antsImageClone( t1 )
if( ! is.null( flair ) )
{
flairPreprocessed <- antsImageClone( flair )
}
brainMask <- thresholdImage( t1, 0, 0, 0, 1 )
}
imageShape <- c( 160, 214, 176 )
onesArray <- array( data = 1, dim = imageShape )
reorientTemplate <- as.antsImage( onesArray, origin = c( 0, 0, 0 ),
spacing = c( 1, 1, 1 ),
direction = diag( 3 ) )
centerOfMassTemplate <- getCenterOfMass( reorientTemplate )
centerOfMassImage <- getCenterOfMass( brainMask )
xfrm <- createAntsrTransform( type = "Euler3DTransform",
center = round( centerOfMassTemplate ),
translation = round( centerOfMassImage - centerOfMassTemplate ) )
t1Preprocessed <- applyAntsrTransformToImage( xfrm, t1Preprocessed,
reorientTemplate )
if( ! is.null( flair ) )
{
flairPreprocessed <- applyAntsrTransformToImage( xfrm, flairPreprocessed,
reorientTemplate )
}
################################
#
# Load models and predict
#
################################
batchY <- NULL
if( is.null( flair ) )
{
batchX <- array( data = 0, dim = c( 1, imageShape, 1 ) )
batchX[1,,,,1] <- as.array( t1Preprocessed )
modelIds <- c( whichModel )
if( whichModel == "all" )
{
modelIds <- c( 0, 1, 2, 3, 4, 5 )
}
for( i in seq.int( length( modelIds ) ) )
{
modelFile <- getPretrainedNetwork( paste0( "pvs_shiva_t1_", modelIds[i] ),
antsxnetCacheDirectory = antsxnetCacheDirectory )
if( verbose )
{
cat( "Loading", modelFile, "\n" )
}
model <- tensorflow::tf$keras$models$load_model( modelFile, compile = FALSE )
if( i == 1 )
{
batchY <- model$predict( batchX, verbose = verbose )
} else {
batchY <- batchY + model$predict( batchX, verbose = verbose )
}
}
batchY <- batchY / length( modelIds )
} else {
batchX <- array( data = 0, dim = c( 1, imageShape, 2 ) )
batchX[1,,,,1] <- as.array( t1Preprocessed )
batchX[1,,,,2] <- as.array( flairPreprocessed )
modelIds <- c( whichModel )
if( whichModel == "all" )
{
modelIds <- c( 0, 1, 2, 3, 4 )
}
for( i in seq.int( length( modelIds ) ) )
{
modelFile <- getPretrainedNetwork( paste0( "pvs_shiva_t1_flair_", modelIds[i] ),
antsxnetCacheDirectory = antsxnetCacheDirectory )
if( verbose )
{
cat( "Loading", modelFile, "\n" )
}
model <- tensorflow::tf$keras$models$load_model( modelFile, compile = FALSE )
if( i == 1 )
{
batchY <- model$predict( batchX, verbose = verbose )
} else {
batchY <- batchY + model$predict( batchX, verbose = verbose )
}
}
batchY <- batchY / length( modelIds )
}
pvs <- as.antsImage( drop( batchY ), origin = antsGetOrigin( reorientTemplate ),
spacing = antsGetSpacing( reorientTemplate ),
direction = antsGetDirection( reorientTemplate ) )
pvs <- applyAntsrTransformToImage( invertAntsrTransform( xfrm ), pvs, t1 )
return( pvs )
}