重采样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)