File Exchange

image thumbnail

xiangruili/dicm2nii

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

99 Downloads

Updated 08 Aug 2018

View License on GitHub

DICOM to NIfTI conversion, NIfTI tools

Comments and Ratings (163)

MEJ Campbell

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 https://github.com/xiangruili/dicm2nii .Thanks.
-Xiangrui

MEJ Campbell

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.
Cheers,
Megan

Brian

Brian (view profile)

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.
-Xiangrui

%===========================
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
end
save_json(s0, [dirs{i} '/' s.NiftiName]); % save json into nifti folder
end
end

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!
Bests,

Marc

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.

-Xiangrui

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!
Bests,

Marc

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.
-Xiangrui

chen xiaoyu

Hi,

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?

Best,
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.
-Xiangrui

Abdel Benm

Hello
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.
-Xiangrui

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?
Thanks,
Chris

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 gmail.com.
-Xiangrui

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!

Lorena

Teresa Nordin

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

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:
https://www.ncbi.nlm.nih.gov/pubmed/26945974

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.

-Xiangrui

Teresa Nordin

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?
BR
Teresa

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!!

Brian

Brian (view profile)

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.
-Xiangrui

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!

Best,
Clara

Brian

Brian (view profile)

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

Brian

Brian (view profile)

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 xiangrui.li at gmail.com), so I can look into the problem.
-Xiangrui

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!
Best,
Clara

Rajdeep Das

Roger Mullins

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.
-Xiangrui

Kamil Cepuch

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 (xiangrui.li at gmail.com), I may confirm the cause.
-Xiangrui

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!

Greeting,
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.
-Xiangrui

Hi Xiangrui,

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

Greetings
Constantin

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.
-Xiangrui

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
C.

Elies Fuster

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.
-Xiangrui

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.
-Xiangrui

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!

-Shereif

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.
-Xiangrui

Hi,

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

Best,
Shereif

Xiangrui Li

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

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!

Best,
Shereif Haykal

yu li

yu li (view profile)

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.
-Xiangrui

yu li

yu li (view profile)

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

Jurgen

Jurgen (view profile)

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?
-Xiangrui

Dickson Wong

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.

Thanks,
Dickson

Megan Sperry

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 (xiangrui.li at gmail.com) the PAR file? REC file is not necessary.
Thanks.
-Xiangrui

Tanguy

Tanguy (view profile)

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 https://github.com/neuropoly/qMRLab/tree/Ian/External/dicm2nii was working efficiently.
I can send you the data privatly.

Regards,

Tanguy

Tanguy (view profile)

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.
-Xiangrui

Jessica Huang

Hello,

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?

-Jess

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.
-Xiangrui

Hello,
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.
Thanks!

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.
-Xiangrui

Robert Welsh

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

dicm2nii
Xiangrui Li's dicm2nii.m 20170211 (feedback to xiangrui.li@gmail.com)
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.
-Xiangrui

Navot

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

Navot

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?

addpath('/home/navotn/EE/Scripts/')
addpath('/home/navotn/dcim2nii')

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
cd('/home/navotn/EE/Group_data/Subjects/')
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}])
end

Xiangrui Li

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

Navot

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

Wasna,
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.
-Xiangrui

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.
-Xiangrui

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.
-Xiangrui

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?
thanks

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
-Xiangrui

anaston

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.
Cheers,
Agoston

Xiangrui Li

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

-Xiangrui

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?

Thanks,
Ellankavi

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 (xiangrui.li at gmail) one of the files which generate the error?
-Xiangrui

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 like.it. For the NIfTI conversion, you can find the paper info from dicm2nii GUI menu About -> A paper about conversion.
-Xiangrui

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.
-Xiangrui

Marius

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?

Thanks,
Marius

xiaoping qu

Lena

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.
-Xiangrui

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.

Thanks
Xiaoping

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.
-Xiangrui

John

John (view profile)

Thanks for the helpful software!

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

Thanks,
John

Jiri

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.

-Xiangrui

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.
-Xiangrui

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

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.
-Xiangrui

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.
-Xiangrui

PAT

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.

jfcabana

Thank you for this tool. Very well done!

Jens

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 =
read_csa(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)
dicm2nii_gui(dataFolder);

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 =
read_csa(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)
dicm2nii_gui(dataFolder);

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

Peter

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.

-Hyojeong

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.
-Xiangrui

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.

-Raveena

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.
-Xiangrui

Hyojeong Kim

Hi Xiangrui,

Thank you very much for your help. I really appreciate it. I put the files on my dropbox linked below:
https://www.dropbox.com/sh/er1owws2lhvkrdv/AAC22TV0kK1evI-kEN1UpcdCa?dl=0

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.
-Xiangrui

Hyojeong Kim

Thanks Xiangrui Li,

I figured it has different image size..it 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)
dicm2nii_gui(dataFolder);

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

dysonsphere

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

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.
-Xiangrui

Hyojeong Kim

Hi,

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)
dicm2nii_gui(dataFolder);

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.

dysonsphere

dysonsphere

hi

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.

example:
[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.
-Xiangrui

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.

-Xiangrui

carloreve

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!
Carlo

carloreve

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.
-Xiangrui

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

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.
-Xiangrui

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

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

-Xiangrui

kammcm

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.

Bob Spunt

Naho

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 DicomVCL.com 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.

-Xiangrui

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):

dicm2nii
Xiangrui Li's dicm2nii (feedback to xiangrui.li@gmail.com)
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 xiangrui.li@gmail.com)
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.

Marco

peter888

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.

Cheers.

-Xiangrui

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.
Paul

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).

-Xiangrui

JuanesA89

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,
subjName);

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.
-Xiangrui

Qingyan

Hi,
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?

Hi,

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

Thx

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.

-Xiangrui

Hi,

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 ?

Regards,

O.A.

Xiangrui Li

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

Updates

2018.08.08

1. use GetFullPath from Jan
2. accept mixture of files and folders as input
3. other fixes

2018.6.14.0

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

2018.6.5.0

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.

2018.5.23.0

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.

2018.4.20.0

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

2018.3.9.0

nii_viewer:
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

2018.1.19.0

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.

2018.1.3.0

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

2017.12.29.0

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

2017.12.28.0

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.

2017.12.14.0

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.

2017.10.31.0

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

2017.9.27.0

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.

2017.8.3.0

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

2017.7.20.0

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.

2017.6.18.0

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

2017.3.22.0

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

2017.2.15.0

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.

2017.1.3.0

anonymize_dicm: replace PatientName with ID rather than scratching it.

2016.12.29.0

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.

2016.11.30.0

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.

2016.11.15.0

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.

2016.10.10.0

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.

2016.9.21.0

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

2016.9.20.0

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

2016.8.26.0

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.

2016.7.10.0

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

2016.6.10.0

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.

2016.6.1.0

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

2016.5.21.0

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

2016.5.16.0

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

2016.5.12.0

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

2016.5.9.0

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

2016.5.6.0

Corrected version number

2016.5.5.0

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.

2016.3.24.0

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.

2016.1.31.0

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

2016.1.27.0

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

2016.1.15.0

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

2016.1.14.0

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.

2016.1.12.0

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

2016.1.5.0

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.

2015.11.28.0

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

2015.11.27.0

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

2015.11.22.0

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

2015.11.20.0

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.

2015.11.5.0

Bug fix for Show NIfTI hdr/ext

2015.11.4.0

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.

2015.9.26.0

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.44.0.0

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.

1.43.0.0

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

1.42.0.0

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

1.41.0.0

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

1.40.0.0

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.39.0.0

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.38.0.0

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

1.37.0.0

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

1.36.0.0

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.34.0.0

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

1.33.0.0

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.

1.32.0.0

See previous update

1.31.0.0

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.30.0.0

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.

1.29.0.0

Optional output argument for sort_dicm

1.28.0.0

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.

1.27.0.0

Take care of different carriage return issue in Philips PAR file

1.26.0.0

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

1.25.0.0

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

1.24.0.0

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

1.23.0.0

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.22.0.0

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.21.0.0

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.

1.20.0.0

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

1.19.0.0

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.18.0.0

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

1.17.0.0

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.16.0.0

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

1.15.0.0

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.14.0.0

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

1.13.0.0

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.12.0.0

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.11.0.0

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

1.10.0.0

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.

1.9.0.0

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

1.8.0.0

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

1.6.0.0

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.

1.5.0.0

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

1.4.0.0

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

1.3.0.0

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.2.0.0

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.

1.1.0.0

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

MATLAB Online Live Editor Challenge

View the winning live scripts from faculty and students who participated in the recent challenge.

Learn more

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

» Watch video