示例#1
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 preprocess_images(
    atlas_id: int,
    atlas_csf_id: int,
    atlas_grey_id: int,
    atlas_white_id: int,
    dataset_id: int,
    replace: bool = False,
    downsample: float = 3.0,
):
    atlas = models.Atlas.objects.get(pk=atlas_id)
    atlas_csf = models.Atlas.objects.get(pk=atlas_csf_id)
    atlas_grey = models.Atlas.objects.get(pk=atlas_grey_id)
    atlas_white = models.Atlas.objects.get(pk=atlas_white_id)
    dataset = models.Dataset.objects.get(pk=dataset_id)

    print('Downloading atlas files')
    with NamedTemporaryFile(
            suffix='atlas.nii') as tmp, atlas.blob.open() as blob:
        for chunk in blob.chunks():
            tmp.write(chunk)
        atlas_img = ants.image_read(tmp.name)

    with NamedTemporaryFile(
            suffix='atlas_csf.nii') as tmp, atlas_csf.blob.open() as blob:
        for chunk in blob.chunks():
            tmp.write(chunk)
        atlas_csf_img = ants.image_read(tmp.name)

    with NamedTemporaryFile(
            suffix='atlas_grey.nii') as tmp, atlas_grey.blob.open() as blob:
        for chunk in blob.chunks():
            tmp.write(chunk)
        atlas_grey_img = ants.image_read(tmp.name)

    with NamedTemporaryFile(
            suffix='atlas_white.nii') as tmp, atlas_white.blob.open() as blob:
        for chunk in blob.chunks():
            tmp.write(chunk)
        atlas_white_img = ants.image_read(tmp.name)

    print('Creating mask')
    priors = [atlas_csf_img, atlas_grey_img, atlas_white_img]
    mask = priors[0].copy()
    mask_view = mask.view()
    for i in range(1, len(priors)):
        mask_view[priors[i].numpy() > 0] = 1
    mask_view[mask_view > 0] = 1

    for image in dataset.images.all():
        if replace:
            _delete_preprocessing_artifacts(image)
        elif _already_preprocessed(image):
            continue
        with NamedTemporaryFile(
                suffix=image.name) as tmp, image.blob.open() as blob:
            for chunk in blob.chunks():
                tmp.write(chunk)
            input_img = ants.image_read(tmp.name)

        print(f'Running N4 bias correction: {image.name}')
        im_n4 = ants.n4_bias_field_correction(input_img)
        del input_img
        print(f'Running registration: {image.name}')
        reg = ants.registration(atlas_img, im_n4)
        del im_n4
        jac_img = ants.create_jacobian_determinant_image(
            atlas_img, reg['fwdtransforms'][0], 1)
        jac_img = jac_img.apply(np.abs)

        reg_model = models.RegisteredImage(source_image=image, atlas=atlas)
        reg_img = reg['warpedmovout']
        with NamedTemporaryFile(suffix='registered.nii') as tmp:
            ants.image_write(reg_img, tmp.name)
            reg_model.blob = File(tmp, name='registered.nii')
            reg_model.save()

        jac_model = models.JacobianImage(source_image=image, atlas=atlas)
        with NamedTemporaryFile(suffix='jacobian.nii') as tmp:
            ants.image_write(jac_img, tmp.name)
            jac_model.blob = File(tmp, name='jacobian.nii')
            jac_model.save()

        print(f'Running segmentation: {image.name}')
        seg = ants.prior_based_segmentation(reg_img, priors, mask)
        del reg_img

        seg_model = models.SegmentedImage(source_image=image, atlas=atlas)
        with NamedTemporaryFile(suffix='segmented.nii') as tmp:
            ants.image_write(seg['segmentation'], tmp.name)
            seg_model.blob = File(tmp, name='segmented.nii')
            seg_model.save()

        print(f'Creating feature image: {image.name}')
        seg_img_view = seg['segmentation'].view()
        feature_img = seg['segmentation'].copy()
        feature_img_view = feature_img.view()
        feature_img_view.fill(0)
        feature_img_view[seg_img_view == 3] = 1  # 3 is white matter label

        intensity_img_view = jac_img.view()
        feature_img_view *= intensity_img_view

        if downsample > 1:
            shape = np.round(np.asarray(feature_img.shape) / downsample)
            feature_img = ants.resample_image(feature_img, shape, True)

        feature_model = models.FeatureImage(source_image=image,
                                            atlas=atlas,
                                            downsample_factor=downsample)
        with NamedTemporaryFile(suffix='feature.nii') as tmp:
            ants.image_write(feature_img, tmp.name)
            feature_model.blob = File(tmp, name='feature.nii')
            feature_model.save()

    dataset.preprocessing_complete = True
    dataset.save()
示例#3
0
ants.image_write(registrationNoMask['warpedfixout'],
                 outputPrefix + "InverseWarped.nii.gz")

# Plot the fixed and warped moving image
ants.plot(fixedImage,
          overlay=registrationNoMask['warpedmovout'],
          overlay_cmap="viridis",
          alpha=0.9)

# Plot the moving and warped fixed image
ants.plot(movingImage,
          overlay=registrationNoMask['warpedfixout'],
          overlay_cmap="viridis",
          alpha=0.9)

jacobian = ants.create_jacobian_determinant_image(
    fixedImage, registrationNoMask['fwdtransforms'][0])
ants.plot(jacobian)

#######
#
# Perform registration with mask
#

outputDirectory = './OutputWithMaskANTsPy/'
if not os.path.isdir(outputDirectory):
    os.mkdir(outputDirectory)

outputPrefix = outputDirectory + 'antsr'

registrationWithMask = ants.registration(fixed=fixedImage,
                                         moving=movingImage,
示例#4
0
def performAntsRegistration(param,
                            mv_path,
                            target_path,
                            registration_type='syn',
                            record_path=None,
                            ml_path=None,
                            tl_path=None,
                            fname=None):
    """
    call [AntsPy](https://github.com/ANTsX/ANTsPy),

    :param param: ParameterDict, affine related params
    :param mv_path: path of moving image
    :param target_path: path of target image
    :param registration_type: type of registration, support 'affine' and 'syn'(include affine)
    :param record_path: path of saving results
    :param ml_path: path of label of moving image
    :param tl_path: path of label fo target image
    :param fname: pair name or saving name of the image pair
    :return: warped image, warped label, transformation map (None), jacobian map
    """
    loutput = None
    phi = None
    moving = ants.image_read(mv_path)
    target = ants.image_read(target_path)
    if ml_path is not None:
        ml_sitk = sitk.ReadImage(ml_path)
        tl_sitk = sitk.ReadImage(tl_path)
        ml_np = sitk.GetArrayFromImage(ml_sitk)
        tl_np = sitk.GetArrayFromImage(tl_sitk)
        l_moving = ants.from_numpy(np.transpose(ml_np),
                                   spacing=moving.spacing,
                                   direction=moving.direction,
                                   origin=moving.origin)
        l_target = ants.from_numpy(np.transpose(tl_np),
                                   spacing=target.spacing,
                                   direction=target.direction,
                                   origin=target.origin)

    start = time.time()
    if registration_type == 'affine':
        affine_file = ants.affine_initializer(target, moving)
        af_img = ants.apply_transforms(fixed=target,
                                       moving=moving,
                                       transformlist=affine_file)
        if ml_path is not None:
            loutput = ants.apply_transforms(fixed=l_target,
                                            moving=l_moving,
                                            transformlist=affine_file,
                                            interpolator='nearestNeighbor')
            loutput = loutput.numpy()
        output = af_img.numpy()
        print('affine registration finished and takes: :', time.time() - start)
    #print("param_in_ants:{}".format(param_in_ants))
    if registration_type == 'syn':
        syn_res = ants.registration(
            fixed=target,
            moving=moving,
            type_of_transform='SyNCC',
            grad_step=0.2,
            flow_sigma=3,  # intra 3
            total_sigma=0.1,
            aff_metric='mattes',
            aff_sampling=8,
            syn_metric='mattes',
            syn_sampling=32,
            reg_iterations=(80, 50, 20))

        print(syn_res['fwdtransforms'])
        if 'GenericAffine.mat' in syn_res['fwdtransforms'][0]:
            tmp1 = syn_res['fwdtransforms'][0]
            tmp2 = syn_res['fwdtransforms'][1]
            syn_res['fwdtransforms'][0] = tmp2
            syn_res['fwdtransforms'][1] = tmp1
        if ml_path is not None:
            time.sleep(1)

            loutput = ants.apply_transforms(
                fixed=l_target,
                moving=l_moving,
                transformlist=syn_res['fwdtransforms'],
                interpolator='nearestNeighbor')
            loutput = loutput.numpy()
        output = syn_res['warpedmovout'].numpy()
        print('syn registration finished and takes: :', time.time() - start)

    output = np.transpose(output, (2, 1, 0))
    loutput = np.transpose(loutput, (2, 1, 0)) if loutput is not None else None
    # #disp = nifty_read_phi(syn_res['fwdtransforms'][0])
    # #disp = np.transpose(disp, (0,1,4, 3, 2))
    # composed_transform = ants.apply_transforms(fixed=target, moving=moving,
    #                                       transformlist=syn_res['fwdtransforms'],compose= record_path)
    # cmd = 'mv ' + composed_transform + ' ' + os.path.join(record_path,fname+'_disp.nii.gz')
    # composed_inv_transform = ants.apply_transforms(fixed=target, moving=moving,
    #                                       transformlist=syn_res['invtransforms'],compose= record_path)
    # cmd = 'mv ' + composed_inv_transform + ' ' + os.path.join(record_path,fname+'_invdisp.nii.gz')
    cmd = 'mv ' + syn_res['fwdtransforms'][0] + ' ' + os.path.join(
        record_path, fname + '_disp.nii.gz')
    cmd += '\n mv ' + syn_res['fwdtransforms'][1] + ' ' + os.path.join(
        record_path, fname + '_affine.mat')
    cmd += '\n mv ' + syn_res['invtransforms'][0] + ' ' + os.path.join(
        record_path, fname + '_invdisp.nii.gz')
    process = subprocess.Popen(cmd, shell=True)
    process.wait()
    jacobian_np = None
    if registration_type == 'syn':
        jacobian = ants.create_jacobian_determinant_image(
            target, os.path.join(record_path, fname + '_disp.nii.gz'), False)
        jacobian_np = jacobian.numpy()

    return expand_batch_ch_dim(output), expand_batch_ch_dim(
        loutput), phi, jacobian_np
示例#5
0
# 图像的保存
ants.image_write(warped_img, img_name)
ants.image_write(warped_label, label_name)

# 将antsimage转化为numpy数组
warped_img_arr = warped_img.numpy(single_components=False)
# 从numpy数组得到antsimage
img = ants.from_numpy(warped_img_arr,
                      origin=None,
                      spacing=None,
                      direction=None,
                      has_components=False,
                      is_rgb=False)
# 生成图像的雅克比行列式
jac = ants.create_jacobian_determinant_image(domain_image=f_img,
                                             tx=mytx["fwdtransforms"][0],
                                             do_log=False,
                                             geom=False)
ants.image_write(jac, "./result/jac.nii.gz")
# 生成带网格的moving图像,实测效果不好
m_grid = ants.create_warped_grid(m_img)
m_grid = ants.create_warped_grid(m_grid,
                                 grid_directions=(False, False),
                                 transform=mytx['fwdtransforms'],
                                 fixed_reference_image=f_img)
ants.image_write(m_grid, "./result/m_grid.nii.gz")
'''
以下为其他不常用的函数:

ANTsTransform.apply_to_image(image, reference=None, interpolation='linear')
ants.read_transform(filename, dimension=2, precision='float')
# transform的格式是".mat"