File Exchange

image thumbnail

DICOM to NIfTI converter, NIfTI tool and viewer

version 2017.03.22 (327 KB) by

NIfTI conversion, visualization and transformation tools



View License

1. dicm2nii.m converts dicom and other into NIfTI;
2. Included dicom tools can read, sort and rename dicom files;
3. nii_tool can read/write almost any kinds of NIfTI files;
4. nii_viewer is for NIfTI visualization and picture output.

Comments and Ratings (93)

Xiangrui Li

Hi Robert,
That was a bug for mixed MAG/PHASE multi-frame dicom with 3 or more volumes. Please update the package from either dicm2nii or nii_viewer GUI. Thanks.

Robert Welsh

Trying to convert a Phillips DICOM file and getting these errors (I've removed the subject name) (using matlab R2015b):

Xiangrui Li's dicm2nii.m 20170211 (feedback to
Validating 9 files ...
Converting 1 series (Philips) into 4-D .nii: subject 'XXXXX'
Reference to non-existent field 'nFrames'.

Error in dicm_hdr>read_sq (line 389)
            if isnan(p.nFrames) || isempty(tag1) % 1st frame has no asked tag

Error in dicm_hdr>read_item (line 356)
    [dat, info, i] = read_sq(b8, i, nEnd, p, tag==1375769136); % isPerFrameSQ?

Error in dicm_hdr (line 265)
    [dat, name, info, i, tg] = read_item(b8, i, p);

Error in dicm2nii>split_philips_phase (line 1980)
        s1 = dicm_hdr(s.Filename, dict, iFrames);

Error in dicm2nii (line 877)
    [nii, niiP] = split_philips_phase(nii, s); % split Philips mag&phase img

Error in dicm2nii>gui_callback (line 1547)
        dicm2nii(src, dst, rstFmt);

Error while evaluating UIControl Callback


Xiangrui Li

Dear Navot,
The "inconsistent slice spacing" complain could be true which means the dicom can not be converted into nifti. It could be false positive caused by numeric inaccuracy of the slice spacing. Is this CT image? From the problem, you can see which series gives this complain, and send me several dicom so I can take a close look.


Navot (view profile)

Dear Xiangrui,

Sorry for continuing to bother you with questions. i run the conversion on a set i have and for a few of the participants i received an error "inconsistent slice spacing". What is causing that issue? how can i fix this?
Thank you!

Xiangrui Li

Something like following should work. You won't specify result nifti names. If needed, you can rename them afterwards.

SUBJ = {'111' '112' '113'};
for i = 1:length(SUBJ)
    dicm2nii (['/home/navotn/EE/Group_data/Subjects/' SUBJ{i}], ['/home/navotn/EE/participants/' SUBJ{i}(1:3)]);


Navot (view profile)

Hi Xiangrui,

Thank you for your answer, i tryed writing up a code to run through all the folders and runs, but all i managed to get it to do is to open your GUI, i think there is a problam with the way call your function, would mind having a look?


SUBJ={I REMOVED PARTICIPANTS NAME FROM HERE TO PROTECT PRIVACY, but there is a list something like '1', '2',.... }

for i = 1:length(SUBJ)
    clearvars -except SUBJ i
    subnum = SUBJ(1:3);
    disp(['started run 1' SUBJ{i}])
    dicm2nii (['/home/navotn/EE/Group_data/Subjects/' SUBJ{i} '/Run1_EE1/Slices/', '/home/navotn/EE/participants/' subnum '/fMRI_EE1', 'nii.gz']);
    disp(['started run 2' SUBJ{i}])
    dicm2nii (['/home/navotn/EE/Group_data/Subjects/' SUBJ{i} '/Run2_EE2/Slices/', '/home/navotn/EE/participants/' subnum '/fMRI_EE2', 'nii.gz']);
    disp(['finished ' SUBJ{i}])

Xiangrui Li

Hi Navot,
The wild card (* or ?) is for file names, not folder names, like
The converter will get files under all sub-folders under the specified folder. Hope this helps. Thanks.


Navot (view profile)

Hi Xiangrui,

Thank you for this great tool.
But i am haveing some difficulties using the wild card. Once i change the path to the dicoms so it would include * the script fails:
Error using dicm2nii (line 414)
home/navotn/EE/Group_data/Subjects/*/Run*/Slices/ does not exist.

What am i doing wrong?

Xiangrui Li

You can create a folder and put the unzipped files into it. Then you either change Matlab Current Directory to the folder, or add the folder to Matlab path by "Set Path" at the Command Window toolbar. Google search may be your friend too.

Please tell me where to copy unzipped files and command in order to run this software?

I am a beginner

Yunhui Zhou

Hi Xiangrui,

What you said is exactly correct! The MRI scan that was flipped in SliceTiming field has head-to-foot direction in the dicom files.

Thanks for your help!

Xiangrui Li

Hi Yunhui,
This excellent question shows how confusing the slice timing can be. The SliceTiming field in dcmHeaders.m, as well as in nifti extension, stores the timing in the order of slices in the corresponding nifti file, which may be opposite to the order in Siemens mosaic image. For example of a typical axial acquisition, the mosaic image can be stored either in foot-to-head direction or the opposite. During nifti conversion, it is more natural to store slices in the order of foot-to-head direction.
For your two cases, I believe the order in mosaic files is opposite. You can verify this by viewing the mosaic files by imshow(dicm_img('mosaicFile.dcm'), []).
In short, one should always use the slice order in the nifti file and ignore the order in dicom file.

Yunhui Zhou

Hi Xiangrui,

Thanks for this great tool! But I have some questions related to the sliceTimging field in dimHeaders.mat generated by dicm2nii.m

So I have two functional MRI scans from a Siemens MRI scanner, and they are all scanned in interleaved mode, but with exactly the opposite order in the "MosaicRefAcqTimes" field of dicom files. However after conversion, in the output file "dcmHeaders.m" I see the same order in SliceTiming field.

After digging into the source code I found that one sliceTiming was flipped in line 996 of dicm2nii.m, but I don't really know why. Can you please explain this to me? If you want more information related to my data files I'm happy to provide. Also I'm using the newest version of this tool.

Thanks for the help!

Allan Alves

Xiangrui Li

Dear atira,
The package can convert compressed and enhanced dicoms into nifti, but it won't export standard dicom for now. It seems most dicom tools can deal with those dicom, so the export of standard dicom is normally not needed. Correct me if I am wrong.

atira bick

Seems like a useful package.
I have compressed dicoms/enhanced dicoms from Philips - would it be possible to export to standard dicom with the toolbox?

Xiangrui Li

Hi Agoston,
It seems it is not easy to take care of the incomplete PAR/REC issue. The major reason, IMO, is due to the unusual order of Philips data, like XYTZ, where T means time or volume. Others all use natural XYZT order, which means the last volume will be in the end. Philips data is exported afterwards, so maybe you can find a way to let the export tool fix this issue? I suppose Philips should take care of this


Hi Xiangrui,
Great toolbox! I am just wondering if there is a way to improve the toolbox to handle incomplete PAR/REC data? Sometimes we have data, where the scanner has been terminated resulting in the last volume including incomplete number of slices. At the moment, the toolbox gives an error for that.

Xiangrui Li

Hi Ellankavi,
It is around line 925 for the current version.
R(1:2,:) = -R(1:2,:); % dicom LPS to nifti RAS


Hi Xiaoxu,

When I looked into the code, I wasn't able to locate the portion of the code that transforms the coordinate systems between DICOM and NIfTI (from LPS to RAS). Could you please let me know which lines do this transformation?


Xiangrui Li

Hi Xiaoxu,
Does the file have image data? If no, that error is expected. If it has image data, could you send me ( at gmail) one of the files which generate the error?

Xiaoxu Lei

Hi Xiangrui,

Very great work! Thank you very much for sharing!

I have encountered a problem that I would like to seek for your help. My purpose of using your toolbox is to load partial dicom information and the images instead of using the time-consuming matlab builtin dicominfo and dicomread functions.

My input data are a series of MRI studies in one folder. The vendor is Philips. When i run my code, there is an error for the dicm_img function, saying "reference to non-existent field 'PixelData'". However, i succeeded to load all the images using 3D slicer. What's more, i found not all dicom files under that folder will cause your dicm_img function to generate this error. I am just confused whether this is indeed caused by the problem inside the input dicom data or something else? Could you please help me with this?

Xiangrui Li

Hi Ellankavi,
I am glad you For the NIfTI conversion, you can find the paper info from dicm2nii GUI menu About -> A paper about conversion.

Thanks for the wonderful toolbox Xiangrui! Can you please let me know how I might be able to cite your toolbox in my paper?

Xiangrui Li

Hi Marius,
If you open the .bvec and .bval files with a text editor, you will see they are text files with 3 and 1 rows respectively. The number of columns is the number of directions. If analysis tool requires other format, e.g. nDirections by 4, or 4 by nDirections, you will need to organize the table accordingly.


Marius (view profile)

Thanks for your helpful tool!
I'm currently experiencing one problem with it, maybe you can help me:
I am trying to convert DTI images in DICOM format into a NIfTI file, which works fine at first without any errors. But when analyzing the newly created NIfTI file in another software (DSI-Studio) it looks like the b-table has been somehow messed up in the conversion process. Do you have any idea on what the problem might be or how to solve this?


xiaoping qu


Lena (view profile)

Xiangrui Li

Hi Xiaoping,
The input can be one or more files, but the simple way is to input a folder which contains convertible files.

xiaoping qu

Hi Xiangrui,
May I know how to convert par rec to nifti using your toolbox?
It seems like the input is just one file but par rec are two.


Xiangrui Li

Hi John,
The current version saves PatientName (it is coded ID for us, so we don't care) into NIfTI. If this is what you like to remove, I can provide an option for this.


John (view profile)

Thanks for the helpful software!

Does your suite of tools implement the Anonymize function in dicm2nii?



Jiri (view profile)

Thank you for your great work! It has saved me a lot of time converting everything to matlab.
I only recently found out it also converts par-rec (Philips) to NIFTI!

I was Googling for so long before I found that this tool can do the par/rec to nifiti as well!

Xiangrui Li

Dear Alina,
It seems you did not download the package completely. After you unzip the downloaded zip file into a folder, you can either add the folder to matlab path (better), or change the current directory as the folder.

You don't need Image Processing Toolbox for dicm2nii to work.


Alina Dinu

Hello. Could you please help me? Imam a tudent, just starting to work with this. I donwloaded the matlab version for students and i tried to run this code. It didn't work. Then I bought Image Processing toolbox. And I still get the following error:
Undefined function or variable 'dicm_dict'.

Error in dicm2nii (line 474)
dict = dicm_dict('SIEMENS', flds); % dicm_hdr will update vendor if needed

Error in S016_makeNiifromDicoms1 (line 5)
dicm2nii(dcmFolderINV2, niiFolder)

My guess is that I have to open the toolbox? Could someone please explain me how can I do this?

Rob Campbell

Rob Campbell (view profile)

Thanks. Useful with lots of comments. Maybe you should put it on GitHub? Then you wouldn't need to put the version notes in the help text and it might have a wider audience.

Xiangrui Li

Dear Bradley Wilkes,
Could you provide more information, such as error message, if any, and the screen output. The default output format is 4D nifti, which mean all volumes from a series are in a single file.

I'm having trouble getting the script to convert multiple volumes from a DTI series. It is only converting the first (b0) volume. Any suggestions? Data is from a SIEMENS scanner, in .IMA format.

Khoi Vo


Yuwen (view profile)

This is really a great tool! Very helpful! Work very fast and easy understand! Thank you so much, Xiangrui!

Xiangrui Li

Dear Qinwan Rabbani,
The output file name adopts the protocol name used on scanner console. In case of the same file names for two series, the series number will be appended to distinguish them. After creating the nii files, you can rename the files if needed.

I really like your program. I was just wondering if there was a way to specify the output file names?

Xiangrui Li

Dear PAT,
Thank you for the feedback. The design is to read bvalue from first slice of each volume, which should extract all bvalue. For the GE data I tested, it gives correct .bval file.
Did you see a .bval file with all zeros? If so, then your suspicion is right. Please let me know. Thanks.


PAT (view profile)

I really like this program! It's clean and nicely written!
However, I think there maybe a bug for bvalue extraction for GE DTI dicom files. If I read correctly, the program reads bval from the first dicom file of the whole volume which is actually b0 acquisition on GE scanner and the dicom tag for this is 0. The applied bvals appears in the later slices when the diffusion gradient is on.


Thank you for this tool. Very well done!


Jens (view profile)

Thx for that code. It's fast and versatile, very helpful.

Peter Bohn

Dear Xiangrui,

thanks for the great tool! I would like to transform some DICOM files but I keep on getting the following error:

Validating 148 files ...
Index exceeds matrix dimensions.

Error in dicm_hdr>read_csa (line 436)
if ~strcmp(char(b(1:4)), 'SV10'), return; end %
no op if not SV10

Error in dicm_hdr (line 268)
    s.CSAImageHeaderInfo =

Error in dicm2nii (line 531)
        s = dicm_hdr(s.Filename); % full header
        for 1st file

Error in dicm2nii_dicm2nii_gui (line 1480)
        dicm2nii(src, dst, rstFmt, mocoOpt);

Error in dicm2nii (line 326)
Error while evaluating UIControl Callback

Validating 148 files ...
Index exceeds matrix dimensions.

Error in dicm_hdr>read_csa (line 436)
if ~strcmp(char(b(1:4)), 'SV10'), return; end %
no op if not SV10

Error in dicm_hdr (line 268)
    s.CSAImageHeaderInfo =

Error in dicm2nii (line 531)
        s = dicm_hdr(s.Filename); % full header
        for 1st file

Error in dicm2nii_dicm2nii_gui (line 1480)
        dicm2nii(src, dst, rstFmt, mocoOpt);

Error in dicm2nii (line 326)
Error while evaluating UIControl Callback

Is something wrong with the data or am I making some mistake?

Thanks a lot for your help!

Best regards


Hyojeong Kim

Dear Xiangrui,

Thank you very much for your response. As you said, I will try again with the original data and let you know if I figure things out :) I really appreciate your help and your brilliant tool. Thank you again.


Xiangrui Li

Hi Raveena,
It seems that you did not download the package correctly. Please download and unzip it again. You can verify the download by opening a .m file in the editor to make sure the code looks right.

Hello Xiangrui,

Thank you for the converter. I downloaded the code and attempted to run it and got the following error.

??? Error: File: dicm2nii.m Line: 400 Column: 7
Expression or statement is incorrect--possibly unbalanced (, {, or [.

I attempted commenting out this portion of the code since it was for unzipping a folder and my folders are not zipped but that only caused me to get this error:

??? Error: File: dicm2nii.m Line: 583 Column: 11
Expression or statement is incorrect--possibly unbalanced (, {, or [.

I cannot see any unbalanced statements so I'm unsure why this is occurring. Thank you for the help.


Xiangrui Li

Hi Hyojeong,
I tried all three files, and they are all mosaic images (768x768). None of them is multiframe dicom. Maybe you uploaded wrong files?
Also I noticed the images are compressed likely by OSIRIX. If you have access to the original data, it is a good idea to try it, and often times, we see problems introduced by third party dicom archiving system.

Hyojeong Kim

Hi Xiangrui,

Thank you very much for your help. I really appreciate it. I put the files on my dropbox linked below:

2 files for image size error
- 1983292.dcm (error occurs in this file in 345 volumes for one run, when converting whole volumes to 4D nifti file. I tried to convert this file only, and in the case, no error occurs)
- 1985099.dcm (in 370 volumes)

1 files for 'zero' using error
- 1984538.dcm

Thank you again :)
- Hyojeong

Xiangrui Li

Hi Hyojeong,
The number of frames the converter got is wrong for sure. Also I did not see Siemens using multiframe dicom. So it is likely that dicm_hdr.m interprets the header incorrectly.
If you can isolate the dicom file which gives this error, and send the file to me, it will be easier for me to figure out the cause. Thanks.

Hyojeong Kim

Thanks Xiangrui Li,

I figured it has different image should be 768 * 768, but some reason, it's 768*768*1*2 (the error occurs for only one file). And this is SIEMENS data.

Now, I have different error.
Error using zeros
Maximum variable size allowed by the program is exceeded.

Error in dicm_img (line 101)
    img = zeros(s.Rows, s.Columns, spp, nFrame, fmt(2:end)); % pre-allocate

Error in dicm2nii (line 734)
            for j = 2:nFile, img(:,:,j) = dicm_img(h{i}{j}, 0); end

Error in dicm2nii>dicm2nii_gui (line 1499)
        dicm2nii(src, dst, rstFmt, mocoOpt);

Error in dicm2nii (line 303)
101 img = zeros(s.Rows, s.Columns, spp, nFrame, fmt(2:end)); % pre-allocate

I debugged it and it says there is an error using 'zeros.'
Error using zeros
Maximum variable size allowed by the program is exceeded.
Then number of nFrame is 864581738.
Since some dicom files still are converted well, I think it could be the problem from data itself.

Hope you can give me some suggestion I can try out. Thank you very much for your support. I really appreciate that.

-- Best, Hyojeong


thanks Xiangrui Li,

i managed to piece together a little script that looks into each echo folder in my data sets.

looking good so far!

thanks again on a very useful tool.

Xiangrui Li

Hi Hyojeong,
That error likely indicates the image size of files within a series are different. Could you check and verify this? A simple way will be to check the file size for the problematic series. The dicom file size within a series should be similar. Is this Philips data?

Xiangrui Li

Hi dysonsphere,
The converter ignores folder structure, and convert all convertible files. This design tries to take care of some Siemens backup scheme where one folder contain 1000 files.
You may try two options to convert two echos into two nii files. First option is to convert two folders separately. This should be easy since you already sorted two echoes, which is not required by the converter. The second option is to choose "SPM 3D" to force 3D output. This option has the problem to force all nii into 3D if you convert multiple series together.

Hyojeong Kim


Thank you very much for the converter!!

During the process, I had an error as below:
Assignment has more non-singleton rhs dimensions than non-singleton subscripts

Error in dicm2nii (line 734)
            for j = 2:nFile, img(:,:,j) = dicm_img(h{i}{j}, 0); end

Error in dicm2nii>dicm2nii_gui (line 1499)
        dicm2nii(src, dst, rstFmt, mocoOpt);

Error in dicm2nii (line 303)
Error while evaluating uicontrol Callback

Can you help me out to solve the error? For your information, I used 64-channel Head coils.

Thank you very much.




thanks for this great tool.

i have a question with regards to converting dicom files in multiple directories.

i have a directory of a sequence that is divided into 2 spin echos, each in a separate directory. when the files are converted both echos are combined into a single nii.

[subject_1] -> [sequence_1] -> [echo_1] [echo_2]
            -> [sequence_2] -> [echo_1] [echo_2]...

running dicm2nii on subject_1 results in a .nii for each sequence instead of for each echo. is there a way to have it split into the separate echos?

Xiangrui Li

If the inconsistent ImageOrientationPatient is for something like localizer, it is expected, and we won't need it anyway. If not, then something went wrong.
Unknown InPlanePhaseEncodingDirection means the converter doesn't understand "OTHER", and won't store phase encoding direction. But the image should be converted into NIfTI.

Thank you very much.

I am not sure how important the warnings are.
For instance:
- Inconsistent 'ImageOrientationPatient' for ...
- Unknown InPlanePhaseEncodingDirection for cor: OTHER

Does it mean that something went wrong? The nifti seems ok when I look (fast) at it.

Xiangrui Li

Dear Carlo,
Thank you for reporting the problem. It is weird to have phase and mag nii unaligned, since they are from the same scan and have the same location parameters. We also use Trio and don't have the problem.

Could you send me the dcmHeaders.mat file under the nii data folder? It contains the dicom header of the first file of each series, and hope I can figure out the problem from that.



Thanks for this very nice tool.
I experienced a problem. I used your tool to create .nii (SPM12) images from Siemens Trio dicoms for a field map sequence. In some subjects I get the phase and the magnitude images not aligned in the z axis. This causes an error in the unwarp procedure in SPM.

The Dicom Import in SPM does not work as well: the magnitude image is slit in two files on larger (more slices) then the other.

Any advice? Thanks!


Xiangrui Li

Hi mary kd,
The converter won't alter the data at all. If you see blurred image, it is likely due to the setting in the viewer.

mary kd

I have tried to convert PAR/REC image to nii by dcm2nii but .nii image is just blurred. Did you guys have the same problem?


gooey (view profile)

I see... that makes sense. Thanks for the quick and helpful reply!

Xiangrui Li

There are some difference between the struct from dicm_hdr and dcmHeaders.mat. The former is simply the information from dicom files, like those from Matlab's dicominfo, but it labels those private tags. During the conversion by dicm2nii, some extra information is extracted from dicom header, and saved in the MAT file. Note that some of the extra information, like UnwarpDirection and SliceTiming, are related to the generated NIfTI files. In other words, if the NIfTI data is saved differently, those parameters can be different.

Due to this reason, it makes more sense to save those information into NIfTI files, rather than a MAT file, to reduce confusion. That was the idea to use NIfTI extension. But ecode of 40 could cause problem for some FSL builds to read the NIfTI image correctly, as mentioned in my previous post.


gooey (view profile)

Many thanks for these useful tools. A quick suggestion: I noticed that the struct returned by dicm_hdr does not have some of the useful fields (e.g., EffectiveEPIEchoSpacing, UnwarpDirection) found in the struct returned by dicm2nii (and saved in dcmHeaders.mat). It'd be great to be able to extract this info from a dcm without having to convert it to nii. In any case, thanks again!

Xiangrui Li

Dear dicm2nii users,
I would like to have your attention that the NIfTI files from dicm2nii may have problem with some versions of FSL.
Cause: dicm2nii may save extra info in NIfTI extension with ecode=40. Some builds of FSL (even with the same version e.g. 5.08) cannot read vox_offset with ecode>30 correctly, while some can.
You are suggested to re-convert NIfTI files if
1. You did the conversion on a computer with FSL versions other 5.06/5.07 installed,
2. You downloaded dicm2nii between 20141229 and 20150423, and
3. You may analyze the data under FSL.
A simple way is to check one of the NIfTI files like following:
ext = nii_tool('ext', 'myNiiFile.nii.gz')
If the returned ext is not empty, you'd better re-convert, unless you are sure you won't use the data in FSL.
For this reason, we will not include ecode=40 extension for a long time until FSL fixes this issue.
Sorry for the inconvenience.

Xiangrui Li

Then your files are likely in big-endian. dicm_hdr doesn't support big-endian file. It seems most machines are using little-endian nowadays. Do you know your data is saved in big-endian? You may send me one of the dicom files if that is fine. If it turns out big-endian is still in use, I can support it, with a little speed loss for dicom file parsing.

Don Catanzaro

Thanks Xiangrui! By the way, the command line throws error 'Likely big-endian file (not supported)'

Is this a similar problem?

Xiangrui Li

Dear Don,
Thank you for reporting the issue. It is because new version of Matlab refuses uint32 figure handle. The command line should work though. I will do a quick fix and update it today.

Don Catanzaro

Starting the GUI throws error.

>> dicm2nii;
Error using figure
Invalid convenience arg handle

Error in dicm2nii>create_gui (line 1603)
fh = figure(typecast(uint8('dicm'), 'uint32')); % arbitury integer

Error in dicm2nii (line 313)
    create_gui; % show GUI if input is not enough


kammcm (view profile)

Many thanks, for some reason it hadn't unzipped into the folder, that solved it.

Xiangrui Li

Dear kammcm,
It seems at least dicm_dict.m is missing. Maybe you moved files to a new folder? Please try to download the package, and unzip files into the folder where dicm2nii.m resides. You can get the folder by
which dicm2nii



kammcm (view profile)

I tried to use your program today but I am getting this error:

Undefined function 'dicm_dict' for input arguments of type 'cell'.

Error in dicm2nii (line 393)
dict = dicm_dict('SIEMENS', flds); % get partial dict

I give a folder as the first and second argument. The first one contains 110 images in a dicom series.

Can you please advise what could be the problem?
Many thanks.


gooey (view profile)


Naho (view profile)

This was really helpful. Thank you so much!!! :)

Xiangrui Li

Dear Macro,
Thank you for the error report, and for sending me the file for diagnose.

The problem is caused by some 3rd party dicom converter, which loses the VR info for vendor-specific tags (private tags) during the conversion. Without correct VR, these tags are not correctly interpreted by dicm2nii.

I guess the problem reported by JuanesA89 is likely the same cause.

We now know that GDCM and converters, at least some versions of these converters, may cause this problem.

So the suggested solution is to use original dicom data from scanner without other conversion.


Marco Rotonda

Hi Xiangrui,
I'm trying to load some dicom files with dicm2nii.
With general gui I have this error (I'm copying all the command window):

Xiangrui Li's dicm2nii (feedback to
Validating 20 files (GE) ...
Converting 1 series into .nii.gz: subject R A
Cor_T2_FRFSE 20

In an assignment A(I) = B, the number of elements in B and I must be the same.

Error in dicm2nii (line 625)
        for j = 1:dim(3), t(j) = tryGetField(h{i}{j}, flds{ind}, nan); end

Error in dicm2nii>dicm2nii_gui (line 1688)
            dicm2nii(src, dst, rstFmt, mocoOpt, subjName);

Error in dicm2nii (line 224)
    dicm2nii_gui(dataFolder); % mis-use first two input for GUI

Error while evaluating uicontrol Callback

This is what I have if I give a more specific instruction:
dicm2nii('/Users/blond/Documents/NIC/AR/SER006', '/Users/blond/Documents/NIC/AR/SER006/corrected',1,1);
Xiangrui Li's dicm2nii (feedback to
Validating 24 files (GE) ...
Converting 1 series into .nii.gz: subject R A
 Cor_T2_FRFSE 20
625 for j = 1:dim(3), t(j) = tryGetField(h{i}{j}, flds{ind}, nan); end

In an assignment A(I) = B, the number of elements in B and I must be the same.

Error in dicm2nii (line 625)
        for j = 1:dim(3), t(j) = tryGetField(h{i}{j}, flds{ind}, nan); end

Any idea?

Thanks in advance.



the dicm2nii tool is very useful...
thanks Dr Xiangrui Li.

Xiangrui Li

Hi Paul,
Thank you for the comments and suggestions.

Now the missing file check is not as strict as before. For Philips data, this check is skipped due to the possible sparse instance numbering. For other vendors, missing files at beginning is allowed now.

The bug in save_dti_para is fixed.

The converter can deal with dicom files without meta info now.



Paul Groot

Hi Xiangrui,

Nice work! I just converted a bunch of PAR/RECs and a single DICOM series containing Philips DTI data. All PAR/RECs seem to be OK, so that's really nice. However, I had to change a few lines to get it working for the DICOM files.

One issue has to do with the instance numbering of the DICOMs. Our DTI series have sparse instance numbering. So, instead of skipping the series at the line where it prints a line about a missing instance file, I inserted the following:

H = h{i}; % cell array containing empty elements
h{i} = H(~ind); % only keep the non-empty ones

The second thing I had to modify, was the Manufacturer test in function save_dti_para. It seems that structure s initially contains a rather complete DICOM header, but when the for-loops continues, the structure is replaced by a reduced DICOM header that doesn't contain the Manufacturer string anymore. The solution is to store the manufacturer string in a separate variable, or to keep a separate copy of the initial structure s.

I also noticed that the DICOM reading part is very strict when it comes to PART10 compatibility. If the meta header is missing, it will report an unsupported file format. Strictly speaking, this is true, but a lot of (older) applications don't store the meta header at all.

Thanks for making these scripts available.

Xiangrui Li

Hi JuanesA89,
The error means number of slices extracted by the code is not a single number, which is odd. If you don't mind, you can send me one of your dicom files, or dicom header of a file returned by hdr = dicm_hdr(dicmFileName).



Hi Xiangrui,
I used your code for converting a dicom file to a nii. And I get this error:

"Operands to the || and && operators
must be convertible to logical
scalar values.

Error in dicm2nii (line 493)
        if ~isempty(nSL) && nSL>1

Error in dicm2nii>dicm2nii_gui
(line 1469)
            dicm2nii(src, dst,
            rstFmt, mocoOpt,

Error in dicm2nii (line 168)
    dicm2nii_gui(dataFolder); %
    mis-use first two input for GUI
Error while evaluating uicontrol Callback"

Can you help me? Thanks

Xiangrui Li

Hi Qingyan,
I just did an update last night, and it may be available sometime today. I believe it should get bval/bvec from your PAR file. If no, please let me know.


I used your code to convert a DTI par file. I don't have any error, but it didn't give me the bval/bvec file either.
I have par v4.2 file.
Any suggestion?


I think it's a v4.2 Par file.


Xiangrui Li

Hi O.A,
Thank you for the feedback. I realize it is because fullfile in older Matlab doesn't support cellstr input. Now I use strcat to fix the issue. Please wait for the next update to be available.

Also I tested only V4 of PAR file. In case of PAR file parsing problem, please send me a PAR file if yours is not V4.



I would like to use your converter to convert rec/par files to nifti but when I use dicm2nii GUI, it says this :

Undefined function 'eq' for input arguments of type 'cell'.

Error in fullfile (line 37)
      if (f(end)==fs) && (part(1)==fs),

Error in dicm2nii>dicm2nii_gui (line 1311)
            src = fullfile(folder, src);

Error in dicm2nii (line 146)
    dicm2nii_gui(dataFolder); % mis-use first two input for GUI
Error while evaluating uicontrol Callback

Any advice ?



Xiangrui Li

The test on GE/Philips data was based limited dataset. Please report problem to author if there is any problem.



1. dicm2nii: better precision requirement for ImagePositionPatient;
2. dicm2nii: bug fix for mixed MAG/PHASE multi-frame dicom with >2 volumes.


1. nii_viewer: Can open DICOM etc files by converting into NIfTI without saving, allowing to view image from one or more files without converting.
2. dicm2nii: can convert FreeSurfer mgh/mgz files into NIfTI.
3. other fixes and improvement.


anonymize_dicm: replace PatientName with ID rather than scratching it.


1. nii_moco: new implementation to perform motion correction;
2. anonymize_dicm: new implementation to remove Patient Name in dicom files;
3. dicm2nii: transform CT image with gantry tilt;
4. other minor improvement and fix.


1. dicm2nii: fix for irregular image order in Philips multi-frame dicom;
2. dicm_hdr: avoid error due to missing value for a tag;
3. other minor improvements.


1. nii_viewer: allow to manually remove excessive neck tissue;
2. nii_viewer: better overlay treatment for Analyze files;
3. nii_tool: fast hdr/ext read for gz file by memory gunzip;
4. minor improvement here and there.


1. nii_viewer: implement warped overlay;
2. nii_viewer: implement “Save volume as”;
3. dicm_hdr: fix problem for some Philips PAR file;
4. Other minor fixes.


dicm2nii: fix bug introduced by update hours ago (slope/intercept wrongly applied to files expect 1st).


1. dicm2nii: Add preferences to GUI
2. dicm2nii: Convert series with inconsistent Rescale slope or intercept
3. other minor fixes and improvement


1. dicm2nii: add pref to allow to not use SeriesInstanceUID;
2. nii_viewer: option to load single volume for large dataset;
3. dicm_hdr: can read dicom without PixelData;
4. other minor fixes and improvement.


nii_viewer: file list GUI improvement; implement histogram plot and sphere ROI creation.
Other minor fix and improvement.


nii_viewer: add 'RGB' LUT so 3-volume image can be in RGB;
dicm2nii: avoid skipping series due to empty-PixedlData junk dicom;
               allow setpref to not save PatientName and not use parfor;
Other minor fixes.


dicm2nii: always save ReadoutSeconds for topup;
nii_viewer: implement image center of gravity display;
Other minor fixes and improvements.


nii_stc: new file for nifti slice timing correction.
dicm_img: try to support files with BitsStored~=HighBit+1.
dicm2nii & nii_viewer: minor fixes.


dicm2nii: big fix for error due to missing file(s).


 1. GE bvec sign correction for sag/cor acquisition;
 2. Avoid error due to missing info in Siemens B15 CSASeriesHeaderInfo.
 Bug fix for zoom in/out by key press.


nii_viewer: Update phase LUTs to three; Add "Open in new window"


Corrected version number


dicm2nii: better mosaic detection for old/bad data; Convert MoCo series by default.
nii_viewer: added two LUT for complex data: useful for retinotopy.
dicm_hdr: performance tweaks: almost 100% improvement.
Many minor fixes and improvements.


1. dicm2nii: Fix Siemens mosaic detection for rare cases.
2. nii_viewer: Allow background image to move in stack;
    Remove some restriction for DTI vector lines.
3. Some minor fixes.


1. nii_viewer: bug fix for messed-up callback in set_file;
2. some minor improvement.


1. dicm2nii: support big endian dicom files;
2. other minor fixes.


check update: fix the problem to download into current directory.


1. nii_viewer: implement time course plot;
2. nii_viewer: fix hanging problem for some Matlab versions due to invisible figure;
3. dicm_img: bug fix for not casting bytes into double.


1. Implement update check from dicm2nii and nii_viewer GUI;
2. Use matlab pref method for dicm2nii, nii_tool and nii_viewer;
3. dicm2nii: fix for files missing SeriesInstanceUID;
4. nii_viewer: some improvement and bug fix. Faster display


Fixes and improvements for dicm2nii, nii_tool, and mostly for nii_viewer:
1. Friendly file list GUI;
2. add overlay by Ctrl drag&drop;
3. modulated image display;
4. ROI label display, such as AAL;
5. more LUT options, including custom LUT.


nii_viewer: bug fix introduced in previous update (reorient problem)


1. avoid error for white background under Linux;
2. bug fix for alpha and case of unmatched s/qform.


nii_viewer fix and improvement:
1. bug fix for nii with sform=0;
2. Add "Show NIfTI essentials";
3. better effect for white backgroun.


1. dicm2nii: GUI supports drag and drop of folder/files; optionally save JSON file;
2. nii_tool: partial gz unzip makes hdr only read much faster;
3. nii_viewer: Key navigation and zoom implemented; allow L/R flip, white background and more.


Bug fix for Show NIfTI hdr/ext


1. Implement nii_viewer.m for nii visualization;
2. Add file nii_xform to resample/transform nii image;
3. Some minor improvement for dicm2nii, nii_tool etc;
4. Include dndcontrol by Maarten van der Seijs.


1. Take care irregular slice ordering for PAR/REC and multiframe dicom;
2. Bug fix for case of nSlices = 1;
3. Other minor fixes.


1. nii_tool: auto detects RGB style for image reading;
2. try to fix slice timing for some multiband data;
3. some other minor fixes.


Major: Store text NIfTI extension for information, like DTI bval/bvec, slice timing, unwarp parameters etc
Minor: more missing files check and some minor fixes and improvements


Do not store ecode=40 NIfTI extension due to possible problem with FSL


Fix problems with latest Matlab versions: uint32 figure handle and parpool.


1. Can convert BrainVoyager files into NIfTI;
2. Bug fix for phaseDir for Philips data;
3. nii_tool allows to set default NIfTI version and RGB style;
4. Other minor fix and improvement.


1. Works multi subject/study data;
2. Won't skip derived data, such as those from GLM/DTI;
3. Transformation takes care of possible shear at slice direction;
4. Many minor improvement.


1. Bug fix for phase encoding direction;
2. Improved DTI bvec sign treatment;
3. Many minor fixes and improvements.


1. dicm2nii can save SPM style NIfTI;
2. nii_tool can convert between 3D and 4D NIfTI;
3. many other fixes and improvements.


1. Include new file nii_tool.m, which can read/write almost any datatype of NIfTI files with different versions;
2. dicm_img returns the same as dicomread by default (transposed img);
3. Include pigz for Windows and Linux for fast gz (de)compression.


1. Fix error for multiframe dicom with single frame;
2. Make number of slices detection more reliable;
3. Other minor improvements.


1. Use ImagePositionPatient to derive SliceThickness if possible;
2. Override number of slices in dicom header with unique ImagePositionPatient;
3. Add RescaleIntercept and RescaleSlope consistency check.


See previous update


1. Use parallel tool if available and worthy;
2. First tested version for Octave 3.8.1(GUI not working);
3. Some minor fixes.


1. bug fix for missing number of slices in GE multiframe dicom;
2. sort_dicm takes care of multiple StudyID;
3. minor improvements on dicm2nii, dicm_hdr and dicm_dict.


Optional output argument for sort_dicm


1. Include new file sort_dicm, which sorts files for different subjects into sub-folders;
2. Remember the GUI setting from last conversion;
3. Other minor improvements.


Take care of different carriage return issue in Philips PAR file


1. Take care of missing VR by some 3rd party dicom converter;
2. some minor improvements.


1. Fix the problem caused by PAR 4.2 keyword case change;
2. Ignore PAR file extension case.


1. can deal with compressed tgz, tar file
2. some minor fixes


1. Take care of non-unique ixyz;
2. Bug fix for slice_code for interleaved descending;
3. Bug fix for GE interleaved file order;
4. Store readout for DTI.


1. Image storage change to make DTI data work for FSL 5.05 and later
2. Change phase direction in image space for FSL
3. Use ProtocolName for Siemens data
4. GE data: can get phase direction for later version; take care of interleaved numbering


1. Fix to work for new GE data, including DTI;
2. Improved multi-subject data conversion;
3. Better file name for GE/Philips data;
4. Many minor fix and improvement.


Not set cal_min and cal_max anymore, so avoid display range problem.


1. Store FSL slice timing in dcmHeaders.mat;
2. Implement slice timing for multiband dicom;
3. Bug fix for slice order for some GE data;
4. Other minor improvements;


1. bug fix for MoCo series detection;
2. bug fix in rename_dicm: missing Manufacturer


1. Support dicom without meta info;
2. Bug fix for gzip.m detection;
3. Fix problem with ~ as home folder;
4. Improvement for error info file.


1. skip missing file check;
2. Allow missing files at the beginning of a series.
1. Bug fix for DTI parameter parsing;
2. Also save error info into a file;
3. Other minor improvements.


1. Bug fix and improvement for DTI parameters.
2. Deal Philip multi-frame B0 map correctly.
3. Great speed improvement for multi-frame dicom.


1. Implement conversion for AFNI HEAD/BRIK files.
2. Bug fixes for dealing with current folder as src folder etc.


1. Minor improvement for dicm_hdr: read V4.1 PAR file correctly;
2. Make some MRI parameter non-mandatory, so may work for other modality.


1. Support implicit VR dicom;
2. Make dicm_hdr, dicm_img and dicm_dict available to users by extracting them from dicm2nii. Add rename_dicm.
3. Improve dicm_hdr


1. First working version for Philips multiframe dicom
2. Some tweaks to dicm_hdr
3. Minor bug fixes


1. Works for Siemens non-mosaic DTI data too.
2. Make xform matrix robust, aiming to work for Philips single dicom file (no data for test though).
3. dicm_hdr can decode SQ now.
4. Avoid fullfile, since it doesn't accept cellstr in older Matlab.


Major: first implementation for conversion of GE and Philips data.
Minor: remove dependency on normc, etc.


Bug fix for DTI bval/bvec files introduced in last update


1. Try and suggest to use pigz for gz compression
2. Fix the missing-field error for DTI data with more that one excitations.
3. Protect GUI from command line plotting.


A bug fix for '*' input, and some minor improvement for dicom header reading


Some SPM users may not have Imaging Processing Toolbox. This update removed this dependency. This also speeds up the dicom header parsing.


1. File name is changed from dcm2nii.m to dicm2nii.m. This will avoid confusion with MRICron's dcm2nii converter.
2. GUI is implemented.
3. Bug fix for cellstr input for multiple files.


1. Allow to specify a subjectID for nii;
2. Accept more input source options, like 1 or more dicom files, or wildcard like run1*.dcm;
3. Include related NIfTI toolbox code in the m file for easy distribution.


Some minor improvement for the code. Add a line for usage.

MATLAB Release
MATLAB 8.6 (R2015b)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video