Ed K
Ed K

Reputation: 1

converting multiple .nii into one .nii.gz

I need to convert mutiple .nii files into one .nii.gz file.

In Matlab, I used gzip('*.nii'), but it creates multiple nii.gz files for each single nii file. How could I create one combined nii.gz file from many .nii files?

Thanks in advance

Upvotes: 0

Views: 1023

Answers (1)

alle_meije
alle_meije

Reputation: 2480

If you download the Tools for NIfTI and Analyze Images library to /tmp/tools4nifti and copy, say two instances of the T1 MNI template, e.g., from the FSL directories:
/tmp$ cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz ./copy1.nii.gz
/tmp$ cp $FSLDIR/data/standard/MNI152_T1_2mm.nii.gz ./copy2.nii.gz
then you can concatenate the binary data using standard matlab functions and use the library to write the result:

addpath ( 'tools4nifti' );                               % add library

NII = load_untouch_nii ( 'copy1.nii.gz' );               % 1st copy
im1 = double ( NII.img );                                % load binary
NII = load_untouch_nii ( 'copy2.nii.gz' );               % 2nd copy
im2 = 10000 - double ( NII.img );                        % load binary, inverted
im  = cat ( 4, im1, im2 );                               % join along dim 4

NII.hdr.dime.dim = [ length( size(im) ) size(im) ];      % update NIfTI record
NII.hdr.dime.dim ( end+1:8 ) = 1;                        % give 8 dimensions
NII.img = im;                                            % put binary data in

save_untouch_nii ( NII, 'twocopies.nii.gz' );            % write the file

You load as many ims as you want and you can add as many arguments as you want to the cat command as well -- or put the whole operation in a for-loop.

The library is not mine but I use it a lot, because it can load .nii.gz files without additional explicit (de-)compression commands.

Upvotes: 0

Related Questions