def fishplot(img, overl = '', orient = 'axial', sliceno = 20, al = .5, col = 'magma'): #=============================================================================== # N.B This breaks frequently - I have no idea what is wrong with the implementation import ants import numpy as np r = img.shape if orient == 'coronal': axs = 0; ri = 0 elif orient == 'sagittal': axs = 1; ri = 1 elif orient == 'axial': axs = 2; ri = 2 # ALERT ALERT I HAVE NO IDEA WHAT THE SLICE INDEXING WANTS FROM ME # Does it live in the physical space? # Does it live in the voxel space? # I DON'T KNOW - so I'm fudging it sliceno = min([sliceno,r[ri]]) if orient == 'axial': mx_dim = r[ri] - 1 else: mx_dim = r[ri] * img.spacing[ri]-1 sli = list(map(int, np.ndarray.tolist(np.linspace(0, mx_dim, sliceno)))) if not overl: ants.plot(img, axis = axs, slices = sli, figsize = 6) else: ants.plot(img, overl, overlay_cmap = col, overlay_alpha= al, axis = axs, slices = sli, figsize = 6)
def load_ants(args): import ants images = load_patients(args) for i in images: img = ants.image_read(i) # Create save dir in parent folder save_dir = output_dir(args, i) ants.plot(img, filename=f'{save_dir}.png', cmap='plasma')
def cde_mot_meancalc(imgs, Fimg, noimages=100, delfirst=True, crop=False, plot='do'): import numpy as np import ants import os print('I found ' + str(len(imgs)) + ' images') # Load subsection of tifs #--------------------------------------------------------------------------- maxno = np.min([len(imgs), noimages]) loadi = np.linspace(0, len(imgs) - 1, maxno) loadi = loadi.astype(int) print('Of these I' 'm loading ' + str(maxno)) if delfirst: loadi = np.delete(loadi, 0) print('I' 'm ignoring the first volume') # Load initial image for dimensions #--------------------------------------------------------------------------- if type(imgs[0]) == str: templ = ants.image_read(Fimg + os.sep + imgs[0]) elif type(imgs[0]) == ants.core.ants_image.ANTsImage: templ = imgs[0] if crop: templ = ants.crop_indices(templ, [0, 0, 1], templ.shape) mean_arr = np.multiply(templ.numpy(), 0) imglist = [] for i in loadi: if type(imgs[0]) == str: img = ants.image_read(Fimg + os.sep + imgs[i]) elif type(imgs[0]) == ants.core.ants_image.ANTsImage: img = imgs[i] if crop: img = ants.crop_indices(img, [0, 0, 1], img.shape) mean_arr = mean_arr + img.numpy() / maxno imglist.append(img) mimg = ants.from_numpy(mean_arr) if plot == 'do': ants.plot(mimg, axis=2, slices=range(mimg.shape[2]), figsize=3) return mimg, imglist
def fishplot(img, overl='', orient='axial', sliceno=20, al=.5, col='magma'): #=============================================================================== """ This function plots output of registration. Inputs: im (ants image): Atlas to plot overl (ants image): warped image to overlay onto atlas orient (str): plotting orientation sliceno (int): number of slices to visualise al (int): alpha col (str): color map """ import ants import numpy as np r = img.shape if orient == 'coronal': axs = 0 ri = 0 elif orient == 'sagittal': axs = 1 ri = 1 elif orient == 'axial': axs = 2 ri = 2 sliceno = min([sliceno, r[ri]]) if orient == 'axial': mx_dim = r[ri] - 1 else: mx_dim = r[ri] * img.spacing[ri] - 1 sli = list(map(int, np.ndarray.tolist(np.linspace(0, mx_dim, sliceno)))) if not overl: ants.plot(img, axis=axs, slices=sli, figsize=6) else: ants.plot(img, overl, overlay_cmap=col, overlay_alpha=al, axis=axs, slices=sli, figsize=6)
nuisance = np.c_[ nuisance, motCorr['FD'] ] nuisance = np.c_[ nuisance, mycompcor['basis'] ] gmmat = regress_components( gmmat[goodtimes[0],:], nuisance[goodtimes[0],:] ) dfnmat = ants.timeseries_to_matrix( simg, ants.threshold_image( dfnImg, 1, dfnImg.max() ) ) dfnmat = regress_components( dfnmat[goodtimes[0],:], nuisance[goodtimes[0],:] ) # dfnmatf = frequencyFilterfMRI( dfnmat, tr = tr, freqLo = 0.01, freqHi = 0.1, opt = "trig" ) dfnsignal = dfnmat.mean( axis = 1 ) gmmatDFNCorr = np.zeros( gmmat.shape[1] ) for k in range( gmmat.shape[1] ): gmmatDFNCorr[ k ] = pearsonr( dfnsignal, gmmat[:,k] )[0] corrImg = ants.make_image( gmseg, gmmatDFNCorr ) corrImgPos = corrImg * ants.threshold_image( corrImg, 0.25, 1 ) ants.plot( avgBold, corrImgPos, axis=2, overlay_alpha = 0.6, cbar=False, nslices = 24, ncol=8, cbar_length=0.3, cbar_vertical=True ) """ needs to be translated to python still TODO: ilr - image based linear regression frequencyFilterfMRI - scipy probably butter filtfilt getNetworkBeta <-function( motcorrIn, networkName = 'Default Mode' ) { *implement* noiseu = compcor( ccmat, ncompcor = 10 ) smth = c( 1.0, 1.0, 1.0, 2.0 ) # this is for sigmaInPhysicalCoordinates = F
def show(self, **kwargs): ants.plot(self.obj)
import ants import os import glob dataDirectory = './' populationFiles = glob.glob(dataDirectory + "OASIS*Slice121.nii.gz") population = list() for i in range(len(populationFiles)): population.append(ants.image_read(populationFiles[i], dimension=2)) btp = ants.build_template(initialTemplate=None, image_list=population, iterations=4, gradient_step=0.2, verbose=True, syn_metric='CC', reg_iterations=(100, 70, 50, 0)) ants.plot(btp)
fixedImage = ants.image_read( '../mmwhs/CT_test/205_5/ct-image_crop_man_reg_resize/ct_train_1013_image.nii.gz' ) fixedMask = ants.image_read( '../mmwhs/CT_test/205_5/ct-label_crop_man_reg_resize/ct_train_1013_label.nii.gz' ) movingImage = ants.image_read( '../mmwhs/CT_test/205_5/ct-image_crop_man_reg_resize/ct_train_1014_image.nii.gz' ) movingMask = ants.image_read( '../mmwhs/CT_test/205_5/ct-label_crop_man_reg_resize/ct_train_1014_label.nii.gz' ) # Plot the fixed image/mask ants.plot(fixedImage, overlay=fixedMask, overlay_cmap="viridis", alpha=0.9) # Plot the moving image/mask ants.plot(movingImage, overlay=movingMask, overlay_cmap="viridis", alpha=0.9) ####### # # Perform registration with no mask # outputDirectory = './OutputNoMaskANTsPy/' if not os.path.isdir(outputDirectory): os.mkdir(outputDirectory) outputPrefix = outputDirectory + 'antsr'
import ants import os import glob dataDirectory = './' populationFiles = glob.glob( dataDirectory + "OASIS*Slice121.nii.gz" ) population = list() for i in range( len( populationFiles ) ): population.append( ants.image_read( populationFiles[i], dimension = 2 ) ) btp = ants.build_template( initialTemplate = None, image_list = population, iterations = 4, gradient_step = 0.2, verbose = True, syn_metric = 'CC', reg_iterations = ( 100, 70, 50, 0 ) ) ants.plot( btp )
def load_prereg(experiment, file, modality, condition, prefix, disk, Fdata): #=============================================================================== """ This function loads prereg data in ants and also loads trace and coord data, and plots output. Inputs: experiment (str): experiment subfolder name file (str): fish name modality (str): imaging modality condition (str): imaging condition prefix (str): genotype, if None no genotype, if 'Yes' genotype is added disk (str): path to mean images Fdata (str): path to trace and coords data Returns: f (ants image): image stack to register Fish (dict): dictionary containing cell and trace data meanimg_fold (list): list containing the folder with the image tif """ import numpy as np import os #Find fish image #-------------------------------------------------------- img_type = adfn.return_files(disk + 'Project/', file + os.sep + modality + os.sep, '**')[0] meanimg_fold = adfn.return_files( disk + 'Project/', file + os.sep + modality + os.sep + img_type, '*' + condition + '*meanimgstack*') num = meanimg_fold[0][meanimg_fold[0].find(modality) - 3:meanimg_fold[0].find(modality) - 1] dpf = meanimg_fold[0][meanimg_fold[0].find('dpf') - 1:meanimg_fold[0].find('dpf') + 3] if prefix == 'Yes': pref = file[file.find(modality) - 4:file[0].find(modality) - 2] else: pref = '' #Find coords and trace files #-------------------------------------------------------- name_list = [ '*_realcoord.npy', '*_realtrace.npy', '*_binarised.npy', '*_deltaff.npy' ] dict_list = ['coord', 'trace', 'bind', 'dff'] Fish = {} def grab(Fdata, experiment, condition, pref, number, age, name): #out = adfn.return_files(Fdata, experiment, '*' + experiment + pref + '-' + number + '*' + age + '*' + condition + name out = adfn.return_files( Fdata, 'PTZ-WILDTYPE-CCM/comb_2/', '*' + 'PTZ-WILDTYPE' + pref + '-' + number + '*' + age + '*' + condition + name) if len(out) > 1: print('More than one file found - check list length') return () if len(out) < 1: print('No files found found - check list length') return () return (out) for i, nom in enumerate(name_list): Fish.update({ dict_list[i]: np.load( grab(Fdata, experiment, condition, pref, num, dpf, nom)[0]) }) # Visualise fish #--------------------------------------------------------------------------- f = ants.image_read(disk + 'Project/' + file + os.sep + modality + os.sep + img_type + os.sep + meanimg_fold[0]) f.set_spacing([.3, .3, 15.]) f.set_direction(np.array([[-1., 0., 0.], [0., 1., 0.], [0., 0., 1.]])) ants.plot(f, axis=2, nslices=5, slices=np.arange(0, 5, 1), figsize=10) savename = adfn.save_name( grab(Fdata, experiment, condition, pref, num, dpf, nom)[0]) return (f, Fish, meanimg_fold, savename)
import ants import os # Read in the images dataDirectory = './data/' fixedImageFile = dataDirectory + 'chalf.nii.gz' fixedImage = ants.image_read( fixedImageFile, dimension = 2 ) movingImageFile = dataDirectory + 'c.nii.gz' movingImage = ants.image_read( movingImageFile, dimension = 2 ) # Plot the fixed and moving images ants.plot( movingImage, overlay = fixedImage, overlay_cmap = "viridis", alpha = 0.9 ) ####### # # Perform registration # outputDirectory = './OutputANTsPy/' if not os.path.isdir( outputDirectory ): os.mkdir( outputDirectory ) outputPrefix = outputDirectory + 'antsr' registration = ants.registration( fixed = fixedImage, moving = movingImage, type_of_transform = 'TVMSQC', grad_step = 2.0, verbose = True, outprefix = outputPrefix )
def test_plot_example(self): for img in self.imgs: ants.plot(img)
import ants import os # Read in the images dataDirectory = './data/' fixedImageFile = dataDirectory + 'chalf.nii.gz' fixedImage = ants.image_read(fixedImageFile, dimension=2) movingImageFile = dataDirectory + 'c.nii.gz' movingImage = ants.image_read(movingImageFile, dimension=2) # Plot the fixed and moving images ants.plot(movingImage, overlay=fixedImage, overlay_cmap="viridis", alpha=0.9) ####### # # Perform registration # outputDirectory = './OutputANTsPy/' if not os.path.isdir(outputDirectory): os.mkdir(outputDirectory) outputPrefix = outputDirectory + 'antsr' registration = ants.registration(fixed=fixedImage, moving=movingImage, type_of_transform='TVMSQC', grad_step=2.0, verbose=True,