def __relative_intensity(self):
        logger.info('computing relative intensity')
        print('computing relative intensity')
        if self._t1file != None and self._t2file != None:
            t1_n4_gm = self._t1_n4 * self._t1_n4.new_image_like(self._gm)
            t1_n4_wm = self._t1_n4 * self._t1_n4.new_image_like(self._wm)
            bg_t1 = peakfinder(t1_n4_gm, t1_n4_wm, 1, 99.5)
            t1_ri = compute_RI(self._t1_n4.numpy(), bg_t1, self._mask.numpy())
            tmp = self._t1_n4.new_image_like(t1_ri)
            self._ri = ants.smooth_image(tmp, sigma=3, FWHM=True)
            ants.image_write(
                self._ri,
                os.path.join(self._outputdir,
                             self._id + '_t1_relative_intensity.nii.gz'))

        if self._t1file != None and self._t2file == None:
            t1_n4_gm = self._t1_n4 * self._t1_n4.new_image_like(self._gm)
            t1_n4_wm = self._t1_n4 * self._t1_n4.new_image_like(self._wm)
            bg_t1 = peakfinder(t1_n4_gm, t1_n4_wm, 1, 99.5)
            t1_ri = compute_RI(self._t1_n4.numpy(), bg_t1, self._mask.numpy())
            tmp = self._t1_n4.new_image_like(t1_ri)
            self._ri = ants.smooth_image(tmp, sigma=3, FWHM=True)
            ants.image_write(
                self._ri,
                os.path.join(self._outputdir,
                             self._id + '_t1_relative_intensity.nii.gz'))
def Save_Images_Transformed(nameSubject, ImageToSave, isT1, *cont):
    #cwd = Path.cwd()
    #Sacamos nuestra ruta actual
    mod_path = Path(__file__).parent

    #A través de una ruta relativa buscamos la carpeta de almacenamiento de datos.
    pathOfData = str((mod_path / str("../Datos")))
    #Si data working no existe lo creamos
    if not (os.path.exists(str(pathOfData + "/DataWorking"))):
        os.mkdir(str(pathOfData + "/DataWorking"))

    pathOfData2 = str((mod_path / str("../Datos/DataWorking")))
    #Si el sujeto no ha sido todavía creado, lo creamos (La carpeta)
    if not (os.path.exists(str(pathOfData2 + "/" + nameSubject))):
        os.mkdir(str(pathOfData2 + "/" + nameSubject))
    #Si es la imagen transformada...
    if (isT1):
        #Creamos la ruta de donde guardarlo
        savePath = (mod_path /
                    str("../Datos/DataWorking/" + nameSubject + "/" +
                        nameSubject + "_t1.nii.gz")).resolve()
        #Lo guardamos, se hace el casteo para evitar errores con pathlib
        ants.image_write(ImageToSave, str(savePath))
    #Si no es la imagen, es la mascara de la lesión.
    else:
        savePath = (
            mod_path /
            str("../Datos/DataWorking/" + nameSubject + "/" + nameSubject +
                "_lesson[" + str(cont[0]) + "].nii.gz")).resolve()
        ants.image_write(ImageToSave, str(savePath))
 def crop(self, img_dir, label_dir):
     img_pix = ants.image_read(img_dir)
     img = img_pix.numpy()
     label_pix = ants.image_read(label_dir)
     label = label_pix.numpy()
     # label_nib = nib.load('Label/N001_Q_QSM_SyNAggro_moved_ROIs.nii.gz')
     # np_data = np.array(label_nib.dataobj)
     # # print(np.where(np_data>3))
     label_bounding_box_0 = np.where(label > 0)  # label =1 to 10
     label_bounding_box_11 = np.where(label < 11)
     print(label_bounding_box_11)
     x_min = np.min(label_bounding_box_0[0])
     y_min = np.min(label_bounding_box_0[1])
     z_min = np.min(label_bounding_box_0[2])
     x_max = np.max(label_bounding_box_0[0])
     y_max = np.max(label_bounding_box_0[1])
     z_max = np.max(label_bounding_box_0[2])
     print(x_min, y_min, z_min, x_max, y_max, z_max, img_dir)
     cropped_label = ants.crop_indices(label_pix, (x_min, y_min, z_min),
                                       (x_max, y_max, z_max))
     #  cropped = ants.crop_image(img,label,3)
     cropped_img = ants.crop_indices(img_pix, (x_min, y_min, z_min),
                                     (x_max, y_max, z_max))
     if not os.path.exists("data/QSM_masked_cropped/"):
         os.makedirs("data/QSM_masked_cropped/")
     if not os.path.exists("data/label_cropped/"):
         os.makedirs("data/label_cropped/")
     img_name = re.split(r'[/.]', img_dir)[2]
     label_name = re.split(r'[/.]', label_dir)[2]
     ants.image_write(
         cropped_img,
         "data/QSM_masked_cropped/" + img_name + "_cropped.nii.gz")
     ants.image_write(
         cropped_label,
         "data/label_cropped/" + label_name + "_cropped.nii.gz")
Example #4
0
    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()
Example #5
0
def robex(img, out_mask, skull_stripped=False):
    """
    perform skull-stripping on the registered image using the
    ROBEX algorithm

    Args:
        img (str): path to image to skull strip
        out_mask (str): path to output mask file
        skull_stripped (bool): return the mask
            AND the skull-stripped image [default = False]

    Returns:
        mask (ants.ANTsImage): mask/skull-stripped image
    """

    with warnings.catch_warnings():
        warnings.filterwarnings('ignore')
        _ = ROBEX.robex(img, outfile=out_mask)
    skull_stripped_img = ants.image_read(out_mask)
    mask = skull_stripped_img.get_mask(low_thresh=1)
    ants.image_write(mask, out_mask)
    if skull_stripped:
        # write the skull-stripped image to disk if desired (in addition to mask)
        dirname, base, _ = split_filename(out_mask)
        base = base.replace(
            'mask', 'stripped') if 'mask' in base else base + '_stripped'
        ants.image_write(skull_stripped_img,
                         os.path.join(dirname, base + '.nii.gz'))
    return mask
def reg(fix_path,fix_label_path,move_path,move_label_path,type='SyN'):
    #读取数据,格式为: ants.core.ants_image.ANTsImage
    fix_img = ants.image_read(fix_path)
    fix_label_img = ants.image_read(fix_label_path)
    move_img = ants.image_read(move_path)
    move_label_img = ants.image_read(move_label_path)	


    g1 = ants.iMath_grad( fix_img )
    g2 = ants.iMath_grad( move_img )


    demonsMetric = ['demons', g1, g2, 1, 1]
    ccMetric = ['CC', fix_img, move_img, 2, 4 ]
    metrics = list( )
    metrics.append( demonsMetric )

    #配准
    # outs = ants.registration(fix_img,move_img,type_of_transforme = 'Affine')
    # outs = ants.registration( fix_img, move_img, 'ElasticSyN',  multivariate_extras = metrics )  
    outs = ants.registration( fix_img, move_img, type)

    #获取配准后的数据,并保存
    reg_img = outs['warpedmovout']  
    save_path = './warp_image.nii.gz'
    ants.image_write(reg_img,save_path)

    #获取move到fix的转换矩阵;将其应用到 move_label上;插值方式选取 最近邻插值; 这个时候也对应的将label变换到 配准后的move图像上
    reg_label_img = ants.apply_transforms(fix_img ,move_label_img,transformlist= outs['fwdtransforms'],interpolator = 'nearestNeighbor')  
    save_label_path = './warp_label.nii.gz'
    ants.image_write(reg_label_img,save_label_path)
    return dice_compute(reg_label_img.numpy().astype(np.int32),fix_label_img.numpy().astype(np.int32),indexes=[5])
Example #7
0
    def identifyLeads(self, fileID, CTimaging, threshold, areas):
        """Estimate number of electrodes found using regionprops routine and generate a PointCloud for every lead.
         Details can be found in the book chapter by Husch et al (2015)"""

        detected_leads = []
        pca = PCA()
        for i, comp in enumerate(areas):
            X = np.multiply(comp.coords, np.tile(list(CTimaging.spacing), (len(comp.coords), 1)))
            n_samples = X.shape[0]
            X_transformed = pca.fit_transform(X)
            X_centered = X - np.mean(X, axis=0)
            cov_matrix = np.dot(X_centered.T, X_centered) / n_samples
            latent = pca.explained_variance_

            if self.debug:  # sanity check
                for latent_test, eigenvector in zip(latent, pca.components_):
                    print(np.dot(eigenvector.T, np.dot(cov_matrix, eigenvector)))

            if len(latent) < 3:
                continue

            latent = np.sqrt(latent) * 2
            lowerAxesLength = sorted(latent[1:3])
            if (latent[0] >
                    float(cfg['lead_detection']['PaCER']['lambda']) and latent[0] / np.mean(latent[1:3]) > 10
                    and lowerAxesLength[1] / (lowerAxesLength[0] + .001) < 8):
                detected_leads.append(comp)

        if not detected_leads:
            while threshold < 3000:
                print("Trying a higher threshold to ensure leads are detected.")
                leadpoint_cloudstruct = self.electrodeEstimation(fileID, threshold * 1.2)
                return leadpoint_cloudstruct
            else:
                raise Exception("\t\tEven w/ thresholds around 3000 HU, no leads were detected. Double-check input!")

        # TODO include transformation matrix from file if selected in options
        transformation_matrix = np.multiply(np.eye(3), [round(f, 1) for f in
                                                        CTimaging.spacing])  # transformation only necessary if selected in options; otherwise all remains in "AN space"
        leadpoint_cloudstruct = []  # initialise variable in workspace
        items = ['pixelList', 'elecMask', 'points', 'pixelValues']
        CTimagingData = CTimaging.numpy()  # get the shape of CT imaging to later fill it with content

        for i, leadID in enumerate(detected_leads):
            leadpoint_cloudstruct.append({k: [] for k in items})
            pixelList = leadID['coords']
            leadpoint_cloudstruct[i]['pixelList'] = pixelList
            leadpoint_cloudstruct[i]['points'] = pixelList @ abs(transformation_matrix[:3, :3])
            leadpoint_cloudstruct[i]['pixelValues'] = np.array([CTimagingData[tuple(pixelList[i])]
                                                                for i, k in enumerate(pixelList)])
            elecMask_temp = np.zeros(shape=CTimaging.shape)
            for x, y, z in pixelList:
                elecMask_temp[x, y, z] = 1

            leadpoint_cloudstruct[i]['elecMask'] = elecMask_temp
            filename_elecMask = os.path.join(os.path.split(fileID[0])[0], 'elecMask_no' + str(i) + '.nii')
            ants.image_write(image=CTimaging.new_image_like(elecMask_temp), filename=filename_elecMask)  # mask to NIFTI

        return leadpoint_cloudstruct, transformation_matrix
 def save_mask_of_targetpic(self, pic_dir):
     if not os.path.exists("data/mask/"):
         os.makedirs("data/mask/")
     file_name = re.split(r'[/.]', pic_dir)[-3]
     image = ants.image_read(pic_dir)
     mask = image.clone()
     mask[mask != 0] = 1
     ants.image_write(mask, "data/mask/mask_of_" + file_name + ".nii.gz")
def tract2standard(t_fn, t1_fn, fixed_fn, trans_type='SyNRA'):
    print(f'registration using ANTs {trans_type}...')
    fixed = ants.image_read(fixed_fn)
    moving = ants.image_read(t1_fn)

    # this is a workaround to emulate antsRegistrationSyNQuick.sh.
    # Unfortunately it is not possible to equally emulate the script.
    # There are differences in terms of parameters (shrink factor and num of
    # iterations) in the rigid and in the affine registration
    if trans_type == 'SyNRA':
        # values taken from https://github.com/ANTsX/ANTs/blob/952e7918b47385ebfb730f9c844977762b8437f8/Scripts/antsRegistrationSyNQuick.sh#L455
        # Notes:
        # 1. syn_metric and num_of_bins (syn_sampling) are the same as default:
        # "mattes" and 32 respectively
        # 2. the three values that configure the SyN[x,x,x] optimization are
        # respectively grad_step, flow_sigma, and total_sigma
        # 3. syn_iterations correspond to reg_iterations
        # 4. smoothing sigmas and shrink factor are automatically set inside the
        # function. As desired they are set to be: "3x2x1x0vox" and "8x4x2x1"
        # respectively
        mytx = ants.registration(fixed=fixed,
                                 moving=moving,
                                 type_of_transform=trans_type,
                                 reg_iterations=(100, 70, 50, 0),
                                 grad_step=0.1,
                                 flow_sigma=3,
                                 total_sigma=0)
    else:
        mytx = ants.registration(fixed=fixed,
                                 moving=moving,
                                 type_of_transform=trans_type)

    ants.image_write(mytx['warpedmovout'], f'{tmp_dir}/struct_warped.nii.gz')

    print('correcting warp to mrtrix convention...')
    os.system(f'warpinit {fixed_fn} {tmp_dir}/ID_warp[].nii.gz -force')

    for i in range(3):
        temp_warp = ants.image_read(f'{tmp_dir}/ID_warp{i}.nii.gz')
        temp_warp = ants.apply_transforms(fixed=moving,
                                          moving=temp_warp,
                                          transformlist=mytx['invtransforms'],
                                          whichtoinvert=[True, False],
                                          defaultvalue=2147483647)
        ants.image_write(temp_warp, f'{tmp_dir}/mrtrix_warp{i}.nii.gz')

    os.system(f'warpcorrect {tmp_dir}/mrtrix_warp[].nii.gz ' +
              f'{tmp_dir}/mrtrix_warp_cor.nii.gz ' +
              '-marker 2147483647 -tolerance 0.0001 -force')

    print('applaying warp to tractogram...')
    t_mni_fn = t_fn[:-4] + '_mni.tck'
    os.system(
        f'tcktransform {t_fn} {tmp_dir}/mrtrix_warp_cor.nii.gz {t_mni_fn} ' +
        '-force -nthreads 0')

    return t_mni_fn
def cde_mot_rigidreg(fixed,
                     images,
                     Fimg='..',
                     spacing=list([1.6, 1.6, 8]),
                     crop=False,
                     saveprog=False,
                     savesuff='',
                     savedir='.'):
    import ants
    import os
    import datetime
    import time

    print('>> Starting rigid registration <<')

    if type(fixed) == str: fi = ants.image_read(Fimg + os.sep + fixed)
    else: fi = fixed
    if crop: fi = ants.crop_indices(fi, [0, 0, 1], fi.shape)

    if savesuff: savesuff = '_' + savesuff

    mvd = []
    cnt = 0
    pct1 = len(images) / 100

    for i in images:
        cnt = cnt + 1

        if type(i) == str: img = ants.image_read(Fimg + os.sep + i)
        else: img = i

        img.set_spacing(spacing)
        if crop: img = ants.crop_indices(img, [0, 0, 1], img.shape)
        fi.set_spacing(spacing)

        # Actual ants registration step
        #-----------------------------------------------------------------------
        moved = ants.registration(fi, img, type_of_transform='QuickRigid')

        if saveprog:
            savename = savedir + os.sep + str(cnt).zfill(4) + savesuff + '.tif'
            ants.image_write(moved["warpedmovout"], savename)
            mvd.append(savename)

        else:
            mvd.append(moved["warpedmovout"])

        if cnt / pct1 % 5 == 0:  # < this doesn't work robustly
            ts = time.time()
            st = datetime.datetime.fromtimestamp(ts).strftime(
                '%Y-%m-%d %H:%M:%S')
            print('Completed ' + str((cnt) / pct1) + '% at ' + st)

    print('All done with rigid registration')
    if saveprog: print('The returned file contains tifs')

    return mvd
Example #11
0
def runeachsess(subj,ses):
        targ = os.path.join(derivatives,"sub-"+subj,"ses-"+ses,"anat") # find path to anat folder for this subject and this session
        fpaths = glob.glob(targ+"/*T2w.nii.gz") # find the T1
        fpaths = ''.join(fpaths)
        if len(fpaths) > 0:
            img = ants.image_read(fpaths)
            mask  = ants.get_mask(img)
            dn = ants.denoise_image(img,mask,noise_model='Rician')
            ants.image_write(dn,fpaths[0:-7]+'_dn.nii.gz',)
Example #12
0
def average_images():
    """Return the average of all images in list"""
    combined_image = ants.image_read("../DeformReg/DeformReg-1-50.nii.gz")

    for i in range(2, 22):
        image_name = "../DeformReg/DeformReg-" + str(i) + "-50.nii.gz"
        combined_image += ants.image_read(image_name)

    combined_image /= 21
    ants.image_write("ants_average_template.nii.gz")
Example #13
0
    def create_brainmask(input_folder, subj, registered_images):
        """this function import antspynet in order to obtain a probabilistic brain mask for the T1 imaging"""
        import ants, antspynet
        filename_brainmask = os.path.join(input_folder, 'brainmask_T1.nii')

        brainmask = antspynet.brain_extraction(image=registered_images,
                                               verbose=False)
        ants.image_write(image=brainmask, filename=filename_brainmask)

        return (filename_brainmask, subj)
Example #14
0
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)))
Example #15
0
 def __init__(self,
              image_fixed='path',
              atlas_template_moved='path',
              atlas_label_moved='path',
              output_template_name='path',
              output_label_name='path',
              interpolator="enumerate(('linear',\
                                       'nearestNeighbor',\
                                       'multiLabel',\
                                       'genericlabel',\
                                       'gaussian',\
                                       'bSpline',\
                                       'cosineWindowedSinc',\
                                       'welchWindowedSinc',\
                                       'hammingWindowedSinc',\
                                       'lanczosWindowedSinc'))",
              transform="enumerate(('Translation',\
                                    'Rigid',\
                                    'Similarity',\
                                    'QuickRigid',\
                                    'DenseRigid',\
                                    'BOLDRigid',\
                                    'Affine',\
                                    'AffineFast',\
                                    'BOLDAffine',\
                                    'TRSAA',\
                                    'ElasticSyN',\
                                    'SyN',\
                                    'SyNRA',\
                                    'SyNOnly',\
                                    'SyNCC',\
                                    'SyNabp',\
                                    'SyNBold',\
                                    'SyNBoldAff',\
                                    'SyNAggro',\
                                    'TVMSQ',\
                                    'TVMSQC'))"):
     import ants
     img_fi = ants.image_read(image_fixed)
     atlas_temp_mo = ants.image_read(atlas_template_moved)
     atlas_lab_mo = ants.image_read(atlas_label_moved)
     warpedmoveout = ants.registration(fixed=img_fi,
                                       moving=atlas_temp_mo,
                                       type_of_transform=transform)
     imagetransformed = ants.apply_transforms(
         fixed=warpedmoveout['warpedmovout'],
         moving=atlas_lab_mo,
         transformlist=warpedmoveout['fwdtransforms'],
         interpolator=interpolator)
     ants.image_write(warpedmoveout['warpedmovout'], output_template_name)
     ants.image_write(imagetransformed, output_label_name)
     self.temp_reg = output_template_name
     self.lab_reg = output_label_name
Example #16
0
def affine_registration():
    """Affinely register each image to the fixed image (21)"""
    fixed_image = ants.image_read("../KKI2009-ALL-MPRAGE/KKI2009-21-MPRAGE.nii.gz")

    for i in range(1, 21):
        moving_image = ants.image_read("../KKI2009-ALL-MPRAGE/KKI2009-" + str(i) + "-MPRAGE.nii.gz")
        after_reg = ants.registration(fixed=fixed_image,
                                    moving=moving_image,
                                    type_of_transform='Affine',
                                    aff_metric='meansquares')
        ants.image_write(after_reg["warpedmovout"],
                        "../AffineReg/AntsAffineReg-" + str(i) + "-to-21.nii.gz")
Example #17
0
 def crop_onpic(self, img_dir, label_dir, lowerind, upperind, path):
     img_pix = ants.image_read(img_dir)
     label_pix = ants.image_read(label_dir)
     cropped_img = ants.crop_indices(img_pix, lowerind, upperind)
     cropped_label = ants.crop_indices(label_pix, lowerind, upperind)
     img_name = re.split(r'[/.]', img_dir)[-3]
     label_name = re.split(r'[/.]', label_dir)[-3]
     ants.image_write(
         cropped_img,
         path + "QSM_masked_cropped/" + img_name + "_cropped.nii.gz")
     ants.image_write(
         cropped_label,
         path + "label_cropped/" + label_name + "_cropped.nii.gz")
Example #18
0
def evaluate_test_subject(scan_path: str, scan_name: str, options: dict,
                          model):
    # Read the image to analize:
    scan = ants.image_read(os.path.join(scan_path, scan_name + ".nii.gz"))
    scan_np = scan.numpy()

    # define the torch.device
    device = torch.device('cuda') if options['gpu_use'] else torch.device(
        'cpu')

    # Create the patches of the image to evaluate
    infer_patches, coordenates = get_inference_patches(
        scan_path=scan_path,
        input_data=[scan_name + "_norm.nii.gz"],
        roi=scan_name + "_ROI.nii.gz",
        patch_shape=options['patch_size'],
        step=options['sampling_step'],
        normalize=options['normalize'])

    # Get the shape of the patches
    sh = infer_patches.shape
    segmentation_pred = np.zeros((sh[0], 4, sh[2], sh[3], sh[4]))
    batch_size = options['batch_size']

    # model Evaluation
    model.eval()
    b = 0
    with torch.no_grad():
        for b in range(0, len(segmentation_pred), batch_size):
            x = torch.tensor(infer_patches[b:b + batch_size]).to(device)
            pred = model(x)
            # save the result back from GPU to CPU --> numpy
            segmentation_pred[b:b + batch_size] = pred.cpu().numpy()

    # reconstruct image takes the inferred patches, the patches coordenates and the image size as inputs
    all_probs = np.zeros(scan_np.shape + (4, ))
    for i in range(4):
        all_probs[:, :, :, i] = reconstruct_image(segmentation_pred[:, i],
                                                  coordenates, scan.shape)

    segmented = np.argmax(all_probs, axis=3).astype(np.uint8)

    # Create a nifti image
    segm_img = ants.from_numpy(segmented)
    segm_img = ants.copy_image_info(scan, segm_img)

    # Save the segmentation mask
    output_name = os.path.join(scan_path, scan_name + '_result.nii.gz')
    ants.image_write(segm_img, output_name)

    return segm_img
def main(inputpath: str, outdir: str):

    tmpdir = "/tmp"

    ventricledistmap = sitk.ReadImage("/media/yannick/MANAGE/BraTS20/ventricle_distancemap.nii.gz")

    # create output directory, if it does not already exist
    if not os.path.isdir(outdir):
        os.makedirs(outdir, exist_ok=True)

    # get patient directories
    patdirs = [elem for elem in os.listdir(inputpath) if os.path.isdir(os.path.join(inputpath, elem))]

    skippedlist = []

    for patdir in tqdm(patdirs):
        currpatdir = os.path.join(inputpath, patdir)

        caseid = ('_').join([patdir, tp])
            t1_patfile = os.path.join(currpatdir, "T1_r2s_bet-biascorr.nii.gz")
            if not os.path.isfile(t1_patfile) or os.path.isfile(os.path.join(outdir, caseid + "_t1_atlasspace.nii.gz")):
                print("Skipped " + str(caseid))
                continue

            else:
                fi = ants.image_read(t1_patfile)
                mi = ants.image_read(atlaspath)
                try:
                    tx = ants.registration(fixed=fi, moving=mi, type_of_transform='SyN', verbose=False)


                    # save transform and warped images to output folder
                    shutil.copy(tx["fwdtransforms"][1], os.path.join(outdir, caseid + "_atlas_to_t1.mat"))
                    shutil.copy(tx["invtransforms"][0], os.path.join(outdir, caseid + "_t1_to_atlas.mat"))
                    ants.image_write(tx["warpedmovout"], os.path.join(outdir, caseid + "_atlas_t1space.nii.gz"))
                    ants.image_write(tx["warpedfixout"], os.path.join(outdir, caseid + "_t1_atlasspace.nii.gz"))

                    # delete temporary *.nii.gz and *.mat files
                    try:
                        niftitmp = glob(os.path.join(tmpdir, "*.nii.gz"))
                        mattmp = glob(os.path.join(tmpdir, "*.mat"))

                        [os.remove(elem) for elem in niftitmp]
                        [os.remove(elem) for elem in mattmp]
                    except:
                        pass

                except:
                    skippedlist.append(caseid)
                    print("Skipped " + str(caseid))
                    continue
    def __bias_correction(self):
        logger.info("performing N4 bias correction")
        print("performing N4 bias correction")
        if self._t1file != None and self._t2file != None:
            self._t1_n4 = ants.iMath(
                self._t1_reg['warpedmovout'].abp_n4(usen3=self._usen3),
                "Normalize") * 100
            self._t2_n4 = ants.iMath(self._t2_reg.abp_n4(usen3=self._usen3),
                                     "Normalize") * 100
            ants.image_write(
                self._t1_n4,
                os.path.join(self._outputdir, self._id + '_t1_final.nii.gz'))
            ants.image_write(
                self._t2_n4,
                os.path.join(self._outputdir, self._id + '_t2_final.nii.gz'))

        if self._t1file != None and self._t2file == None:
            self._t1_n4 = ants.iMath(
                self._t1_reg['warpedmovout'].abp_n4(usen3=self._usen3),
                "Normalize") * 100
            ants.image_write(
                self._t1_n4,
                os.path.join(self._outputdir, self._id + '_t1_final.nii.gz'))

        if self._t2file != None and self._t1file == None:
            self._t2_n4 = ants.iMath(
                self._t2_reg['warpedmovout'].abp_n4(usen3=self._usen3),
                "Normalize") * 100
            ants.image_write(
                self._t2_n4,
                os.path.join(self._outputdir, self._id + '_t2_final.nii.gz'))
def deformable_registration(indir,aff_template,outdir):
    """

    """
    fixed_image = ants.image_read(aff_template)
    for subdir,directory,files in os.walk(indir):
        for i,fname in enumerate(files):
            file = subdir+'/'+fname
            print(file)
            moving_image = ants.image_read(file)
            transform = ants.registration(fixed_image,moving_image,\
                                    'SyNOnly',reg_iterations=(60,40,0))
            reg_img = ants.apply_transforms(fixed_image,moving_image,transform['fwdtransforms'])
            ants.image_write(reg_img,outdir+'/'+fname)
def deformable_registration(threet,sevent,fname):
    """
    :param threeT: String path Input file for 3T
    :param sevenT: String path Input file for 7T
    :param fname: String path 7T to 3T registered image
    return none
    """
    fixed_image = ants.image_read(threet)
    moving_image = ants.image_read(sevent)

    transform = ants.registration(fixed_image,moving_image,\
                                     'SyNOnly',reg_iterations=(60,40,0))
    reg_img = ants.apply_transforms(fixed_image,moving_image,transform['fwdtransforms'])
    ants.image_write(reg_img,fname)
def affine_registration(threet, sevent, fname):
    """
    :param threeT: String path Input file for 3T
    :param sevenT: String path Input file for 7T
    :param fname: String path 7T to 3T registered image
    return none
    """
    fixed_image = ants.image_read(threet)
    moving_image = ants.image_read(sevent)
    transform = ants.registration(fixed_image,moving_image,\
               'Affine',aff_metric='meansquares')
    affine_img = ants.apply_transforms(fixed_image, moving_image,
                                       transform['fwdtransforms'])
    ants.image_write(affine_img, fname)
Example #24
0
def rigid_registration(threet, sevent, mask, fname):
    """
    :param threeT: String path Input file for 3T
    :param sevenT: String path Input file for 7T
    :param fname: String path 7T to 3T registered image
    return none
    """
    fixed_image = ants.image_read(threet)
    moving_image = ants.image_read(sevent)
    transform = ants.registration(fixed_image,moving_image,\
               'Rigid',mask=mask,verbose=True)
    rigid_img = ants.apply_transforms(fixed_image, moving_image,
                                      transform['fwdtransforms'])
    ants.image_write(rigid_img, fname)
Example #25
0
    def apply_to_images(self,
                        fn,
                        modality,
                        image_type=None,
                        subjects='*',
                        out_suffix=''):
        for subject in self.subjects:
            in_file = self.get_modality(subject=subject, modality=modality)

            img = ants.image_read(in_file)
            img_proc = fn(img)

            out_file = in_file.replace('.nii.gz', '%s.nii.gz' % out_suffix)
            ants.image_write(img_proc, out_file)
Example #26
0
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)
Example #27
0
def main(args=None):
    args = arg_parser().parse_args(args)
    if args.verbosity == 1:
        level = logging.getLevelName('INFO')
    elif args.verbosity >= 2:
        level = logging.getLevelName('DEBUG')
    else:
        level = logging.getLevelName('WARNING')
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=level)
    logger = logging.getLogger(__name__)
    try:
        img_fns = glob_nii(args.img_dir)
        if not os.path.exists(args.output_dir):
            logger.info('Making Output Directory: {}'.format(args.output_dir))
            os.mkdir(args.output_dir)
        if args.template_dir is None:
            logger.info('Registering image to MNI template')
            template = ants.image_read(ants.get_ants_data('mni')).reorient_image2(args.orientation)
            orientation = args.orientation
        else:
            template_fns = glob_nii(args.template_dir)
            if len(template_fns) != len(img_fns):
                raise NormalizationError('If template images are provided, they must be in '
                                         'correspondence (i.e., equal number) with the source images')
        for i, img in enumerate(img_fns):
            _, base, _ = split_filename(img)
            logger.info('Registering image to template: {} ({:d}/{:d})'.format(base, i+1, len(img_fns)))
            if args.template_dir is not None:
                template = ants.image_read(template_fns[i])
                orientation = template.orientation if hasattr(template, 'orientation') else None
            input_img = ants.image_read(img)
            input_img = input_img.reorient_image2(orientation) if orientation is not None else input_img
            if not args.no_rigid:
                logger.info('Starting rigid registration: {} ({:d}/{:d})'.format(base, i+1, len(img_fns)))
                mytx = ants.registration(fixed=template, moving=input_img, type_of_transform="Rigid")
                tx = mytx['fwdtransforms'][0]
            else:
                tx = None
            logger.info('Starting {} registration: {} ({:d}/{:d})'.format(args.registration, base, i+1, len(img_fns)))
            mytx = ants.registration(fixed=template, moving=input_img, initial_transform=tx, type_of_transform=args.registration)
            logger.debug(mytx)
            moved = ants.apply_transforms(template, input_img, mytx['fwdtransforms'], interpolator='bSpline')
            registered = os.path.join(args.output_dir, base + '_reg.nii.gz')
            ants.image_write(moved, registered)
        return 0
    except Exception as e:
        logger.exception(e)
        return 1
def affine_registration(indir,outdir):
    """

    """
    for subdir,directory,files in os.walk(indir):
        for i,fname in enumerate(files):
            file = subdir+'/'+fname
            print(file)
            if(i==0):
                fixed_image = ants.image_read(file)
            else:
                moving_image = ants.image_read(file)
                transform = ants.registration(fixed_image,moving_image,\
                                    'Affine',aff_metric='meansquares')
                affine_img = ants.apply_transforms(fixed_image,moving_image,transform['fwdtransforms'])
                ants.image_write(affine_img,outdir+'/'+fname)
Example #29
0
def deformable_registration():
    """Deformably register each image to the fixed image (21) with Demons algo"""
    fixed_image = ants.image_read("../AffineReg/ants-affine-template.nii.gz")
    iterations = [25, 50]
    for iteration in iterations:
        for i in range(1, 21):
            moving_image = ants.image_read("../AffineReg/AntsAffineReg-" +
                                           str(i) + "-to21.nii.gzz")
            after_reg = ants.registration(fixed=fixed_image,
                                          moving=moving_image,
                                          type_of_transform='SyN',
                                          aff_metric='meansquares',
                                          syn_metric='demons',
                                          reg_iterations=[iteration])
            ants.image_write(
                after_reg["warpedmovout"], "../DeformReg/AntsDeformReg-" +
                str(i) + "-" + str(iteration) + ".nii.gz")
    def __gradient_magnitude(self):
        logger.info("computing gradient magnitude")
        print("computing gradient magnitude")
        if self._t1file != None and self._t2file != None:
            self._grad_t1 = ants.iMath(self._t1_n4, "Grad", 1)
            # self._grad_t2 = ants.iMath(self._t2_n4, "Grad", 1)
            ants.image_write(
                self._grad_t1,
                os.path.join(self._outputdir,
                             self._id + '_t1_gradient_magnitude.nii.gz'))
            # ants.image_write( self._grad_t1, os.path.join(self._outputdir, self._id+'_t2_gradient_magnitude.nii.gz'))

        if self._t1file != None and self._t2file == None:
            self._grad_t1 = ants.iMath(self._t1_n4, "Grad", 1)
            ants.image_write(
                self._grad_t1,
                os.path.join(self._outputdir,
                             self._id + '_t1_gradient_magnitude.nii.gz'))
Example #31
0
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 )

ants.image_write( registration['warpedmovout'], outputPrefix + "Warped.nii.gz" )
ants.image_write( registration['warpedfixout'], outputPrefix + "InverseWarped.nii.gz" )

# Plot the moving and warped fixed image
ants.plot( movingImage, overlay = registration['warpedfixout'], overlay_cmap = "viridis", alpha = 0.9 )
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'] ) ):
  ants.image_write( atroposResults['probabilityimages'][i],
    outputPrefix + "AtroposSegmentationProbability" + str( i ) + ".nii.gz" )