Batch change the number of layers of nii files

Problem description:
There is a batch of fMRI files, and the number of time points needs to be changed in batches.
Idea:
The time point is the time [dimension] of the 4D nii file. After reading the nii file, change the fourth dimension.
step:

import os
import numpy as np
import nibabel as nib
"""
effect:
Read the nii files in the subfolders, change the number of time points, and output the nii files to each subfolder of the subjects, overwriting the original files.
illustrate:
No other files, such as .mat files, can be included in the total folder and subfolders
The operation will overwrite the original file, pay attention to backup.
The folder structure is:
path - sub001 - 1.nii
     - sub002 - 2.so
     ...
"""

#Read the nii file 
path= ( r'C:\Users\FunImg' ) #path where the nii file is located 
fileList = os.listdir(path) #Extract the file name as list format variable

for i in fileList:
    path1 = (path + os.sep + i)
    fileList2 = os.listdir(path1)
    example_filename = os.path.join(path1, fileList2[0])

    img = nib.load(example_filename)

    img_data = img.get_fdata()

    #Extract the first 240 time points, delete the following time points 
    # still need to remove first 10 points during preprocessing. 
    img_data_1 = img_data[:,:,:,: 240 ]


    #Save affine matrix and header file
    affine = img.affine.copy()
    hdr = img.header.copy()

    #generate new nii file
    new_nii = nib.Nifti1Image(img_data_1, affine, hdr);

    #Save the nii file, the following parameter is the saved file name 
    nib.save(new_nii, path1 + os.sep + fileList2[ 0 ])

Leave a Comment

Your email address will not be published. Required fields are marked *