自定义fMRINIfTI加载教程详解
时间:2025-08-13 09:24:28 328浏览 收藏
golang学习网今天将给大家带来《加载自定义fMRI NIfTI文件教程详解》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习文章或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
本文档旨在指导用户如何将自定义的fMRI NIfTI文件加载到现有的Python代码中,该代码使用了monai库进行图像处理。我们将重点介绍如何利用nilearn库加载NIfTI文件,并将其集成到现有的数据处理流程中,以便进行后续的分析和处理。同时,我们也简单提及了多进程处理的建议,以便加速数据处理流程。
使用 nilearn 加载 NIfTI 文件
nilearn 是一个专门用于神经影像数据分析的 Python 库,它提供了方便的函数来加载和处理 NIfTI 文件。相比于从头开始解析文件,使用 nilearn 可以大大简化代码并提高效率。
首先,确保你已经安装了 nilearn 库。如果没有安装,可以使用 pip 进行安装:
pip install nilearn
安装完成后,就可以使用 nilearn.image.load_img 函数加载 NIfTI 文件了。
from nilearn.image import load_img # 指定 NIfTI 文件的路径 nifti_file_path = "F:\\New folder\\cn_processed data\\Sub1\\S1.nii" # 加载 NIfTI 文件 try: nifti_image = load_img(nifti_file_path) print(f"Successfully loaded NIfTI image from: {nifti_file_path}") except FileNotFoundError: print(f"Error: NIfTI file not found at: {nifti_file_path}") exit() except Exception as e: print(f"An error occurred while loading the NIfTI image: {e}") exit() # 获取图像数据,返回一个 NumPy 数组 data = nifti_image.get_fdata() # 打印数据的形状,以确认加载成功 print("Data shape:", data.shape)
代码解释:
- from nilearn.image import load_img: 导入 nilearn.image 模块中的 load_img 函数。
- nifti_file_path = "F:\\New folder\\cn_processed data\\Sub1\\S1.nii": 定义 NIfTI 文件的路径。请确保路径正确。
- nifti_image = load_img(nifti_file_path): 使用 load_img 函数加载 NIfTI 文件。
- data = nifti_image.get_fdata(): 使用 get_fdata() 方法获取图像数据,返回一个 NumPy 数组。
- print("Data shape:", data.shape): 打印数据的形状,可以用来验证文件是否正确加载。
将 nilearn 集成到现有代码
现在,我们需要将使用 nilearn 加载 NIfTI 文件的代码集成到你提供的原始代码中。修改 read_data 函数,使用 nilearn 加载数据,并移除 monai 的 LoadImage:
from nilearn.image import load_img import torch import os import time from multiprocessing import Process, Queue import numpy as np # 导入 NumPy def read_data(filename, load_root, save_root, subj_name, count, queue=None, scaling_method=None, fill_zeroback=False): print("processing: " + filename, flush=True) path = os.path.join(load_root, filename) try: # 使用 nilearn 加载 NIfTI 文件 nifti_image = load_img(path) data = nifti_image.get_fdata() except FileNotFoundError: print(f"Error: NIfTI file not found at: {path}") return None except Exception as e: print(f"An error occurred while loading the NIfTI image: {e}") return None #change this line according to your file names save_dir = os.path.join(save_root,subj_name) isExist = os.path.exists(save_dir) if not isExist: os.makedirs(save_dir) # change this line according to your dataset data = data[:, 14:-7, :, :] # width, height, depth, time # Inspect the fMRI file first using your visualization tool. # Limit the ranges of width, height, and depth to be under 96. Crop the background, not the brain regions. # Each dimension of fMRI registered to MNI space (2mm) is expected to be around 100. # You can do this when you load each volume at the Dataset class, including padding backgrounds to fill dimensions under 96. background = data==0 if scaling_method == 'z-norm': global_mean = data[~background].mean() global_std = data[~background].std() data_temp = (data - global_mean) / global_std elif scaling_method == 'minmax': data_temp = (data - data[~background].min()) / (data[~background].max() - data[~background].min()) data_global = torch.empty(data.shape) data_global[background] = data_temp[~background].min() if not fill_zeroback else 0 # data_temp[~background].min() is expected to be 0 for scaling_method == 'minmax', and minimum z-value for scaling_method == 'z-norm' data_global[~background] = data_temp[~background] # save volumes one-by-one in fp16 format. data_global = torch.tensor(data_global) #Convert numpy array to tensor data_global = data_global.type(torch.float16) data_global_split = torch.split(data_global, 1, 3) for i, TR in enumerate(data_global_split): torch.save(TR.clone(), os.path.join(save_dir,"frame_"+str(i)+".pt")) def main(): # change two lines below according to your dataset dataset_name = 'ABCD' load_root = 'F:\\New folder\\cn_processed data' # This folder should have fMRI files in nifti format with subject names. Ex) sub-01.nii.gz save_root = f'/storage/7.{dataset_name}_MNI_to_TRs_minmax' scaling_method = 'z-norm' # choose either 'z-norm'(default) or 'minmax'. # make result folders filenames = os.listdir(load_root) os.makedirs(os.path.join(save_root,'img'), exist_ok = True) os.makedirs(os.path.join(save_root,'metadata'), exist_ok = True) # locate your metadata file at this folder save_root = os.path.join(save_root,'img') finished_samples = os.listdir(save_root) queue = Queue() count = 0 for filename in sorted(filenames): # Assuming filename is like "Sub1.nii" subj_name = filename[:-4] # extract subject name from nifti file. [:-4] rules out '.nii' # we recommend you use subj_name that aligns with the subject key in a metadata file. expected_seq_length = 1000 # Specify the expected sequence length of fMRI for the case your preprocessing stopped unexpectedly and you try to resume the preprocessing. # change the line below according to your folder structure if (subj_name not in finished_samples) or (len(os.listdir(os.path.join(save_root,subj_name))) < expected_seq_length): # preprocess if the subject folder does not exist, or the number of pth files is lower than expected sequence length. try: count+=1 p = Process(target=read_data, args=(filename,load_root,save_root,subj_name,count,queue,scaling_method)) p.start() if count % 32 == 0: # requires more than 32 cpu cores for parallel processing p.join() except Exception: print('encountered problem with'+filename) print(Exception) if __name__=='__main__': start_time = time.time() main() end_time = time.time() print('\nTotal', round((end_time - start_time) / 60), 'minutes elapsed.')
关键修改:
- 移除 from monai.transforms import LoadImage: 不再需要 monai 的 LoadImage。
- 使用 nilearn 加载数据: 在 read_data 函数中,使用 load_img 加载 NIfTI 文件,并使用 get_fdata() 获取数据。
- 错误处理: 添加了 try...except 块来处理文件未找到或其他加载错误。
- subj_name提取: 修改了 subj_name 的提取方式,从 filename[:-7] 改为 filename[:-4],以适应 .nii 文件名。
- load_root修改: 修改了 load_root 以匹配您的数据路径。
- data_global类型转换: 将data_global从numpy array转换成tensor
注意事项:
- 确保 load_root 变量指向包含 NIfTI 文件的正确目录。
- 根据你的实际文件名修改 subj_name 的提取方式。 如果文件名是 S1.nii.gz,则使用 filename[:-7]。 如果文件名是 S1.nii,则使用 filename[:-4]。
- 根据你的数据特点调整数据处理步骤,例如裁剪操作 data = data[:, 14:-7, :, :]。
多进程处理建议
joblib 库提供了一种更简洁的方式来进行多进程处理,它可以更方便地并行处理多个任务。
from joblib import Parallel, delayed import os from nilearn.image import load_img import numpy as np import torch def read_data(filename, load_root, save_root, subj_name, scaling_method=None, fill_zeroback=False): path = os.path.join(load_root, filename) try: nifti_image = load_img(path) data = nifti_image.get_fdata() except FileNotFoundError: print(f"Error: NIfTI file not found at: {path}") return None except Exception as e: print(f"An error occurred while loading the NIfTI image: {e}") return None save_dir = os.path.join(save_root, subj_name) os.makedirs(save_dir, exist_ok=True) data = data[:, 14:-7, :, :] background = data == 0 if scaling_method == 'z-norm': global_mean = data[~background].mean() global_std = data[~background].std() data_temp = (data - global_mean) / global_std elif scaling_method == 'minmax': data_temp = (data - data[~background].min()) / (data[~background].max() - data[~background].min()) data_global = torch.empty(data.shape) data_global[background] = data_temp[~background].min() if not fill_zeroback else 0 data_global[~background] = data_temp[~background] data_global = torch.tensor(data_global) #Convert numpy array to tensor data_global = data_global.type(torch.float16) data_global_split = torch.split(data_global, 1, 3) for i, TR in enumerate(data_global_split): torch.save(TR.clone(), os.path.join(save_dir, "frame_" + str(i) + ".pt")) def main(): dataset_name = 'ABCD' load_root = 'F:\\New folder\\cn_processed data' save_root = f'/storage/7.{dataset_name}_MNI_to_TRs_minmax' scaling_method = 'z-norm' filenames = os.listdir(load_root) os.makedirs(os.path.join(save_root, 'img'), exist_ok=True) os.makedirs(os.path.join(save_root, 'metadata'), exist_ok=True) save_root = os.path.join(save_root, 'img') # Use joblib for parallel processing Parallel(n_jobs=os.cpu_count())( # Use all available CPU cores delayed(read_data)( filename, load_root, save_root, filename[:-4], # Extract subj_name scaling_method ) for filename in sorted(filenames) ) if __name__ == '__main__': start_time = time.time() main() end_time = time.time() print('\nTotal', round((end_time - start_time) / 60), 'minutes elapsed.')
代码解释:
- from joblib import Parallel, delayed: 导入 joblib 库的 Parallel 和 delayed 函数。
- Parallel(n_jobs=-1)(delayed(read_data)(...)): 使用 Parallel 函数并行执行 read_data 函数。n_jobs=-1 表示使用所有可用的 CPU 核心。delayed(read_data)(...) 创建一个延迟执行的 read_data 函数调用。
- 移除了Queue的参数,简化了read_data函数。
总结:
通过使用 nilearn 库,可以方便地加载 NIfTI 文件,并将其集成到现有的代码中。同时,利用 joblib 库可以更有效地进行多进程处理,从而加速数据处理流程。请根据你的实际情况调整代码,并确保数据路径和文件名正确。
本篇关于《自定义fMRINIfTI加载教程详解》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
291 收藏
-
198 收藏
-
402 收藏
-
487 收藏
-
325 收藏
-
341 收藏
-
327 收藏
-
161 收藏
-
141 收藏
-
454 收藏
-
228 收藏
-
101 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 511次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 498次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习