Problem reading multiple images from a folder in Matlab
I have a set of images located in a folder and I am trying to read these images and store their names in a text file. Where the order of images is very important.
My code:
imagefiles = dir('*jpg');
nfiles = length(imagefiles); % Number of files found
%*******************
for ii=1:nfiles
currentfilename = imagefiles(ii).name;
% write the name in txt file
end
Images saved in the folder in the following order: {1,2,3,4,100,110}
.
The problem is that Matlab reads and writes a sequence of images as { 1,100,110,2,3,4}
. This is not the correct order.
How can this be overcome?
source to share
I would suggest using scanf
to find the file number. To do this, you need to create a format specification that shows how your filename is generated. If this number is, then .jpg
, it would be: '%d.jpg'
. You can call sscanf
(scan string) on name
files with cellfun
:
imagefiles = dir('*jpg');
fileNo = cellfun(@(x)sscanf(x,'%d.jpg'),{imagefiles(:).name});
Then you sort fileNo
, store the indices of the sorted array, and loop through those indices in a for-loop:
[~,ind] = sort(fileNo);
for ii=ind
currentfilename = imagefiles(ii).name;
% write the name in txt file
end
source to share