Question

I have some 1000 images I need to load as training data for a facial recognition program.

There are 100 people, each have 10 unique pictures.

Saved in a folder like:

    myTraining  //main folder
         - John // sub folder
               - John_Smith_001, John_Smith_002, ... , 00n, //images
         - Mary // sub folder
               - Mary_Someone_001... you get the idea :)

I'm familiar with a lot of matlab but not ways of iterating through external files.

What is an easy implementation to go through each folder, one by one and load the images, ideally using the retrieving the file names and using them as variable/image names.

Thanks in advance.

Was it helpful?

Solution 2

You can do it like this:

basePath = pwd;  %your base path which is in your case myTraining  
allPaths = dir(basePath);  %get all directory content
subFolders = [allPaths(:).isdir]; %get only indices of folders
foldersNames = {allPaths(subFolders).name}'; % filter folders names
foldersNames(ismember(foldersNames,{'.','..'})) = []; %delete default paths for parents return '.','..'
for i=1:length(foldersNames), %loop through all folders
    tmp = foldersNames{i};  %get folder by index
    p = strcat([basePath '\']); 
    currentPath =strcat([p tmp]); % add base to current folder
    cd(currentPath);   % change directory to new path
    files = dir('*.jpg'); % list all images in your path which in your case could be John or Mary 
    for j=1:length(files), % loop through your images 
        img = imread(files(j).name); % read each image and do what you want 
    end
end

OTHER TIPS

Using the following commands will recursively list all files in a specific directory and its sub-directories. I have listed it for both Windows and Mac/Linux. I unfortunately can not test the Mac/Linux version since I am not near any of those machines, but it will be fairly similar to what is written below.

Windows

[~,result] = system('dir C:\Users\username\Desktop /a-d /s /b');
files = regexp(result,'\n','Split')

Mac/Linux

[~,result] = system('find /some/Directory -type file);
files = regexp(result,'\n','Split')

You can then iterate through the cell array created, files, and do whatever loading you may need with imread, or something like that

for jpg images it would be

files = dir('*.jpg');
for file = files'
    img = imread(file.name);
    % Do some stuff
end

and if you have multiple extensions use

files = [dir('*.jpg'); dir('*.gif')]

I hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top