MATLAB: How to load multiple images and processing them

loading images with a loop

Hi!!!
i've been looking for some info about loading "n" images with a script but i havent find anything…
well my idea was create a function with a for loop that changes the index of the image to load, in that way if the firts image its called "1.jpg" the program will load and process the images 'till it reaches a variable called "m" that is the total of images in my directory….
well i've tried like this a lot of times but i cant find the way to make it work. 🙁 so if anyone can help me i will be realy grateful

Best Answer

% Read files file1.txt through file20.txt, mat1.mat through mat20.mat
% and image1.jpg through image20.jpg. Files are in the current directory.
for k = 1:20
matFilename = sprintf('mat%d.mat', k);
matData = load(matFilename);
jpgFilename = strcat('image', num2str(k), '.jpg');
imageData = imread(jpgFilename);
textFilename = ['file' num2str(k) '.txt'];
fid = fopen(textFilename, 'rt');
textData = fread(fid);
fclose(fid);
end
A very slight adaptation gives you:
% Read 1.jpg through m.jpg.
% Files are in the "yourFolder" directory.
for k = 1:m
jpgFilename = sprintf('%d.jpg', k);
fullFileName = fullfile(yourFolder, jpgFilename);
if exist(fullFileName, 'file')
imageData = imread(fullFileName );
else
warningMessage = sprintf('Warning: image file does not exist:\n%s', fullFileName);
uiwait(warndlg(warningMessage));
end
imshow(imageData);
end
Note how I make it more robust by using exist() to check for the file's existence before attempting to show it, and how I make it more flexible by allowing you to specify that the files live in some particular folder "yourFolder" rather than living in the current folder only.
However if you want to do all the image files in the folder, then use the second chunk of code in the FAQ. That will also eliminate the need to use exist() because dir() will only give you files that are known to exist. However, if you want to be alerted if a file is missing, then you could still use the part of the first example to warn you of a missing file.