主要内容

使用YOLO V3深度学习的对象检测的代码

这个例子展示了如何生成CUDA®MEX一个你只看一次(YOLO) v3对象检测器与自定义层。YOLO v3在YOLO v2的基础上进行了改进,增加了多尺度的检测,帮助检测更小的对象。此外,将用于训练的损失函数分离为边界盒回归的均方误差和用于目标分类的二叉交叉熵,有助于提高检测精度。本例中使用的YOLO v3网络是从物体检测使用YOLO V3深度学习示例在计算机视觉工具箱(TM)。有关更多信息,请参阅物体检测使用YOLO V3深度学习(电脑视觉工具箱)

第三方的先决条件

要求

  • CUDA使NVIDIA®GPU和兼容的驱动程序启用。

可选

对于非mex构建,如静态、动态库或可执行文件,本例有以下附加要求。

验证GPU环境

要验证编译器和运行此示例的库是否正确设置,请使用coder.checkGpuInstall功能。

envcfg = coder.gpuenvconfig(“主机”);envCfg.DeepLibTarget =“cudnn”;envCfg。DeepCodegen = 1;envCfg。安静= 1;coder.checkGpuInstall (envCfg);

YOLO V3网络

此示例中的YOLO V3网络是基于挤压(深度学习工具箱),并且使用在SqueezeNet特征提取网络与另外的两个检测头在末端。第二探测头是第一检测头大小的两倍,因此它能够更好地检测小的物体。注意,可以基于对象的大小来指定任意数量的不同尺寸的检测头被检测到。利用训练数据估计的YOLO v3网络使用锚箱具有对应于数据集的类型更好的初始先验,并帮助网络学会准确地预测框。有关锚箱信息,请参阅用于物体检测的锚盒(电脑视觉工具箱)

在此示例中的YOLO V3网络示于下图中。

每个检测头预测的边界框的坐标(X,Y,宽度,高度),物体的信心,和类的概率针对各锚箱掩模。因此,对于每个检测头,输出滤波器的过去卷积层的数目是锚箱掩模乘以每锚箱预测元素的数目的数目。该检测头包括所述网络的输出层。

预训练YOLO v3网络

下载YOLO v3网络。

filename = matlab.internal.examples.download万博1manbetxsupportfile('愿景/数据/''yolov3SqueezeNetVehicleExample_21a.zip');解压缩(文件名);

使用该示例中使用的YOLO V3网络使用中描述的步骤训练物体检测使用YOLO V3深度学习(电脑视觉工具箱)

matfile ='yolov3squeezenetvehicleexample_21a.mat';预制=负载(matfile);net = pretray.net;

YOLO V3网络使用resize2dlayer.(图像处理工具箱)通过被实现为支持代码生成定制层通过2. resize2DLayer缩放因子复制所述相邻像素值来调整2-d的输入图像。万博1manbetx有关更多信息,请参阅定义代码生成的自定义深度学习层(深度学习工具箱)

注意:您还可以通过用于YOLO V3对象检测支持包的计算机VISION TOOLBOX™型号使用预磨损的探测器网络。万博1manbetx

要使用这个预先训练过的网络,您必须首先从附加资源管理器中安装用于YOLO v3对象检测的计算机视觉工具箱模型。有关安装附加组件的详细信息,请参见获取和管理附加组件

然后,从中保存网络yolov3ObjectDetector对象到Mat文件并继续。例如,

探测器= yolov3objectdetector('Darknet53-Coco');网= detector.Network;matfile ='pretrowsyolov3detectormat';保存(matFile,“净”);

yolov3Detect入口点函数

yolov3Detect入口点函数取输入图像并将其传递给经过训练的网络进行预测Yolov3预期功能。当Yolov3预期函数将网络对象从MAT文件加载到持久变量中,并重用持久对象以获取后续预测调用。具体地,该函数使用dlnetwork.(深度学习工具箱)在经训练的网络的表示物体检测使用YOLO V3深度学习(电脑视觉工具箱)的例子。从YOLO v3网格单元坐标得到的预测Yolov3预期然后使用支持函数将调用转换为边界框坐标万博1manbetxGenerateTileDanchors.ApplyAnchorBoxOffsets.

键入('yolov3detect.m'
函数[Bboxes,Scores,LabelsIndex] = Yolov3Detect(Matfile,IM,... NetworkInputSize,NetworkOutputs,ConcidenceThreshold,...重叠,类)%Yolov3Detect函数检测图像中的边界框,分数和%LabelSindex。%#codegen%copyright 2020-2021 Mathworks,Inc. %%预处理数据%此示例将所有预处理变换应用于在培训期间应用的数据集中的数据集,但数据增强除外。由于示例性%使用预先磨碎的YOLO V3网络,因此输入数据必须是原始数据的代表性%,并且未经修改以进行无偏的评估。%特别是以下预处理操作应用于%输入数据。%1.将图像调整为网络输入大小,因为图像比NetworkInputSize大。2.缩放范围[0 1]的图像像素。3.将调整大小和重新定义的图像转换为Dlarray对象。IM = DLARRAY(PreprocessData(IM,NetworkInputSize),“SSCB”);图像=尺寸(IM,[1,2]);%%定义锚框%指定基于培训YOLO V3网络时使用的预处理%训练数据估计的锚盒。 These anchor box % values are same as mentioned in "Object Detection Using YOLO v3 Deep % Learning" example. For details on estimating anchor boxes, see "Anchor % Boxes for Object Detection". anchors = [ 41 34; 163 130; 98 93; 144 125; 33 24; 69 66]; % Specify anchorBoxMasks to select anchor boxes to use in both the % detection heads of the YOLO v3 network. anchorBoxMasks is a cell array of % size M-by-1, where M denotes the number of detection heads. Each % detection head consists of a 1-by-N array of row index of anchors in % anchorBoxes, where N is the number of anchor boxes to use. Select anchor % boxes for each detection head based on size-use larger anchor boxes at % lower scale and smaller anchor boxes at higher scale. To do so, sort the % anchor boxes with the larger anchor boxes first and assign the first % three to the first detection head and the next three to the second % detection head. area = anchors(:, 1).*anchors(:, 2); [~, idx] = sort(area, 'descend'); anchors = anchors(idx, :); anchorBoxMasks = {[1,2,3],[4,5,6]}; %% Predict on Yolov3 % Predict and filter the detections based on confidence threshold. predictions = yolov3Predict(matFile,im,networkOutputs,anchorBoxMasks); %% Generate Detections % indices corresponding to x,y,w,h predictions for bounding boxes anchorIndex = 2:5; tiledAnchors = generateTiledAnchors(predictions,anchors,anchorBoxMasks,... anchorIndex); predictions = applyAnchorBoxOffsets(tiledAnchors, predictions,... networkInputSize, anchorIndex); [bboxes,scores,labelsIndex] = generateYOLOv3DetectionsForCodegen(predictions,... confidenceThreshold, overlapThreshold, imageSize, classes); end function YPredCell = yolov3Predict(matFile,im,networkOutputs,anchorBoxMask) % Predict the output of network and extract the confidence, x, y, % width, height, and class. % load the deep learning network for prediction persistent net; if isempty(net) net = coder.loadDeepLearningNetwork(matFile); end YPredictions = cell(coder.const(networkOutputs), 1); [YPredictions{:}] = predict(net, im); YPredCell = extractPredictions(YPredictions, anchorBoxMask); % Apply activation to the predicted cell array. YPredCell = applyActivations(YPredCell); end

评估对象检测的入口点函数

按照以下步骤从测试数据中评估图像上的入口点函数。

  • 指定置信度阈值如0.5只保留检测与置信度得分高于此值。

  • 将重叠阈值指定为0.5以消除重叠检测。

  • 从输入数据读取图像。

  • 使用入口点功能yolov3Detect获得预测的边框,信心分数,和类的标签。

  • 显示图像与边界框和信心分数。

定义所需的阈值。

ConcidenceThreshold = 0.5;重叠= 0.5;

指定训练网络的网络输入大小和网络输出数量。

NetworkInputSize = [227 227 3];NetworkOutputs = numel(net.outputnames);

从标记数据集中读取示例图像数据物体检测使用YOLO V3深度学习(电脑视觉工具箱)的例子。此图像包含类型车辆对象的一个​​实例。

我= imread('LastImage.jpg');

指定类名。

一会= {“汽车”};

在YOLO v3网络上调用检测方法并显示结果。

[bboxes,分数,labelsIndex] = yolov3Detect(matFile,I,......networkInputSize,networkOutputs,confidenceThreshold,overlapThreshold,类名);标签= ClassNames(LabelsIndex);%显示的图像上的检测ianotated = InsertObjectAnnotation(I,'矩形'、bboxes strcat(标签,{' - '}, num2str(分数)));图imshow (IAnnotated)

生成CUDA MEX

生成CUDA®代码yolov3Detect为MEX目标创建一个GPU代码配置对象,并将目标语言设置为c++。使用编码器。DeepLearningConfig函数创建一个CuDNN深度学习的配置对象,并将其分配给DeepLearningConfig图形处理器代码配置对象的属性。

cfg = coder.gpuconfig('MEX');cfg.targetlang =.'c ++';cfg.deeplearningconfig = coder.deeplearningconfig(targetlibrary =“cudnn”);args = {coder.constant(matfile),i,coder.constant(networkinputsize),......编码器.Constant(NetworkOutputs),ConcidenceThreshold,......overlapThreshold,类名};Codegen.-Config.CFG.yolov3Detect-  args.args.报告
代码生成成功:查看报告

为了产生TensorRT目标创建和使用TensorRT深学习的配置对象,而不是CuDNN配置对象的代码CUDA®。类似地,为了产生用于MKLDNN目标代码,创建一个CPU代码配置对象,并使用MKLDNN深学习配置对象作为其DeepLearningConfig财产。

运行生成的mex

用相同的图像输入拨打生成的CUDA MEX如前所述并显示结果。

[bboxes,scores,labelsindex] = yolov3detect_mex(matfile,我,......networkInputSize,networkOutputs,confidenceThreshold,......重叠,C​​lassNames);标签= ClassNames(LabelsIndex);图;ianotated = InsertObjectAnnotation(I,'矩形'、bboxes strcat(标签,{' - '}, num2str(分数)));imshow (IAnnotated);

实用功能

下面列出的实用程序函数是基于物体检测使用YOLO V3深度学习(电脑视觉工具箱)示例并修改以使实用程序函数适合于代码生成。

键入(“applyActivations.m”
函数ypredcell = applyactivations(ypredcell)%#codegen%copyright 2020-2021 Mathworks,Inc. numcells = size(ypredcell,1);对于ICELL = 1:Numcell用于IDX = 1:3 YPRedCell {icell,Idx} = SigMoidactivation(YpredCell {icell,Idx});icell终端= 1:numcell for idx = 4:5 ypredcell {icell,idx} = exp(ypredcell {icell,idx});iCell末端= 1:Numcells Ypredcell {icell,6} =唾液变性(Ypredcell {icell,6});结束功能OUT = SigMoidactivation(x)Out = 1./ (1 + exp(毒奏));结束
键入('aselletpredictions.m'
函数预测= extractPredictions(YPredictions,anchorBoxMask)%#代码生成%版权所有2020年至2021年MathWorks公司numPredictionHeads =尺寸(YPredictions,1);预测=细胞(numPredictionHeads,6);为II = 1:numPredictionHeads%获取有关特征尺寸所需要的信息。numChannelsPred =尺寸(YPredictions {二},3);numAnchors =尺寸(anchorBoxMask {II},2);numPredElemsPerAnchors = numChannelsPred / numAnchors;allIds =(1:numChannelsPred);跨度= numPredElemsPerAnchors;endIdx = numChannelsPred;YPredictionsData = ExtractData由(YPredictions {II}); % X positions. startIdx = 1; predictions{ii,2} = YPredictionsData(:,:,startIdx:stride:endIdx,:); xIds = startIdx:stride:endIdx; % Y positions. startIdx = 2; predictions{ii,3} = YPredictionsData(:,:,startIdx:stride:endIdx,:); yIds = startIdx:stride:endIdx; % Width. startIdx = 3; predictions{ii,4} = YPredictionsData(:,:,startIdx:stride:endIdx,:); wIds = startIdx:stride:endIdx; % Height. startIdx = 4; predictions{ii,5} = YPredictionsData(:,:,startIdx:stride:endIdx,:); hIds = startIdx:stride:endIdx; % Confidence scores. startIdx = 5; predictions{ii,1} = YPredictionsData(:,:,startIdx:stride:endIdx,:); confIds = startIdx:stride:endIdx; % Accumulate all the non-class indexes nonClassIds = [xIds yIds wIds hIds confIds]; % Class probabilities. % Get the indexes which do not belong to the nonClassIds classIdx = setdiff(allIds, nonClassIds, 'stable'); predictions{ii,6} = YPredictionsData(:,:,classIdx,:); end end
键入(“generateTiledAnchors.m”
函数tiledanchors = generateTiledanchors(ypredcell,anchorboxes,... anchorboxmask,anchorIndex)%生成瓷砖锚偏移,用于将预测转换为从yolo%V3网格单元坐标转换为边界框坐标%#codegen%2020-2021 MathWorks,Inc。numpredictionheads = size(ypredcell,1);Tiledanchors = Cell(NumPredictionHeads,尺寸(锚定指示,2));对于i = 1:numpredictionheads anchors =锚箱(anchorboxmask {i},:);[h,w,〜,n] =大小(ypredcell {i,1});[Tiledanchors {i,2},倾斜者{i,1}] = ndgrid(0:h-1,0:w-1,... 1:尺寸(锚,1),1:n);[〜,〜,Tiledanchors {i,3}] = ndgrid(0:h-1,0:w-1,锚(:,2),1:n);[〜,〜,Tiledanchors {i,4}] = ndgrid(0:h-1,0:w-1,锚(:,1),1:n);结束
键入(“applyAnchorBoxOffsets.m”
函数ypredcell = applyanchorboxoffsets(tiledanchors,ypredcell,... InputImagesize,anchorIndex)%#codegen%从yolo v3网格小区的预测转换为%边界框坐标%2020-2021 Mathworks,Inc。对于i = 1:尺寸(ypredcell,1)[h,w,〜,〜] =大小(ypredcell {i,1});ypredcell {i,anchorIndex(1)} =(蒂尔美女{i,1} + ... ypredcell {i,anchorindex(1)})./ w;ypredcell {i,anchorIndex(2)} =(蒂尔美女{i,2} + ... ypredcell {i,anchorindex(2)})./ h;ypredcell {i,anchorIndex(3)} =(蒂尔美女{i,3}。* ... ypredcell {i,anchorIndex(3)})./ InputImagesize(2);ypredcell {i,anchorIndex(4)} =(蒂尔美女{i,4}。* ... ypredcell {i,anchorindex(4)})./ingimagesize(1);结束
键入('preprocessData.m'
函数映像=预处理数据(图像,targetsize)%调整图像大小并将像素缩放到0到1.%#codegen%copyright 2020-2021 mathworks,Inc.Inmgsize = size(图像);%使用单通道转换输入图像到3个通道。如果numel(Imgsize)<1图像= Repmat(图像,1,1,3);结束图像= IM2Single(Rescale(图像));image = iLetterBoxImage(图像,编码器.Const(targetsize(1:2)));End函数Inew = iLetterBoxImage(I,Targencsize)%LeterBoxImage通过保留输入图像I的宽度和高度%宽高比来返回调整大小的图像。“TargetSize”是一个由目标维度的1×2向量组成的1.Y×2矢量。%%输入I可以是UINT8,UINT16,INT16,DOUBLE,SINGLE或LOGICAL,并且必须%是真实的和非稀疏。[ICOL,ICOL,ICH通道] =尺寸(i);%计算宽高比。ARI = IROW./ICOL; % Preserve the maximum dimension based on the aspect ratio. if arI<1 IcolFin = targetSize(1,2); IrowFin = floor(IcolFin.*arI); else IrowFin = targetSize(1,1); IcolFin = floor(IrowFin./arI); end % Resize the input image. Itmp = imresize(I,[IrowFin,IcolFin]); % Initialize Inew with gray values. Inew = ones([targetSize,Ichannels],'like',I).*0.5; % Compute the offset. if arI<1 buff = targetSize(1,1)-IrowFin; else buff = targetSize(1,2)-IcolFin; end % Place the resized image on the canvas image. if (buff==0) Inew = Itmp; else buffVal = floor(buff/2); if arI<1 Inew(buffVal:buffVal+IrowFin-1,:,:) = Itmp; else Inew(:,buffVal:buffVal+IcolFin-1,:) = Itmp; end end end

参考文献

1. Redmon,Joseph和Ali Farhadi。“yolov3:增量改善。”预印刷品,2018年4月8日提交。https://arxiv.org/abs/1804.02767。

另请参阅

功能

对象

相关例子

更多关于