File Exchange

image thumbnail


version 2018.08.08 (1.83 MB) by Xiangrui Li
NIfTI conversion, visualization and transformation tools


Updated 17 Jul 2020

GitHub view license on GitHub

DICOM to NIfTI conversion, NIfTI tools

Cite As

Xiangrui Li (2020). xiangruili/dicm2nii (, GitHub. Retrieved .

Comments and Ratings (203)

Xiangrui Li

dicm2nii will convert par/rec files into nifti, just it does for dicom.


Is there still available the function which converts par to nifti? anyone willing to help?
thank you

Xiangrui Li

Hi Nam Le,
The error message indicates the dicom file has no ImagePositionPatient or ImageOrientationPatient.
From the file name (likely dots are replace by underscore), it seems it is CBF data which may have different dicom parameters from common MRI data.
If you don't mind, you may share some dicom files, so we can look into the issue.

Nam Le

Hi Xiangrui,

When converting dicom to nii, I had this problem with a specific folder

No orientation/location information found for x1_2_840_113704_7_1_0_244225253169723_1595947046_2_p02_CBF

What does it mean and how can I fix it

Xiangrui Li

Hi Erin Kim,
If the dicom source contains both original and MoCo series, the MoCo series will have "_MoCo" appended to the nii name. For example, if the SeriesDescription is "run1", the original nifti will be run1.nii (or with .gz), while the motion-corrected series will be run1_MoCo.nii.

Erin Kim

Hi Xiangrui,
Thanks for the powerful tool. I've noticed that two functional .nii files are being exported.
One that says "ep2d_bold_moco_resting.nii" and the other "MoCoSeries_MoCo.nii". I've been using ep2d_moco over the MoCoSeries.
Wondering what the difference is? Tried reading the documentation, but seems like I'm still lost.

Xiangrui Li

Hi Xingwang,
It sounds you are dealing with some special or new scanning sequence. The current converter supposes all images in a series have the same TR, or TR is not of interest.
For multiple TEs, the converter should sort the TEs corresponding to the volumes in the nii file, so you should have correspondence for TE.
The result nii file name adopts the series description. In case of name conflict, it will append series number to the name, such as mySeries_s005.nii. If you choose to save 3D files, volume number will be appended to file name. Then the volume number may not be corresponding to the dicom files, but corresponding to the TEs in json and dcmHeaders.mat files.
If you don't mind, you may share a dicom series of images which you think we need to treat in a special way for your purpose. Thanks.

Hi Xiangrui,
Thanks for your reply. It does make sense to save one json file per volume in my application. I acquired several images with different TR and TE to do T1 and T2 mapping. If only one json file is generated, it is impossible to retrieve TR and TE for every image. Although I noticed that the TEs will be saved into json file, the correspondance between image and TE is lost.
By the way, I found that sometimes name of converted nii file and name of original dicom file does not correspond to each other, e.g. IM_0001, IM_0002, IM_0003, IM_0004 will become xxx_0003.nii, xxx_0004.nii, xxx_0001.nii, xxx_0002.nii. It seems that name of the nii file is given accoding to TR and TE, when the images have the same TR and TE, dicom and nii file names correspond to each other.

Xiangrui Li

Hi Xingwang Yong,
Thank you for the comment. The change log is not accurate. It should be one json file per series, event if you choose 3D output. On the other hand, it won't make much sense to save one file per volume, since that will repeat the same thing many times.

Hi Xiangrui,
Thanks for this great tool. I have a problem about the json file. You mentioned in the comment of dicm2nii.m, "% 180530 .... json for each file (thx ChrisR)." . I expect that I would get 1 json file for each dicom file. However, when I select the "Save json file" on GUI, I can only get 1 json file for each series. Did I misunderstand the usage or it is a bug?

Xiangrui Li

Thank you for pointing out the problem, @James Ford.
I just fixed it by simply using the Matlab String rather than datetime().
Please update it from either dicm2nii or nii_viewer GUI.

James Ford

This is a great package. I ran into an error with datetime() and needed to add a little patch around line 621 (my AcquisitionDate includes time and I was falling into the Octave code and erroring out there...).

if length(acq{1}) == 14
AcquisitionDate = datetime(acq{1},'InputFormat','yyyyMMddHHmmSS');
AcquisitionDate.Format = 'yyyy-MM-dd';
AcquisitionDate = datetime(acq{1},'InputFormat','yyyyMMdd');
AcquisitionDate.Format = 'yyyy-MM-dd';

Xiangrui Li

I copied your message to Github(, so all authors can attend to it. You can following there and provide more information, like the scanner manufacturer etc.


Dear Xiangrui,
I used dicm2nii and related functions outside gui to convert dicom files for 1 anatomical series to bids for subject x, all goes well, but I invariably get:
Warning: Could not save sub-subjx_sessions.tsv
Warning: Could not save participants.tsv

what is to be done? How can I use dcm2nii so that all output (json, tsv) is saved? (Only the nii.gz file is saved, no warning re json, but no json file saved either)
Thank you,

Xiangrui Li

Hi Roger Mullins,
There is no option for that. But since the Matlab code is open to users, you can easily disable it by commenting out the if-block for MRScaleSlope in sub function set_nii_hdr in dicom2nii.m.

When I convert Phillips .PAR/REC files with this my images suffer the same scaling problem (see PMC3998685) that affects dcm2niix. Is or will there be an option to turn this off (similar to dcm2niix's -p n option) ?

Xiangrui Li

Hi Clara Raithel,
The design is to convert into one nifti file for one dicom SERIES, unless user chooses to save one file per volume (spm format). If you are sure the files are from 9 runs, it sounds like the dicom SeriesInstanceUID is messed up by some third party dicom tool. If this is true, you can fix it by unchecking the "Use SeriesInstanceUID if exists" at the dicm2nii GUI.
If this does not fix the problem, you may share with me ( at the files at box or google drive, so I can dig into the cause. Thanks.

Hi Xiangrui,

I just tried to converts some DICOM files into compressed nifti files (BIDS format), but unfortunately my 9 fMRI BOLD runs are merged into a single file. I am not sure if I am doing something utterly wrong - any help would be highly appreciated. Many thanks!

Hi Xiangrui,

I am trying to convert some files, but I am getting this error message:

Cell contents reference from a non-cell array object.

Error in dicm_hdr>read_ProtocolDataBlock (line 612)
ch = struct(ch{:});

Error in dicm_hdr (line 319)
s.ProtocolDataBlock = read_ProtocolDataBlock(s.ProtocolDataBlock);

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

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

Error while evaluating UIControl Callback

Do you have any idea on how I can fix it?
Thank you

Xiangrui Li

Hi Jianzhang Li,
I believe the dataset you are talking about is structural data with sagittal acquisition. The converter re-orients the nii into xyz order in this case, and stores the original slice dim information in the nii header.
This won't cause any problem, but bring some benefit to early version of FSLview. So in my opinion, you don't need to worry for this at all.

Hi Xiangrui,
Thanks for this powerfull tool! A problem relating to dimentions showed up when I finished the converting.
I use a software called "ITK-SNAP" to check the DICOM and NII file. When I for example open 100 pieces of DICOM files(with 520x520 Pixels) for a knee joint, the dimension info in ITK-SNAP is: X=520; Y=520; Z=100. But if I convert those DICOM into NII file and open the NII in ITK-SNAP, the dimention info is changed to: X=100; Y=520; Z=520.
Do you know how to deal with this?

Xiangrui Li

Hi Jacob Levman,
Could you provide the full error message? It also helps if you can send me ( at a dicom file which gives the error. Thanks.

I keep getting the error of the cell array input must be a cell array of characters why is this

Xiangrui Li

Hi John,
Thank you for reporting the problem. The bug was introduced when I tried to take care of compatibility to matlab 2013a or earlier. I just fixed it at GitHub. Please "Check update" from dicm2nii GUI or nii_viewer GUI.

John Madsen

Hi Xiangrui,

I am trying to convert DCE MRI dicom images into a nifti file. When running your code, I am receiving the following error:
??? Error using ==> flipdim at 21
Requires two arguments.

Error in ==> dicm2nii>flip at 3066
y = flipdim(varargin); %#ok

Error in ==> dicm2nii>set_nii_hdr at 1323
for k = 1:3, if flp(k), nii.img = flip(nii.img, k); end; end

Error in ==> dicm2nii at 1099
[nii, h{i}] = set_nii_hdr(nii, h{i}, pf); % set most nii hdr
Any help would be appreciated.

Xiangrui Li

Hi Aravinthan Varatharaj,
That sounds like a problem that the data type in dicom is not determined correctly. It would be helpful to verify if you can share a dicom file showing this problem. You could send it to at

Thanks for the great code. I sometimes have a problem with rescaling where the maximum voxel value becomes 255 and the image is flattened, have you seen this before?

Xiangrui Li

Hi Yi,
The `if` block around line 1300 in dicm2nii.m performs the re-orient. I have not tested it, but I believe you can simply commend out that if-end block.

Yi Zhang

Hi Xiangrui,

Is there an easy way to avoid this conversion by modifying your source code (maybe a couple of lines)? I could not figure out which part to change. Can you please give me some clues?

Thanks a lot,

Xiangrui Li

Hi Yi,
Yes, the converter re-orient sag/cor slices into tra orientation, except for functional data. This is not necessary in term of nifti standard, but it makes the nii files work better for some tools, like old FSLview. As far as I know, there is no any concern with tra orientation for T1w nii, so I did not bother to provide the option to keep original orientation. The reason to keep functional nii in original orientation is that some analysis tools assumes the 3rd dimension is for slices, so it will work well for slice timing correction.
If you like to know the original orientation, it is stored in nii.hdr.dim_info. You can also get the decoded dim_info from nii_view -> Window -> Show NIfTI essentials.

Yi Zhang

Hi Xiangrui,

It's a fantastic tool! I have been using it for a while. Today, I converted Siemens 3D T1w images into the nifiti format. However, the images were transformed from a sagittal orientation into a transverse orientation, which is not desirable. I wonder whether you force such a kind of reorientation in your code.

Thanks a lot,

Dan Evans

Xiangrui Li

Hi Dennis,
The default is to save one series into one 4D nii file. I guess you selected "SPM 3D" checkbox. You can deselect it once, and the preference will be remembered for future use.

Hi Xiangrui,
After conversion, I got nii files for each image. Is that possible to convert into one nii file?
Thank you.

Xiangrui Li

Hi Aaron, I think last commit at github fixed the problem. Let me know otherwise. Thanks. -Xiangrui

Hi Xiangrui, I've encountered a bug when trying to load some enhanced dicom philips data (using 20181102) :

Error using *
Integers can only be combined with integers of the same class, or scalar doubles.

Error in dicm2nii>set_nii_hdr (line 1237)
nii.img = nii.img * slope + inter; % apply to img if no rounding

Error in dicm2nii (line 879)
[nii, h{i}] = set_nii_hdr(nii, h{i}, pf); % set most nii hdr

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

I've set a break point at line 1237 in dicm2nii.m, here nii.img is int16, slope and inter are both floats (slope = 1, inter = 0), which is why it complains. That line is in the following condition:

if isa(nii.img, 'float') || (mod(slope,1)==0 && mod(inter,1)==0 ...
&& val(1)>=intmin(dClass) && val(2)<=intmax(dClass))
nii.img = nii.img * slope + inter; % apply to img if no rounding

perhaps the best thing to do here is to cast slope and inter to the same class as nii.img. Given that there are checks they the values are integers anyway this shouldn't lead to a loss in precision?


Thanks Xiangrui that's great! I will see if my wrap around MATLAB code ends up clean enough to share! ha! I'm a relative noob so...

Thanks for replying so quickly too!

Xiangrui Li

Hi Megan,
Currently dicm2nii.m can optionally save json files for BIDS, but it does not take care of the folder structure or file names for BIDS. If you like, you can contribute at .Thanks.

Hi Xiangrui, this is great. Do you perchance use BIDS? I'm hunting for a Matlab script that would use your dicm2nii and then build a BIDS directory tree for the output, a Matlab version of Heudiconv but I'm not keen having to adopt python and bash and would like to continue with Matlab.


Xiangrui Li

Hello Abdel Benm,
You could use the dcmHeaders.mat saved with NIfTI to create json files. Here is the code for this purpose.

myDir = '/data/'; % data folder where dcmHeaders.mat will be found
dirs = genpath(myDir); % get all folder and sub-folders
dirs = strsplit(dirs, ';');

flds = { % possible fields to store to json from dcmHeaders.mat, copied from dicm2nii.m
'ConversionSoftware' 'SeriesNumber' 'SeriesDescription' 'ImageType' 'Modality' ...
'AcquisitionDateTime' 'bval' 'bvec' 'VolumeTiming' ...
'ReadoutSeconds' 'DelayTimeInTR' 'SliceTiming' 'RepetitionTime' ...
'UnwarpDirection' 'EffectiveEPIEchoSpacing' 'EchoTime' 'deltaTE' 'EchoTimes' ...
'SecondEchoTime' 'InversionTime' 'CardiacTriggerDelayTimes' ...
'PatientName' 'PatientSex' 'PatientAge' 'PatientSize' 'PatientWeight' ...
'PatientPosition' 'SliceThickness' 'FlipAngle' 'RBMoCoTrans' 'RBMoCoRot' ...
'Manufacturer' 'SoftwareVersion' 'MRAcquisitionType' ...
'InstitutionName' 'InstitutionAddress' 'DeviceSerialNumber' ...
'ScanningSequence' 'SequenceVariant' 'ScanOptions' 'SequenceName' ...
'TableHeight' 'DistanceSourceToPatient' 'DistanceSourceToDetector'};
save_json = dicm2nii('', 'save_json', 'func_handle'); % function handle from dicm2nii.m

for i = 1:numel(dirs)
dcmHdr = [dirs{i} '/dcmHeaders.mat']; % possible dcm header file
if ~exist(dcmHdr, 'file'), continue, end % skip if not exist
load(dcmHdr); % variable is 'h'
runs = fieldnames(h);
for j = 1:numel(runs) % loop through each run
s = h.(runs{j});
s0 = struct;
for m = 1:numel(flds) % copy needed flds from s to s0
if isfield(s, flds{m}), s0.(flds{m}) = s.(flds{m}); end
save_json(s0, [dirs{i} '/' s.NiftiName]); % save json into nifti folder

Abdel Benm

Hello xiangrui li,

You says :
If you already have nifti and want to only create json, the simple solution is to re-convert nifti.

Ok, but, i just would like to create json from a lot of DVD containing Dicom files. The dataset from DVD is very heavy, big data, and demand a very long time to reconvert Dicomfile to nifti.

Thank you

Thanks of your quick answer Xiangrui,
The issue is that the slice order/timing is not stored in the original '.nii' since it was acquired with a Philips machine, so even if I use your dcm2nii tool when I try to apply the slice time correction an error message pops up warning me that there is no slice info in the nii header.
That being said, I will follow your other advice and try to figure out the slice timing from the slice order and the TR of my data.

Thank you very much!


Xiangrui Li

Hi Marc,
The NIfTI slice_code can not encode multiband slice order. If the NIfTI is converted by dicm2nii.m, the slice timing is stored in both NIfTI extension and dcmHeaders.mat. nii_stc will use the information from the extension, and perform slice timing correction if you don't override slice order.

If you have slice order, you can convert it into slice timing. Here I copied some help text from dicm2nii.m:
load('dcmHeaders.mat'); % or drag and drop the MAT file into Command Window
s = h.myFuncSeries; % field name is the same as nii file name
spm_ms = (0.5 - s.SliceTiming) * s.RepetitionTime;
[~, spm_order] = sort(-s.SliceTiming);
You can figure out the opposite way to get SliceTiming from your sliceOrder.

That being said, since multiband often has shorter TR, the practical way may be simply to skip the slice timing correction.


Hi Xiangrui,
I am trying to perform a slice time correction on my fmri resting state data but the thing is that it was acquired with Multiband, I have the slice order (unfortunately just the order, not the timings) of my slices. I have taken a look at your nii_stc.m script and I see that it obtains the timings from the header but there is a comment that says it is not valid for multiband sequences. My question is, it is just the extraction of the timings which is not valid for Multiband or all the script at all? Is there any way to use my slice order to perform the slice timing correction?

Thanks in advance and great work, this is amazing!


Xiangrui Li

Hi chen xiaoyu,
You are right. As far as I know, the slice timing information is not available in Philips dicom or PAR.

chen xiaoyu


I am trying to use dicm2nii to extract the slice timing information of a fMRI data obtained by a Philips scanner.
However, no "SliceTiming" field was found in the dcmHeaders.mat. Is it not available for Philips data?

Xiaoyu Chen

Xiangrui Li

Hello Abdel Benm,
Thank you for the suggestion. In case you did not notice, dicm2nii has the option to save json file for BIDS, while the default is not to save json. You can turn it on at the GUI, and it will stay on for both GUI and command line conversion until you turn it off.
If you already have nifti and want to only create json, the simple solution is to re-convert nifti. A major concern for creating json and nifti separately is that some of the parameters in json are related to the way how images are organized in nifti. So it is recommended to use the json/nifti file pair from the same converter and even the same version of a converter.
Let me know if you have questions.

Abdel Benm

can you add an option to allow to create json file BIDS with/without convert DICOM image Please?
Thank you.

Thank you, Xiangrui. It was not because of compression, but apparently there was an error during file selection. Repeated it and received identical image size (+/- 1 byte). Thanks for taking care!

Xiangrui Li

Hi Chris,
Did you save files as nii or nii.gz (dicm2nii default is compressed, while spm nifti is not compressed)? Even that won't make 10-folder difference, unless the data has many repeated values, like zeros. The safe way will be to visualize one of the pairs using nii_viewer in this package, or spm tools, and figure out what is different. If indeed it is due to gz compression, then we have no worry.

Hi Xiangrui,
tried out dicm2nii as tool to bring data in BIDS format. When I compared resulting 4D-nifti files I was surprised that they need much less space on the harddrive, compared to 4D-niftis received with spm12's dicom-import and 3D-to-4D conversion functions (the latter files need about ten-fold more bytes). Can you comment on this?

Xiangrui Li

Hi Lorena,
I don't receive any info about bval/bvec problem for Siemens Magnetom Prisma. I am guessing the problem is due to a new Siemens software version, or some 3rd party dicom tool messing up dicom tags. Either way, it will be helpful to share several or a series of dicom files by dropbox etc to xiangruili at

Hi Xiangrui,

Thanks so much for this! I have a question: On my data using a Siemens Magnetom Prisma I only get 0's on all bvals and bvecs. Did Kamil Cepuch ever get back to you? Do you know why this might be? Thanks again!


Hi Xiangrui,
Thank you very much for the answer! Like your tool and now I'm more confident in using it.

Xiangrui Li

Hi Teresa,
The Philips and Siemens dicom store bvec in patient coordinate system, while most analysis software needs bvec in image reference. For this reason, the converters perform a transformation to bvec. That is why you see the difference. You can find more detail for this in our paper for dicom to NIfTI conversion:

For this reason, if a converter does the transformation correctly, you may see different bvec (row order and signs) from different converters, since different converters may store the images differently. But this should not affect the analysis result.


Hi Xiangrui,
I'm trying to convert dwi data from a Philips camera. However in the output bvec-file the vectors doesn't seem to be consistent with what I see when I read the dicom-header. Intrestingly the output from this tool is equal to when I try mricrons dcm2nii. I have looked at the comments here and checked that the patient position is HFS, so that shouldn't be a problem. Do you have any idea what the problem might be?

Allen LI

hi, i just downloaded this package, i have no idea how to use it. so i basically just uncompress it. then what is the next? please tell me about more. appreciate!!


Hello Xiangrui, I installed the pigz compression and that removed the problem. Thank you for your prompt assistance.

Xiangrui Li

Hi Brian,
That sounds like the compression command is called before the nii file is finalized. The consequence should be that the nii file was not compressed into nii.gz. Please check if this is the case. I am going to check if the nii file exists before compression.

Dear Xiangrui,
Thank you very much! I have sent you an email and shared a dataset via dropbox. I also just heard back from the physicist involved in acquiring the data and he said all the datasets were acquired feet first in a supine position.
Thanks again!



Thanks very much for the useful converter! I did however encounter an error, which says "Error during compression: gzip: can't stat: OutputPath/sub-S25/MB_Contour_SBRef_s033.nii (OutputPath/sub-S25/MB_Contour_SBRef_s033.nii): No such file or directory". Strangely, I cannot (yet) find any problems with the output files despite the error. I am using Matlab 2013b, MacBook Pro, and the data derive from Siemens 3T Tim Trio. Any help would be great. Yours, Brian


Xiangrui Li

HI Clara,
The possible reason may be that the PatientPosition is not 'HFS'. The converter is mainly for brain imaging, and is tested only for 'HFS'. You may share the dataset with me (via dropbox or google drive with at, so I can look into the problem.

Hi Xiangrui,
I am converting DTI data from a Siemens Prisma 3T scanner of the lower leg of patients to do muscle fascicle tracking using DSI studio. However, I now realized that the b-vectors seem to be wrong after the conversion. I saw that this might be a common problem and I read your paper about DICOM to NIfTI conversion but my knowledge in this is not good enough to figure out how to fix this. Do you maybe have any recommendations for me? Thank you very much in advance!

Rajdeep Das

Fantastic, actually pulled out my .bvec and .bval files from our scanner's DICOMs, which even dcm2niix won't do properly.
Total life-saver.

Xiangrui Li

Hi KC,
Is your data with very new or very old Siemens software version? If you can figure out the series which gives the problem, you may send me a couple of dicom files within that series, so I can take a look. Thanks.

Hi Xiangrui,
I'm using Siemens scanner and for some time during conversion, I don't obtain bvals and bvecs. Moreover .json file line DiffusionBValue and DiffusionGradientOrientation are filled with zeros.
Cheers, KC

Xiangrui Li

Hi Anouk van der Straten,
It seems you are using an earlier version of dicm2nii.m, but that probably won't make difference for the issue. The likely reason is that the PAR file does not have bval/bvec information. If you can send the PAR file to me ( at, I may confirm the cause.

Hi Xiangrui,

Thank you for the tool and all the good work!
I am currently working on an older diffusion wheighted dataset (2006-2007) that has been scanned at a Phillips scanner (V4).
The conversion from PAR/REC to nifti fails in some of the subjects. I tried the conversion in dcm2niix and it did convert to nifti but it did not give me the .bval and .bvec files. The error code I get is:

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

Error in dicm2nii>get_dti_para (line 1272)
bval(j) = val;

Error in dicm2nii (line 861)
if s.isDTI, [h{i}, nii] = get_dti_para(h{i}, nii); end

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

Do you maybe know what the problem is? Thanks in advance!

Anouk van der Straten

Xiangrui Li

Hi Constantinos,
The 'save' command will do that for you. If you 'save' then 'load' again, you will see the header is updated accordingly.

Hi Xiangrui,

thanks for the quick answer. Do I have to change anything in the nii-header accordingly?


Xiangrui Li

Hello Constantinos,
I believe dicm2nii.m will give you a 4D NIfTI, with each volume only 1 slice. This is actually your data if I understand correctly, since the first 3 NIfTI dimension are for space (xyz). If you, for any reason, like to put the 4th dim into 3rd dim (violating NIfTI standard), you can achieve it by something like following:
nii = nii_tool('load', 'my_4d_file.nii.gz'); % load converted nifti
nii.img = permute(nii.img, [1 2 4 3]); % put 4th dim into 3rd dim
nii_tool('save', nii, 'my_3d_file.nii.gz'); % new file is 3D

Hope this helps.

Hello Xiangrui,

I am trying to convert multiple dicoms from a siemens heart time serie (2D images over the same slice, where the 3rd dimension is time) in a 3D volume. The old dcm2nii tool from Chris Rorden is doing this, but is flipping the y-axis of the 2D images, so the whole is upside-down. Could you suggest which parameters I should use with your tool in order a)to get a 3D volume b) avoid fliping.

Thanks in advance

Jasmine Raw

Hi Xiangrui, thank you so much for your explanation!
Best, Jasmine

Xiangrui Li

Hi Jasmine Raw,
If you move the mouse to an option at the GUI, it will show its meaning. Left-hand storage seems preferred for FSL, and it likely does not matter for other software. It is just a way how images in a NIfTI file is organized for the first dimension, and either way should be fine in theory.
The "inconsistent image orientation" complain is likely from something like localizer scan which is the very first scan to position the coverage, and is not needed for analysis. If that is the case, it is won't hurt to skip it without converting. It does nothing to do the left-handed storage.

Jasmine Raw

Hi Xiangrui, this converter is extremely helpful for my research but I wanted to ask about the 'left-hand storage' function.
For all of my data so far I have selected this option but actually I am not sure if it's needed. Could you help to explain a little more? I am receiving some errors relating to inconsistent image orientation and wondered if this was down to me selecting 'left-handed storage.' Thanks

Xiangrui Li

Hi ritu panda,
This won't save data as dicom. diccomwrite from Image Toolbox will do it, but dicom needs a lot of information, so most dicom field will be fake.

ritu panda

Can I use this to convert a time series fMRI data file in a .mat format to dicom?

Thank you very much

Hi Xiangrui,

The updated package works. Thanks!


Xiangrui Li

Hi Shereif,
Thank you for sharing the files. It was due to a long time bug (ap,fh,rl order) that was never caught. Today's update should fix it, and it ls likely more robust for other variation of the order.
Please update the package from either dicm2nii or nii_viewer GUI.


I just sent you PAR/REC files for both correctly and incorrectly oriented images like you asked. Thanks for the help!


Xiangrui Li

Hello Shereif Haykal,
That sounds a little strange for the same protocol. Could you send me (xiangruili at the PAR file which give the problem? It will be better if you also send a PAR file without problem. Thank you.

Dear Xiangrui Li,

Thank you for the great tool! I have a small problem with converting diffusion PAR/REC files. Most of the files came out fine, but a few were oriented upside-down for some reason! All scans were performed using the exact same scanner and protocol, so I have no idea why some of the converted files end up upside down. When I tried other converters, the NIFTI files all came out properly oriented (right side up). Do you have any idea what could be causing this problem, and how I can fix it? Thanks!

Shereif Haykal

yu li

Xiangrui Li

Hello Yu Li,
It is not recommended to convert images from multiple subjects at one shot, since we typically store files into different folder for different subjects.
In case your dicom images are mixed for multiple subjects, there are several ways to separate them.
1. The code sort_dicm.m in the package is for this purpose.
2. You can use rename_dicm.m to rename files into format of subj1..., subj2.... Then do the following to convert one subject a time:
dicm2nii('/myDicmFolder/subj1*.dcm', /'myNIfTIFolder/subj1/') % convert files subj1*.dcm only
3. After the nifti conversion for mixed images, the subject names will be in file name in case of multiple subjects, so you can read a script to separate them. But you will probably need to rename them after you separate them into folders, so this is not preferred.

Hope this helps.

yu li

Hello Xiangrui Li,
I deal with some data. I choose the source folder which include several subjects' data, and then the all results mixed in one folder. I want to know if we could divide into these different into groups according to each subject rather than all in the one folder. Maybe I can't find this function. and this tool is very helpful,thanks!
Looking forward to your reply.
-Yu Li


Dear developer, an older version of this worked for me, the newest does not. I have Phillips dicoms (240x240x30x3). The problem seems to be with "LocationsInAcquisition" returning 40 instead of 30.

Xiangrui Li

Hello Dickson,
Thank you for the feedback. If the problem is reproducible, could you send me two dicom files, e.g. one with b0 and one with non-b0, so I can look into the problem?

Hello Xiangrui Li,

It seems that the latest version of your toolbox has trouble converting diffusion volumes. It doesn't produce correct bvec and bval files. Instead, the bvals and bvecs outputted from dicm2nii are always zeroes. There was no problem in the previous version.


Xiangrui Li

Hi Tanguy,
That is likely due to bug introduced during last update. I was trying to make it more robust ...
Could you send me ( at the PAR file? REC file is not necessary.


Hi Xiangrui Li,

Thank you so much for this NIFTI converter. Saved me lot of time.
I just noticed that the new version 2017.07.20 of dicm2nii has trouble to detect Philips .PAR files. The old version was working efficiently.
I can send you the data privatly.



Xiangrui Li

Hi Jess,
I believe that is the limitation of load_nii function. You can use nii = nii_tool('load', 'MyFile.nii.gz') included in my package to load data. The hdr fields organization will be different from load_nii, but nii_tool can decode some common NIfTI extension. If you have to keep compatibility with load_nii series for your code, you may find something like load_nii_untouched in Jimmy Shen's package.


Thanks for packaging the dicm2nii.m file to be user-friendly. I did run into an error from the resulting .nii.gz file however. When trying to use Jimmy Shen's load_nii function, I got the following error: "Non-orthogonal rotation or shearing found inside the affine matrix in this NIfTI file."

It appears something went wrong - any suggestions?


Xiangrui Li

Hi Jacob,
Thanks for the feedback. _mag was used in an early version, but I removed it later, since most series are mag image.
NIfTI defined slice order code are 1 through 6, while 0 means no information. It was my decision to make up the code 7, which says it is none of 1~6, but we do have information (in SliceTiming of NIfTI extension and dcmHeaders.mat file saved with NIfTI). We see, unfortunately, some software gives unnecessary error, while they can simply ignore unknown code. Now we have to lie that we have no information by setting it to 0. Before I update the submission, you can open dicm2nii.m, and change 7 to 0 at Line 1227.

Thanks for the converter! Very helpful. A single input path is very user friendly, and the output names are fantastically simple (especially the "_phase" on field map data; perhaps you could add a "_mag" as well).
A comment/request. We have some multiband data from a siemens trio that we are putting through the converter as part of a larger pipeline. That pipeline later calls the bash "mri_info" function from Freesurfer. It errors on the converted multiband data due to "unsupported slice timing pattern 7". If I convert the same dicoms with Freesurfer's "mri_convert" (which is much less user friendly to implement in batch), "mri_info" has no issues with it. I don't know if this is solvable, or due to fundamental differences in how you and the Freesurfer team have chosen to work with Nii conversion. But it's the only issue I have with this converter.

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.

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.


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)]);


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.


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.


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


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.


Thanks for the helpful software!

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



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

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


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.


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!


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


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.

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.

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.


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?

Bob Spunt

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.

Bob Spunt

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.

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.

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



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



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.

Bob Spunt


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.


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. use GetFullPath from Jan
2. accept mixture of files and folders as input
3. other fixes


dicm2nii: implement 16-bit range scale (default off);
dicm_hdr: bug fix for insufficient bytes for search method; improvement for philips_par&xml
Switch to Github


1. dicm_hdr: can read Philips xml file; many improvements for PAR dealing
2. dicm2nii: can deal with incomplete volume for Philips PAR/XML/DICOM;
better dealing for different complex image types.


dicm2nii: take care of some special Philips cases:
1. store VolumeTiming from FrameReferenceTime, seen in pet data;
2. bug fix to remove Philips DTI ADC vol;
3. switch to floating value for rescale.


1. dicm2nii: bug fix for long file name
2. some minor fix.


1. check NIfTI struct in workspace when adding overlay
2. Implement 'Standard deviation' like for 'time course'.
dicm_hdr->philips_par: bug fix for wrong slice flip; work for incomplete volume


1. nii_viewer: map inflated surface click to correct location in volume, even for old matlab
2. dicm2nii: bug fix for fieldmap TEs
3. other minor fixes and improvement.


nii_viewer: support inflated surface to volume mapping. Tested only for HCP surfaces.


surface view uses combined overlay, so it works smoothly for different environment.


1. nii_viewer: implement surface view for CIfTI (HCP gii template included).
2. dicm_hdr: bug fix for possible slice flip in Philips PAR. Thx ShereifH.


1. dicm2ii: work for Siemens multiframe dicom.
2. nii_viewer: try to convert back to volume to visualize CIfTI.
3. dicm_img: bug fix for compressed dicom without offset table.


1. nii_view: two more layout including compact one-row display
2. other minor improvement and fix


1. Save VolumeTiming for missing volumes based on BIDS;
2. Correct Siemens readout time;
3. Use GE SLICEORDER if RTIA_timer not available;
4. Always store TE and readout for distortion correction.


1. Bug fix for reading Philips PAR file;
2. Better tab auto-completion.


1. Add functionSignatures.json file for tab auto-completion;
2. Allow regularly missing InstanceNumbers, like dicom from CMRR for auditory study;
3. Try to take care of GitHub download, so prepare for GitHub hosting.


1. dicm2nii & nii_viewer: can read big-endian AFNI image;
2. dicm2nii: set multiband slice_code to 0 to avoid FreeSurfer error;
3. Users need to manually download once to fix package update from GUI;
4. nii_viewer: improved Ctrl-drop to add overlay


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 Compatibility
Created with R2017a
Compatible with any release
Platform Compatibility
Windows macOS Linux