def test_from_numpy(self): self.setUp() # no physical space info for arr in self.arrs: img = ants.from_numpy(arr) self.assertTrue(img.dimension, arr.ndim) self.assertTrue(img.shape, arr.shape) self.assertTrue(img.dtype, arr.dtype.name) nptest.assert_allclose(img.numpy(), arr) new_origin = tuple([6.9] * arr.ndim) new_spacing = tuple([3.6] * arr.ndim) new_direction = np.eye(arr.ndim) * 9.6 img2 = ants.from_numpy(arr, origin=new_origin, spacing=new_spacing, direction=new_direction) self.assertEqual(img2.origin, new_origin) self.assertEqual(img2.spacing, new_spacing) nptest.assert_allclose(img2.direction, new_direction) # test with components arr2d_components = np.random.randn(69, 70, 4).astype('float32') img = ants.from_numpy(arr2d_components, has_components=True) self.assertEqual(img.components, arr2d_components.shape[-1]) nptest.assert_allclose(arr2d_components, img.numpy())
def antspy_regi(fixed, moving, drift_corr, metric='mattes', reg_iterations=(40,20,0), aff_iterations=(2100,1200,1200,10), aff_shrink_factors=(6,4,2,1), aff_smoothing_sigmas=(3,2,1,0), grad_step=0.2, flow_sigma=3, total_sigma=0, aff_sampling=32, syn_sampling=32): """claculate drift of image from ref using Antspy with provided drift_corr""" try: fixed= ants.from_numpy(np.float32(fixed)) except: pass try: moving= ants.from_numpy(np.float32(moving)) except: pass shift = ants.registration(fixed, moving, type_of_transform=drift_corr, aff_metric=metric, syn_metric=metric, reg_iterations=(reg_iterations[0],reg_iterations[1],reg_iterations[2]), aff_iterations=(aff_iterations[0],aff_iterations[1],aff_iterations[2],aff_iterations[3]), aff_shrink_factors=(aff_shrink_factors[0],aff_shrink_factors[1],aff_shrink_factors[2],aff_shrink_factors[3]), aff_smoothing_sigmas=(aff_smoothing_sigmas[0],aff_smoothing_sigmas[1],aff_smoothing_sigmas[2],aff_smoothing_sigmas[3]), grad_step=grad_step, flow_sigma=flow_sigma, total_sigma=total_sigma, aff_sampling=aff_sampling, syn_sampling=syn_sampling) print(shift['fwdtransforms']) return shift
def planewise_affine(fixed, moving, return_transforms=False): zshift = get_zshift(fixed, moving) fixed = to_numpy(fixed) moving = to_numpy(moving) size_z = fixed.shape[0] warped = np.zeros_like(fixed) transforms = [None]*size_z for z in prog_percent(list(range(max((0, -zshift)), min((size_z, -zshift + size_z))))): mov = ants.from_numpy(moving[z + zshift].swapaxes(0, 1)) fix = ants.from_numpy(fixed[z].swapaxes(0, 1)) res = ants.registration(mov, fix, type_of_transform='Affine', reg_iterations=[500, 500, 500], grad_step=.1, verbose=True) t = ants.read_transform(res['fwdtransforms'][0]) transforms[z] = t trans = ants.apply_ants_transform_to_image(t, mov, fix) warped[z] = trans.numpy().swapaxes(0, 1) if return_transforms: return warped, (transforms, zshift) return warped
def transformImage(image, reference, transformDirectory, sink=None, invert=False, interpolation='bspline'): """Transform a raw data set to reference using the ANTs alignment results Arguments: source (str or array): image source to be transformed reference (str or array): fixed image from transform transformDirectory (str): Directory containing ANTS transform parameters sink (str or None): image sink to save transformed image to. interpolation (str): ANTS interpolator to use for generating image. Returns: array or str: file name of the transformed data. If sink is None, return array """ log.info('transforming image with ' + transformDirectory) log.info('invert: {}'.format(invert)) # get image and tranform im = ants.from_numpy(io.readData(image).astype('float32')) ref = ants.from_numpy(io.readData(reference).astype('float32')) composite_trans = _compose_transforms(transformDirectory, invert=invert) # apply transforms res = composite_trans.apply_to_image(im, ref, interpolation=interpolation) # output if isinstance(sink, str): return io.writeData(sink, res.numpy()) else: return res.numpy()
def main(args): logfile = args['logfile'] save_directory = args['save_directory'] warp_directory = args['warp_directory'] fixed_path = args['fixed_path'] fixed_fly = args['fixed_fly'] fixed_resolution = args['fixed_resolution'] moving_path = args['moving_path'] moving_fly = args['moving_fly'] moving_resolution = args['moving_resolution'] ################### ### Load Brains ### ################### fixed = np.asarray(nib.load(fixed_path).get_data().squeeze(), dtype='float32') fixed = ants.from_numpy(fixed) fixed.set_spacing(fixed_resolution) fixed = ants.resample_image(fixed, (256, 128, 49), 1, 0) moving = np.asarray(nib.load(moving_path).get_data().squeeze(), dtype='float32') moving = ants.from_numpy(moving) moving.set_spacing(moving_resolution) ########################### ### Organize Transforms ### ########################### affine_file = os.listdir( os.path.join(warp_directory, 'func-to-anat_fwdtransforms_lowres'))[0] affine_path = os.path.join(warp_directory, 'func-to-anat_fwdtransforms_lowres', affine_file) syn_files = os.listdir( os.path.join(warp_directory, 'anat-to-meanbrain_fwdtransforms_lowres')) syn_linear_path = os.path.join(warp_directory, 'anat-to-meanbrain_fwdtransforms_lowres', [x for x in syn_files if '.mat' in x][0]) syn_nonlinear_path = os.path.join( warp_directory, 'anat-to-meanbrain_fwdtransforms_lowres', [x for x in syn_files if '.nii.gz' in x][0]) transforms = [affine_path, syn_linear_path, syn_nonlinear_path] ######################## ### Apply Transforms ### ######################## moco = ants.apply_transforms(fixed, moving, transforms, imagetype=3) ############ ### Save ### ############ save_file = os.path.join( save_directory, 'functional_channel_2_moco_zscore_highpass_warped.nii' ) #<--------------------------------------- nib.Nifti1Image(moco.numpy(), np.eye(4)).to_filename(save_file)
def antspy_drift(fixed, moving, shift, check=True): if check == True: try: fixed = fixed.numpy() except: pass try: moving = moving.numpy() except: pass check_ref = fixed.copy() pre_check = check_similarity(check_ref, moving) try: fixed = ants.from_numpy(np.float32(fixed)) except: pass try: moving = ants.from_numpy(np.float32(moving)) except: pass """shifts image based on ref and provided shift""" vol_shifted = ants.apply_transforms(fixed, moving, transformlist=shift).numpy() if check == True: post_check = check_similarity(check_ref, vol_shifted) print('similarity_check', pre_check, 'improved to', post_check) if (pre_check - post_check) > 0.1: vol_shifted = moving.numpy() print( 'similarity_check was smaller after shift, so shift was ignored:', pre_check, '>>', post_check) return vol_shifted
def rigid_registration(stack, fixed_index, moving_indices, out_file, spacing): fixed = stack[fixed_index, :, :, :].astype(np.float32) moving = stack[moving_indices, :, :, :].astype(np.float32) shape = (moving.shape[0] + 1, moving.shape[1], moving.shape[2], moving.shape[3]) rigid = np.empty(shape, dtype=np.float32) rigid[0, :, :, :] = fixed fixed = ants.from_numpy(fixed) start = time.time() for timepoint in range(moving.shape[0] - 1): print('Iteration: ', timepoint) moving_im = moving[timepoint, :, :, :] moving_im = ants.from_numpy(moving_im) rigid_transform = ants.registration(fixed=fixed, moving=moving_im, type_of_transform='Rigid') transformed_image = rigid_transform['warpedmovout'] im = transformed_image.numpy() rigid[timepoint + 1, :, :, :] = im end = time.time() print('time: ', end - start) save(out_file, rigid, spacing) return rigid
def align_anat(fixed_path, moving_path, save_dir, type_of_transform, resolution, mirror): ### Load fixed brain fixed = load_numpy_brain(fixed_path) fixed = ants.from_numpy(fixed) fixed.set_spacing(resolution) ### Load moving brain moving = load_numpy_brain(moving_path) if mirror: moving = moving[::-1, :, :] moving = ants.from_numpy(moving) moving.set_spacing(resolution) ### Align with stderr_redirected( ): # to prevent itk gaussian error infinite printing moco = ants.registration(fixed, moving, type_of_transform=type_of_transform) ### Save fixed_fly = fixed_path.split('/')[-1].split('.')[0] moving_fly = moving_path.split('/')[-1].split('.')[0] if mirror: save_file = os.path.join(save_dir, moving_fly + '_m' + '-to-' + fixed_fly) else: save_file = os.path.join(save_dir, moving_fly + '-to-' + fixed_fly) save_file += '.nii' nib.Nifti1Image(moco['warpedmovout'].numpy(), np.eye(4)).to_filename(save_file)
def test_image_header_info(self): # def image_header_info(filename): for img in self.imgs: img.set_spacing([6.9] * img.dimension) img.set_origin([3.6] * img.dimension) tmpfile = mktemp(suffix='.nii.gz') ants.image_write(img, tmpfile) info = ants.image_header_info(tmpfile) self.assertEqual(info['dimensions'], img.shape) nptest.assert_allclose(info['direction'], img.direction) self.assertEqual(info['nComponents'], img.components) self.assertEqual(info['nDimensions'], img.dimension) self.assertEqual(info['origin'], img.origin) self.assertEqual(info['pixeltype'], img.pixeltype) self.assertEqual(info['pixelclass'], 'vector' if img.has_components else 'scalar') self.assertEqual(info['spacing'], img.spacing) try: os.remove(tmpfile) except: pass # test on vector image img = ants.from_numpy(np.random.randn(69, 60, 4).astype('float32'), has_components=True) tmpfile = mktemp(suffix='.nii.gz') ants.image_write(img, tmpfile) info = ants.image_header_info(tmpfile) self.assertEqual(info['dimensions'], img.shape) nptest.assert_allclose(info['direction'], img.direction) self.assertEqual(info['nComponents'], img.components) self.assertEqual(info['nDimensions'], img.dimension) self.assertEqual(info['origin'], img.origin) self.assertEqual(info['pixeltype'], img.pixeltype) self.assertEqual(info['pixelclass'], 'vector' if img.has_components else 'scalar') self.assertEqual(info['spacing'], img.spacing) img = ants.from_numpy(np.random.randn(69, 60, 70, 2).astype('float32'), has_components=True) tmpfile = mktemp(suffix='.nii.gz') ants.image_write(img, tmpfile) info = ants.image_header_info(tmpfile) self.assertEqual(info['dimensions'], img.shape) nptest.assert_allclose(info['direction'], img.direction) self.assertEqual(info['nComponents'], img.components) self.assertEqual(info['nDimensions'], img.dimension) self.assertEqual(info['origin'], img.origin) self.assertEqual(info['pixeltype'], img.pixeltype) self.assertEqual(info['pixelclass'], 'vector' if img.has_components else 'scalar') self.assertEqual(info['spacing'], img.spacing) # non-existant file with self.assertRaises(Exception): tmpfile = mktemp(suffix='.nii.gz') ants.image_header_info(tmpfile)
def motion_correction(brain_master, brain_slave, motcorr_directory, printlog, meanbrain, suffix=''): motCorr_brain_master = [] motCorr_brain_slave = [] durations = [] transform_matrix = [] for i in range(np.shape(brain_master)[-1]): #printlog('Aligning brain volume {}'.format(i)) t0 = time() #First, align given master volume to master meanbrain with stderr_redirected(): # to prevent dumb itk gaussian error bullshit infinite printing # note meanbrain is already an ants object motCorr_vol = ants.registration(meanbrain, ants.from_numpy(brain_master[:,:,:,i]), type_of_transform='SyN') motCorr_brain_master.append(motCorr_vol['warpedmovout'].numpy()) transformlist = motCorr_vol['fwdtransforms'] #Use warp parameters on slave volume if provided if brain_slave: motCorr_brain_slave.append(ants.apply_transforms(meanbrain,ants.from_numpy(brain_slave[:,:,:,i]),transformlist).numpy()) #Lets immediately grab the transform file because otherwise I think it is auto deleted due to "tmp" status...? #Indeed I think CentOS possibly perges /tmp pretty frequently #printlog('fwd_files: {}'.format(transformlist)) for x in transformlist: if '.mat' in x: temp = ants.read_transform(x) transform_matrix.append(temp.parameters) os.remove(x) #printlog('Deleted fwd: {}'.format(x)) # Delete invtransforms for /tmp directory size issue. note that .mat are shared, so only need to delete .nii.gz transformlist = motCorr_vol['invtransforms'] #printlog('inv_files: {}'.format(transformlist)) for x in transformlist: if '.mat' not in x: os.remove(x) #printlog('Deleted inv: {}'.format(x)) print(F"[{i+1}]") #IMPORTANT FOR COMMUNICATION WITH DATAFLOW MAIN sys.stdout.flush() # Save motcorr brains save_motCorr_brain(motCorr_brain_master, motcorr_directory, suffix='red'+suffix) if brain_slave: save_motCorr_brain(motCorr_brain_slave, motcorr_directory, suffix='green'+suffix) # Save transforms transform_matrix = np.array(transform_matrix) save_file = os.path.join(motcorr_directory, 'motcorr_params{}'.format(suffix)) np.save(save_file,transform_matrix)
def to_ants(img): if type(img) == ants.core.ants_image.ANTsImage: return img if type(img) == np.ndarray: if len(img.shape) == 3: return ants.from_numpy(img.swapaxes(0, 2).astype(np.uint32)) elif len(img.shape) == 2: return ants.from_numpy(img.swapaxes(0, 1).astype(np.uint32)) raise ValueError('Cannot convert img')
def setUp(self): img2d = ants.image_read(ants.get_ants_data('r16')).clone('float') img3d = ants.image_read(ants.get_ants_data('mni')).clone('float') arr2d = np.random.randn(69,70).astype('float32') arr3d = np.random.randn(69,70,71).astype('float32') vecimg2d = ants.from_numpy(np.random.randn(69,70,4), has_components=True) vecimg3d = ants.from_numpy(np.random.randn(69,70,71,2), has_components=True) self.imgs = [img2d, img3d] self.arrs = [arr2d, arr3d] self.vecimgs = [vecimg2d, vecimg3d] self.pixeltypes = ['unsigned char', 'unsigned int', 'float']
def process_MSD(root, task='Heart2', num_surf=5): img_list, gt_list = get_MSD_list(root, task) save_dir = os.path.join(root, task) n = len(img_list) for i in range(n): print('Process img: {}'.format(img_list[i])) img = ants.image_read(img_list[i]) gt = ants.image_read(gt_list[i]) # iso-resample img_ = iso_resample(img, [1.5, 1.5, 1.5], islabel=False) gt_ = iso_resample(gt, [1.5, 1.5, 1.5], islabel=True) # crop img_np = img_.numpy() gt_np = gt_.numpy() img_np = crop(img_np) gt_np = crop(gt_np) # normal img_np = normalize(img_np) # sample surf init for j in tqdm(range(num_surf)): gt_dfm = elasticdeform.deform_random_grid(gt_np, 4, 4, 0) gt_dfm_smooth = mcubes.smooth_gaussian(gt_dfm, 1) v, e = mcubes.marching_cubes(gt_dfm_smooth, 0) mcubes.export_obj( v, e, os.path.join( save_dir, 'surfs_unaligned', '{:0>2d}_{:0>2d}surf_init.obj'.format(i + 1, j + 1))) # write image img_nii = ants.from_numpy(img_np, img_.origin, img_.spacing, img_.direction, img_.has_components, img_.is_rgb) gt_nii = ants.from_numpy(gt_np, gt_.origin, gt_.spacing, gt_.direction, gt_.has_components, gt_.is_rgb) ants.image_write( img_nii, os.path.join(save_dir, 'images', '{:0>2d}img.nii'.format(i + 1))) ants.image_write( gt_nii, os.path.join(save_dir, 'labels', '{:0>2d}gt.nii'.format(i + 1))) gt_smooth = mcubes.smooth_gaussian(gt_np, 1) v, e = mcubes.marching_cubes(gt_smooth, 0) mcubes.export_obj( v, e, os.path.join(save_dir, 'surfs_unaligned', '{:0>2d}surf.obj'.format(i + 1)))
def test_init_with_template(self): arr2d = np.abs(np.random.randn(*self.img2d.shape)) template2d = ants.from_numpy(arr2d) lbl_img2d = ants.LabelImage(label_image=self.img2d, label_info=self.info2d, template=template2d) arr3d = np.abs(np.random.randn(*self.img3d.shape)) template3d = ants.from_numpy(arr3d) lbl_img3d = ants.LabelImage(label_image=self.img3d, label_info=self.info3d, template=template3d)
def apply_ants_channels(ref, image, drift_corr, xy_pixel, z_pixel, ch_names, ref_ch=-1, metric='mattes', reg_iterations=(40,20,0), aff_iterations=(2100,1200,1200,10), aff_shrink_factors=(6,4,2,1), aff_smoothing_sigmas=(3,2,1,0), grad_step=0.2, flow_sigma=3, total_sigma=0, aff_sampling=32, syn_sampling=3, check_ch='', save=True, save_path='',save_file=''): """calculate and apply shift on both channels of image based on ref, which is dictionary of two channels. if save is True, save shifted channels individually with provided info""" for ch, value in ref.items(): try: ref[ch]= ants.from_numpy(np.float32(value)) except: pass for ch, value in image.items(): image[ch]= ants.from_numpy(np.float32(value)) shift = antspy_regi(ref[ch_names[ref_ch]], image[ch_names[ref_ch]], drift_corr, metric, reg_iterations=reg_iterations, aff_iterations=aff_iterations, aff_shrink_factors=aff_shrink_factors, aff_smoothing_sigmas=aff_smoothing_sigmas, grad_step=grad_step, flow_sigma=flow_sigma, total_sigma=total_sigma, aff_sampling=aff_sampling, syn_sampling=syn_sampling) shifted = image.copy() for ch, img in shifted.items(): shifted[ch]= antspy_drift(ref[ch],img,shift=shift['fwdtransforms'],check=False) if check_ch in image.keys(): check_ref = ref[check_ch].numpy() pre_check = check_similarity(check_ref, image[check_ch].numpy()) post_check = check_similarity(check_ref, shifted[check_ch]) print('similarity_check', pre_check, 'improved to', post_check) image = shifted if (pre_check - post_check) > 0.1: for ch, img in shifted.items(): image[ch] = img.numpy() print('similarity_check was smaller after shift, so shift was ignored:', pre_check, '>>', post_check) else: print(check_ch, 'not a recognized ch in image') image = shifted if save == True: for ch, img in image.items(): img_save = img_limits(image[ch]) save_name = str(save_path+drift_corr+'_'+ch+'_'+save_file) if '.tif' not in save_name: save_name += '.tif' save_image(save_name, img_save, xy_pixel=xy_pixel, z_pixel=z_pixel) return image, shift
def registration(reference, image, segmentation): import ants reference_as_ants = ants.from_numpy(reference) image_as_ants = ants.from_numpy(image) output = ants.registration(reference_as_ants, image_as_ants) registered_image = output.get("warpedmovout") segmentation_as_ants = ants.from_numpy(segmentation) registered_segmentation = ants.apply_transforms( reference_as_ants, segmentation_as_ants, output.get("fwdtransforms")) registered_segmentation = registered_segmentation.numpy() registered_segmentation[registered_segmentation > 0] = 1 return registered_image.numpy(), registered_segmentation
def alignData(fixedImage, movingImage, resultDirectory=None, type_of_transform='SyNRA', **kwargs): """Align images using elastix, estimates a transformation :math:`T:` fixed image :math:`\\rightarrow` moving image. Arguments: fixedImage (str): image source of the fixed image (typically the reference image) movingImage (str): image source of the moving image (typically the image to be registered) resultDirectory (str or None): result directory for transform parameters. None saves to bq3ddefault temp file transform: (str): type of transform to apply as defined in 'ants.registration' type_of_transform **kwargs: additional arguments to pass to 'ants.registration' Returns: str: path to elastix result directory """ log_parameters(fixedImage=fixedImage, movingImage=movingImage, resultDirectory=resultDirectory, type_of_transform=type_of_transform) # setup input mi = ants.from_numpy(io.readData(movingImage).astype('float32')) fi = ants.from_numpy(io.readData(fixedImage).astype('float32')) # setup output directory if not resultDirectory: tmp_folder = os.path.join(config.temp_dir, 'ANTs') resultDirectory = tmp_folder resultDirectory = resultDirectory + '/' if not resultDirectory.endswith( '/') else resultDirectory #make sure ends with '/' os.makedirs(resultDirectory, exist_ok=True) # run result = ants.registration(fi, mi, type_of_transform=type_of_transform, outprefix=resultDirectory, verbose=True, **kwargs) # save output io.writeData(os.path.join(resultDirectory, 'result.tif'), result['warpedmovout'].numpy()) # cleanup# if not resultDirectory: shutil.rmtree(tmp_folder) return resultDirectory
def test2(self): import ants import numpy as np rgb_img = ants.from_numpy(np.random.randint( 0, 255, (20, 20, 3)).astype('uint8'), is_rgb=True) vec_img = rgb_img.rgb_to_vector() print(ants.allclose(rgb_img, vec_img)) vec_img = ants.from_numpy(np.random.randint( 0, 255, (20, 20, 3)).astype('uint8'), has_components=True) rgb_img = vec_img.vector_to_rgb() print(ants.allclose(rgb_img, vec_img))
def registration(reference, image, segmentation): import ants reference_as_ants = ants.from_numpy(reference) image_as_ants = ants.from_numpy(image) #Rigid, Affine, Similarity, SyN output = ants.registration(reference_as_ants, image_as_ants, type_of_transform='SyN') registered_image = output.get("warpedmovout") segmentation_as_ants = ants.from_numpy(segmentation) registered_segmentation = ants.apply_transforms( reference_as_ants, segmentation_as_ants, output.get("fwdtransforms")) registered_segmentation = registered_segmentation.numpy() registered_segmentation[registered_segmentation > 0] = 1 return registered_image.numpy(), registered_segmentation
def pyAntsApp(reg, fixed_image, moving_image, output_filename): # moving_image = ants.image_read(moving_image) # fixed_image = ants.image_read(fixed_image) fixed_image = imread(fixed_image) moving_image = imread(moving_image) fixed_image = ants.from_numpy(fixed_image) moving_image = ants.from_numpy(moving_image) warped_moving_image = ants.apply_transforms(fixed=fixed_image, moving=moving_image, transformlist=reg['fwdtransforms']) # warped_moving_image.plot() # cv2.waitKey() assert output_filename.endswith('.npy') ants.image_write(warped_moving_image, output_filename) warped_moving_image_numpy = warped_moving_image.numpy() imsave(output_filename.replace('.npy', '.tif'), warped_moving_image_numpy)
def test_images_to_matrix(self): # def images_to_matrix(image_list, mask=None, sigma=None, epsilon=0): for img in self.imgs: mask = img > img.mean() imglist = [img.clone(), img.clone(), img.clone()] imgmat = ants.images_to_matrix(imglist, mask=mask) self.assertTrue(imgmat.shape[0] == len(imglist)) self.assertTrue(imgmat.shape[1] == (mask > 0).sum()) # go back to images imglist2 = ants.matrix_to_images(imgmat, mask) for i1, i2 in zip(imglist, imglist2): self.assertTrue(ants.image_physical_space_consistency(i1, i2)) nptest.assert_allclose(i1.numpy() * mask.numpy(), i2.numpy()) if img.dimension == 2: # with sigma mask = img > img.mean() imglist = [img.clone(), img.clone(), img.clone()] imgmat = ants.images_to_matrix(imglist, mask=mask, sigma=2.) # with no mask mask = img > img.mean() imglist = [img.clone(), img.clone(), img.clone()] imgmat = ants.images_to_matrix(imglist) # with mask of different shape s = [65] * img.dimension mask2 = ants.from_numpy(np.random.randn(*s)) mask2 = mask2 > mask2.mean() imgmat = ants.images_to_matrix(imglist, mask=mask2)
def add_3dvolume(self, volume, tag, global_step=None, walltime=None): filename = tag + "_" if global_step is None: filename += datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') else: filename += str(global_step) if isinstance(volume, torch.Tensor): volume = volume.detach().cpu().numpy() img = ants.from_numpy(volume) ants.image_write(img, os.path.join(self._log_dir, filename + ".nii.gz")) plugin_data = tf.SummaryMetadata.PluginData( plugin_name="tb_3d_volume_plugin", content=TextPluginData(version=0).SerializeToString()) metadata = tf.SummaryMetadata(plugin_data=plugin_data) tensor = TensorProto( dtype='DT_STRING', string_val=[filename.encode(encoding='utf_8')], tensor_shape=TensorShapeProto(dim=[TensorShapeProto.Dim(size=1)])) summary = summary_pb2.Summary(value=[ summary_pb2.Summary.Value( tag=tag, metadata=metadata, tensor=tensor) ]) self._file_writer.add_summary(summary, global_step=global_step, walltime=walltime) self._file_writer.flush()
def test_merge_channels(self): for img in self.imgs: imglist = [img.clone(), img.clone()] merged_img = ants.merge_channels(imglist) self.assertEqual(merged_img.shape, img.shape) self.assertEqual(merged_img.components, len(imglist)) nptest.assert_allclose(merged_img.numpy()[..., 0], imglist[0].numpy()) imglist = [img.clone(), img.clone(), img.clone(), img.clone()] merged_img = ants.merge_channels(imglist) self.assertEqual(merged_img.shape, img.shape) self.assertEqual(merged_img.components, len(imglist)) nptest.assert_allclose(merged_img.numpy()[..., 0], imglist[-1].numpy()) for comparr in self.comparrs: imglist = [ ants.from_numpy(comparr[..., i].copy()) for i in range(comparr.shape[-1]) ] merged_img = ants.merge_channels(imglist) for i in range(comparr.shape[-1]): nptest.assert_allclose(merged_img.numpy()[..., i], comparr[..., i])
def test_new_image_like(self): #self.setUp() for img in self.imgs: myarray = img.numpy() myarray *= 6.9 imgnew = img.new_image_like(myarray) # test physical space consistency self.assertTrue(ants.image_physical_space_consistency(img, imgnew)) # test data nptest.assert_allclose(myarray, imgnew.numpy()) nptest.assert_allclose(myarray, img.numpy()*6.9) # test exceptions with self.assertRaises(Exception): # not ndarray new_data = img.clone() img.new_image_like(new_data) with self.assertRaises(Exception): # wrong shape new_data = np.random.randn(69,12,21).astype('float32') img.new_image_like(new_data) with self.assertRaises(Exception): # wrong shape with components vecimg = ants.from_numpy(np.random.randn(69,12,3).astype('float32'), has_components=True) new_data = np.random.randn(69,12,4).astype('float32') vecimg.new_image_like(new_data)
def load_partial_brain(file, start, stop): brain = nib.load(file).dataobj[:, :, :, start:stop] brain = ants.from_numpy(np.asarray(np.squeeze(brain), 'float64')) # always keep 4 axes: if len(np.shape(brain)) == 3: brain = brain[:, :, :, np.newaxis] return brain
def np2ants(image, ants_params): image = np.squeeze(image) image = (image > 0.5).astype(np.float32) image = ants.from_numpy(image, origin=ants_params[0], spacing=ants_params[1], direction=ants_params[2]) return image
def standardize(item: NiftiImage, do_resolve=False, *args, **kwargs): "Standardize our custom itembase `NiftiImage` to have zero mean and unit std based on non-zero voxels only" arr = item.obj.numpy() arr_nonzero = arr[arr != 0] arr_nonzero = (arr_nonzero - arr_nonzero.mean()) / arr_nonzero.std() arr[arr != 0] = arr_nonzero / arr_nonzero.max() item.obj = ants.from_numpy(arr) return item
def align_volume(fixed, moving, vol): moving_vol = ants.from_numpy(moving[:,:,:,vol]) with stderr_redirected(): # to prevent dumb itk gaussian error bullshit infinite printing motCorr_vol = ants.registration(fixed, moving_vol, type_of_transform='SyN') return motCorr_vol
def mi_img(y_true, y_pred, mask=None, metric_type="MattesMutualInformation"): """Compute the mutual information (MI) between two images. Parameters ---------- y_true : np.array Image 1. Either (h, w) of (N, h, w). If (N, h, w), the decorator `multiple_images_decorator` takes care of the sample dimension. y_pred : np.array Image 2. Either (h, w) of (N, h, w). If (N, h, w), the decorator `multiple_images_decorator` takes care of the sample dimension. mask: np.array, optional Optional, can be specified to have the computation carried out on a precise area. metric_type: str, {'MattesMutualInformation', 'JointHistogramMutualInformation'} Type of mutual information computation. Returns ------- mi : float The mutual information (MI) metric. Similarity metric, the higher the more similar the images are. """ y_true_ants = ants.image_clone(ants.from_numpy(y_true), pixeltype="float") y_pred_ants = ants.image_clone(ants.from_numpy(y_pred), pixeltype="float") if mask is None: mi = ants.image_similarity(y_true_ants, y_pred_ants, metric_type=metric_type) else: mask_ants = ants.image_clone(ants.from_numpy(mask.astype(float)), pixeltype="float") mi = ants.image_similarity( y_true_ants, y_pred_ants, fixed_mask=mask_ants, moving_mask=mask_ants, metric_type=metric_type, ) return -mi
def binarize_mask(mask_path): """ :param mask: String path Input file for Slant seg file :return binarized antsImage """ mask = ants.image_read(mask_path) mask_np = mask.numpy() binary_mask = np.where(mask_np > 0, 0.0, 1.0) return ants.from_numpy(binary_mask)