这个例子是利用已经学习好的Alexnet 对摄像头中图像进行实时识别
Step1.
加载网络以及网络摄像头, 由于没有网络摄像头暂时用笔记本上摄像头代替
camera = webcam;
net = alexnet;
Step 2.
拍照并识别
inputSize = net.Layers(1).InputSize(1:2)
figure
im = snapshot(camera);
image(im)
im = imresize(im,inputSize);
[label,score] = classify(net,im);
title({char(label),num2str(max(score),2)});
效果如下
可能由于像素等原因,识别的结果有些偏差
Step3
连续识别,让摄像头一直连续拍照并识别,并显示识别概率靠前的5个的概率值
classNames = net.Layers(end).ClassNames;
h = figure;
h.Position(3) = 2*h.Position(3);
ax1 = subplot(1,2,1);
ax2 = subplot(1,2,2);
ax2.ActivePositionProperty = 'position';
keepRolling = true;
set(gcf,'CloseRequestFcn','keepRolling = false; closereq');
while keepRolling
% Display and classify the image
im = snapshot(camera);
image(ax1,im)
im = imresize(im,inputSize);
[label,score] = classify(net,im);
title(ax1,{char(label),num2str(max(score),2)});
% Select the top five predictions
[~,idx] = sort(score,'descend');
idx = idx(5:-1:1);
scoreTop = score(idx);
classNamesTop = classNames(idx);
% Plot the histogram
barh(ax2,scoreTop)
title(ax2,'Top 5')
xlabel(ax2,'Probability')
xlim(ax2,[0 1])
yticklabels(ax2,classNamesTop)
ax2.YAxisLocation = 'right';
drawnow
end
效果如下