Beispiel #1
0
def main(inputpath: str):

    tmpdir = "/tmp"

    # ventricledistmap = sitk.ReadImage("ventricle_distancemap.nii.gz")
    ventricledistpath = "/media/yannick/c4a7e8d3-9ac5-463f-b6e6-92e216ae6ac0/BRATS/BraTS2020/ventricle_distancemap.nii.gz"
    atlaspath = "/media/yannick/c4a7e8d3-9ac5-463f-b6e6-92e216ae6ac0/BRATS/BraTS2020/MNI152_T1_1mm_brain.nii.gz"

    t1suffix = "_t1.nii.gz"

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

    ventricledistmap = ants.image_read(ventricledistpath)

    skippedlist = []

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

        try:

            fi = ants.image_read(t1_patfile)
            mi = ants.image_read(atlaspath)

            tx = ants.registration(fixed=fi, moving=mi, type_of_transform='SyN', verbose=True)
            ventrdist_t1space = ants.apply_transforms(fi, ventricledistmap, tx["fwdtransforms"], interpolator='linear', imagetype=0,
                                                      whichtoinvert=None, compose=None, verbose=False)

            # save transform and warped images to output folder
            shutil.copy(tx["fwdtransforms"][1], os.path.join(currpatdir, "Atlas_to_t1.mat"))
            shutil.copy(tx["invtransforms"][0], os.path.join(currpatdir, "T1_to_atlas.mat"))
            ants.image_write(tx["warpedmovout"], os.path.join(currpatdir, "Atlas_t1space.nii.gz"))
            ants.image_write(tx["warpedfixout"], os.path.join(currpatdir, "T1_atlasspace.nii.gz"))
            ants.image_write(ventrdist_t1space, os.path.join(currpatdir, "ventricledistmap_t1space.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(patdir)
            print("Skipped " + str(patdir))
            continue

    print("###### COMPLETED ######")
    print("Skipped cases:")
    print(skippedlist)
Beispiel #2
0
    def _run_coregistration(self):
        img_reference = ants.image_read(self.dict_img[self.reference], reorient=True)

        # Register the reference to MNI, if needed
        if self.mni:
            print(f"[INFO] Registering to 1x1x1mm MNI space using ANTsPy")
            print(f"{self.reference} is used as reference")
            img_mni = ants.image_read(self.mni_path, reorient=True)
            reg = ants.registration(img_mni, img_reference, "Affine")
            img_reference = reg["warpedmovout"]
            self._save_scan(img_reference, f"{self.prefix}{self.reference}", self.coregistration_folder)
            reg_tomni = reg["fwdtransforms"]
            if not self.label is None:
                img_label = ants.image_read(self.label, reorient=True)
                warped_label = ants.apply_transforms(img_mni, img_label, reg_tomni, interpolator="nearestNeighbor")
                self._save_scan(warped_label, f"{self.prefix}Label", self.coregistration_folder)
        else:
            self._save_scan(img_reference, f"{self.prefix}{self.reference}", self.coregistration_folder)
            if not self.label is None:
                img_label = ants.image_read(self.label, reorient=True)
                self._save_scan(img_label, f"{self.prefix}Label", self.coregistration_folder)

        # Register the other scans, if needed
        modalities_toregister = list(self.modalities)
        modalities_toregister.remove(self.reference)
        for mod in modalities_toregister:
            if self.already_coregistered: 
                if self.mni: # if the scans are already co-registered we reuse the ref to MNI transformation
                    img_mod = ants.image_read(self.dict_img[mod], reorient=True)
                    warped_img = ants.apply_transforms(img_mni, img_mod, reg_tomni, interpolator="linear")
                    self._save_scan(warped_img, f"{self.prefix}{mod}", self.coregistration_folder)
                    print(f"[INFO] Registration performed to MNI for {mod}")
                else:
                    img_mod = ants.image_read(self.dict_img[mod], reorient=True)
                    self._save_scan(img_mod, f"{self.prefix}{mod}", self.coregistration_folder)
                    print(f"No co-registration performed for {mod}")

            else: # Scans are not co-registered
                img_mod = ants.image_read(self.dict_img[mod], reorient=True)
                reg = ants.registration(img_reference, img_mod, "Affine")
                self._save_scan(reg["warpedmovout"], f"{self.prefix}{mod}", self.coregistration_folder)
                print(f"[INFO] Registration using ANTsPy for {mod} with {self.reference} as reference")
Beispiel #3
0
    def test_registration_types(self):
        print("Starting long registration interface test")
        fi = ants.image_read(ants.get_ants_data("r16"))
        mi = ants.image_read(ants.get_ants_data("r64"))
        fi = ants.resample_image(fi, (60, 60), 1, 0)
        mi = ants.resample_image(mi, (60, 60), 1, 0)

        for ttype in self.transform_types:
            print(ttype)
            mytx = ants.registration(fixed=fi,
                                     moving=mi,
                                     type_of_transform=ttype)

            # with mask
            fimask = fi > fi.mean()
            mytx = ants.registration(fixed=fi,
                                     moving=mi,
                                     mask=fimask,
                                     type_of_transform=ttype)
        print("Finished long registration interface test")
Beispiel #4
0
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
Beispiel #5
0
def get_zshift(fixed, moving):
    fixed_ants = to_ants(fixed)
    moving_ants = to_ants(moving)

    res = ants.registration(fixed_ants, moving_ants,
                            type_of_transform='Translation',
                            grad_step=.2)
    t = ants.read_transform(res['fwdtransforms'][0])
    zshift_float = t.parameters[-1]
    zshift = int(round(zshift_float))
    return zshift
Beispiel #6
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")
Beispiel #7
0
    def test_example(self):
        fi = ants.image_read(ants.get_ants_data('r16'))
        mi = ants.image_read(ants.get_ants_data('r64'))
        mygr = ants.create_warped_grid(mi)

        mytx = ants.registration(fixed=fi,
                                 moving=mi,
                                 type_of_transform=('SyN'))
        mywarpedgrid = ants.create_warped_grid(mi,
                                               grid_directions=(False, True),
                                               transform=mytx['fwdtransforms'],
                                               fixed_reference_image=fi)
Beispiel #8
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
    def __register_to_MNI_space(self):
        logger.info("registration to MNI template space")
        print("registration to MNI template space")
        if self._t1file != None and self._t2file != None:
            self._t1_reg = ants.registration(fixed=self._icbm152,
                                             moving=self._t1,
                                             type_of_transform='Affine')
            self._t2_reg = ants.apply_transforms(
                fixed=self._icbm152,
                moving=self._t2,
                transformlist=self._t1_reg['fwdtransforms'])

        if self._t1file != None and self._t2file == None:
            self._t1_reg = ants.registration(fixed=self._icbm152,
                                             moving=self._t1,
                                             type_of_transform='Affine')

        if self._t2file != None and self._t1file == None:
            self._t2_reg = ants.registration(fixed=self._icbm152,
                                             moving=self._t2,
                                             type_of_transform='Affine')
Beispiel #10
0
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
Beispiel #11
0
    def _run_coregistration(self):
        print("[INFO] Performing Coregistration using ANTsPy")
        print(f"{self.reference} is used as reference")
        img_reference = ants.image_read(self.dict_img[self.reference],
                                        reorient=True)
        if self.mni:
            print("[INFO] Registering to 1x1x1mm MNI space")
            img_mni = ants.image_read(self.mni_path, reorient=True)
            reg = ants.registration(img_mni, img_reference, 'Affine')
            img_reference = reg['warpedmovout']
            self._save_scan(img_reference, self.reference,
                            self.coregistration_folder)

        modalities_toregister = list(self.dict_img.keys())
        modalities_toregister.remove(self.reference)
        for mod in modalities_toregister:
            img_mod = ants.image_read(self.dict_img[mod], reorient=True)
            reg = ants.registration(img_reference, img_mod, 'Affine')
            self._save_scan(reg['warpedmovout'], mod,
                            self.coregistration_folder)
            print(f"Registration performed for {mod}")
Beispiel #12
0
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
Beispiel #13
0
 def test_example(self):
     fi = ants.image_read(ants.get_ants_data("r16"))
     mi = ants.image_read(ants.get_ants_data("r64"))
     fi = ants.resample_image(fi, (128, 128), 1, 0)
     mi = ants.resample_image(mi, (128, 128), 1, 0)
     mytx = ants.registration(fixed=fi,
                              moving=mi,
                              type_of_transform=("SyN"))
     try:
         jac = ants.create_jacobian_determinant_image(
             fi, mytx["fwdtransforms"][0], 1)
     except:
         pass
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
        if type_of_transform == 'SyN':
            moco = ants.registration(fixed,
                                     moving,
                                     type_of_transform=type_of_transform,
                                     flow_sigma=5,
                                     total_sigma=5)
        else:
            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 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
Beispiel #16
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)
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)
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 warp(self, masked_dir_list, label_dir_list, target_num):
        basicTool = basic()
        basicTool.mkdir('data/fusion_label_multi/QSM_warped')
        basicTool.mkdir('data/fusion_label_multi/label_warped')
        # target img
        testsubject_img = ants.image_read(masked_dir_list[target_num])
        testsubject_label = ants.image_read(label_dir_list[target_num])

        target_file_name = re.split(r'[/.]', masked_dir_list[target_num])[-3]
        target_label_name = re.split(r'[/.]', label_dir_list[target_num])[-3]
        ants.image_write(
            testsubject_img, 'data/fusion_label_multi/QSM_warped/' +
            target_file_name + '_warped.nii.gz')
        ants.image_write(
            testsubject_label, 'data/fusion_label_multi/label_warped/' +
            target_label_name + '_warped.nii.gz')

        # del target img
        del masked_dir_list[target_num]
        del label_dir_list[target_num]
        print(masked_dir_list, label_dir_list)

        # 读取文件, 24个atlas
        for i in range(24):
            move_img = ants.image_read(masked_dir_list[i])  # subject的图像
            # 配准,使用SyN
            outs = ants.registration(testsubject_img,
                                     move_img,
                                     type_of_transforme='SyN')
            atlas_name = re.split(r'[/.]', masked_dir_list[i])[-3]
            print(atlas_name, ' has been warped')
            # atlas的label_img
            atlas_label_img = ants.image_read(label_dir_list[i])  # atlas的标签图像
            # 模板标签warp到图像,move_img是要配准到的空间即(fix),label_img是要应用变化的图像(move),transformlist是move到fix的转换矩阵,genericLabel用于多标签的插值
            warped_atlas_label_img = ants.apply_transforms(
                fixed=testsubject_img,
                moving=atlas_label_img,
                transformlist=outs['fwdtransforms'],
                interpolator='nearestNeighbor')  # 'genericLabel'
            # get file name( without .nii.gz)
            label_name = re.split(r'[/.]', label_dir_list[i])[-3]
            print(label_name, 'has been warped')

            # 保存变换后的图像
            warped_atlas_filename = 'data/fusion_label_multi/QSM_warped/' + atlas_name + '_warped.nii.gz'
            warped_atlas_label_filename = 'data/fusion_label_multi/label_warped/' + label_name + '_warped_label.nii.gz'
            ants.image_write(warped_atlas_label_img,
                             warped_atlas_label_filename)
            ants.image_write(outs['warpedmovout'], warped_atlas_filename)
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
Beispiel #22
0
def transform_rois(fixed, moving, rois, **kwargs):
    def set_ifn(key, val):
        if not key in kwargs:
            kwargs[key] = val

    set_ifn('type_of_transform', 'Affine')
    set_ifn('reg_iterations', [500, 500, 500])
    set_ifn('grad_step', .1)

    res = ants.registration(fixed, moving, **kwargs)
    t = ants.read_transform(res['fwdtransforms'][0])
    xyzs = rois[:, :3]
    rs = rois[:, 3:]

    xyzs_transformed = np.array(list(map(lambda xyz: transform_xyz(t.invert(), xyz, moving, fixed), xyzs)))
    return np.concatenate([xyzs_transformed, rs], axis=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)
Beispiel #24
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")
Beispiel #25
0
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
Beispiel #26
0
    def test_example(self):
        # test ANTsPy/ANTsR example
        fixed = ants.image_read( ants.get_ants_data('r16') )
        moving = ants.image_read( ants.get_ants_data('r64') )
        fixed = ants.resample_image(fixed, (64,64), 1, 0)
        moving = ants.resample_image(moving, (64,64), 1, 0)
        mytx = ants.registration(fixed=fixed , moving=moving, type_of_transform='SyN' )
        mywarpedimage = ants.apply_transforms(fixed=fixed, moving=moving,
                                            transformlist=mytx['fwdtransforms'] )

        # bad interpolator
        with self.assertRaises(Exception):
            mywarpedimage = ants.apply_transforms(fixed=fixed, moving=moving,
                                    transformlist=mytx['fwdtransforms'], interpolator='unsupported-interp' )

        # transform doesnt exist
        with self.assertRaises(Exception):
            mywarpedimage = ants.apply_transforms(fixed=fixed, moving=moving,
                                    transformlist=['blah-blah.mat'], interpolator='unsupported-interp' )
def register3D():
    start = time.time()

    # Register a good image pair as standrad.
    # The paths are for cropped .tiff OCT images & .tiff LS imgae.
    fix_path = '/home/ruijiao/A_research/registration/embryo_DAPI/MK_3D/OCT_Cropped/142.png'
    move_path = '/home/ruijiao/A_research/registration/embryo_DAPI/MK_3D/MPE_Refocused_3/142.png'
    # save_path = join(TIFF_PATH, 'std.tif')
    fix_ants = ants.image_read(fix_path)
    move_ants = ants.image_read(move_path)
    outs = ants.registration(fix_ants, move_ants, type_of_transform='SyN')
    # std_img = ants.apply_transforms(fix_ants, move_ants, transformlist = outs['fwdtransforms'], interpolator = 'linear')
    # ants.image_write(std_img, save_path)

    stop1 = time.time()
    print("registration time: " + str(stop1 - start) + " s.")
    for i_MPE in os.listdir(MPE_PATH):
        # Set images path.
        img_Name = i_MPE
        i_OCT = img_Name
        save_path = join(REG_TIF_PATH, 'registered' + img_Name[0:-4] + '.tiff')

        move_img = ants.image_read(join(MPE_PATH, i_MPE))
        fix_img = ants.image_read(join(OCT_PATH, i_OCT))

        # Apply transformation field "outs" to each image pair.
        reg_img = ants.apply_transforms(fix_img,
                                        move_img,
                                        transformlist=outs['fwdtransforms'],
                                        interpolator='linear')

        # Set the direction, origin, spacing of registered image the same as fixed images.
        reg_img.set_origin(fix_img.origin)
        reg_img.set_spacing(fix_img.spacing)
        reg_img.set_direction(fix_img.direction)

        # Save registered image as .tiff.
        ants.image_write(reg_img, save_path)

    stop = time.time()
    print("Applying transformation field to all images time: " +
          str(stop - stop1) + " s.")
Beispiel #28
0
 def compute_registration_python(self, moving, fixed, registration_method):
     moving_ants = ants.image_read(moving, dimension=3)
     fixed_ants = ants.image_read(fixed, dimension=3)
     try:
         # @FIXME: "antsRegistrationSyNQuick[s]" does not work across all platforms, so I temporarily swapped with "SyN".
         #   Read docs for supported transforms: https://antspy.readthedocs.io/en/latest/_modules/ants/registration/interface.html
         self.reg_transform = ants.registration(fixed_ants, moving_ants,
                                                'SyN')
         warped_input = ants.apply_transforms(
             fixed=fixed_ants,
             moving=moving_ants,
             transformlist=self.reg_transform['fwdtransforms'],
             interpolator='linear',
             whichtoinvert=[False, False])
         warped_input_filename = os.path.join(self.registration_folder,
                                              'input_volume_to_MNI.nii.gz')
         ants.image_write(warped_input, warped_input_filename)
     except Exception as e:
         print('Exception caught during registration. Error message: {}'.
               format(e))
def test_ants():
    # fixed = ants.image_read( ants.get_ants_data('r16') ).resample_image((64,64),1,0)
    fixed = ants.image_read("/home1/quanquan/datasets/LPBA40/fixed.nii.gz")
    print("-------------")
    # moving = ants.image_read( ants.get_ants_data('r64') ).resample_image((64,64),1,0)

    names = np.array([
        x.path for x in os.scandir("/home1/quanquan/datasets/LPBA40/train")
        if x.name.endswith("nii.gz")
    ])
    name = names[0]
    print("name: ", name)
    moving = ants.image_read(name)

    # fixed.plot(overlay=moving, title='Before Registration')
    mytx = ants.registration(
        fixed=fixed, moving=moving,
        type_of_transform='Affine')  # type_of_transform='SyN'
    print(mytx)
    warped_moving = mytx['warpedmovout']
    # fixed.plot(overlay=warped_moving,
    #            title='After Registration')

    mywarpedimage = ants.apply_transforms(fixed=fixed,
                                          moving=moving,
                                          transformlist=mytx['fwdtransforms'])
    # fixed.plot(filename="mywarpedimage.nii.gz")
    im = mywarpedimage.numpy()
    im = im.transpose((2, 1, 0))
    print(im.shape)

    print(mytx['fwdtransforms'])
    # import ipdb; ipdb.set_trace()
    annots = loadmat(mytx['fwdtransforms'][0])

    writer = sitk.ImageFileWriter()
    writer.SetFileName("mywarpedimage.nii.gz")
    writer.Execute(sitk.GetImageFromArray(im))

    import ipdb
    ipdb.set_trace()
def Transform_Image(imagePath):
    #Necesario para que el relative path funcione de manera correcta,
    my_path = os.path.abspath(os.path.dirname(__file__))
    #Utilizamos la plantilla MANI152
    templatePath = os.path.join(my_path, "../Datos/MNI152.nii.gz")
    #Cargamos el path que recibe por parametro, si el path da erroneo, ha de cambiarse en el código de Busqueda.
    path = os.path.join(my_path, imagePath)
    #Leemos los paths y los transformamos en imagenes
    template = ants.image_read(templatePath)
    image = ants.image_read(path)
    #Reesamblamos
    template = ants.resample_image(template, (64, 64, 64), 1, 0)
    image = ants.resample_image(image, (64, 64, 64), 1, 0)
    #Realizamos la transformación
    mytx = ants.registration(fixed=template,
                             moving=image,
                             type_of_transform='SyN')
    mywarpedimage = ants.apply_transforms(fixed=template,
                                          moving=image,
                                          transformlist=mytx['fwdtransforms'])
    return mywarpedimage, mytx
Beispiel #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 )