nii convert to 2D image【python】

2024-02-07 14:04
文章标签 python image 2d convert nii

本文主要是介绍nii convert to 2D image【python】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

可以自己精简,我的label是二分类

import SimpleITK as sitk
import cv2
from PIL import Image
import numpy as np
import nibabel as nib  # nii格式一般都会用到这个包
import imageio  # 转换成图像
import osimport numpy as np
from scipy.ndimage import rotate
from scipy.ndimage import median_filter
import matplotlib.pyplot as pltxy = 128
vol1 = int(xy/2)
vol2 = int(xy/4)
vol3 = int(vol2+16)def preprocess(image):result = median_filter(image, size=3)"""# 添加高斯噪声noise = np.random.normal(0, 25, size=image.shape)noise_img = image + noise.astype('uint8')# 双边滤波result = cv2.bilateralFilter(noise_img, 9, 75, 75)# 显示图像cv2.imshow('src', image)cv2.imshow('noise', noise_img)cv2.imshow('result', result)cv2.waitKey()cv2.destroyAllWindows()"""return resultdef create_dirs(out_path, num):for i in range(1, num):  # 这里需要注意,i取不到6,因为range()是前闭后开的,即i的取值范围为1-5。dir = os.path.join(r'crop/test4/ct/')# 前者为路径,后者为待创建文件夹的名称。注意,批量创建文件夹时不能有重复名称的,因此可以对文件夹加上序号信息。isExists = os.path.exists(dir)if not isExists:os.mkdir(dir)def mask2d(input_path, output_folder, idx):# 加载NIfTI文件img = nib.load(input_path)data = img.get_fdata()# 获取数据的形状信息num_slices = data.shape[2]  # 切片数量print(data.shape, num_slices)# 遍历每个切片并保存为PNG图像for i in range(num_slices):slice_data = data[:, :, i]  # 提取当前切片数据# Image.fromarray(255*img_array_list[foo].astype('int')).convert('L')image = Image.fromarray(255 * slice_data.astype('int')).convert('L')image = image.rotate(270)# image = Image.fromarray(slice_data)  # 创建PIL图像对象output_name = f"{output_folder}slice_{idx}_{i}.png"  # 设置输出文件名image.save(output_name)  # 保存为PNG图像def nii2d(img_addr, target_folder, idx):img_addr_n = nib.load(img_addr)# Convert them to numpy format,data = img_addr_n.get_fdata()# clip the images within [-125, 275],data_clipped = np.clip(data, -125, 275)# normalize each 3D image to [0, 1], anddata_normalised = (data_clipped - (-125)) / (275 - (-125))split_root = img_addr.split('\\')  # 通过\\来进行截断print(split_root) # ['crop/test4/ct/volume-0.nii']# extract 2D slices from 3D volume for training cases while# e.g. slice 000for i in range(data.shape[2]):formattedi = "{:03d}".format(i)slice000 = data_normalised[:, :, i] * 255image = Image.fromarray(slice000)image = image.convert("L")image = image.rotate(270)image = image.transpose(Image.Transpose.FLIP_LEFT_RIGHT)image.save(target_folder +str(idx)+"-"+str(i)+ ".png")for i in range(20):k = i + 1image_path = "ct/volume-{}.nii".format(str(i))label_path = "label/segmentation-{}.nii.gz".format(str(i))label = sitk.ReadImage(label_path, sitk.sitkInt16)label_array = sitk.GetArrayFromImage(label)image = sitk.ReadImage(image_path, sitk.sitkInt32)image_array = sitk.GetArrayFromImage(image)  # 分别读图像和标签数据print("\nimage_array=",image_array.shape, " label_array=",label_array.shape)center_x = (image_array.shape[1]) // 2center_y = (image_array.shape[2]) // 2center_z = (image_array.shape[0]) / 2  # 分别计算出xyz方向上的中心print("center_x=", center_x, "center_y=", center_y, "center_z=",center_z)center_x = center_x - vol2image_array = image_array[:, center_x - vol3:center_x + vol3, center_y - xy:center_y + xy]label_array = label_array[:, center_x - vol3:center_x + vol3, center_y - xy:center_y + xy]  # 在XY裁剪出一个256 * 256的区域#####只需要保存有标签的序列就行了z = np.any(label_array, axis=(1, 2))start_slice, end_slice = np.where(z)[0][[0, -1]]# 截取保留区域image_array = image_array[start_slice:end_slice + 1, :, :]label_array = label_array[start_slice:end_slice + 1, :, :]# print("Preprocessed shape:",ct_array.shape,seg_array.shape)new_image = sitk.GetImageFromArray(image_array)new_image.SetDirection(image.GetDirection())new_image.SetOrigin(image.GetOrigin())new_image.SetSpacing(image.GetSpacing())new_seg = sitk.GetImageFromArray(label_array)new_seg.SetDirection(label.GetDirection())new_seg.SetOrigin(label.GetOrigin())new_seg.SetSpacing(label.GetSpacing())sitk.WriteImage(new_image, "crop/test4/ct/volume-{}.nii".format(str(i)))sitk.WriteImage(new_seg, "crop/test4/label/segmentation-{}.nii.gz".format(str(i)))nii2d("crop/test4/ct/volume-" + str(i) + ".nii", "crop/png_ct/", i)mask2d("crop/test4/label/segmentation-" + str(i) + ".nii.gz", "crop/png_label/", i)"""对于label来说是ok的,但是对于那个来说不行"""

这篇关于nii convert to 2D image【python】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/687965

相关文章

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

通过Docker容器部署Python环境的全流程

《通过Docker容器部署Python环境的全流程》在现代化开发流程中,Docker因其轻量化、环境隔离和跨平台一致性的特性,已成为部署Python应用的标准工具,本文将详细演示如何通过Docker容... 目录引言一、docker与python的协同优势二、核心步骤详解三、进阶配置技巧四、生产环境最佳实践

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Python实现批量CSV转Excel的高性能处理方案

《Python实现批量CSV转Excel的高性能处理方案》在日常办公中,我们经常需要将CSV格式的数据转换为Excel文件,本文将介绍一个基于Python的高性能解决方案,感兴趣的小伙伴可以跟随小编一... 目录一、场景需求二、技术方案三、核心代码四、批量处理方案五、性能优化六、使用示例完整代码七、小结一、

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e