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

这段代码主要处理MRI数据集,将.nii.gz文件按x、y、z轴方向切片,并保存为PNG图像。使用了numpy、nibabel和imageio库进行数据读取、切片和图像保存。图像经过缩放和正则化处理,以适应256x256的尺寸。此外,代码还会创建相应的文件夹结构来组织切片图像。
摘要由CSDN通过智能技术生成

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) * 255
    return image

nii_to_image(IXI/T1')

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

某个方向 指定slice数量

import scipy, numpy, shutil, os, nibabel
import sys, getopt
import imageio
 
def 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 folder
        if not os.path.exists(outputfile):
            os.makedirs(outputfile)   #不存在输出文件夹则新建
            print("Created ouput directory: " + outputfile)
        print('Reading NIfTI file...')
 
    # Create a folder for each input file
        file_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 slices
        for current_slice in range(50, 50+total_slices):
            # alternate slices
            if (slice_counter % 1) == 0:
                data = image_array[:, :, current_slice]  #保存该切片,可以选择不同方向。
 
                # alternate slices and save as png
                if (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 image
                    resized_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 folder
                    image_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 += 1
                    print('Moved.')
 
    print('Finished converting images')
 
if __name__ == '__main__':
    niito2D('/IXI/T2/')

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值