Saturday, June 15, 2013

Creating NIFTI Images from Scratch: CreateNIFTI.m

There may come a time, for whatever reason, where you want to create your own NIFTI image with your own values at each voxel. After all, those processed t-maps and beta maps tend to become a nuisance once in a while, and it feels far better to simply create your own.

First, you need to create a text file with the voxel coordinates and the value at that coordinate. For my script, for example, there are four columns: The first column is the value, and the next three columns are the x-, y-, and z-coordinates for that value. (Note that these are the native coordinates of the image, and not MNI or Talairach coordinates; if you want to use normalized coordinates, open up the image in a viewer, navigate to those normalized coordinates, and write down the corresponding native coordinates.) A sample text file might look something like this:


4 50 40 30 %Insert value of 4 at coordinates 50, 40, 30
5 50 40 31
7 50 40 32
10 50 40 33
500 50 40 35


Once you have saved the text file, you can either use an existing image or create a blank template image using a program like "nifti_tool -create_im ". Then, use the following script with both the image and the text file as arguments (making sure to pass them as strings):

function createNIFTI(imageFile, textFile)


hdr = spm_vol(imageFile);
img = spm_read_vols(hdr);

fid = fopen(textFile);
nrows = numel(cell2mat(textscan(fid,'%1c%*[^\n]')));
fclose(fid);

fid = 0;



for i = 1:nrows
    if fid == 0
        fid = fopen(textFile);
    end
   
    Z = fscanf(fid, '%g', 4);
   
    img(Z(2), Z(3), Z(4)) = Z(1);
    spm_write_vol(hdr, img);
end


This can then be modified to suit your evil purposes.

Tutorial video coming soon; in the meantime, I have some business to attend to, which involves going back home and having fun and laughing with my friends. Just hang tight.

No comments:

Post a Comment