how to read images one by one

3 views (last 30 days)
rui
rui on 18 Feb 2015
Edited: Stephen23 on 18 Apr 2021
There is multiple images in a folder, but the name is not in order, for example, 01.jpg, 21.jpg, 41.jpg,......101.jpg. How to read these images successively? Thanks very much.

Accepted Answer

Stephen23
Stephen23 on 18 Feb 2015
Edited: Stephen23 on 18 Apr 2021
If you have a cell array of the names, then use that. If you don't know the names, then use dir to read the names from the directory where they are saved. The MATLAB Wiki gives an complete working example of how to do this:
(Just scroll down a little to find the example using dir.)
One way to sort filenames into alphanumeric order is to download my FEX submission NATSORTFILES:
>> S = dir('*.txt');
>> S.name
ans =
'1.txt'
ans =
'10.txt'
ans =
'2.txt'
>> S = natsortfiles(S); % alphanumeric sort by filename
>> S.name
ans =
'1.txt'
ans =
'2.txt'
ans =
'10.txt'
  3 Comments
Joe Perkins
Joe Perkins on 14 Sep 2017
Unfortunately dir can't find the file pattern for my files. I have used the example straight from the FAQ Image Analyst posted. The images are not labelled in a sequential way. (Particle_3),.. (Particle_11),.. etc
myFolder = 'c:/Users/ezxjp1/Documents/MATLAB/ParticleImages';
% Upload particles, measure size & shape
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, 'Particle_%d.tif'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(myFolder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
imageArray = imread(fullFileName);
Image Analyst
Image Analyst on 14 Sep 2017
Here is what the FAQ correctly says:
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.jpg'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
and here is how you incorrectly modified it:
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, 'Particle_%d.tif'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
Take note that * is a wildcard character and can be used in functions like dir. The "%d" is not a wildcard symbol and is intended to be used in the functions sprintf() or fprintf().
Change the "%d" to "*" and it should work.

Sign in to comment.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!