Question

I have a directory that contains several folders. Each of these folders contains several images.

If we suppose that we have a directory that contains images, I know how to read these images (see my code below); If we suppose that these images are placed in subdirectories in this directory, then I don't know how to edit my code.

directory = 'my_direct';
dnames1={directory};
c{1} = dir(dnames1{1}); % struct array with 5 fileds (name, isdir,...)

if length(c{1}>0)
    if c{1}(1).name =='.'
        c{1} = c{1}(3:end); %ignore the '.' and '..'
    end
end

for k = 1: length(c{1})
    image= double(imread([dnames{1} '/' h{1}(L).name]))./255;
end
Was it helpful?

Solution

assuming that you want to go inside each sub-directory and read the images

 Root_directory='The directory location';
 sub_directories=dir(Root_directory);
 sub_directories(1,2)=[]; % to remove . and ..
 for sub_dir_index=1:length(sub_directories)
    images=dir(fullfile(Root_directory,sub_directories(sub_dir_index).name));

     the rest of your code

 end

OTHER TIPS

You can use this code for reading multiple images, all you should know is the path to that directory. Just write the path and the code will read your images according to the pattern you stored them. I hope you will find it useful.

myFolder = 'path';
if ~isdir(myFolder)
  errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
  uiwait(warndlg(errorMessage));
  return;
end
filePattern = fullfile(myFolder, '*.jpg');
jpegFiles = dir(filePattern);
for i = 1:length(jpegFiles)
  baseFileName = jpegFiles(i).name;
  fullFileName = fullfile(myFolder, baseFileName);
  fprintf(1, 'Now reading %s\n', fullFileName);
 Input_image = imread(fullFileName);
end

If you have the R2014b release of MATLAB with the Computer Vision System Toolbox, you can use the imageSet object:

imgSets = imageSet('my_direct','recursive')

imgSets will be an array of imageSet objects, each of which contains the paths to all image files in the sub-directories of my_direct. You can then read the j-th image from the i-th sub-directory as follows:

im = read(imgSets(i), j);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top