针对一个大文件夹以及子文件内所有的dicom格式图像
1.重采样,目的使空间分辨率一致
2.归一化(最大-最小值缩放):(x-min(x)) / (max(x)-min(x))
目的消除图像亮度差异,使像素值缩放到[0, 1]之间
3.Z-score标准化:(x-x(averge))/标准差
目的使图像具有统一的特征
import os
import SimpleITK as sitk
import numpy as np
# 进行归一化和Z-score标准化处理
def normalize_and_standardize(image_array):
# 归一化
min_val = np.min(image_array)
max_val = np.max(image_array)
if min_val == max_val:# 以防出现归一化时分母为0
normalized_array = np.zeros_like(image_array)# 如果相等,则将所有值设为0
else:
normalized_array = (image_array - min_val) / (max_val - min_val)
# Z-score
mean = np.mean(normalized_array)
std = np.std(normalized_array)
if std == 0:
standardized_array = np.zeros_like(normalized_array)# 避免标准差为0而报错
else:
standardized_array = (normalized_array - mean) / std
return standardized_array
CT_path = r'C:\Users\lyp\Desktop\CT03802522'
file_list = []
for root, dirs, files in os.walk(CT_path):
for file in files:
if file.endswith('dcm'):
file_list.append(os.path.join(root, file))
for image_path in file_list:
image = sitk.ReadImage(image_path)
new_spacing = [1, 1, 1]# 定义新的空间分辨率
original_size = image.GetSize()#获取原始图像像素尺寸和空间分辨率,均为一个三元素元组()
original_spacing = image.GetSpacing()
# 计算新的像素尺寸
new_size = [int(np.round(original_size[0] * original_spacing[0] / new_spacing[0])),
int(np.round(original_size[1] * original_spacing[1] / new_spacing[1])),
int(np.round(original_size[2] * original_spacing[2] / new_spacing[2]))
]# 分别计算X,Y,Z轴大小
resample = sitk.ResampleImageFilter()
resample.SetOutputSpacing(new_spacing)
resample.SetSize(new_size)
resample.SetOutputDirection(image.GetDirection())
resample.SetOutputOrigin(image.GetOrigin())
resample.SetTransform(sitk.Transform())
resample.SetDefaultPixelValue(image.GetPixelIDValue())# 以上四个操作均采用保留原始图像属性
resample.SetInterpolator(sitk.sitkBSpline)# 插值方法,这种为双线性插值,大多数情况下使用,或者线性插值(sitk.sitkLinear)
resample_image = resample.Execute(image)
resample_array = sitk.GetArrayFromImage(resample_image)
standardized_array = normalize_and_standardize(resample_array)
processed_image = sitk.GetImageFromArray(standardized_array)# 倒回来,从array得到图像
processed_image.SetSpacing(new_spacing)
processed_image.SetOrigin(resample_image.GetOrigin())
processed_image.SetDirection(resample_image.GetDirection())# 确保处理后的图像是正确的
# 将图像强制转换为指定的像素类型,防止报错
processed_image = sitk.Cast(processed_image, sitk.sitkInt16)
save_file = image_path.replace('.dcm', '_processed.dcm')
sitk.WriteImage(processed_image, save_file)