python读取nii文件,并对4DfMRI与sMRI切片
第一次写博客,决定把最近新学习的如何用python读取nii.gz文件以及如何切片写上来,如有错误,请大家指正。
主要是使用nibabel库,nibabel官网有教程,可以自行搜索查看~
我的fMRI数据是.nii.gz文件。
4DfMRI沿时间轴的切片并保存为npy文件
最终保存的为[样本数,时间轴,X, Y, Z]
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 12 19:54:27 2020
@author: Fsyuee
"""
import numpy as np
import nibabel as nib
from nilearn import image
import os
def axis_append(img_numpy, num, i): #维度扩张,扩张为[样本数, 时间轴, X, Y, X]
if i == 1:
img_numpy = num
img_numpy = img_numpy[np.newaxis,:,:,:]
#print(img_numpy.shape,num.shape)
else:
num = num[np.newaxis,:,:,:]
img_numpy = np.append(img_numpy,num,axis=0)
print(img_numpy.shape,num.shape)
return img_numpy
def nii_to_image(niifile):
filenames = os.listdir(niifile) #读取nii文件夹
img_numpy = np.array([])
count = 0 #记录读取到第几个样本
for f in filenames:
if '.nii' in f :
count = count + 1
print(count)
img_path = os.path.join(filepath, f)
img = nib.load(img_path) #读取nii
(x,y,z,t) = image.load_img(img).shape
print(f,image.load_img(img).shape) #显示图像尺寸fmri_0040144.nii.gz (27, 32, 26, 150)
img1 = img.slicer[:,:,:,0]
num = img1.get_fdata() #转为npy
num = num[np.newaxis,:,:]
#print(11,num.shape)
#num = np.array(img1)
for i in range(1,t): #延时间轴切片
img1 = img.slicer[:,:,:,i]
#print(img1.shape)
img_fdata = img1.get_fdata() #npy
img_fdata = img_fdata[np.newaxis,:,:]
#print(img_fdata.shape)
#print(num.shape)
num = np.append(num,img_fdata, axis = 0)
#print(num.shape)
img_numpy = axis_append(img_numpy, num, count)
print(img_numpy.shape)
np.save('img_numpy',img_numpy)
if __name__ == '__main__':
filepath = r'C:\Users\Fsyuee\nilearn_data\cobre'
imgfile = r'C:\Users\Fsyuee\nilearn_data\cobre'
nii_to_image(filepath)
4D沿时间轴切片后还可以继续沿X,Y,Z轴进行切片,利用读取不同维度的numpy方式。
img_fdata2 = img_fdata[:,:,2] #二维
3DsMRI切片
import nibabel as nib
from nilearn import image
import os
import imageio #转换成图像
def nii_to_image(niifile):
filenames = os.listdir(niifile) #读取nii文件夹
for f in filenames:
img_path = os.path.join(filepath, f)
img = nib.load(img_path) #读取nii
#print(image.load_img(img).shape) #显示图像尺寸(240,240,240)
img_fdata = img.get_fdata() #转为npy
print(img_fdata.shape)
(x,y,z) = img.shape
for i in range(0,z):
img_fdata2 = img_fdata[:,:,i]
print(img_fdata2.shape)
#print(img_fdata2)
if __name__ == '__main__':
filepath = r'E:\fMRI\sMRI\new'
imgfile = r'E:\fMRI\sMRI\new'
nii_to_image(filepath)