主要内容

代码生成对象检测使用YOLO v3意思深入学习

这个例子展示了如何生成CUDA®墨西哥人对你只看一次(YOLO)意思v3对象探测器使用自定义层。YOLO v3改善在YOLO v2意思意思通过添加检测在多个尺度来帮助检测更小的物体。此外,损失函数用于培训分为均方误差为对象边界框回归和二叉分类来帮助提高检测精度。YOLO v3意思网络本例中使用的训练对象检测使用YOLO v3意思深入学习在计算机视觉的工具箱(TM)。有关更多信息,请参见对象检测使用YOLO v3意思深入学习(计算机视觉工具箱)

第三方的先决条件

要求

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

可选

等non-MEX构建静态、动态库或可执行文件,这个例子有以下额外的需求。

验证GPU环境

验证编译器和库设置正确,运行这个示例使用coder.checkGpuInstall(GPU编码器)函数。

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

YOLO v3意思网络

YOLO v3意思网络在这个例子中是基于squeezenet,并使用在SqueezeNet特征提取网络的两个检测头。第二个检测头是第一个检测头大小的两倍,所以能更好地检测小物体。注意,任何数量的检测头可以指定大小不同的基于对象的大小被检测出来。YOLO v3网络使用锚箱意思估计使用训练数据有更好的初始先验对应数据集的类型和帮助网络学习预测准确的箱子。关于锚箱信息,看到锚箱对象检测(计算机视觉工具箱)

YOLO v3意思网络在这个例子见下图。

每个探测头预测边界框坐标(x, y,宽度、高度),对象的信心和类概率相应的锚箱面具。因此,对于每一个检测头,最后的输出滤波器卷积层是锚箱面具的数量乘以预测元素的数量每锚盒子。检测网络的输出层组成。

Pretrained YOLO v3意思网络

下面的例子使用了yolov3SqueezeNetVehicleExample_21a.zip文件包含pretrained YOLO v3意思网络。这个文件是大约9 mb大小。从MathWorks网站下载该文件,然后解压文件。

文件名= matlab.internal.examples.downloadSuppor金宝apptFile (“视觉/数据/”,“yolov3SqueezeNetVehicleExample_21a.zip”);解压缩(文件名);

YOLO v3意思网络在这个例子中被训练使用中描述的步骤对象检测使用YOLO v3意思深入学习(计算机视觉工具箱)

matFile =“yolov3SqueezeNetVehicleExample_21a.mat”;pretrained =负载(matFile);网= pretrained.net;

YOLO v3网络使用一个意思resize2dLayer(图像处理工具箱)调整的二维输入图像复制的相邻像素值2的比例因子。resize2DLayer被实现为一个自定义层支持代码生成。金宝app有关更多信息,请参见定义定制的深度学习层代码生成

注意:您还可以使用pretrained探测器通过计算机视觉网络十分感激工具箱YOLO v3意思™模型对象检测支持包。金宝app

使用这个pretrained网络,您必须首先安装的计算机视觉工具箱模型YOLO v3意思扩展浏览器的目标检测。关于安装插件的更多信息,请参阅获取和管理插件

然后,保存的网络yolov3ObjectDetector对象MAT-file和继续。例如,

探测器= yolov3ObjectDetector (“darknet53-coco”);网= detector.Network;matFile =“pretrainedYOLOv3Detector.mat”;保存(matFile,“净”);

yolov3Detect入口点函数

yolov3Detect入口点函数接受一个输入图像并将其传递到一个训练有素的网络预测通过yolov3Predict函数。的yolov3Predict函数将从MAT-file网络对象加载到一个持续的后续预测变量和重用持久对象调用。具体地说,函数使用dlnetwork网络训练的代表对象检测使用YOLO v3意思深入学习(计算机视觉工具箱)的例子。的预测YOLO v3网格单元坐标得到的意思yolov3Predict然后调用转换边界框坐标通过使用支持功能金宝appgenerateTiledAnchorsapplyAnchorBoxOffsets

类型(“yolov3Detect.m”)
函数[bboxes,分数,labelsIndex] = yolov3Detect (matFile, im,…networkInputSize、networkOutputs confidenceThreshold,……overlapThreshold类)% yolov3Detect函数检测边界框,分数,和% labelsIndex在一个图像。% # codegen % 2020 - 2021版权MathWorks, Inc . % % %预处理数据这个例子中所有的预处理变换适用于数据集%应用培训期间,除了数据增大。因为示例%使用pretrained YOLO v3意思网络,输入数据必须代表%的原始数据和修改的公正的评价。%专门应用于%以下预处理操作输入数据。% 1。调整网络输入的图像大小,图像%比networkInputSize。2。规模的图像像素在% [0 1]。 3. Convert the resized and rescaled image to a dlarray object. im = dlarray(preprocessData(im, networkInputSize), "SSCB"); imageSize = size(im,[1,2]); %% Define Anchor Boxes % Specify the anchor boxes estimated on the basis of the preprocessed % training data used when training the YOLO v3 network. 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分数预测边界框,信心,和类标签。

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

定义所需的阈值。

confidenceThreshold = 0.5;overlapThreshold = 0.5;

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

networkInputSize = (227 227 3);networkOutputs =元素个数(net.OutputNames);

阅读示例图像数据获得的标签数据集对象检测使用YOLO v3意思深入学习(计算机视觉工具箱)的例子。这张照片包含一个车辆类型的对象的一个实例。

我= imread (“vehicleImage.jpg”);

指定类名。

一会= {“汽车”};

网络上YOLO v3意思调用检测方法和显示结果。

[bboxes,分数,labelsIndex] = yolov3Detect (matFile,我,networkInputSize、networkOutputs confidenceThreshold overlapThreshold,类名);标签=一会(labelsIndex);%显示图像的检测IAnnotated = insertObjectAnnotation(我“矩形”、bboxes strcat(标签,{“- - -”},num2str(分数)));图imshow (IAnnotated)

生成CUDA墨西哥人

生成CUDA®代码yolov3Detect入口点函数,创建一个GPU代码配置对象为一个墨西哥人的目标和目标语言设置为c++。使用coder.DeepLearningConfig(GPU编码器)函数创建一个CuDNN深度学习配置对象,并将其分配给DeepLearningConfigGPU代码配置对象的属性。

cfg = coder.gpuConfig (墨西哥人的);cfg。TargetLang =“c++”;cfg。DeepLearningConfig = coder.DeepLearningConfig (TargetLibrary =“cudnn”);args = {coder.Constant (matFile),我,coder.Constant (networkInputSize),confidenceThreshold coder.Constant (networkOutputs),overlapThreshold,一会};codegen配置cfgyolov3Detectarg游戏arg游戏报告
代码生成成功:查看报告

生成CUDA®代码TensorRT目标创建和使用一个TensorRT深度学习配置对象而不是CuDNN配置对象。同样,为MKLDNN目标生成代码,创建一个CPU配置对象代码和使用MKLDNN深度学习配置对象的DeepLearningConfig财产。

运行生成的墨西哥人

调用生成的CUDA墨西哥人使用相同的输入图像像以前一样和显示结果。

[bboxes,分数,labelsIndex] = yolov3Detect_mex (matFile,我,networkInputSize、networkOutputs confidenceThreshold,overlapThreshold,类名);标签=一会(labelsIndex);图;IAnnotated = insertObjectAnnotation(我“矩形”、bboxes strcat(标签,{“- - -”},num2str(分数)));imshow (IAnnotated);

效用函数

下面列出的utillity函数是基于使用的对象检测使用YOLO v3意思深入学习(计算机视觉工具箱)例子和修改的效用函数适用于代码生成。

类型(“applyActivations.m”)
函数YPredCell = applyActivations (YPredCell) % # codegen % 2020 - 2021版权MathWorks, inc . numCells =大小(YPredCell, 1);iCell = 1: numCells idx = 1:3 YPredCell {iCell, idx} = sigmoidActivation (YPredCell {iCell, idx});结束结束iCell = 1: numCells idx = 4:5 YPredCell {iCell, idx} = exp (YPredCell {iCell, idx});结束结束iCell = 1: numCells YPredCell {iCell 6} = sigmoidActivation (YPredCell {iCell 6});结束结束函数= sigmoidActivation (x) = 1. / (1 + exp (- x));结束
类型(“extractPredictions.m”)
函数预测= extractPredictions (YPredictions anchorBoxMask) % # codegen % 2020 - 2021版权MathWorks, inc . numPredictionHeads =大小(YPredictions, 1);预测=细胞(numPredictionHeads 6);2 = 1:numPredictionHeads %在特征尺寸得到所需的信息。numChannelsPred =大小(YPredictions {2}, 3);numAnchors =大小(anchorBoxMask {2}, 2);numPredElemsPerAnchors = numChannelsPred / numAnchors;allIds = (1: numChannelsPred);步= numPredElemsPerAnchors;endIdx = numChannelsPred;YPredictionsData = extractdata (YPredictions {2}); % 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 =大小(YPredCell, 1);tiledAnchors =细胞(numPredictionHeads、大小(anchorIndex 2));i = 1: numPredictionHeads锚= anchorBoxes (anchorBoxMask我}{:);[h, w ~ n] =大小(YPredCell{我1});[tiledAnchors{2},我tiledAnchors{1}我]= ndgrid (h - 0: 0: w1,…1:尺寸(锚,1),1:n);[~,~,tiledAnchors{我3}]= ndgrid (h - 0: 0: w1,锚(:,2),1:n);[~,~,tiledAnchors{我4}]= ndgrid (h - 0: 0: w1,锚(: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{我1});YPredCell{我anchorIndex (1)} = (tiledAnchors{1}我+……YPredCell{我anchorIndex (1)})。/ w;YPredCell{我anchorIndex (2)} = (tiledAnchors{我2}+……YPredCell{我anchorIndex (2)}) / h;YPredCell{我anchorIndex (3)} = (tiledAnchors{3}我。*……YPredCell{我anchorIndex (3)})。/ inputImageSize (2);YPredCell{我anchorIndex (4)} = (tiledAnchors{4}我。*……YPredCell{我anchorIndex (4)})。/ inputImageSize (1); end end
类型(“preprocessData.m”)
函数图像= preprocessData(形象,targetSize) %改变图像的大小和规模在0和1之间的像素。% # codegen % 2020 - 2021版权,MathWorks公司imgSize =大小(图片);%与单通道输入图像转换为3频道。如果元素个数(imgSize) < 1 = repmat图像(图像,1,1,3);终端形象= im2single(重新调节(图片);形象= iLetterBoxImage(形象,coder.const (targetSize (1:2)));结束函数Inew = iLetterBoxImage(我targetSize) % LetterBoxImage返回一个缩放图像保存输入图像的宽度和高度%纵横比。“targetSize”是一个1×2向量组成%目标维度。% %输入我可以uint8、uint16 int16,翻倍,单身,或逻辑,%必须真实和non-sparse。[Irow, Icol Ichannels] =大小(我); % Compute aspect Ratio. 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,约瑟夫和阿里蒂。“YOLOv3:增量改进。“预印本,2018年4月8日提交。https://arxiv.org/abs/1804.02767。