-
Notifications
You must be signed in to change notification settings - Fork 29
Quick example
Nick Tustison edited this page Apr 18, 2020
·
1 revision
import numpy as np
import keras as ke
import ants
import antspynet
import antspynet.architectures as apa
import antspynet.utilities as apu
nChannels = 1
patchWidth = 32
pw2 = ( patchWidth, patchWidth )
image = ants.image_read(ants.get_ants_data('r16'))
image2 = ants.image_math( image, "Grad" )
image_patches = apu.extract_image_patches(image, patch_size = pw2,
max_number_of_patches = 64, return_as_array = True, random_seed = 1 )
image2_patches = apu.extract_image_patches(image2, patch_size = pw2,
max_number_of_patches = 64, return_as_array = True, random_seed = 1 )
xarray = np.zeros( [len( image_patches ), patchWidth, patchWidth, nChannels ] )
yarray = np.zeros( [len( image_patches ), patchWidth, patchWidth, nChannels ] )
for x in range( 0, len( image_patches ) ):
xarray[x,:,:,0] = image_patches[x][:,:]
yarray[x,:,:,0] = image2_patches[x][:,:]
##########################################
model = apa.create_unet_model_2d( ( None, None, nChannels ),
number_of_layers = 4, mode = 'regression' )
model.summary()
model.compile( loss = ke.losses.mse,
optimizer = ke.optimizers.Adam( lr = 0.0001 ) )
model.fit( xarray, yarray, epochs = 125, batch_size = 8 )
preds = model.predict( xarray )
k = 12
pimgIn = ants.from_numpy( xarray[k,:,:,0] )
pimgPred = ants.from_numpy( preds[k,:,:,0] )
pimgGT = ants.from_numpy( yarray[k,:,:,0] )
ants.plot( pimgIn )
ants.plot( pimgPred )
ants.plot( pimgGT )
compare to ANTsRNet
library( keras )
library( tensorflow )
library( ANTsR )
library( ANTsRNet )
nChannels = 1
patchWidth = 32
pw2 = c( patchWidth, patchWidth )
image = antsImageRead( getANTsRData( "r16" ) )
image_patches = extractImagePatches( image, patchSize = pw2,
maxNumberOfPatches = 64, returnAsArray = TRUE, randomSeed = 1 )
image2 = iMath( image, "Grad" )
image2_patches = extractImagePatches( image2, patchSize = pw2,
maxNumberOfPatches = 64, returnAsArray = TRUE, randomSeed = 1 )
xarray = array( dim = c( nrow( image_patches ), patchWidth, patchWidth, nChannels ) )
yarray = array( dim = c( nrow( image_patches ), patchWidth, patchWidth, nChannels ) )
for ( x in 1:nrow( image_patches ) ) {
xarray[x,,,1] = image_patches[x,,]
yarray[x,,,1] = image2_patches[x,,]
}
modelR = createUnetModel2D( list( NULL, NULL, nChannels ), numberOfLayers = 2,
mode = 'regression' )
modelR %>% compile( loss = 'mse',
optimizer = optimizer_adam( lr = 1e-2 ) )
modelR %>% fit( xarray, yarray, epochs = 10, batch_size = 8 )
preds = modelR %>% predict( xarray )
k = 10
pimgIn = as.antsImage( xarray[k,,,1] )
pimgPred = as.antsImage( preds[k,,,1] )
pimgGT = as.antsImage( yarray[k,,,1] )
layout( matrix( 1:3, nrow=1 ))
plot( pimgIn , colorbar = FALSE )
plot( pimgPred , colorbar = FALSE )
plot( pimgGT , colorbar = FALSE )