def __init__(self, ants_image=[[0.0]], mask_ants=[[0.0]], **options): import ants self.atropos = ants.atropos(a = ants_image, x = mask_ants, **options)
def __segmentation(self): logger.info("computing GM, WM, CSF segmentation") print("computing GM, WM, CSF segmentation") # https://antsx.github.io/ANTsPyNet/docs/build/html/utilities.html#applications priors = { "csf": os.path.join('./templates', 'mni_icbm152_csf_tal_nlin_sym_09a.nii.gz'), "gm": os.path.join('./templates', 'mni_icbm152_gm_tal_nlin_sym_09a.nii.gz'), "wm": os.path.join('./templates', 'mni_icbm152_wm_tal_nlin_sym_09a.nii.gz') } # list_of_priors = (ants.image_read(priors['csf']), ants.image_read(priors['gm']), ants.image_read(priors['wm'])) if self._t1file != None and self._t2file != None: # segm = deep_atropos(self._t1_n4 * self._mask, do_preprocessing=False, use_spatial_priors=0, verbose=False) # self._segm = segm['segmentation_image'] segm = ants.atropos(a=(self._t1_n4, self._t2_n4), i='Kmeans[3]', m='[0.2,1x1x1]', c='[3,0]', x=self._mask) self._segm = segm['segmentation'] self._gm = np.where((self._segm.numpy() == 2), 1, 0).astype('float32') self._wm = np.where((self._segm.numpy() == 3), 1, 0).astype('float32') if self._t1file != None and self._t2file == None: # segm = deep_atropos(self._t1_n4 * self._mask, do_preprocessing=False, use_spatial_priors=0, verbose=False) # self._segm = segm['segmentation_image'] segm = ants.atropos(a=self._t1_n4, i='Kmeans[3]', m='[0.2,1x1x1]', c='[3,0]', x=self._mask) self._segm = segm['segmentation'] self._gm = np.where((self._segm.numpy() == 2), 1, 0).astype('float32') self._wm = np.where((self._segm.numpy() == 3), 1, 0).astype('float32')
def test_multiple_inputs(self): img = ants.image_read(ants.get_ants_data("r16")) img = ants.resample_image(img, (64, 64), 1, 0) mask = ants.get_mask(img) segs1 = ants.atropos(a=img, m='[0.2,1x1]', c='[2,0]', i='kmeans[3]', x=mask) # Use probabilities from k-means seg as priors segs2 = ants.atropos(a=img, m='[0.2,1x1]', c='[2,0]', i=segs1['probabilityimages'], x=mask) # multiple inputs feats = [img, ants.iMath(img, "Laplacian"), ants.iMath(img, "Grad")] segs3 = ants.atropos(a=feats, m='[0.2,1x1]', c='[2,0]', i=segs1['probabilityimages'], x=mask)
link = '/ROBEX_Output/' # Skull stripped data output by ROBEX mylist = os.listdir('/ROBEX_Output/') # fixed image is the template to which the registration will be fitted found in the downloaded ANTs package fixed = ants.image_read('/ANTsPy-master/data/mni.nii.gz') # This runs the entire dataset through registration for i in mylist: #registraction moving = ants.image_read('/arc/project/ex-rtam-1/BrainExt_AllData/' + i) mytx = ants.registration(fixed=fixed, moving=moving, type_of_transform='SyNAggro') mywarpedimage = ants.apply_transforms(fixed=fixed, moving=moving, transformlist=mytx['fwdtransforms']) mywarpedimage.to_file('/Output_ants_SyNAggro/Registration/' + i) #segmentation mask = ants.get_mask(mywarpedimage) img_seg = ants.atropos(a=mywarpedimage, m='[0.2,1x1x1]', c='[2,0]', i='kmeans[3]', x=mask) gm = img_seg['probabilityimages'][1] gm.to_file('/Output_ants_SyNAggro/Greymatter/' + i) continue
os.mkdir( outputDirectory ) outputPrefix = outputDirectory + 'antspy' numberOfOuterIterations = 5 image = ants.image_read( dataDirectory + 'KKI2009-01-MPRAGE_slice150.nii.gz', dimension = 2 ) mask = ants.image_read( dataDirectory + 'KKI2009-01-MPRAGE_slice150_mask.nii.gz', dimension = 2 ) weightMask = None for i in range( numberOfOuterIterations ): print( "*************** N4 <---> Atropos iteration ", i, " ******************\n" ) n4Results = ants.n4_bias_field_correction( image, mask = mask, weight_mask = weightMask, verbose = True ) image = n4Results atroposResults = ants.atropos( a = image, x = mask ) onesImage = ants.make_image( image.shape, voxval = 0, spacing = ants.get_spacing( image ), origin = ants.get_origin( image ), direction = ants.get_direction( image ) ) weightMask = atroposResults['probabilityimages'][1] *\ ( onesImage - atroposResults['probabilityimages'][0] ) *\ ( onesImage - atroposResults['probabilityimages'][2] ) +\ atroposResults['probabilityimages'][2] *\ ( onesImage - atroposResults['probabilityimages'][1] ) *\ ( onesImage - atroposResults['probabilityimages'][0] ) ants.image_write( image, outputPrefix + "N4Corrected.nii.gz" ) ants.image_write( atroposResults['segmentation'], outputPrefix + "AtroposSegmentation.nii.gz" ) for i in range( len( atroposResults['probabilityimages'] ) ):
def test_example(self): # test ANTsPy/ANTsR example img = ants.image_read(ants.get_ants_data('r16')) img = ants.resample_image(img, (64, 64), 1, 0) mask = ants.get_mask(img) ants.atropos(a=img, m='[0.2,1x1]', c='[2,0]', i='kmeans[3]', x=mask)
def longitudinal_cortical_thickness(t1s, initial_template="oasis", number_of_iterations=1, refinement_transform="antsRegistrationSyNQuick[a]", antsxnet_cache_directory=None, verbose=False): """ Perform KellyKapowski cortical thickness longitudinally using \code{deepAtropos} for segmentation of the derived single-subject template. It takes inspiration from the work described here: https://pubmed.ncbi.nlm.nih.gov/31356207/ Arguments --------- t1s : list of ANTsImage Input list of 3-D unprocessed t1-weighted brain images from a single subject. initial_template : string or ANTsImage Input image to define the orientation of the SST. Can be a string (see get_antsxnet_data) or a specified template. This allows the user to create a SST outside of this routine. number_of_iterations : int Defines the number of iterations for refining the SST. refinement_transform : string Transform for defining the refinement registration transform. See options in ants.registration. antsxnet_cache_directory : string Destination directory for storing the downloaded template and model weights. Since these can be resused, if is None, these data will be downloaded to a ~/.keras/ANTsXNet/. verbose : boolean Print progress to the screen. Returns ------- Cortical thickness image and segmentation probability images. Example ------- >>> t1s = list() >>> t1s.append(ants.image_read("t1w_image.nii.gz")) >>> kk = longitudinal_cortical_thickness(image) """ from ..utilities import get_antsxnet_data from ..utilities import preprocess_brain_image from ..utilities import deep_atropos ################### # # Initial SST + optional affine refinement # ################## sst = None if isinstance(initial_template, str): template_file_name_path = get_antsxnet_data(initial_template, antsxnet_cache_directory=antsxnet_cache_directory) sst = ants.image_read(template_file_name_path) else: sst = initial_template for s in range(number_of_iterations): if verbose: print("Refinement iteration", s, "( out of", number_of_iterations, ")") sst_tmp = ants.image_clone(sst) * 0 for i in range(len(t1s)): if verbose: print("***************************") print( "SST processing image", i, "( out of", len(t1s), ")") print( "***************************" ) transform_type = "antsRegistrationSyNQuick[r]" if s > 0: transform_type = refinement_transform t1_preprocessed = preprocess_brain_image(t1s[i], truncate_intensity=(0.01, 0.99), do_brain_extraction=False, template=sst, template_transform_type=transform_type, do_bias_correction=False, do_denoising=False, intensity_normalization_type="01", antsxnet_cache_directory=antsxnet_cache_directory, verbose=verbose) sst_tmp += t1_preprocessed['preprocessed_image'] sst = sst_tmp / len(t1s) ################### # # Preprocessing and affine transform to final SST # ################## t1s_preprocessed = list() for i in range(len(t1s)): if verbose: print("***************************") print( "Final processing image", i, "( out of", len(t1s), ")") print( "***************************" ) t1_preprocessed = preprocess_brain_image(t1s[i], truncate_intensity=(0.01, 0.99), do_brain_extraction=True, template=sst, template_transform_type="antsRegistrationSyNQuick[a]", do_bias_correction=True, do_denoising=True, intensity_normalization_type="01", antsxnet_cache_directory=antsxnet_cache_directory, verbose=verbose) t1s_preprocessed.append(t1_preprocessed) ################### # # Deep Atropos of SST for priors # ################## sst_atropos = deep_atropos(sst, do_preprocessing=True, antsxnet_cache_directory=antsxnet_cache_directory, verbose=verbose) ################### # # Traditional Atropos + KK for each iamge # ################## return_list = list() for i in range(len(t1s_preprocessed)): if verbose: print("Atropos for image", i, "( out of", len(t1s), ")") atropos_output = ants.atropos(t1s_preprocessed[i]['preprocessed_image'], x=t1s_preprocessed[i]['brain_mask'], i=sst_atropos['probability_images'][1:7], m="[0.1,1x1x1]", c="[5,0]", priorweight=0.5, p="Socrates[1]", verbose=int(verbose)) kk_segmentation = ants.image_clone(atropos_output['segmentation']) kk_segmentation[kk_segmentation == 4] = 3 gray_matter = atropos_output['probabilityimages'][1] white_matter = atropos_output['probabilityimages'][2] + atropos_output['probabilityimages'][3] kk = ants.kelly_kapowski(s=kk_segmentation, g=gray_matter, w=white_matter, its=45, r=0.025, m=1.5, x=0, verbose=int(verbose)) t1_dict = {'preprocessed_image' : t1s_preprocessed[i]['preprocessed_image'], 'thickness_image' : kk, 'segmentation_image' : atropos_output['segmentation'], 'csf_probability_image' : atropos_output['probabilityimages'][0], 'gray_matter_probability_image' : atropos_output['probabilityimages'][1], 'white_matter_probability_image' : atropos_output['probabilityimages'][2], 'deep_gray_matter_probability_image' : atropos_output['probabilityimages'][3], 'brain_stem_probability_image' : atropos_output['probabilityimages'][4], 'cerebellum_probability_image' : atropos_output['probabilityimages'][5], 'template_transforms' : t1s_preprocessed[i]['template_transforms'] } return_list.append(t1_dict) return_list.append(sst) return(return_list)