MATLAB Answers


How do I access images from directories using an input command for the extensive file?

Asked by Sara Foster on 6 Sep 2019
Latest activity Commented on by Sara Foster on 7 Sep 2019
I have a function which accesses images from a directory using inputs dirname and the filetype. When I type filenames = image(dirname,filetype), (e.g. filenames = image('/Users/Macbookair','jpg'), I can access all the files from the directory if the code has the line fileIdentity = fullfile(dirname, '*.jpg').
However, if I type in filenames = image('/Users/Macbookair','png'), the folders of jpg still appear in the command window. My question is how do I add an input command, such as filetype, so that whenever I type 'png', 'jpg' or any other extensive file it will show up as that specific file.
Thank you!


Why did you name your function "image", when that is the name of a key matlab function for drawing images? imshow() and imagesc() also internally depend upon image() so by naming your function "image" you make it quite difficult to draw images.
We do not know how your existing function accesses file names, which makes it difficult to know what to suggest.

Sign in to comment.

1 Answer

Answer by Neuropragmatist on 6 Sep 2019
 Accepted Answer

In the example function you gave the second input 'fileType' is not used, is that the problem?
You could use this in the line calling fullfile to get only the filetypes you want, i.e.:
function [filenames] = GenerateImageList(dirname, fileType)
fileIdentity = fullfile(dirname, ['*' fileType]);
files = dir(fileIdentity);
for i = 1:length(files)
filenames = files(i).name;
fprintf('%s\n', filenames);
For example you can run this code as:
filenames = GenerateImageList(pwd,'png')
% or
filenames = GenerateImageList(pwd,'jpg')
However, there are some problems with your code - if there are no files with the extension you ask for the function throws an error because filenames is left undefined. Also, I think you want filenames to contain a list of all the filenames? But the way it is written here it will only ever contain the last filename it found because you overwite it on every loop. Might I suggest something like this:
function [filenames] = GenerateImageList(dirname, fileType)
fileIdentity = fullfile(dirname, ['*' fileType]);
files = dir(fileIdentity);
filenames = {files(:).name};
fprintf(1, '%s\n', filenames{:})
If you don't need to display the text in the command window for every filename (why do you want that?) you can just call dir directly for the filename list:
function [filenames] = GenerateImageList(dirname, fileType)
df = dir(fullfile(dirname, ['*' fileType]));
filenames = {df(:).name};
And then maybe you don't need the GenerateImageList function at all, you could just put those lines of code directly inb the parent function...
Hope this helps,


I recommend using fullfile(dirname,.....) on the {} so that fully qualified file names are returned.

Sign in to comment.