import numpy as np
import SimpleITK as sitk
from glob import glob
import nibabel as nib
def get_spacing(nifti_file_path):
nifti_img = nib.load(nifti_file_path)
spacing = nifti_img.header.get_zooms() # 直接返回spacing元组
return spacing
def resize_image_itk(image_file, resamplemethod=sitk.sitkNearestNeighbor):
itkimage = sitk.ReadImage(image_file)
resampler = sitk.ResampleImageFilter()
originSpacing = get_spacing(image_file) # 获取原图spacing
print("originSpacing:", originSpacing)
newSpacing = (0.4, 0.4, 0.4)
factor = [0,0,0]
for i in range(3):
factor[i]= newSpacing[i]/originSpacing[i]
print("factor",factor)
newSize =[0,0,0]
for i in range(3):
newSize[i] =itkimage.GetSize()[i]/factor[i]
newSize = np.array(newSize)
newSize = newSize.astype(np.int32) # spacing格式转换
resampler.SetReferenceImage(itkimage)
resampler.SetSize(newSize.tolist())
resampler.SetOutputSpacing(newSpacing)
resampler.SetTransform(sitk.Transform(3, sitk.sitkIdentity))
resampler.SetInterpolator(resamplemethod)
itkimgResampled = resampler.Execute(itkimage)
return itkimgResampled
image_path = r'文件夹'
image_files = glob(image_path + "/*")
for i in range(len(image_files)):
itkimgResampled = resize_image_itk(image_files[i], resamplemethod=sitk.sitkLinear)
output_path = '文件夹' + image_files[i][len(image_path):]
# 修改输出路径
sitk.WriteImage(itkimgResampled, output_path)
print("Resampled image saved to:", output_path)
该代码只能修改图像,因为标签没有spcing属性。
标签:newSize,nii,reSpacing3D,image,spacing,gz,sitk,resampler,path From: https://blog.csdn.net/snowy_zhang/article/details/137074301