MATLAB Answers

Saving Label output using for loop

2 views (last 30 days)
image_folder = cd;
filenames = dir(fullfile(image_folder, '*.jpg'));
total_images = numel(filenames);
col = cell(1, total_images);
for n = 1:total_images
net = googlenet;
inputSize = net.Layers(1).InputSize;
classNames = net.Layers(end).ClassNames;
numClasses = numel(classNames);
f = fullfile(image_folder, filenames(n).name);
our_images = imread(f);
I = imresize(our_images,inputSize(1:2));
[label,scores] = classify(net,I);
label
col{1,n} = sprintf(label, n);
end
I am using the following code, what it does is run each image and assign a label to it. What I am trying to do is save each label in the same array also to save me writing it all out on excel as they are a lot of photos. there is a problem with the final line as saying label is not suitable. When i type 'label' it just saves the word label in each array section. Anyone have any idea how to save each outputted label? An example of the output labels for one of the images = "Fridge". When i dont add the final line it just outputs all the labels in the command window. Thanks

Accepted Answer

Srivardhan Gadila
Srivardhan Gadila on 23 Mar 2021
Instead of using sprintf you can save the labels into a categorical array as follows:
image_folder = cd;
filenames = dir(fullfile(image_folder, '*.jpg'));
net = googlenet;
inputSize = net.Layers(1).InputSize;
classNames = net.Layers(end).ClassNames;
numClasses = numel(classNames);
total_images = numel(filenames);
labels = categorical.empty(total_images,0);
for n = 1:total_images
f = fullfile(image_folder, filenames(n).name);
our_images = imread(f);
I = imresize(our_images,inputSize(1:2));
[label,scores] = classify(net,I);
label
labels(n,1) = label;
end
Based on the use case the categorical array labels can be converted to string array as follows:
labelsStr = string(labels)
Alternatively you can make use of imageDatastore, augmentedImageDatastore and avoid the for loop and use YPred = classify(net,ds) function to get the predictions directly using the datastore.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!