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.
The time point is the time [dimension] of the 4D nii file. After reading the nii file, change the fourth dimension.

import os
import numpy as np
import nibabel as nib
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.
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 -

#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, path1 + os.sep + fileList2[ 0 ])

Leave a Comment

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