版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
说明:此示例是加载已经训练好的googLeNet网络。
1. GoogLeNet网络介绍
此示例说明如何使用预训练的深度卷积神经网络 GoogLeNet 对图像进行分类。
GoogLeNet 已经对超过一百万个图像进行了训练,可以将图像分为 1000 个对象类别(例如键盘、咖啡杯、铅笔和多种动物)。该网络已基于大量图像学习了丰富的特征表示。网络以图像作为输入,然后输出图像中对象的标签以及每个对象类别的概率。
完整代码示例:
-
clear
-
close all
-
clc
-
% Access the trained model
-
net = googlenet;
-
% See details
of the architecture
-
net.Layers
-
%
Read the image
to classify
-
I = imread(
'peppers.png');
-
% Adjust size
of the image
-
sz = net.Layers(
1).InputSize
-
I = I(
1:sz(
1),
1:sz(
2),
1:sz(
3));
-
% Classify the image using GoogLeNet
-
label = classify(net, I)
-
% Show the image
and the classification results
-
figure
-
imshow(I)
-
text(
10,
20,char(
label),
'Color',
'white')
一般情况下,在第5行会出现报错,那是因为我们需要下载和安装GoogLeNet Network模块,在报错的红字中有安装的路径(Add-On-Explorer),只需要点击进去登陆便可以下载此模块:
代码运行结果:
完美识别了此张图片为辣椒.
官方help示例;
-
clear
-
close all
-
clc
-
%% 加载预训练网络
-
net = googlenet;
-
-
inputSize = net.Layers(
1).InputSize
-
-
classNames = net.Layers(end).ClassNames;
-
numClasses = numel(classNames);
-
disp(classNames(randperm(numClasses,
10)))
-
-
%% 读取图像并调整图像大小
-
I = imread(
'peppers.png');
-
figure
-
imshow(I)
-
-
size(I)
-
-
I = imresize(I,inputSize(
1:
2));
-
figure
-
imshow(I)
-
-
%% 对图像进行分类
-
[label,scores] = classify(net,I);
-
label
-
-
figure
-
imshow(I)
-
title(string(label) + ", " + num2str(100*scores(classNames == label),3) + "%");
-
-
%% 显示排名靠前的预测值
-
[
~,idx] = sort(scores,
'descend');
-
idx = idx(
5:
-1:
1);
-
classNamesTop = net.Layers(end).ClassNames(idx);
-
scoresTop = scores(idx);
-
-
figure
-
barh(
scoresTop)
-
xlim(
[0 1])
-
title(
'Top 5 Predictions')
-
xlabel(
'Probability')
-
yticklabels(
classNamesTop)