classify images in matlab

To classify images in MATLAB, one option is to use a trained neural network. Here are the general steps:

  1. Import the image dataset and split the images into training, validation, and testing sets.
main.m
imds = imageDatastore('path_to_image_folder');
[imdsTrain,imdsValidation,imdsTest] = splitEachLabel(imds,0.7,0.15,0.15,'randomized');
134 chars
3 lines
  1. Define the layers of the neural network using the Deep Learning Toolbox.
main.m
layers = [
    imageInputLayer([32 32 3])
    convolution2dLayer(3,32,'Padding','same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2,'Stride',2)
    convolution2dLayer(3,64,'Padding','same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2,'Stride',2)
    convolution2dLayer(3,128,'Padding','same')
    batchNormalizationLayer
    reluLayer
    maxPooling2dLayer(2,'Stride',2)
    fullyConnectedLayer(10)
    softmaxLayer
    classificationLayer];
486 chars
18 lines
  1. Train the neural network using the training set and the validation set.
main.m
options = trainingOptions('adam', ...
    'MaxEpochs',20, ...
    'MiniBatchSize',128, ...
    'ValidationData',imdsValidation, ...
    'ValidationFrequency',30, ...
    'Plots','training-progress');
net = trainNetwork(imdsTrain,layers,options);
246 chars
8 lines
  1. Classify the images in the testing set using the trained neural network.
main.m
YPred = classify(net,imdsTest);
YTest = imdsTest.Labels;
accuracy = sum(YPred == YTest)/numel(YTest);
102 chars
4 lines

Note that this is just one example. Depending on your specific problem, you may need to adjust the layers and training options.

gistlibby LogSnag