目标检测就是找出图像中所感兴趣的物体,并确定它们的种类和位置。传统的目标检测方法以特征提取和匹配为核心,存在时间复杂度较高,特征提取鲁棒性较差等缺点。
本文在Alexnet网络模型的基础上,基于迁移学习原理,来训练R-CNN目标检测网络。并对Matlab自带的stop sign(停止标志)图像数据集进行识别,该数据集已标注好。其实现步骤如下:
步骤一:导入Alexnet预训练的模型(需要提前下载好, 可参考https://blog.youkuaiyun.com/shitao99/article/details/106536156)。实现代码如下:
%% 步骤1:载入AlexNet
% net=alexnet;
net =load('alexnet.mat');
net =net.netTransfer;
步骤二:载入训练集图像,实现代码如下:
data = load('stopSignsAndCars.mat', 'stopSignsAndCars');
stopSignsAndCars = data.stopSignsAndCars;
% 设置图像路径参数
visiondata = fullfile(toolboxdir('vision'),'visiondata');
stopSignsAndCars.imageFilename = fullfile(visiondata, stopSignsAndCars.imageFilename);
% 显示数据
summary(stopSignsAndCars)
% 只保留文件名及其所包含的“stop sign”区域
stopSigns = stopSignsAndCars(:, {'imageFilename','stopSign'});
步骤三:设置训练参数,并基于迁移学习原理,在Alexnet卷积神经网络基础上,通过41幅包括stop sign的图像训练R-CNN检测器。实现代码如下:
% 设置训练策略
options = trainingOptions('sgdm', ...
'MiniBatchSize', 128, ...
'InitialLearnRate', 1e-3, ...
'LearnRateSchedule', 'piecewise', ...
'LearnRateDropFactor', 0.1, ...
'LearnRateDropPeriod', 100, ...
'MaxEpochs', 2, ...
'Plots','training-progress', ...
'Verbose', true);
% 训练网络.
rcnn = trainRCNNObjectDetector(stopSigns, net, options, ...
'NegativeOverlapRange', [0 0.3], 'PositiveOverlapRange',[0.5 1])
步骤四:使用测试图像检验训练好的目标检测器对stop sign图像的检测效果,在原图上标记目标区域并显示类别和置信度。实现代码如下:
% 载入测试图片
testImage = imread('stopSignTest.jpg');
% 检测“stop sign“标志
[bboxes,score,label] = detect(rcnn,testImage,'MiniBatchSize',128)
% 计算置信度并显示
[score, idx] = max(score);
bbox = bboxes(idx, :);
annotation = sprintf('%s: (Confidence = %f)', label(idx), score);
outputImage = insertObjectAnnotation(testImage, 'rectangle', bbox, annotation);
figure
imshow(outputImage)
以上就是matlab实现R-CNN目标检测的全部代码,供大家参考学习。如果有不懂的小伙伴儿,欢迎评论留言或者私信,代码订制也可私信博主(Q:809315756)。