Reanimation
Reanimation

Reputation: 3336

Matlab - Name variable same as File name?

I'm building a facial recognition program and loading a whole bunch of images which will be used for training.

Currently, I'm reading my images in using double loops, iterating through subfolders in a folder.

Is there any way, as it iterates, that the images file name can be used before the image is read and stored?

eg. I have an image person001.jpg. How can you retrieve that name (person001) then read the image in like: person001 = imread('next iteration of loop which happens to be person001');

Thanks in advance.

Upvotes: 0

Views: 137

Answers (1)

Daniel
Daniel

Reputation: 36710

I strongly recommend not to use unstructured variables. First it's very difficult to do operations like "iterate over all images", second you can get strange problems covering a function name with a variable name. Instead i would use a struct with dynamic field names or a map. A solution with a Map propably allows all possible file names.

Dynamic field names:

dirlisting=dir('.jpg');
for imageIX=1:numel(dirlisting)
 %cut of extension:
 [~,name,~]=fileparts(dirlisting(imageIX).name);
 allImages.(name)=imread(dirlisting(imageIX).name);
end

You can access the images in a struct with allImages.person001 or allImages.(x)

Map:

allImages=containers.Map
dirlisting=dir('.jpg');
for imageIX=1:numel(dirlisting)
 %cut of extension:
 [~,name,~]=fileparts(dirlisting(imageIX).name);
 allImages(name)=imread(dirlisting(imageIX).name);
end

You can access the images in a Map using allImages('person001'). Using a Map there is no need to cut of the file extension.

Upvotes: 5

Related Questions