Fetching image files from all sub folders within a folder
Show older comments
I am using following code to fetch the files in a folder. However my folder does contain some subfolders that also contain images. How can I fetch all the possible .jpg files in subfolders too.
directory = uigetdir();
files = dir(fullfile(directory, '*.jpg'));
I have also tried, it doesnt list any file
function files = getFilesFromDirectory(mainSelectedFolder)
files = [];
folderNamesList = {};
filenames = [];
mainIndex = 0;
% Fetchign all possible sub folders
subFoldersList = genpath(mainSelectedFolder);
while true
[subfolder, subFoldersList] = strtok(subFoldersList, ';');
if isempty(subfolder)
break;
end
folderNamesList = [folderNamesList subfolder];
end
for x = 1 : length(folderNamesList)
selectedFolder = folderNamesList{x};
pngFiles = sprintf('%s/*.png', selectedFolder);
filenames = dir(pngFiles);
filePattern = sprintf('%s/*.jpg', selectedFolder);
filenames = [filenames; dir(filePattern)];
imagesCount = length(filenames);
if imagesCount >= 1
% fetching the full path names
for y = 1 : imagesCount
fullFileName = fullfile(selectedFolder, filenames(y).name);
files(mainIndex) = fullFileName;
end
end
end
2 Comments
Stephen23
on 22 Sep 2018
@Muhammad Umar: what version of MATLAB are you using?
Muhammad Umar
on 22 Sep 2018
Answers (2)
Walter Roberson
on 22 Sep 2018
files = dir(fullfile(directory, '**', '*.jpg'));
This requires 2016ish (I would need to investigate the exact release)
Image Analyst
on 22 Sep 2018
0 votes
Or you could try imageDataStore().
Categories
Find more on Blocked Images 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!