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开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

Python中图片与PDF识别文本(OCR)的全面指南

《Python中图片与PDF识别文本(OCR)的全面指南》在数据爆炸时代,80%的企业数据以非结构化形式存在,其中PDF和图像是最主要的载体,本文将深入探索Python中OCR技术如何将这些数字纸张转... 目录一、OCR技术核心原理二、python图像识别四大工具库1. Pytesseract - 经典O

基于Linux的ffmpeg python的关键帧抽取

《基于Linux的ffmpegpython的关键帧抽取》本文主要介绍了基于Linux的ffmpegpython的关键帧抽取,实现以按帧或时间间隔抽取关键帧,文中通过示例代码介绍的非常详细,对大家的学... 目录1.FFmpeg的环境配置1) 创建一个虚拟环境envjavascript2) ffmpeg-py

python使用库爬取m3u8文件的示例

《python使用库爬取m3u8文件的示例》本文主要介绍了python使用库爬取m3u8文件的示例,可以使用requests、m3u8、ffmpeg等库,实现获取、解析、下载视频片段并合并等步骤,具有... 目录一、准备工作二、获取m3u8文件内容三、解析m3u8文件四、下载视频片段五、合并视频片段六、错误

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

Python打印对象所有属性和值的方法小结

《Python打印对象所有属性和值的方法小结》在Python开发过程中,调试代码时经常需要查看对象的当前状态,也就是对象的所有属性和对应的值,然而,Python并没有像PHP的print_r那样直接提... 目录python中打印对象所有属性和值的方法实现步骤1. 使用vars()和pprint()2. 使

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

一文深入详解Python的secrets模块

《一文深入详解Python的secrets模块》在构建涉及用户身份认证、权限管理、加密通信等系统时,开发者最不能忽视的一个问题就是“安全性”,Python在3.6版本中引入了专门面向安全用途的secr... 目录引言一、背景与动机:为什么需要 secrets 模块?二、secrets 模块的核心功能1. 基

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.