重采样nii文件,插值法

重采样nii文件,插值法

原来的nii文件是(869,869,120),spacing为(0.3795,03795,1.7) 现在要转化成(340,340,204),spacing为(1,1,1)的文件
(869,869,120).*(0.3795,03795,1.7)=(329.78,329.78,204)约等于(340,340,204)

import os
import torch
import torch.nn.functional as F
import nibabel as nib
import numpy as np

def resample_image(image, new_shape, new_spacing):
    # Move tensors to the GPU device
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    tensor = torch.from_numpy(image.get_fdata()).unsqueeze(0).unsqueeze(0).float().to(device)

    # Calculate the resize factor
    current_shape = tensor.shape[-3:]
    resize_factor = [n / o for n, o in zip(new_shape, current_shape)]

    # Perform the resampling using interpolate function
    resampled_tensor = F.interpolate(
        tensor,
        size=new_shape,
        mode='trilinear',
        align_corners=False
    )

    # Create a new NIfTI image with updated data and spacing
    resampled_nifti = nib.Nifti1Image(resampled_tensor.squeeze().cpu().numpy(), affine=image.affine)

    # Update the affine matrix for the desired spacing
    current_spacing = image.header.get_zooms()[:3]
    scale_factor = [c / (r * rf) for c, r, rf in zip(current_spacing, new_spacing, resize_factor)]
    resampled_nifti.header.set_zooms(new_spacing + (image.header.get_zooms()[3:]))

    # Scale the affine matrix
    resampled_nifti.affine[:3, :3] = np.diag(scale_factor)

    return resampled_nifti

# Define the path to your NIfTI file
nifti_path = r"D:\BaiduNetdiskDownload\A\P0.nii.gz"

# Load the NIfTI image
image = nib.load(nifti_path)

# Define the desired shape and spacing for resampling
new_shape = (340, 340, 204)
new_spacing = (1.0, 1.0, 1.0)

# Perform resampling
resampled_image = resample_image(image, new_shape, new_spacing)

# Define the new file name and path
output_dir = os.path.dirname(nifti_path)
output_filename = "resampled.nii.gz"
output_path = os.path.join(output_dir, output_filename)

# Save the resampled image to the new file path
nib.save(resampled_image, output_path)

print("Resampled image saved to:", output_path)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值