File Exchange

image thumbnail

Tools for NIfTI and ANALYZE image

version (426 KB) by Jimmy Shen
Load, save, make, reslice, view (and edit) both NIfTI and ANALYZE data on any platform


Updated 22 Jan 2014

View Version History

View License

Editor's Note: Popular File 2018 2019 2020

Please always check NIfTI_tools.pdf for detail descriptions and latest updates.

If you are confused by the Left / Right of an ANALYZE image, please read UseANALYZE.pdf.

You may also want to go through FAQ.pdf for practical solutions and real examples.

Basic Programs:

1. load_untouch_header_only.m: Load only the header section of NIfTI or ANALYZE file. The input file will be automatically detected. NIfTI structure will be returned for NIfTI file, and ANALYZE structure will be returned for ANALYZE file.

2. load_nii.m: Load N-Dimensional NIfTI file (where N can be from 3 to 7) or ANALYZE file (where N can be from 3 to 4), and apply header info (e.g. affine geometric transform, voxel intensity scaling, etc.) to the data. If your file has more than 3-Dimension (e.g. time series etc.), you can also specify a range to extract only 1 or several volumes.

3. save_nii.m: Save N-Dimensional NIfTI structure (where N can be from 3 to 7) that is loaded by "load_nii.m" or made by "make_nii.m" into a NIfTI file.

4. make_nii.m: Make N-Dimensional NIfTI structure (where N can be from 3 to 7) based on the N-Dimensional matrix and other optional parameters (e.g. voxel_size, origin, etc.). Using "save_nii" command, the NIfTI structure that is made by "make_nii" can be saved into a NIfTI file.

5. make_ana.m: Make 3D ANALYZE structure based on the 3D matrix and other optional parameters (e.g. voxel_size, origin, etc.). Using "save_untouch_nii" command, the ANALYZE structure that is made by "make_ana" can be saved into an ANALYZE file in order to be compatible with some ANALYZE only programs.

6. reslice_nii.m: Re-sample 3D (or 4D) NIfTI file, or ANALYZE file with affine matrix M in .mat file, and save the re-sampled data into a new NIfTI file. The program will base on the affine matrix, which is especially useful for oblique images with non-orthogonal rotation or shearing that cannot be loaded with "load_nii.m". You can also specify voxel_size, etc. It will not cause negative effect, as long as you remember not to do slice time correction after using "reslice_nii.m".

7. pad_nii.m: Pad the volume(s) in NIfTI structure from any of the six sides, while keeping the originator, voxel size, data type, and description unchanged. The program is especially useful after you use reslice_nii, since the new volume will most likely have different dimensions.

8. clip_nii.m: Clip the volume(s) in NIfTI structure from any of the six sides, while keeping the originator, voxel size, data type, and description unchanged. The program is especially useful after you use reslice_nii, since the new volume will most likely have different dimensions.

9. view_nii.m: View & Edit 3D (or 4D) NIfTI or ANALYZE structure that is loaded by "load_nii.m" or made by "make_nii.m". Activation map, ROI, etc. can be overlaid on top of a background image (see above picture). Plotted view can be embedded into your existing figure window. If you use it as an individual program, it can also edit the orientation and voxel value of the image, view volume histogram, and save the modified image.

10. load_untouch_nii.m: Load N-Dimensional NIfTI file (where N can be from 3 to 7) or ANALYZE file (where N can be from 3 to 4), but do not apply any changes that are indicated in the header. WARNING: Do not use "view_nii.m" to view the structure that is loaded by "load_untouch_nii.m".

11. save_untouch_nii.m: Save N-Dimensional NIfTI structure (where N can be from 3 to 7) or ANALYZE structure (where N can be from 3 to 4) that is loaded by "load_untouch_nii.m" or made by "make_ana.m" into a new NIfTI or ANALYZE file. If you do not modify the loaded dataset, the header and data in the new saved file should be the same as those in the original file.

Other Programs:

1. collapse_nii_scan.m: Integrate multiple single-scan NIfTI or ANALYZE files into a multiple-scan NIfTI file.

2. expand_nii_scan.m: Break a multiple-scan NIfTI file into multiple single-scan NIfTI files.

3. save_untouch_slice.m: Save back to the original image with a portion of slices that was loaded by load_untouch_nii. You can process those slices matrix in any way, as long as their dimension is not altered.

4. get_nii_frame.m: Return the number of time frames of a NIfTI file.

5. flip_lr.m: Flip NIfTI or ANALYZE file Left-Right along the plane across the originator, and save the L-R flipped data into a NIfTI file. WARNING: Please use this program with caution, although you can always flip it back.

6. load_nii_ext.m: Load header extension from a NIfTI file.

7. mat_into_hdr.m: Integrate affine matrix in old SPM .mat file into its .hdr header file. Thus, the ANALYZE file is converted into a NIfTI file with the updated .hdr header file.

Cite As

Jimmy Shen (2021). Tools for NIfTI and ANALYZE image (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (222)

Edite Figueiras

Hi, I have a big data set (arround 100 GB) that I would like to save with nii format. I can't open the full data set as I don't have enough memory. Is there a way to save the full data set in a single nii file?

Hello, is it possible to save an image in nifti format (converted from Analyze) without modifying the header of the nifti image?
I have programs that won't let me open it because the header is modified, especifically the frame duration. (I have been using save_nii function). My email is


Mehul Jain

I got 22 side band as output. How can wire this to CSV file???

Markus Adamek

The problem I experienced is that by default load_nii allows for 10% deviation from orthogonal transformation which turns out to be quite much.

Markus Adamek

Comparing the mm Coordinates with Freeview, there is a definite problem in the transformation, causing wrong mm coordinates!

Zakir Aralbaev

I downloaded the NIFTI zip.files saved them to afile then added to the Set path in Matlab. Now how do I open the toolbox? What to type in matlab command window?

Qianqian Fang

if anyone sees a need to read NIfTI-2 files, or reading .nii.gz/.hdr.gz/.img.gz files in -nojvm mode under MATLAB, or reading these files under GNU Octave, please try my new toolbox "JNIfTI"

It uses memmapfile in MATLAB for fast disk-reading. It also support conversion from the rigid NIfTI-1/2 binary format to the more flexible text/binary JSON based new JNIfTI format, defined in the JNIfTI specification , making the data file smaller in size, faster to load/save, human-readable and extensible.

The JNIfTI toolbox can use Java based gzip compression, same as in this toolbox, but can also use the ZMat toolbox ( for fast compression/decompression.

Erik Solis


i am also facing the axis change when I use niftiwrite...Anterior changes to posterior and right ot left...
Do these files address that issue?


Hi, I meet a problem.When i load nii, do this like blew:
info = load_nii (str);
image = info.img;
I found that the nii change opposite.How to solve it easily, the save nii the same as load nii.


Tom Kirk

Unfortunately I have found this to be very buggy. A simple example of this is to load an image and then save a copy of it using the load_nii and save_nii functions. On my machine this results in the copy having a slightly different vox2ras matrix (and it is definitely not a rounding error). As such this toolbox has given me a lot of trouble over the last few months, it is extremely difficult troubleshooting your code when you can't even be sure that utility functions such as these are doing their job. I mean this criticism only to be constructive and to serve as a warning to others and I nevertheless thank the author for their efforts.

nermeen abdo

I downloaded the NIFTI zip.files saved them to afile then added to the Set path in Matlab. Now how do I open the toolbox? What to type in matlab command window?

Jose Bourbon Teles

Hi all,

I downloaded the NIFTI zip.files saved them to afile then added to the Set path in Matlab. Now how do I open the toolbox? What to type in matlab command window?

Jayendra Bhalodiya

Haoran Liu

D. Li

MATLAB 2017b has niftiread(' ') function, and it works really good. A few days ago i was also suffering from loading nii files, just want share this "news" and hopefully, this might help some of you :)

hao zhang

nssk suraj

After loading the image using load_nii(tst.nii)
How to access the img matrix from nii 1*1 struct?

Jobin T Philip


I created images using this tool. However, when I try to read them, using a C function, it gives error. Of course, with other Analyze image, my function works fine.
Has anyone encountered this problem?

Umit Kilic

Hi, thanks for sharing. It works. I work with brain mri and need to apply some image processing on them. How can i convert them to apprepriate file for implementing some image processing/mining operations.

André Silva

Helmar Waiczies


Javaid Iqbal

hitesh tekchandani
Dear have you read .nii images and convert inro .jpg ?
if you have solution please share me.

hitesh tekchandani

Hi, After converting .nii to jpeg (using load_nii and imwrite) coordinates of jpeg images are mismatch. i think some flip and rotation instruction are needed but in which order i don't know. Please help.

hitesh tekchandani

Hi, After converting .nii to jpeg (using load_nii and imwrite) coordinates of jpeg images are mismatch. i think some flip and rotation instruction are needed but in which order i don't know. Please help.

Silvia Caminiti

Hi Jimmy,
I'm using your toolbox to modify .nii image with a set (n=95) masks/ROI. I need to change the name of each single mask with a specific name. How can I do it?


Stella Guldner

Hi Jimmy,

I'm trying to use your toolbox to change the datatype of my images from int16 to float32. I've seen in an earlier comment that this might be possible, but I have some trouble with the conversion. This is what I have done so far:

datatype = 16; % change datatype to float32
nii2 = make_nii(myoldnii_file.nii, [],[], datatype);
save_nii(nii2, 'mynewnii_file.nii');

the error message i get is: Datatype is not supported by make_nii.

Is it possible to convert nii files this way or am I doing something wrong here?

Thank you in advance for any help.
Best wishes!

Farzana Parvin

all the files show error when run! how will the .nii image be read??

Dong Kyu Kim

Ellankavi Ramasamy

Hi Jimmy,

Thanks for the toolbox. It was really helpful and I'd like to cite your work. How may I cite your work?


Panda Big

I'am failed to get the
Could you please provide a new adress to get the EEG.nii and Ti.nii
Thank you!

Angelina B.

I have 3D and 4D brain MRI nii files. I get some trouble when I want to load files and view them.
My method is: nii = load_nii ('VSD.Brain.XX.O.MR_4DPWI.124517.nii');
Error using xform_nii>change_hdr

Next, I try to use reslice_nii.m, but the problem is:
my input: reslice_nii('VSD.Brain.XX.O.MR_4DPWI.124517.nii', 'VSD.Brain.XX.O.MR_4DPWI.124517b.nii');
error: Index exceeds matrix dimensions.

How can I solve these problems?

Thank you!



Eteri Karamamedogly

I have 200 .hdr/.img file pairs per person which carried out pre-processing using SPM.

How can I extract voxel time courses from the fMRI time series in Matlab?

Yunhui Zhou

@Jiancong Wang This is explained in the first "Orientation related question" in the FAQ.pdf came with the toolbox. For some NIfTI files it will be flipped simply by loading and saving without any further changes. However this flipping will not happen in the new NIfTI file.

However I think it is not a good habit to flip the orientation without notifying the user.

Hesham Alghodhaifi

Hi all,
I found the histogram of the displacement map of the deformation of two nifty file images. I want to know the unit of the x-axis and how can I figure out where is the direction of x, y, and z axises and how I figure out the positive and negative side?

Karl Spuhler

@Shereen, do you mean you need to know how to threshold your images?

This is pretty simple. Just, for an image called nii and a given threshold value th:

nii = nii>th

and you'll get an image of 1's where the original is greater than the threshold and 0's where it is less than or equal to the threshold.

Shereen Ekhlas

Help please
I want to know how to convert .nii image to binary image

Lijia Zhang

As Jiancong Wang and Stefano Orsolini states, the orientation is flipped from radiological system to neurological system without any notice. Also, there's nowhere to specify the data orientation.

All other functions are working though, just have to bear in mind to change the orientation.

Stefano Orsolini

As stated in Jiancong Wang comment (22 Aug 2016) there is a very serious issue with orientation handling.

Radiologically referenced images get turned to Neurologically referenced silently.


Karl Spuhler

Jiancong Wang

This tool sucks. It is not even self-consistent.
you do
[ nii ] = load_nii('some_nii')
write_nii(nii, 'new_nii')

The newly saved version has a different axis orientation with the old one! This is a stupid mistake that no usable image processing toolbox should make.

Justin Blaber


Do you know of the proper way I can use the information in "rot_orient" and "flip_orient" to realign bvectors into RAS for dwmri. For example, after I've loaded my DWI with load_nii() the following are:

rot_orient: [1 2 3]
flip_orient: [3 0 0]

How can I use these fields to change flip/permute bvectors (in FSL format) to also convert them to RAS?


archana malagi

Please help, getting error while using rri_orient:
Attempt to reference field of non-structure array.

Error in rri_orient (line 26)
dim = double(nii.hdr.dime.dim([2:4]));

alaa shamasneh

i don't know how to run this tools

David Groppe

Thanks for this most useful code!

David Groppe

Ali Aghaeifar

Thanks for the great tools.
Running the view_nii in ubuntu doesn't show the menu (Zoom, Interp, ... ). I tried to run it on three different PC with ubuntu. None of them showed menu.
Do you have any solution for that?
Many Thanks.

Elijah Rockers

Same problem as cindy. I tried opening the files in both PMOD and in freeview, but the origin/orientation, or some parameters that determine spatial location seem to be changed, but I did not change the header.

I would like to modify image values without changing anything about the spatial orientation, that would be fantastic.

How can I do this?


Joe Guy

Thank you for these tools. They have proved to be extraordinarily useful. However, recently I have found that the load_nii module has stopped working. I redownloaded the toolset and still have the same issue.

When I type load_nii('path/to/file')
The error I receive is:
Undefined function 'bitset' for input arguments of type 'char'.

Error in xform_nii>change_hdr (line 465)
hdr.dime.xyzt_units = char(bitset(hdr.dime.xyzt_units,2,1));

Error in xform_nii (line 154)

Error in load_nii (line 185)
nii = xform_nii(nii, tolerance, preferredForm);

Any debugging ideas?


Thank you for this toolkit.. actually help me a lot!
I just find a small issue, so when I load my nii image to this toolbox and do some editing and then save it.
I found that the image has been slightly translated (when I opened it in ITK Snap).
I am not really sure if anyone has the same issue, anyone has any idea how I could fix this? or any recommendation how I could get the right orientation back? Thank you.

Samuel Barnes

A small issue where I think the reliability of the "tolerance" option can be improved. When checking the affine matrix in xform.m it would be helpful to remove the resolution scaling form the matrix first, as if you have highly anisotropic voxels (common in MRI, say 0.7x0.7x5.0) it makes it very difficult to do a rational "tolerance" calculation to determine the matrix orientation. In this example all the elements in the third column are *5, so even for nearly straight matrices the secondary element in col 3 (n*5) will be larger than the primary elements in col 1 and 2 (n*0.7). Here is my suggested change (from my git patch file):
--- a/niftitools/xform_nii.m
+++ b/niftitools/xform_nii.m
@@ -324,13 +324,15 @@ function [hdr, orient] = change_hdr(hdr, tolerance, preferredForm)

- if det(R) == 0 | ~isequal(R(find(R)), sum(R)')
+ if det(R) == 0 || ~isequal(R(find(R)), sum(R)')
hdr.hist.old_affine = [ [R;[0 0 0]] [T;1] ];
- R_sort = sort(abs(R(:)));
- R( find( abs(R) < tolerance*min(R_sort(end-2:end)) ) ) = 0;
+ resolution_matrix=diag(hdr.dime.pixdim(2:4));
+ R_prime = R/resolution_matrix;
+ R_prime=R_prime.^2;
+ R( find( R_prime < tolerance ) ) = 0;
hdr.hist.new_affine = [ [R;[0 0 0]] [T;1] ];

I also square the components of the matrix, that way all the columns sum to 1, so you can check the absolute value of each element rather than element<tolerance*min(3rd largest)

Also Matlab wants to change your OR operators from "|" to "||".

sahil bajaj

Hi Jimmy (and all the users of this toolkit),

Thanks a lot for this great toolkit and all the discussion !

I have a question regarding extracting data from a ROI:

I have T1 maps in 4-dimensional (X,Y, slices, time) (in .nii format) and volume of interest files (in .nii format). I want to extract time activity curve from T1 maps for this particular VOI and want to plot it in MATLAB.

Description of view_nii shows that we can do this using this toolbox but I couldn't figure out how?

I would really appreciate if anyone could please help me in sorting this out !


Priyanka Mehta

This is a great tool!

I created hippocampal subfield masks using Freesurfer and I want to use it on my fMRI data to get the subfield voxels. However, how can I find out if the subfields and the fMRI data are in the same space? Is there a way I can use view_nii to see if the two images align properly?

Thanks for any help/suggestion.

Brian C Coe

am i missing something or is there no raw DICOM to NIFTI conversion function here...???
nii= D2N('SRC_folder','full_path\output_name')

it seems there are many out there but each use a different format for loading into matlab. so if i use a different DICOM2NIFTI converter than these files here aren't able to load them properlly. i see a make_nii() but that does not actually convert from a dicom... or am i missing something?

thank for your time.

fares feres

please is it possible to know the value of a pixel of a NIFTI image? because i didn't find any function which do this. i want to know the value of a specific pixel of nii image.
thank you


Aditya Daryanani

I'm trying to save a binary 3d nifti mask but when I try to save it I change the variables nii.hdr.dime.bitpix and nii.hdr.dime.datatype to 1. I am able to save this NII but no external programs other than Matlab are able to read it. I tried opening it with ImageJ and ITK-SNAP but none of them are able to read it.

Hank Jedema

Thank you for writing this nice function. I am trying to plot a series of ROIs (each in a color that reflects a p-value) on top of a template MR image. I get the basics to work, but I can’t seem to flip the colormap so that the lower p-values relate to the more red colors (using the default bipolar colormap). Normally I would use the flipud function on the color matrix, but I can’t seem to get this to work. Any suggestions would be very much appreciated. Thanks very much.

Jon Cleary




I have converted four DICOM series to 3D Nifti volumes using dicm2nii. What I need to do next is to concatenate the four 3D Nifti volumes to a single 3D Nifti volume and for this I have tried using collapse_nii_scan. The result I get is a 4D Nifti file ('multi_scan.nii') having four 'time points' instead of a single 3D volume containing all the images from the initial DICOM series. Any ideas on that would be really appreciated!


Sherryse Corrow

I am brand new to this toolbox (and MatLab) and I am trying to load a .nii file. I entered into the command window the following:
>> topface = load_nii('/Users/MRIuser/fMRI/Homunculus2/P121/Experiment.feat/stats/zstat1.nii')

Then, the command line immediately converted into:

>> uiopen('/Users/MRIuser/fMRI/Homunculus2/P121/Experiment.feat/stats/zstat1.nii',1)

Also, a tab opened in my editor window labeled zstat1.nii with many random characters. But, there was no created variable called "topface." Any suggestions?

Jeff Brooks

When I converted my DICOM images to Nifti format, I had multiple .nii files per run/session. Each of the images have different sizes, too. Does anyone know the reason why that might have happened? Which image is the correct one to proceed with for analysis?


Hi Jimmy,

I have a question about orientation (or perhaps directionality). I see that FSL had a function (fslhd) that reads the header and returns the "qform_xorient" ("Left-to-Right" or "Right-to-Left") but load_untouch_header_only does not. Is "qform_xorient" in the header or is it somehow interpreted from other parameters?




So I was checking your tool, very helpful in viewing .nii.gz file from matlab, but how can I use it to save my file as a .mat file with the same size (256*256*50).


Janki Mehta


Thanks for the toolbox. I have following issue:
I have a 3D matrix in MATLAB which I need to convert to NIfTI or ANALYZE format so as to view it in SPM8. For this I am using "Tools for NIfTI and ANALYZE image". My problem is once I convert this 3D matrix to ANALYZE format using make_ana command, I get the brain volume that is rotated/flipped w.r.t the original volume.
How can I resolve this?
NOTE: co-registering this to original brain volume did not help, the result was still flipped.




Thank you so much for this very helpful code!

I encountered a problem with loading some of my files.
I prepared a mask file in FSL, and want to load it into matlab together with some functional files.
The problem is the affine matrix has non-orthogonal rotation for 2 of my subjects, so I cannot use "load_nii".
I am not sure if I can use "reslice_nii" because I still need this mask file to have the same dimensions as my functional file.
Any ideas would be much appreciated!


Jeremy Manning

incredibly useful and well written toolbox. what a service!


Thanks so much!!!


I came across your MATLAB code on loading and viewing .nii files. I am presently working on brain mapping and brain imaging of Autism patients. I have got the mri images of patients from ABIDE database. But I am really new to MATLAB. I am not able to understand how this code will work. It says to replace the filename with the name of file, I did the same. But I guess it needs some more editing so that i could use it. Could you please help me out as in how to use this code.

Yi Sui

Great work!
I updated it a little bit and added a few new features.
Please check



thank you very much for this useful tool!

Paul Groot

Hi Sangeetha,

About the LAPACK loading error: (dlopen: cannot load any more object with static TLS)

This is a known issue on linux systems with matlab versions R2012b and higher, and is not related specifically to this toolbox:

It seems there is a new workaround, but a previous suggestion was to add the following line to startup.m:


This makes sure that the relevant libraries are loaded at startup, which did the trick on our systems.



Hi, Thanks for this useful work. When I try to load an nii file, I get the error I copied below. What could be the problem?

Error using det
LAPACK loading error:
dlopen: cannot load any more object
with static TLS

Error in xform_nii>change_hdr (line
if det(R) == 0 |
~isequal(R(find(R)), sum(R)')

Error in xform_nii (line 154)

Error in load_nii (line 185)
nii = xform_nii(nii, tolerance,


Hi, and congrats on your amazing work here.
I apologize if something similar has been asked before. I have stacks of 16 grayscale slices in tif format, and want to convert them into the nii format. How can I do this? Thanks.

Jimmy Shen

you can't do it. check faq.pdf when you need load_untouch_nii or load_nii


how can i view the image that is loaded by "load_untouch_nii.m"?

Jimmy Shen

because it's not the business of view_nii to interpret and apply header info.


Thanks the code is a great help.

But could you please help me understand why I can't use "view_nii.m" to view the structure that is loaded by "load_untouch_nii.m"? and how can I view that?



Sorry, I find it, thank you for the amazing functions

Luke Xie

great functions
thanks for the update

Jimmy Shen

Nicolas, please tell me what is the exact "clues" or "messages" that confuse you. In addition, please tell me what you try to do.

Nicolas Yu

the view_nii not work so well.
The example you give is quite well, but to my big data, it gives clues to use load_nii.m when I am using load_untouch_nii.m, but to use load_untouch_nii.m when I am using load_nii.m. why ?

Jimmy Shen

You can use "load_untouch_nii / save_untouch_nii" pair. Here's an example:

nii = load_untouch_nii('avg152T1_LR_nifti.nii');
nii.hdr.hist.descrip = 'Mengye';
save_untouch_nii(nii, 'new_avg152T1_LR_nifti.nii');

Unless you touch nii.img by yourself, e.g. nii.img(1)=0, it will not be changed, although it is also loaded and saved. Only the header (nii.hdr) is edited in the way you make the change.

In addition, if the input file is in Analyze 7.5 format, the output will be kept in Analyze 7.5 format. If the input is in NIfTI format, the output will be kept in NIfTI format.

That is why I have "load_untouch_" as well as "load_" feature. However, in most case, you want to use "load_" feature, since you don't want to interpret affine matrix in the header, and make all sorts of flipping and rotation by yourself, do you?


Hi, Jimmy

Are there ways to load, edit and save .hdr without doing things to .img? Because I found SPM changed my source files headers every time doing co-registration, and I want to change it back. It seems save_nii_hdr() is an internal function and I tried using it but broke my nifti files.



Perfect! Thank you!

Jimmy Shen

Data for "plot" only contain the coordinates information, while data for "make_nii" need intensity value which is assumed to be distributed on a grid with its coordinates from 1 to the dimention of the grid. In addition, unlike plot, coordinates for images contain only the integer. Therefore, you cannot directly extract the data from a plot and make it to an image.

Export your plot data to an image would be an easy alternative. I think you already did good. All you have to do is to hide the background image and the axes before you export the plot to an image. Here's how to do so:

1. Before export, use mouse click your plot (make it active);

2. Hide the axes by running:


3. Hide the background image by running:

h = get(gca,'child');
for i=1:length(h)
if strcmpi(get(h(i),'type'),'image')

4. Export the plot to an image. Now it does not have the background and axes.


Thank you very much for this useful product. I do have a question, if anyone could help me out...

I loaded a .nii file, did some processing and have a new plot that I would like to extract data from and ultimately save as .nii. It is a simple plot that was a result of finding the boundaries of an object. I extracted the data from the plot and entered it into a cell, but the "make_nii" function does not support this datatype. I tried converting the cell to a .mat, but that did not produce a satisfactory result either. I also tried saving the plot as an image and then using "make_nii," which worked, but the result included the border and axes of the image. I want only the data, without the background or axes. Does anyone have any suggestions?


Jimmy Shen

"collapse_nii_scan" is used to integrate multiple single-volume NIfTI or ANALYZE files into one multiple-volume NIfTI file. In your case, if you want to concatenate two 4D NIfTI images into one 4D NIfTI images, you should apply "expand_nii_scan" to your both 4D images. All volumes must be in the same folder, and make sure the file name is correctly renamed (i.e. from 001~999 instead of 1~999). Then, apply "collapse_nii_scan" to all those expanded volumes in the specific folder, and you will get a concatenated 4D NIfTI image file.


Hello, i tried to concatenate two 4D nifti images using collapse_nii_scan but that gives me an image with just 2 volumes. Am i missing something?

Edgar Guevara

Berkin Bilgic

Jimmy Shen

Hi Zhi:

"collapse_nii_scan.m" will do the job.

Hi Samiy:

This tool can not be used to extract spinal cord. However, once you extracted it and saved into another Analyze/NIfTI file, this tool can load the data into MATLAB for further processing.


In FSL, there is a tool called avwmerge, which binds several hdr or nii files into a single hdr or nii file. Some existing applications only use the single hdr/nii file as input. Could I find similar function in your tool box? Many thanks.

Jimmy Shen

Received the image, and it is a special RGB data type one. The nii.img ranges from 0 to 1 as usual, but the output value needs to be scaled by (glmax-glmin)+glmin.

Jimmy Shen

Would you please send me this image, so I can take a look into it for you tomorrow afternoon.

Xiaoying Tang

This package works very well for my research. Thanks first. But now I have a problem with vector image. I want to change the pixel value of a xyz vector image by taking its absolute values. I first used: nii = load_nii(1_xyz.img), if I use view_nii(nii), I found everything correctly. Moving the crosshair to 139,63,91, I can read the value is (-0.1784,0.8963,0.3663), which is correct. But if I used: a = nii.img; a(139,63,91,1:3), it will display values as 0.35555,0.9434,0.6535. It seems that the value of a is always positive. I tried to use nii = load_untouch_nii(1_xyz.img); a = nii.img; It has the same positive value.
Do you have any suggestion about this inconsistency between the value of nii.img and that displayed by view_nii(nii)?
Thanks a lot.

Xiaoying Tang


This package works very well for my research. Thanks first. But now I have a problem with vector image. I want to change the pixel value of a xyz vector image by taking its absolute values. I first used: nii = load_nii(1_xyz.img), if I use view_nii(nii), I found everything correctly. Moving the crosshair to 139,63,91, I can read the value is (-0.1784,0.8963,0.3663), which is correct. But if I used: a = nii.img; a(139,63,91,1:3), it will display values as 0.35555,0.9434,0.6535. It seems that the value of a is always positive. I tried to use nii = load_untouch_nii(1_xyz.img); a = nii.img; It has the same positive value.

Do you have any suggestion about this inconsistency between the value of nii.img and that displayed by view_nii(nii)?

Thanks a lot.


Thanks, that's exactly what I wanted to know!

Jimmy Shen

Sure Mark. You need a reference image by the way, so you can see what will happen before and after you apply the transformation matrix. Here's the example:

1. Download "avg152T1_RL_nifti.nii" from NIfTI site. I use it as reference image.

2. View how the reference image looks like: nii=load_nii('avg152T1_RL_nifti.nii');

3. Assume that I have a Transformation Matrix, which will let the reference image turn 30 degree counter-clockwise on XY plane, here will be the matrix: T=[cos(pi/6) -sin(pi/6) 0; sin(pi/6) cos(pi/6) 0; 0 0 1];

4. Get old_xyz from reference image: rl=load_untouch_nii('avg152T1_RL_nifti.nii');

5. Apply your transformation matrix, and save new_xyz into a new image: new_xyz=T*old_xyz; rl.hdr.hist.srow_x(1:3)=new_xyz(1,:); rl.hdr.hist.srow_y(1:3)=new_xyz(2,:); rl.hdr.hist.srow_z(1:3)=new_xyz(3,:); save_untouch_nii(rl, 'rl30.nii'); Now you already have the "rl30.nii", which is a transformed NIfTI image can be used anywhere.

6. In order to view this image using my toolbox, you need to reslice it: reslice_nii('rl30.nii', 'rl30b.nii'); Now, you can load and view the rotated image: rl30b=load_nii('rl30b.nii'); view_nii(rl30b);

Hopefully this answers your questions.



Is it possible to use reslice_nii to apply a transform to a nifti volume? for example, if I have a transformation matrix that is the result of a 3D coregistration of a functional with an anatomical volume, could I use reslice_nii to apply that transformation matrix to the functional volume to transform it into anatomical space? If so, any chance of some example code?

Thanks very much for the useful code.


Jimmy Shen

To reply your first comment: The problem is that you mixed "make_nii" with "_untouch_" version. If you use "make_nii" to get NIfTI structure, it has to be saved using "save_nii".

To reply your second comment: If you know NIfTI structure well, sure you can modify it and then use "save_nii" to save it. You can even save "non-orthogonal" NIfTI structure to the file with "save_nii".

The reason that I interpret the header with "load_nii" and limit it to "orthogonal" transformation is all about convenience, at least for my work.

BTW, if you take the original NIfTI file, and bring it to other software to display (e.g. SPM), they will also reslice it for you.

Thank you very much for your rating!


I think I figured it out.

I read your updates and realized that the untouch option doesn't load the Transformation matrix, so by adding one I was changing the header.

I resolved by cloning the header and using save_nii()

If you are wondering why I didn't use load_nii(), it is b/c ,y data has non-orthogonal transforms and the open tool wouldn't work.

BTW, I think this behavior maybe unjustified. And the advice to reslice is considered a bad idea in my lab, b/c of interpolation artefacts.


Hi Jimmy,

I am having an issue using save_untouch_nii().

I load a nifti 4D data set with load_untouch_nii(), make no changes, then try to save with save_untouch_nii() and get a failure with the message:Usage: please use 'save_nii.m' for the modified structure.

I even tried cloning the hdr before the save.

nii = load_untouch_nii('foo.nii');
data = nii.img;
%data = data + 10;
nii_mod = make_nii(data);
%nii_mod.hdr = nii.hdr;

Andrew Davis

Jimmy Shen

Got your data, and did the following test using "analyze75read" "load_untouch_nii" and "load_nii", here the results:

max(a1(:)), get 3.3943e-08

max(a2.img(:)), get 3.3943e-08

max(a1.img(:)), get 3.3943e+04

check: a2.hdr.dime.roi_scale
get 1.0000e+12

You told me that you got a voxel value of 1.089e+12 using "analyze75read". I cannot duplicate your result.


Hi Jimmy. I think i understood correctly your tool and i did use "load_nii" indeed. I am sending you the data.

Jimmy Shen

Without more detail, I cannot duplicate your problem. Please send me your data that indicates it. On the other hand, I wish you could take a look at my web page to better understand this tool. In order to display, you must use "load_nii" instead of "load_untouch_nii". i.e. your data is interpreted properly (touched). There could be many cases, e.g. scale factor is specified in the header file, your data has different orientation, etc. However, in no situation it treats double datatype differently.


My first post was not submitted. I was saying that the programme failed to display correct values of Analyze files with double datatype. Matlab analyze75read works without problems.
Do you have any idea why is this?


PS: for example instead of the correct voxel value 1.089e+12, this programme will display 988.1

Jimmy Shen

I never have such a function called "read_nii_img". Please read all functions and usages from:

Jessica Bernard

I've found recently, now that we have upgraded to Matlab 2011a, that many of these functions no longer work properly. When using read_nii_img we are now getting an error saying:

??? Undefined function or method 'read_nii_img' for input arguments of type 'char'

We had successfully run these programs before, but since the update they have not been working. Do you have any suggestions to perhaps work around this? Thanks much!

Jimmy Shen

It seems that "load_nii_hdr" in "apply_fsl_transformation_matrix" has been modified. It should look like this "function [hdr, filetype, fileprefix, machine] = load_nii_hdr(fileprefix)". i.e. It should have 4 output arguments, which is exactly the same amount as "load_untouch_nii" asked for.



using 'load_nii_hdr' within 'load_untouch_nii' I get the following error message:

??? Error using ==> load_nii_hdr
Too many output arguments.

Error in ==> load_untouch_nii at 103
[nii.hdr,nii.filetype,nii.fileprefix,nii.machine] = load_nii_hdr(filename);

Error in ==> apply_fsl_transformation_matrix at 5
vox = load_untouch_nii('/SCR2/DTI/det_track/BM3K/trans/Sem_fun_roi.nii');

Thanks for your help!


Jimmy Shen

NIfTI supports both ".nii" and ".img/.hdr" file extension. If you do not provide any file extension, it will look for ".img/.hdr" files by default. Therefore, you can easily solve your problem by provide appropriate file extension. e.g. nii = load_nii('filtered_func_data.nii');


Trying to load a .nii file, I got a message:
Cannot find file "filtered_func_data.hdr"
The problem apparently lies in the fact that we don't have a separate header file. Is there a solution other than converting it to .hdr and .img?

David N

Jimmy Shen

I assume that you have a series of 3D NIfTI (or Analyze) files with the same header information (i.e. same dimension, voxel size, originator, ... etc.), and you want to integrate it into a single 4D file with time series in the file.

If this is the case, you can use my "collapse_nii_scan.m" to do so. Type help collapse_nii_scan to get more information.

For file extension, this function will follow whatever you have. i.e. you will still get a single .hdr/.img file afterwards.

Since all NIfTI compatible software should be able to load a 4D NIfTI (or Analyze) file, we do not support any conversion from .hdr/img to .nii file.

Lirong TAN


I want to convert a series of .hdr/.img files into one single .nii file. How can I achieve this? Thanks a lot.

Jimmy Shen

You are not supposed to use "load_nii_hdr.m" & "load_nii_img.m". Both are internal functions, and are not supported when you call them directly.

If you want to take look at the header information, please use "load_untouch_header_only.m".

If you would like to change the voxel value, please use "load_nii.m" to load the NIfTI file, and then use "view_nii.m" to edit voxel value at crosshair (under "Edit" tab), and then click "Save displayed image" under "File" tab.

The reason of inconsistency in your case is caused by the scaling factor in the header that was not properly interpreted by yourself.


I am using Tools for NIfTI and ANALYZE image. It is really helpful and my sincere thanks to share your work for the research community.

I am using the images in .hdr and .img format. I am trying to change the pixel value 1 into 5 and then save it as .img. I viewed the saved images using the function view_nii. I could find the pixel value as 5, which i did. But if i open these images in viewer like MRIcroN and FSLVIEW it shows a pixel value as 0.01961. I could not find the reason. Can you please help me in finding the solution to the above problem. I can see that GMax of the output image is 5. But for the input image it is 0.
I have put the lines of code which were used by me.

I would like to send my input file, so it would be better to know my issue. Please let me know a way to send my input file.

[nii1.hdr,nii1.filetype,nii1.fileprefix,nii1.machine] = load_nii_hdr('1sub_110_A-128_5med');
[nii1.img,nii1.hdr] = load_nii_img(nii1.hdr,nii1.filetype,nii1.fileprefix,nii1.machine);
z=find(nii1.img); %number of index---4610

Thanks in advance for your help

Jimmy Shen

This is because those parameters & scaling have been interpreted & applied to the image. It is what NIfTI loader supposed to do.

If you want to interpret header by yourself, feel free to try the following commands:

x = load_untouch_nii('b0.hdr');
save_untouch_nii(x, 'b0xx.nii');

For more details, please carefully read all the instructions through, which can be found on my web page:


I tried converting an HDR image to a nifti image by using two functions in the package
x = load_nii('b0.hdr');
save_nii(x, 'b0xx.nii');

And then I compare the Q Offsets, affine parameters and Calibration Scaling before and after the conversion. However, they are almost completely different. Is it possible to do the conversion without affecting these parameters?

Jimmy Shen

First, when you use 'save_nii.m', the file that you saved will always be in NIfTI instead of Analyze format.

Second, use 'load_untouch_nii' to load both original Analyze file and saved NIfTI file, and check what is the dimension size and data type of '.img' field.

Finally, I have tested to use 'load_nii.m' to load many Analyze and NIfTI files and then use 'save_nii.m' to save into NIfTI files. I did not find data size "increase remarkably". If it is possible, please upload your original Analyze data to somewhere that I can access, and email me the link (DO NOT USE EMAIL ATTACHMENT), so I can try to duplicate your problem.

By the way, I will not be available until Aug 2.

yang liu

Dear everybody:

I have found the following problems in the using this toolbox.
I can get the data in the analyze format file with 'load_nii.m'.
But when I save the data to analyze format file with 'save_nii.m' without any change, the data size increase remarkly.


I downloaded the new program, so I now get a different error suggesting what you just mentioned.

However, reslicing is not an option, as we were using SPM to register images in the first place, so we need the NIFTIs in the current space they are in (I will work on getting images to you, but I don't know if that is a possibility at this point).

Jimmy Shen

First, both "load_nii" & "load_untouch_nii" support SPM NIfTI images. As a matter of fact, there is only one NIfTI standard, all NIfTI compatible software should comply with that standard.

Second, in order to duplicate the error, please upload that image onto anywhere that I can have read access. PLEASE DO NOT SEND BY EMAIL ATTACHMENT.

As you have noticed, NIfTI images can be in any spatial orientation, while "load_nii" can only have 48 orthogonal orientations. In that case, the program will prompt you to use "reslice_nii" to interpolate the image. Since you did not get the appropriate prompt, I am interested to take a look at the image that you are loading.

Please check my NIfTI web page for more details:


Edit: error here

**??? Error using ==> xform_nii>change_hdr at 236
Transform of this NIFTI data is not supported by the

Error in ==> xform_nii at 90
[hdr orient] = change_hdr(hdr);

Error in ==> load_nii at 71
nii = xform_nii(nii);


Mr Shen,

I have had good success in general with this package; however, in dealing with SPM NIFTIs ( I cannot load with load_nii.

I must use load_untouch_nii, however, when I use this, the NIFTIs are in a random spatial orientation, with the image matrix needing to be flipped and/or rotated to be in correct orientation.

Do you know a way to fix this?? It is greatly slowing my research :/



Navid Samavati

Yes, and now that you mentioned sometimes the old analyze format it is read as [0 0 0] it makes more sense. I think that's probably my case.

Jimmy Shen

Have you read: as I mentioned?

As you can see, "origin" in NIfTI is expressed in sform or qform. When you use "load_nii", you should find it under: hdr.hist.originator(1:3)

Sometimes, with old ANALYZE image, the value is [0 0 0] which does not make sense, then you have no choice but use: hdr.dime.dim(2:4)/2.

Hope this helps.

Navid Samavati

Thanks for your response!

By start position, I mean the origin (x,y,z). I couldn't find the origin of my image data anywhere in the header structure in MATLAB.

Jimmy Shen

The start positions for x, y, z are all 1. i.e. XYZvoxal=[1 1 1] is the place to start.

Please also check NIfTI header fields at:

and let me know whether I understand your question correctly.

Navid Samavati

Hi Jimmy,

I can't find the start position of the pixels or voxels in x, y , and z directions in the header structure. I read my analyze image using load_nii. The image is fine. I just don't find the start position.


Jimmy Shen

Here's an example:
nii = load_nii('mydata.img',vol_id);
slice = nii.img(:,:,slice_id);


Hi Jimmy. Really it's a very nice code.

I have a question. How can i do to extract a single slice of a 4D nifti brain volume and save it into a regular image file (i.e.: jpeg, bmp...), using a common color map (i.e.: ge_color)??

Thanks for attention.


Victor Alchanatis

Jimmy Shen

You may not notice the tolerance argument in "load_nii". By default, we allow no more than 10% of distortion. You can set it to 0, you will be prompted to use "reslice_nii" to interpolate the image.

If you just want to change negative value and NAN value to 0, you can simply use "load_untouch_nii" and "save_untouch_nii" pair to do the job.

Xiaoying Tang

Hi Jimmy,

I have some problem. My goal is to change the negative value and the NAN value in an image into 0 and then save it as .nii. I used the load_nii program and then changed the value into 0, and then used the save_nii. Everything seemed to be fine. But I finally found that the FOV of the image changed a little from: Field of VIew-Width: 204; Field of View-Height: 256; Slice Thickness:1 to Field of View-WIdth:203.992; Field of View-Height:255.909;Slice Thickness: 0.99968. But the image dimensions remained the same. Do you understand what I mean? I mean the voxel size changed. Could you please have a look at this problem? It is very strange.

Thanks a lot.

Xiaoying Tang

Hi Jimmy,

I have some problem. My goal is to change the negative value and the NAN value in an image into 0 and then save it as .nii. I used the load_nii program and then changed the value into 0, and then used the save_nii. Everything seemed to be fine. But I finally found that the FOV of the image changed a little from: Field of VIew-Width: 204; Field of View-Height: 256; Slice Thickness:1 to Field of View-WIdth:203.992; Field of View-Height:255.909;Slice Thickness: 0.99968. But the image dimensions remained the same. Do you understand what I mean? I mean the voxel size changed. Could you please have a look at this problem? It is very strange.

Thanks a lot.

Xiaoying Tang


I solved the problem. Thanks a lot.


Jimmy Shen

First, you don't have to use "make_nii", which just creates a NIfTI struct for you based on your N-D matrix.

Second, make_nii supports float data. Type help make_nii for more details. Did you receive any error message?

Xiaoying Tang

Hi Jimmy,

Thank you very much for your scripts. They are really useful.

Now I want to read some nii file and set the pixel value which is below zero. I first load the nii file and then change the value. Now I need to save it back into nii file. I guess I first should make_nii, and then save_nii. But it seems that make_nii doesn't support float data type. Do you have good suggestion?


Jimmy Shen

Hi Juan:

You can check "Question about overlay" category under:
There are several questions and answers in this topic.

You said that you have the x,y and z directions of each voxel. The x,y and z directions must be converted into the index regarding to the first voxel. Probably, you already have the brain region that represents the eigen image. Let's assume that you have it in a binary image called "brain_mask.nii", while the anatomical image is called "ana.nii". Here's what you can try:

1. Use "ana = load_nii(ana.nii)" to load the anatomical image, and make sure that variable "ana.img" is either in "single" or "double". If not, use step 2 to convert it.

2. To convert variable "ana.img" to "single", you need to use "make_nii" command: "ana = make_nii(single(ana.img), ana.hdr.dime.pixdim(2:4), ana.hdr.hist.originator(1:3))".

3. Use "mask = load_nii(brain_mask.nii)" to load the brain
mask image, and assign value and index to "opt" struct: "opt.setvalue.idx = find(mask.img); opt.setvalue.val = eigenvector;". You can see more detail to use "setvalue" by command: "help view_nii".

4. Add other values to "opt" struct: "opt.command = 'init'; opt.useinterp = 0;".

5. Plot eigen image with underlaid background by command: "view_nii(ana, opt);".

6. Don't click "interp on/off" menu. It doesn't work properly. If you would like to see the interpolated one, use: "opt.useinterp = 1; view_nii(ana, opt);" instead.

If you still have question, please feel free to ask me.



Hi Jimmy.
Thank you very much for this extremely useful toolbox.
My question is about how to overlay in the image. I need to overlay the principal eigenvector of each voxel on the image; I have the x,y and z directions of each voxel in a matlab array already but I want to know how can I display over the same image or if its possible to modify your code to keep just the principal image and get rid of all the options that you gave like color and position of crosshair, etc. because I mainly need to show the image and display the eigenvectors over it.

Jimmy Shen

Hi Preeti:

1) That's right, it does not support .avw format. So please save it in .hdr/.img or .nii format before you open them in MATLAB.

2) 300 slices should be okay on many new computers. If your computer cannot hold this much data in its memory, you may want to take 1 or several slices at a time to analyze. This feature was implemented on Jan. 6, 2010.


I am using AnalyzeDirect Software for lung cancer detection and retrieval. i have segmented the lungs from chest CT scan of more than 300 slices (DICOM). I have saved the result in .avw format as well as in Analyze7.5 format. Now when i tried to open these files in MATLAB i got these problems

1) the code only suppports 'hdr/.img' format i.e Analyze7.5 format. i was not able to load .avw file
2) as no. of slices are more than 300 it gives 'Out of Memory' error when i opened '.hdr/.img' data.

how to resolve these two problems. Please help!

Jimmy Shen

Hi Anne-Lene:

Don't worry. The following tips will give you some more help.

If you did not see difference after using "expend_nii_scan', it means that you only have 1 scan (1 volume) in your file. Since you said "...look at the nifti images separatley...", I thought you have several images (volumes or scans) in 1 file, and would like to treat them separately.

The first step you need to do is to load your image into MATLAB by "load_nii" command (Please look at "help load_nii" before using it).

Let's say you have an image "file1.nii" (or "file1.img/hdr"). By command:
nii = load_nii('file1.nii');
nii = load_nii('file1.img');
You can get a 3D matrix in "nii.img", and its header information in "nii.hdr".

You mentioned that you would like to change the image into another datatype. Here's how:

You can either change the header information directly (if you are familiar with the NIfTI header) then use "save_nii", or to use "make_nii" to create a new NIfTI structure (like nii).

For example:
datatype = 16; % change datatype to float32
nii2 = make_nii(nii.img, nii.hdr.dime.pixdim(2:4), nii.hdr.hist.originator(1:3), datatype);
save_nii(nii2, 'file2.nii'); % either to use nii ext
save_nii(nii2, 'file2.img'); % or to use img/hdr ext
By doing this, you changed it to Float32 data type, and saved it into "file2.nii" (or "file2.img/hdr").

If you have a MATLAB algorithm that you made by yourself as you mentioned, I think you will be more interested in the img matrix ("nii.img"). The "nii.hdr" is the header information to describe how "nii.img" is oriented, what is the voxel size, and originator, and many more.

Finally, I have to correct you that "make_nii" will not convert image to any extension. It only makes a NIfTI structure from N-D matrix and some other parameters (voxel size, originator, data type, etc.). Please double check the help, and make sure that you know how to use it.

If you have further question, please be more specific (e.g. make a point list), so I know how to help you.



I have looked at those links and tried expand_nii_scan, and I'm afraid I still don't understand. My file has the nii extension and when I use expand I get another nii file, I don't see the difference between that and my original file, when I use view_nii.

I saw that using make_nii I could convert images with the img/hdr extension, but I couldn't get it to work on my file with nii extension.


Jimmy Shen

Hi Anne-Lene:

No questions are stupid.

Yes. You can use my tool to look at NIfTI images separately and also convert them to another datatype.

Since NIfTI supports both img/hdr and nii extensions, so my tool supports any of them.

Most help can be obtained by using help command. e.g. help make_nii.

There are several other resources that you can get help:

Command "expand_nii_scan" is used to break a multiple-scan NIfTI file into multiple single-scan NIfTI files, so you can look at them separately.

If you want to convert img data type, you can use "save_nii" after use "make_nii" command. If you are familiar with NIfTI structure, you can modify "hdr.dime" directly, and then use "save_nii" to save.

If you have further question, please make it more specific, so I can help you.




I am a beginner in using nifti so this may seem like a stupid question, but i hope you can help me.

I have used fsl prelude to unwrap my mri images, and they are now in the nifti format. I now need to compare these to images with images that I have unwrapped with a matlab algoritm that i made myself.

Can i use your tools to look at the nifti images separatley and perhaps convert them to another datatype that i can use in matlab?

I tought maybe your tip in the help save_nii could help me, but i don't see how to use it, do i need img/hdr files instead of nii?

I will be very greatful for some guidance.


Jimmy Shen

Hi David:

I just got chance to look into this issue.

Since it is too complicated to modify "load_nii.m" to load specific slices of NIfTI and Analyze formats, I modified "load_untouch_nii.m" only. That means, you will take care of image orientation based on its header information, because "load_untouch_nii.m" does not apply any changes to the IMG matrix that is indicated in the HDR.

I hope this could still somehow help you to load large dataset.



This is a fantastic and highly useful piece of software.

I'm just wondering if there is anyway to load just one or more specific slices from analyze and nifti formats? I know it is straightforward to select the desired slices from nii.img after load, but I would like to avoid the memory usage with the full 4D, 5D,tsc load.

Thank you for sharing this work Jimmy

Jimmy Shen

Hi Michael:

First, I am wondering how you could simply rename an .img file to a .nii file. NIfTI supports both extensions, but for .img extension, you need to save the header separately in .hdr file. So there is no way for people to just "... rename the .img file to .nii file ..." like you said.

Second, I looked into Francesca's data, and the size of the image data does not match the size that is indicated in the header. For such a file, I cannot image any software can process it.

I am glad to take a look at your samples. Would you please upload them onto your server, and post the link here?


Michael Zeineh

Hi Francesca and Jimmy,

Funny, I have run into the same problem with MRIcro. I found a workaround. If with MRIcro you save the roi as a separate analyze header (rather than the embedded header), then it will open with MRIcro. However, this will still not open with Jimmy's tools. However, if you rename the .img file to .nii, then both Jimmy's tool will load it.

Jimmy, I am happy to email some limited sample images if you want.


Jimmy Shen

Hi Wei:

Thanks for the rate.

When you use "load_untouch_nii.m", it just load the img and hdr, but does not apply any changes (e.g. scl_slope, affine matrix, etc) indicated in the header. Therefore, I always suggest people to use "load_nii.m" in most cases. Please check the description of "load_untouch_nii.m" & "load_nii.m" on

You are right, the unexpected value was caused by the "scl_slope" parameter, which is properly applied when you use "load_nii.m". However, I am not sure whether you have noticed that this is a radiological image, i.e. Right on LHS and Left on RHS. Here, L/RHS means Left/RightHandSide.

When you use "load_nii.m", it will do all the proper flipping and rotation according to the affine matrix in the header, and the img will always be in RAS orientation (i.e. x: L->R, y: P->A, z: I->S). In your particular case, instead of use [32 32 23], you should use [33 32 23], since x axis is flipped, i.e. new_x = max_x(64) - old_x(32) + 1 = 33.

Other software may choose to do so with proper labeling around Axial / Sagittal / Coronal view, e.g. FSL does so.

Please feel free to let me know if you have further question.



Hi Jimmy,

you're right, I've tried to open the .nii file with MRIcro and an error about expected header dimensions appears. The wrog step is probably when i try to export .roi to .nii, but actually there's no other way to do it with MRIcro. I'll try to find some other way!

Thanks a lot for your help and thanks again for your nifti tool!


Wei Liu

OK I think I found the parameter for scaling: they are hdr.dime.scl_slope and hdr.dime.scl_inter. Now I know how these packages works, and I can scale the voxel intensity myself if I want. Sorry for the cursory questions, and thanks for the good tool! -Wei

Wei Liu

Hi Jimmy,

When reading a nifti file I found the voxel gray values are different with other tools. What I did is:
- 'untouch load' the file: fmri_mean = load_untouch_nii(.../meanfM00223_004');
- print voxel value of mri_mean.img(32,32,23). The value is 9506.
- But when I open the same file with fslview, I found the same voxel has different value. And other voxels are also different. the fslview snapshot is attached. Because in fslview the voxel coordinates begins from 0 to dim-1, the same voxel in fslview has coordinate [31 31 22].

- Use the application 'Imageviewer' from itk, and found the voxel value is same with fslview. Also attached snapshot. Same to fslview the coordinate are [31 31 22] for the same voxel.

- check the header of the nifti file by fsl tool 'fslhd':
datatype 4
nbyper 2
bitpix 16

That means it's int16.

-Check the fmri_mean structure in matlab, and found the data type is 4:
datatype: 4
bitpix: 16

But why did your nifti tool give different gray value with other packages? I put all the snapshot and the nifti files at for your reference.

By the way this is excellent tool. Thanks!

Felipe Salinas

Sorry for not rating this sooner....

Jimmy Shen

Hi Francesca:

First, thank you very much for the rating, and I really appreciate it.

It seems that "lCC_19850624TRTN_2x2x2_b1000_a_fa.nii'" is corrupted. Have you tried to open it successfully under MRIcro? If so, please upload this file and let me take a look at it?

In addition, from the error message that you posted, it seems that you are using a very old version of my tools. I noticed this by the line number showing the error. However, I still believe that the error is caused by the corrupted image.

Please let me know,


Dear Jimmy,

i'm just a beginner with all this "nifti imaging world" but I've already done enough for understanding that you've done a very great and smart job!thanks!

Well, i have a problem with loading a .nii file. (obtained by exporting a .ROI file with MRIcro). I'll post the error that i get:


>> ROI=load_nii('lCC_19850624TRTN_2x2x2_b1000_a_fa.nii');
??? Error using ==> reshape
To RESHAPE the number of elements must not change.

Error in ==> load_nii_img>read_image at 266
img = squeeze(reshape(img, [hdr.dime.dim(2:4) length(img_idx)]));

Error in ==> load_nii_img at 62
[img,hdr] = read_image(hdr,filetype,fileprefix,machine,img_idx,old_RGB);

Error in ==> load_nii at 66
[nii.img,nii.hdr] = ...


Could you help me?

Thanks a lot and all the best!


Jimmy Shen

Hi Alex:

Theoretically, with the header information in hand, it is feasible to do slice collapse/expand in addition to scan collapse/expand. Currently, I didn't find such a tool, but may consider your suggestion in the future.

Thanks for your feedback.

Jimmy Shen

Hi Wen-Tung:

The problem is probably in a module that is used by ImageJ. I tried MRIcron, and got the same result as you described. i.e. when hdr.dime.datatype=32 & hdr.dime.bitpix=64, it does not support. when hdr.dime.datatype=64 & hdr.dime.bitpix=128, it works.

In order to make sure what datatype ANALYZE format is supposed to support, I double checked the Analyze document:
It says that Analyze format should only support 32/64, rather than 64/128.

I also tried other popular software like AFNI. It turns out that 32/64 is supported by AFNI. When I tried 64/128, it complains "Unsupported ANALYZE datatype =64", which is correct.

Therefore, if you have to use datatype=32 complex, you have to find correct software to use. AFNI is one of them that I have just tested.

All the best!


Dear Jimmy,

I would like to create large NIfTI files using a computer with relatively small memory. It seems I could do this by processing several slices at a time, and then reprocessing with collapse_nii_scan. This seems a bit clumsy and I guess it would also believe that collapsed parts were a time series rather than stitching together one large volume? Is there a tool to stream slices into a NIfTI file, supposing that I can provide some header info from the beginning?


Wen-Tung Wang

Thank you for the note, Jimmy.
First, sorry that I didn't write it clearer in my previous posting. ImageJ is a freeware from NIH ( that have numerous users in medical imaging community. ImageJ has a plugin ( that can open/save image in Analyze format. I was trying to save an MRI image, after some processing using Matlab scripts, in Analyze format and view it using ImageJ.
I tried your very nice example, it works well. Yet, it is still not clear to me why ImageJ cannot read the output file. Using datatype=64, ImageJ can read the file, but this is not the correct datatype and there are sinusoidal modulations across the image.
Thank you.

Jimmy Shen

Hi Wen-Tung:

First, thank you for the rating.

Your script is correct, but I didn't get any error message. You said " ... trying to read the test.img using ImageJ, ...". Is it a typo?

Here's an example that I tested, and you can duplicate the process:

ana = make_ana(myMat,[],[],datatype);

Did you get error message when testing the above script?


Wen-Tung Wang

Hi, Jimmy:
I tried to save a comlpex 2D matrix (an MRI image) in Analyze format using your scripts:
ana = make_ans(myMat,[],[],datatype);
When trying to read the test.img using ImageJ, it gave error message "Data type 32 not supported".
Is it that I didn't use the scripts correctly?
Thank you.

Jimmy Shen

Hi Marta:

How did you create your NIfTI file? Here's an example that is reproducable:


As you can see, the highest value of voxel is never set to 1, and you can open 'mynifti.nii' with any NIfTI compatible tools.

Please feel free to ask any questions.


M Var


The programs are great, but I seem to have a problem creating NIFTI files with this program. The created NIFTI files often are completely blank with only the highest value pixel set to 1. This can be sorted by changing the scale of the inout matrix (i.e. multiplying all the values by 100), but it is hard to determine what the right scaling is for all images when I don't know what the mechanism behind this error is.

Do you have an ideas that may help?

Many thanks,

Jimmy Shen

Hi Prateep:

when you load an image file, e.g.:
nii = load_nii('yourimg.nii')

nii.hdr.dime.pixdim(2:4) will be the width, height, and depth of a voxel.

If you view it with view_nii(nii), click menu "View" and then click "Image Information", the "voxel size" is the width, height, and depth of a voxel.

Since both Analyze & NIfTI image should have the same voxel size for all voxels in an image, the maximum and minimum size should be the same.

The distance in voxel from origin can be obtained by subtract value at "[XYZ] at origin" with value at "[XYZ] at crosshair". For distance in millimeter from origin, since value at "[XYZ] at origin" is [0 0 0], you can just read value at "[XYZ] at crosshair".

Please feel free to ask more questions,


prateep mukherjee

Hi Jimmy,

How can we find the maximum and minimum depth,width and height in a 3d .nii image using your tool , assuming that the image is in RAS orientation ?

Also, using this tool, can we find the distance of a pixel from the origin? Please give some hint in this regard.

The images I am using right now are "avg152T1_RL_nifti.nii" and "avg152T1_LR_nifti.nii" from


Jimmy Shen

Hi Kris:

Thanks for your feedback. I have fixed the problem. Instead if using nii.img=double(nii.img); I only made double the three 2D images that are displayed. If the original type is uint8, I will leave it as is.

Again, thanks for the feedback. I have just uploaded the new programs, and you can see it here next week.


Jimmy Shen

Hi Pieter:

It is because you took the advantage of my default "tolerance", which allows 10% distortion. You can use my "reslice.m" program, and specify the voxel size to exactly what you want.


Pieter Vandemaele

Hi Jimmy,

You can ignore my previous question, I did read the FAQ on you site...
I hope you will have time to update/expand the program, it is very usefull.


Pieter Vandemaele

Hi Jimmy,

I got some problems using the headers with your nice tool.

When I load a 4-D nifti file header with load_nii_hdr and compare it with the header from the .hdr field using load_nii, I get different pixdim values:

nifti_hdr = load_nii_hdr('nifti_file');
nifti_image = load_nii('nifti_file');

nifti_hdr.dime.pixdim is [1 4.5313 4.5313 4.5000 200 1 1 1]
nifti_image.hdr.dime.pixdim is [1 4.5212 4.5312 4.4900 200 1 1 1]

The difference of the pixdim arrays is [0 0.01 0 0.01 0 0 0 0]

Did I found a bug or is there a bug in my head?


Kris Thielemans

Hi Jimmy

there seems to be a problem in view_nii when using data that is (natively?) in single format. When I switch to "interp off" and click in one of the panels to move the cross-hair, the other panels get blank, and I see "Warning: CData must be double or uint8.." in my matlab prompt. I can fix this problem by doing something like:


No other problems so far, so many thanks for the nice software!


Kris Thielemans

Hi Jimmy

I have a question regarding the license. The matlab front-end says this is BSD license, and so does your license.txt. However, a few files (including load_nii.m and save_nii.m) contain the lines

% Part of this file is copied and modified under GNU license from
% MRI_TOOLBOX developed by CNSP in Flinders University, Australia

It seems to me that those files should then by distributed under the GNU license as well. Could you please clarify that? Sorry for the trouble.


Jimmy Shen

Hi Maddy:

Yes, it is easy to do so with my tools. Here’s the steps:

1. Load nii file;
2. Find an unused intensity level. If not available, add another level;
3. Find the index of the circle and circles in successive slices;
4. Mark them with the value that you choose in Step 2;
5. Create a colormap file;
6. View brain with circles;

If you are still having problem to create circles, please upload the 2 nii file to your ftp server. The first nii file should be the original volume, the second one should be the one with initial circle. Please also tell me exactly what slices do you want the circle to be drawn, and what color do you want the circle to be drawn. I will then reply you with the modified nii containing the circles.



Hi Jimmy,

Wonderful piece of work and a very useful one at that! I would be pleased to know if I can use it for my specific case.

A rod-like observation chamber that we have inserted in the skull shows up as a circle in some of the initial slices of MRI. What I want to do is to project the exact outline of the circle onto a few other deeper slices, so that it can be found, where exactly the projection of the chamber lies in the successive slices. Thereby, the region that would be encircled if the rod-like chamber were to be inserted further inside can also be found. Simply put, it is like overlaying a circle of specified diameter and position onto each successive slice.

I tried doing it with the view_nii function with the circle saved in .jpeg/.fig formats, giving the figure handle and the nii, using the description in the help section of the view function. But I had trouble with the figure properties, especially the function ‘set’. I get errors in almost every figure property, starting from ‘menu bar’ at line number 291 in the program. I am a beginner in matlab. I was actually surprised I could use other functions, which is why I say that your file is so user-friendly. I would be happy to know how I can go about doing it…

To sum up, all I want to know is, if there is a way of plotting a circle,( given its radius and position in those co-ordinates), onto successive slices.

Jimmy Shen

Hi Nicole:

Here's the definition of AC Origin:

In order to use 'make_nii.m', you already have a 3D matrix, you can only tell the AC Origin by your eye, instead of any conversion.

Because the data generated by 'make_nii.m' is in RAS orientation, the negative z coordinate is downwards, i.e. z coordinates is from Inferior to Superior.



Hi Jimmy,

I'm sorry to repeat my question, but the entries of AC origin are still not clear to me, mainly because I don't know what is meant by "AC origin".

I now know that voxels are being counted (not the position in mm). Now, is it the origin in question related to the x, y, z offset of the slab of slices in the brain (i.e. the offset when positioning the slices during the scan), or is it the origin within the slab of slices itself? I presume it is the former.

If it is the former, then I'm not sure why it has to be relative to img(1,1,1), as opposed to the overall offset of the slab. I have my offset in mm in the readout, phase encode, and slice directions. Can I just convert these values to numbers of voxels?

Finally, is the z coordinate negative upwards, or negative downwards? (i.e. a more superior slice would have a larger negative z coordinate than a more inferior slice)

As a side note, I'm only using make_nii and save_nii, to then analyze the data in FSL.

Hopefully I've made my confusion clearer this time. Thanks for your help,


Jimmy Shen

Hi Nicole:

First: 'origin' parameter in 'make_nii.m' is in voxel, which is relative to the first voxel of 'img' parameter, i.e. img(1,1,1);

Second: It would be much clearer if I use an example to explain this:

img=125:249; img=reshape(img,[5,5,5]);

Yes, we know AC Origin means [0 0 0] in millimeter. However, you must tell the NIfTI data where is your [0 0 0] millimeter, so other people can also know it when they open your NIfTI data. Therefore, parameter 'origin' can only be expressed in voxel to locate the exact position of your 3D matrix to be the AC Origin.



Hi Jimmy,

Your code has been very useful to me; I've been using make_nii and save_nii. My question is regarding the AC origin for make_nii. First of all, I presume the coordinates should be in mm, like the voxel size. Then, I was wondering if AC origin refers to the position of the central slice. If so, for the 3rd coordinate (referring to axial slices), does negative (e.g. -20) indicate an upward translation (i.e. more superior slice)? This is the convention that I'm used to, but I am not sure it applies to make_nii as well.



Simon Robinson

These are great tools for reading and writing NIfTI - a core part of all my programs and very well supported. Thanks.

Simon Robinson

Marianna Jakab

Please take out the ":" of the link below, that takes you to an invalid page.

Two example datasets are provided under NIfTI web site "avg152T1_LR_nifti.nii" and "avg152T1_RL_nifti.nii".
whereas is a very nice and informative page.

so si

mmei rezk

Stefan Haufe

Assaf RMATHALBazon

After a cursory inspection this seems like a great tool.

Mark Bolding

I use this all of the time. I rocks.

Jimmy Shen


Here are the answers:

1. It is correct that "nii_002.original.hdr.hist.originator" is [256 0 0 0 0], because "t1_icbm_normal_1mm_pn0_rf0" is in Analyze 7.5 format and "001" is in NIfTI format that does not have obvious "originator" field. please let me know if you are still not clear.

2. "nii_01.hdr.dime.xyzt_units" is just an information field. When it is 1, xyz are in "meters"; when it is 2, xyz are in "millimeters"; when it is 3, xyz are in "micrometers"; when it is 0, xyz units are unknown and can only be interpreted by the author. I don't know why this field helped you, and wonder if it is the correct way.

3. It is very strange that you got "[-2 -2 -2 0 0]" for "nii_002.hdr.hist.originator". I need to look at both "t1_icbm_normal_1mm_pn0_rf0.img/hdr" & "001.img/hdr" in order to further answer this question. Would you please upload them to your FTP site and send me the link?

Stella zheng

1. I have manually set the nii_01.hdr.dime.xyzt_units=2;It can be converted by freesurfer now. Thanks!
2. The other problems may be due to the orignal Analyze image is created with Big endian, while this toolbox writes the new Analyze file with little endian. I am not sure about it and how to solve it.

Stella Zheng


2.In nii_002, Originator in nii_002.original.hdr.hist is [256 0 0 0 0], while it is [-2 -2 -2 0 0] in nii_002.hdr.hist.

Stella Zheng

Dear everybody:

I have found the followingproblems in the using this toolbox.
Data: t1_icbm_normal_1mm_pn0_rf0.rawb is downloaded from brainweb,then converted to Analyze format(t1_icbm_normal_1mm_pn0_rf0.img and t1_icbm_normal_1mm_pn0_rf0.hdr )(without *.mat).

Following procedures are applied:

nii_001 = load_nii('t1_icbm_normal_1mm_pn0_rf0', [], 1)
save_nii(nii_001,'001', 1);
nii_002 = load_nii('001', [], 1)

It is expected that the header information should be same, but there is following difference:

1. In nii_001, Originator in nii_001.original.hdr.hist is same as in nii.hdr.hist as [0 0 0 0 0].

2.In nii_002, Originator in nii_001.original.hdr.hist is [256 0 0 0 0], while it is [-2 -2 -2 0 0] in nii_001.hdr.hist.

3. The origin of t1_icbm_normal_1mm_pn0_rf0.img shown in MRIcro is [0 0 0], origin of 001.img shown in MRIcro is [2 2 2]

4. rot_orient=[],flip_orient=[] in nii_001.hdr.hist and nii_002.hdr.hist, but not in their origianl header.

5. when 001.img is converted to *.mgz in FreeSurfer, the error message is as below

mri_convert ./orig/001.img ./orig/001.mgz
reading from ./orig/001.img...
INFO: reading as a two-file NIFTI
nifti1Read(): unknown space units 0 in ./orig/001.hdr

Highly appreciate your help if somebody can help to solve the problem.

Best regards,

SCE,Nanyang Technoligical Univeristy

Stella zheng

The best tool I have used for Analyze image reading and writing. Thanks a lot for your contribution and sharing.

Ning Cao

(Possible) Bug Report:

A good toolbox for loading, saving and viewing Analyze MR images. Thank you for improving it from time to time.

I just want to report a possible bug in 20070426 version.

When viewing a 4D image using view_nii, the "value at crosshair" and "value at cursor" always display the value of the first 3D volume.

view_nii.m L3036, the code 'imgvalue = double(img(sag,cor,axi));' making the imgvalue always the value of the first 3D volume.

abbas kader

A good toolbox for the viewing the Nifti formate file in MATLABe especillay when u did processing in FSL and you wnat to interpretted in MATLAB
Thanks alot

jeff a

best utilities to read dynamic analyze files i have found

r Huang

Hi Jimmy,

Your software is very useful. Many thanks for your great offer.

Could you please indicate (1) how to overlay 2 or 3 other images together, (2) how to choose different threshold?

Thanks in advance


Craig Hamilton

Very useful, well done. How about support for complex datatypes?

Jimmy Shen

How scl_slope affect data_type?

Hi Ged:

Thanks for the URL you sent me. The way Jonas handling "scl_slope" is to convert image data type to "double", which makes sense, although it is not specified on NIFTI documentation (see URL below):

I modified my "xform.m". So it will convert the image data to "double" in the case that "scl_slope" is used. I am updating this file to MATLAB Central File Exchange, and NIFTI_20060307 will appear there soon.

Thanks again for your valuable input,


-----Original Message-----

Hi Jimmy,

Thanks for getting back to me. Unfortunately something else must be wrong in that case, since the image in Matlab has only the values 0 or 1, while the image viewed in FSLview or SPM has a range of values between zero and 1, the image type is uint8.


Jimmy Shen

How to get original information from NIFTI hdr?

Hi Ged:

Thank you very much for your input.

Actually both "scl_slope" and "scl_inter" parameters have been correctly
read and applied to the "img" variable of the output NIFTI structure (see
"xform_nii.m" file): nii.img = scl_slope * double(nii.img) + hdr.dime.scl_inter;

The reason to display "hdr.dime.scl_slope" as zero is a feature of my
package. It signifies that the "img" variable has already been modified. You
can also find that "hdr.hist.qform_code" and "hdr.hist.sform_code" will be
set to zero after proper affine transformation.

The original value of "hdr" can be easily found by: hdr =
load_nii_hdr(filename); You should have correct value (0.003922) there.


-----Original Message-----

Hi Jimmy,

I've found your NiFTI toolbox very useful, but I'm having some
problems with some data stored in uint8 .nii with a scaling factor.
the data appears to load in as a binary image, and the value of
nii.hdr.dime.scl_slope is zero, instead of the correct value
(0.003922) which I can see using e.g. spm5 or avwhd from FSL.

Many thanks for any help you can offer,


Jimmy Shen

Hi Henry:

This is an advanced feature, and it is already included in the toolbox.

Here is the brief guide to use this feature:

1. Use "ana = load_nii(ana.img)" to load your analyze image to "ana" struct, and make sure that variable "ana.img" is either in "single" or "double". If not, use step 2 to convert it.

2. To convert variable "ana.img" to "single", you need to use "make_nii" command: "ana = make_nii(ana.img, ana.hdr.dime.pixdim(2:4), ana.hdr.hist.originator(1:3), 16)".

3. Use "thresh = load_nii(thresh.img)" to load your thresholded image to "thresh" struct, and extract its value and index to "opt" struct: "opt.setvalue.idx = find(thresh.img); opt.setvalue.val = thresh.img(find(thresh.img));". You can see more detail to use "setvalue" by command: "help view_nii".

4. Add other values to "opt" struct: "opt.command = 'init'; opt.useinterp = 0;".

5. Plot thresholded image with underlaid analyzed image by command: "view_nii(ana, opt);".

6. Don't click "interp on/off" menu. It doesn't work properly. If you would like to see the interpolated one, use: "opt.useinterp = 1; view_nii(ana, opt);" instead.

Please let me know if you can plot your thresholded image with underlaid analyzed image.


-----Original Message-----
I have been using the Nifti toolbox for Matlab recently and was wondering whether it is possible to make an overlay of a thresholded image onto the analyzed image. In effect that would mean that all 0 values of the thresholded image should be transparent so that the underlying functional image can be seen.

Thanks a lot for your help in advance and for making such a useful tool available!

Yours sincerely,

Henry Lütcke

Biomedizinische NMR Forschungs GmbH

am Max-Planck Institut für Biophysikalische Chemie

Am Fassberg 11

37077 Göttingen


zhi yang

Jimmy Shen

Hi Anita: Thanks for the feedback. However, I checked but did not find any problem to load or save nii file with non-integer datatype. For example, you can download a typical NIFTI data (zstat1.nii) from: This file is in single (float32) datatype. You can output to nii structure using: nii=load_nii('zstat1.nii'), and output to a new file using: save_nii(nii, 'newfile.nii'). If you still have problem, please email me, and let me take a look at your data.

Anita D

this program works good when i output the nii file as int, but when i output the nii file as unint, the image is distorted.

MATLAB Release Compatibility
Created with R11.1
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!