MATLAB: How to loop a DICOM and corresponding ROI folder and write results to a .csv

ctdicomhounsfield unitsroi

I have a directory with 60 CT-DICOM images (named F000001.dcm, F000002.dcm …) and another directory with 60 correspoding region of interests (ROI) in NIFTI format (named 1.nii, 2.nii …).
I need to get the mean hounsfield unit (HU) for every DICOM and corresponding ROI.
I managed to get the right value for one DICOM, however, I do not exactly know how to loop through the DICOM and ROI folder and save all results automatically to a csv with col1=filename and col2=meanHU
close all;
clear all;
% The dicom filename
folderFileName = '.\DICOM\F000001.dcm';
% Read the dicom header info
dinfo = dicominfo(folderFileName);
% Read the dicom image data and rescale to the correct values
myImage = double(dicomread(folderFileName))*dinfo.RescaleSlope + dinfo.RescaleIntercept;
% read the transformed roi
ROI = '\ROI\1.nii'
% extract mean HU:
values = myImage(ROI);
meanHU = mean(values)

Best Answer

diFolderName = '.\DICOM';
roiFolderName = '.\ROI';
numfiles = 60;
filenames = cell(numfiles, 1);
meanHU = cell(numfiles, 1);
for K = 1 : numfiles
basename = sprintf('F%06d.dcm', K);
folderFileName = fullfile(diFolderName, basename );
dinfo = dicominfo(folderFileName);
% Read the dicom image data and rescale to the correct values
myImage = double(dicomread(folderFileName))*dinfo.RescaleSlope + dinfo.RescaleIntercept;
ROIname = fullfile(roiFolderName, sprintf('%d.nii', K));
ROI = niftiread(ROIname); %requires R2017b or later!
values = myImage(ROI);
filenames{K} = basename;
meanHU{K} = mean(values);
end
outdata = [filenames, meanHU];
xlswrite('meanHU_Summary.csv', outdata);
Note: niftiread() is new in R2017b. For earlier versions it is necessary to use something from the File Exchange.