%% Predict Using Imported ONNX Function
% Import an ONNX network as a function, and use the pretrained network to predict the class label of an input image.
%
% Specify the file to import as shufflenet with operator set 9 from the ONNX Model Zoo. shufflenet is a convolutional neural network that is trained on more than a million images from the ImageNet database. As a result, the network has learned rich feature representations for a wide range of images. The network can classify images into 1000 object categories, such as keyboard, mouse, pencil, and many animals.

modelfile = 'shufflenet-9.onnx';

%
% Import the pretrained ONNX network as a function by using importONNXFunction, which returns an ONNXParamaters object that contains the network parameters. The function also creates a new model function in the current folder that contains the network architecture. Specify the name of the model function as shufflenetFcn.

params = importONNXFunction(modelfile,'shufflenetFcn');

%
% Read the image you want to classify and display the size of the image. The image is 792-by-1056 pixels and has three color channels (RGB).

I = imread('peacock.jpg');
size(I)

% Resize the image to the input size of the network. Show the image.

I = imresize(I,[224 224]);
imshow(I)

% The inputs to shufflenet require further preprocessing (for more details, see ShuffleNet in ONNX Model Zoo). Rescale the image. Normalize the image by subtracting the training images mean and dividing by the training images standard deviation.

I = rescale(I,0,1);

meanIm = [0.485 0.456 0.406];
stdIm = [0.229 0.224 0.225];
I = (I - reshape(meanIm,[1 1 3]))./reshape(stdIm,[1 1 3]);

imshow(I)

%
% Import the class names from squeezenet, which is also trained with images from the ImageNet database.

net = squeezenet;
ClassNames = net.Layers(end).ClassNames;

%
% Calculate the class probabilities by specifying the image to classify I and the ONNXParameters object params as input arguments to the model function shufflenetFcn.

scores = shufflenetFcn(I,params);

% Find the class index with the highest probability. Display the predicted class for the input image and the corresponding classification score.

indMax = find(scores==max(scores));
ClassNames(indMax)
scoreMax = scores(indMax)

% Copyright 2020 The MathWorks, Inc.