Fetching image files from all sub folders within a folder

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

@Muhammad Umar: what version of MATLAB are you using?
Please check the edits, i am using 2o18

Sign in to comment.

Answers (2)

files = dir(fullfile(directory, '**', '*.jpg'));
This requires 2016ish (I would need to investigate the exact release)

Asked:

on 22 Sep 2018

Answered:

on 22 Sep 2018

Community Treasure Hunt

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

Start Hunting!