IXI数据集 3d切片——适用所有医学3d图像切片

MRI 数据集切片

从x轴、y轴、z轴

import numpy as np
import os
import nibabel as nib
import imageio
from scipy.ndimage import zoom
from skimage.transform import resize
def nii_to_image(niifile):file_list = os.listdir(niifile)for filename in file_list:if filename.endswith(".nii.gz"):img_path = os.path.join(niifile, filename)img = nib.load(img_path)img_fdata = img.get_fdata()# 创建保存图像的文件夹x_folder = os.path.join(niifile, 'x_slices')filex_folder = os.path.splitext(os.path.basename(filename))[0]filex_folder = filename.split('.')[0]filex_path = os.path.join(x_folder, filex_folder)if not os.path.exists(filex_path):os.makedirs(filex_path)print("Created folder:", filex_path)y_folder = os.path.join(niifile, 'y_slices')filey_folder = os.path.splitext(os.path.basename(filename))[0]filey_folder = filename.split('.')[0]filey_path = os.path.join(y_folder, filey_folder)if not os.path.exists(filey_path):os.makedirs(filey_path)print("Created folder:", filey_path)z_folder = os.path.join(niifile, 'z_slices')filez_folder = os.path.splitext(os.path.basename(filename))[0]filez_folder = filename.split('.')[0]filez_path = os.path.join(z_folder, filez_folder)if not os.path.exists(filez_path):os.makedirs(filez_path)print("Created folder:", filez_path)os.makedirs(x_folder, exist_ok=True)os.makedirs(y_folder, exist_ok=True)os.makedirs(z_folder, exist_ok=True)# 在每个方向上分别保存2D图像切片for i in range(img_fdata.shape[0]):img_slice = img_fdata[i, :, :]filename = filename[:-7] # 保存x方向的切片x_filename = f"{filename}_x_{i}.png"img_slice = zoom(img_slice, (256/img_slice.shape[0], 256/img_slice.shape[1]), order=3)img_slice =(img_slice - np.min(img_slice)) / (np.max(img_slice) - np.min(img_slice))x_path = os.path.join(filex_path, x_filename)imageio.imwrite(x_path, (img_slice * 255).astype(np.uint8))#imageio.imwrite(x_path, img_slice.astype(np.uint8))#imageio.imwrite(x_path, img_slice)for i in range(img_fdata.shape[1]):img_slice = img_fdata[:, i, :]# 保存y方向的切片y_filename = f"{filename}_y_{i}.png"img_slice = zoom(img_slice, (256/img_slice.shape[0], 256/img_slice.shape[1]), order=3)img_slice =(img_slice - np.min(img_slice)) / (np.max(img_slice) - np.min(img_slice))y_path = os.path.join(filey_path, y_filename)imageio.imwrite(y_path, (img_slice * 255).astype(np.uint8))# imageio.imwrite(y_path, img_slice.astype(np.uint8))for i in range(img_fdata.shape[2]):img_slice = img_fdata[:, :, i]# 保存z方向的切片z_filename = f"{filename}_z_{i}.png"img_slice = zoom(img_slice, (256/img_slice.shape[0], 256/img_slice.shape[1]), order=3)img_slice =(img_slice - np.min(img_slice)) / (np.max(img_slice) - np.min(img_slice))z_path = os.path.join(filez_path, z_filename)imageio.imwrite(z_path, (img_slice * 255).astype(np.uint8))# imageio.imwrite(z_path, img_slice.astype(np.uint8))def normalize_image(image):# 可选:将图像数据进行正则化min_val = np.min(image)max_val = np.max(image)image = (image - min_val) / (max_val - min_val) * 255return imagenii_to_image(IXI/T1')

会创建x,y,z 文件夹在T1下,每个nii.gz文件再创一个文件夹,将所有这个方向上的切片放到对应文件中

某个方向 指定slice数量

import scipy, numpy, shutil, os, nibabel
import sys, getopt
import imageiodef niito2D(filepath):inputfiles = os.listdir(filepath)  #遍历文件夹数据outputfile = './mc_slices/'       #输出文件夹print('Input file is ', inputfiles)print('Output folder is ', outputfile)for inputfile in inputfiles:image_array = nibabel.load(filepath+inputfile).get_fdata() #数据读取print(len(image_array.shape))# set destination folderif not os.path.exists(outputfile):os.makedirs(outputfile)   #不存在输出文件夹则新建print("Created ouput directory: " + outputfile)print('Reading NIfTI file...')# Create a folder for each input filefile_folder = os.path.splitext(os.path.basename(inputfile))[0]file_folder = inputfile.split('.')[0]file_path = os.path.join(outputfile, file_folder)if not os.path.exists(file_path):os.makedirs(file_path)print("Created folder:", file_path)total_slices = 50  #总切片数slice_counter = 50 #从第几个切片开始# iterate through slicesfor current_slice in range(50, 50+total_slices):# alternate slicesif (slice_counter % 1) == 0:data = image_array[:, :, current_slice]  #保存该切片,可以选择不同方向。# alternate slices and save as pngif (slice_counter % 1) == 0:print('Saving image...')#切片命名image_name = inputfile[:-7] + "{:0>3}".format(str(current_slice + 1)) + ".png"#image_name = "{:0>3}.png".format(str(current_slice + 1))# Resize the imageresized_data = (data - np.min(data)) / (np.max(data) - np.min(data))resized_data = (resized_data * 255).astype(np.uint8)#保存# Save the image inside the file folderimage_name = os.path.join(file_path, image_name)#imageio.imwrite(image_path, resized_data)imageio.imwrite(image_name, resized_data)print('Saved.')# move images to folder# print('Moving image...')# src = image_name# shutil.move(src, outputfile)slice_counter += 1print('Moved.')print('Finished converting images')if __name__ == '__main__':niito2D('/IXI/T2/')