reading all documents with a for loop
9 views (last 30 days)
Show older comments
I have 750 pictures that I want to work on my code one by one. Their names are like
PetsD2TeC1_00000.jpg
PetsD2TeC1_00001.jpg
PetsD2TeC1_00002.jpg
...
PetsD2TeC1_00750.jpg
Please keep that in mind, there are zeros depending on how many digits the index number has.
0 Comments
Accepted Answer
David Hill
on 19 Oct 2022
Edited: David Hill
on 19 Oct 2022
Assumig all the pictures are the same size.
for k=1:750
A(:,:,:,k)=imread(sprintf('PetsD2TeC1_00%03d.jpg',k));%store all pictures in 4D matrix
end
0 Comments
More Answers (1)
Image Analyst
on 19 Oct 2022
Edited: Image Analyst
on 19 Oct 2022
This gets asked several times per week. See the FAQ for code snippet
Or, more general and able to handle numbers past 999, or whatever the exact number you have is:
% Specify the folder where the files live.
myFolder = 'C:\Users\yourUserName\Documents\My Pictures';
% Check to make sure that folder actually exists. Warn user if it doesn't.
if ~isfolder(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
uiwait(warndlg(errorMessage));
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
return;
end
end
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, 'PETS*.jpg'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now reading %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as reading it in as an image array with imread()
imageArray = imread(fullFileName);
imshow(imageArray); % Display image.
drawnow; % Force display to update immediately.
end
0 Comments
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!