这个例子展示了如何为一个使用深度学习的交通标志检测和识别应用程序生成CUDA®MEX代码。交通标志检测与识别是驾驶员辅助系统的重要应用,为驾驶员提供有关道路标志的信息。
在这个交通标志检测和识别示例中,您执行三个步骤-检测、非最大抑制(NMS)和识别。首先,该示例使用目标检测网络检测输入图像上的交通标志,该网络是YOLO网络的一种变体。然后,利用NMS算法抑制重叠检测。最后,识别网络对检测到的交通标志进行分类。
要求
本例生成CUDA MEX,并具有以下第三方需求。
CUDA®支持NVIDIA®GPU和兼容驱动程序。
可选
对于非mex构建,如静态、动态库或可执行文件,本例有以下附加要求。
英伟达工具包。
英伟达cuDNN图书馆。
编译器和库的环境变量。有关更多信息,请参见第三方硬件和设置前提产品下载188bet金宝搏.
使用coder.checkGpuInstall
函数来验证运行此示例所需的编译器和库是否正确设置。
envCfg = coder.gpuEnvConfig (“主机”);envCfg。DeepLibTarget =“cudnn”;envCfg。DeepCodegen = 1;envCfg。安静= 1;coder.checkGpuInstall (envCfg);
检测网络在Darknet框架中训练,并导入MATLAB®进行推理。由于交通标志相对于图像的大小较小,训练数据中每类的训练样本数量较少,所以将所有的交通标志作为一个单一的类来训练检测网络。
检测网络将输入图像划分为一个7 × 7的网格。如果交通标志的中心位于网格单元内,则每个网格单元检测交通标志。每个细胞预测两个边界框和这些边界框的置信度。置信度得分显示框中是否包含对象。每个单元预测在网格单元中找到交通标志的概率。最后的分数是前面分数的乘积。您可以对这个最终评分应用0.2的阈值来选择检测。
利用MATLAB对同一图像进行网络训练。
的trainRecognitionnet.m辅助脚本显示了识别网络的训练。
下载检测和识别网络。
getTsdr ();
检测网络由卷积层、ReLU泄漏层、全连接层等58层组成。
负载(“yolo_tsr.mat”);yolo
yolo = SeriesNetwork with properties: Layers: [58×1 nnet.cnn.layer.Layer] InputNames: {'input'} OutputNames: {'classoutput'}
若要查看网络架构,请使用analyzeNetwork
(深度学习工具箱)函数。
analyzeNetwork (yolo)的意思
该识别网络包含14层,包括卷积层、全连接层和分类输出层。
负载(“RecognitionNet.mat”);事先
connet = SeriesNetwork with properties: Layers: [14×1 net.cnn.layer. layer] InputNames: {'imageinput'} OutputNames: {'classoutput'}
tsdr_predict
入口点函数的tsdr_predict.m
入口点函数取图像输入,利用检测网络检测图像中的交通标志。该功能通过使用函数抑制重叠检测(NMS)selectStrongestBbox
并利用识别网络对交通标志进行识别。函数从yolo_tsr.mat
变成一个持久变量detectionnet和RecognitionNet.mat
变成一个持久变量recognitionnet.该函数在后续调用中重用持久对象。
类型(“tsdr_predict.m”)
函数[selectedBbox idx] = tsdr_predict (img) % # codegen %这个函数图像中检测交通标志使用检测网络%(修改版Yolo)意思和识别(分类)使用识别网络输入% %:% % im:输入测试图像% %输出:% % selectedBbox:检测边界框% idx:版权所有2017-2021 The MathWorks, Inc. coder.gpu.kernelfun;% resize图像img_rz = imresize(img,[448,448]);%转换为BGR格式img_rz = img_rz(:,:,3:-1:1);img_rz = im2single (img_rz);%% TSD持续检测网;if isempty(detectionnet) detectionnet = coder.loadDeepLearningNetwork('yolo_tsr.mat','Detection'); / /检测网络end predictions = detectionnet.activations(img_rz,56,'OutputAs','channels');%%将预测转换为边界框属性类= 1;num = 2; side = 7; thresh = 0.2; [h,w,~] = size(img); boxes = single(zeros(0,4)); probs = single(zeros(0,1)); for i = 0:(side*side)-1 for n = 0:num-1 p_index = side*side*classes + i*num + n + 1; scale = predictions(p_index); prob = zeros(1,classes+1); for j = 0:classes class_index = i*classes + 1; tempProb = scale*predictions(class_index+j); if tempProb > thresh row = floor(i / side); col = mod(i,side); box_index = side*side*(classes + num) + (i*num + n)*4 + 1; bxX = (predictions(box_index + 0) + col) / side; bxY = (predictions(box_index + 1) + row) / side; bxW = (predictions(box_index + 2)^2); bxH = (predictions(box_index + 3)^2); prob(j+1) = tempProb; probs = [probs;tempProb]; boxX = (bxX-bxW/2)*w+1; boxY = (bxY-bxH/2)*h+1; boxW = bxW*w; boxH = bxH*h; boxes = [boxes; boxX,boxY,boxW,boxH]; end end end end %% Run Non-Maximal Suppression on the detected bounding boxess coder.varsize('selectedBbox',[98, 4],[1 0]); [selectedBbox,~] = selectStrongestBbox(round(boxes),probs); %% Recognition persistent recognitionnet; if isempty(recognitionnet) recognitionnet = coder.loadDeepLearningNetwork('RecognitionNet.mat','Recognition'); end idx = zeros(size(selectedBbox,1),1); inpImg = coder.nullcopy(zeros(48,48,3,size(selectedBbox,1))); for i = 1:size(selectedBbox,1) ymin = selectedBbox(i,2); ymax = ymin+selectedBbox(i,4); xmin = selectedBbox(i,1); xmax = xmin+selectedBbox(i,3); % Resize Image inpImg(:,:,:,i) = imresize(img(ymin:ymax,xmin:xmax,:),[48,48]); end for i = 1:size(selectedBbox,1) output = recognitionnet.predict(inpImg(:,:,:,i)); [~,idx(i)]=max(output); end
tsdr_predict
函数为MEX目标创建GPU配置对象,并设置目标语言为c++。使用编码器。DeepLearningConfig
函数创建CuDNN
的深度学习配置对象,并将其分配给DeepLearningConfig
图形处理器代码配置对象的属性。要生成CUDA MEX,使用codegen
命令并指定输入的大小[480,704,3]。的输入图像大小tsdr_predict
函数。
cfg = coder.gpuConfig (墨西哥人的);cfg。TargetLang =“c++”;cfg。DeepLearningConfig =编码器。DeepLearningConfig (“cudnn”);codegen配置cfgtsdr_predictarg游戏{(480704 3 uint8)}报告
代码生成成功:查看报告
要使用TensorRT生成代码,请通过coder.DeepLearningConfig(“tensorrt”)
作为编码器配置对象的选项,而不是“cudnn”
.
加载一个输入图像。
我= imread (“stop.jpg”);imshow (im);
调用tsdr_predict_mex
在输入图像上。
Im = imresize(Im, [480,704]);[bboxes、类]= tsdr_predict_mex (im);
将类号映射到类字典中的交通标志名称。
一会= {...“addedLane”,“慢”,“下降”,“speedLimit25”,“speedLimit35”,“speedLimit40”,...“speedLimit45”,“speedLimit50”,“speedLimit55”,“speedLimit65”,...“speedLimitUrdbl”,“doNotPass”,“十字路口”,“keepRight”,“laneEnds”,...“合并”,“noLeftTurn”,“noRightTurn”,“停止”,“pedestrianCrossing”,...“stopAhead”,“rampSpeedAdvisory20”,“rampSpeedAdvisory45”,...“truckSpeedLimit55”,“rampSpeedAdvisory50”,“turnLeft”,...“rampSpeedAdvisoryUrdbl”,“turnRight”,“rightLaneMustTurn”,“收益”,...“yieldAhead”,“学校”,“schoolSpeedLimit25”,“zoneAhead45”,“signalAhead”};classRec =类名(类);
显示检测到的交通标志。
outputImage = insertShape (im,“矩形”bboxes,“线宽”3);为i = 1:size(bboxes,1) outputImage = insertText(outputImage,[bboxes(i,1)] +...bboxes(我,3)bboxes(我,2)-20],classRec {},“字形大小”, 20岁,...“输入TextColor”,“红色”);结束imshow (outputImage);
包含的帮助文件tsdr_testVideo.m
从测试视频中抓取帧,进行交通标志检测和识别,并将结果绘制在测试视频的每帧上。
类型tsdr_testVideo
函数tsdr_testVideo %版权所有2017-2021 The MathWorks, Inc. % Input video v = VideoReader('stop.avi');%% Integrated codegeneration for Traffic Sign Detection and Recognition for Traffic Signcfg。GpuConfig = coder.gpu.config;cfg.GpuConfig.Enabled = true;cfg。GenerateReport = false;cfg。TargetLang =“c++”;Create a GPU Configuration object for MEX target setting target language % to c++ Run the |codegen| command specifying an input of input video % frame size. This corresponds to the input image size of tsdr_predict % function. codegen -config cfg tsdr_predict -args {ones(480,704,3 ,'uint8')} fps = 0; while hasFrame(v) % Take a frame picture = readFrame(v); picture = imresize(picture,[480,704]); % Call MEX function for Traffic Sign Detection and Recognition tic; [bboxes,clases] = tsdr_predict_mex(picture); newt = toc; % fps fps = .9*fps + .1*(1/newt); % display diplayDetections(picture,bboxes,clases,fps); end end function diplayDetections(im,boundingBoxes,classIndices,fps) % Function for inserting the detected bounding boxes and recognized classes % and displaying the result % % Inputs : % % im : Input test image % boundingBoxes : Detected bounding boxes % classIndices : Corresponding classes % % Traffic Signs (35) classNames = {'addedLane','slow','dip','speedLimit25','speedLimit35',... 'speedLimit40','speedLimit45','speedLimit50','speedLimit55',... 'speedLimit65','speedLimitUrdbl','doNotPass','intersection',... 'keepRight','laneEnds','merge','noLeftTurn','noRightTurn','stop',... 'pedestrianCrossing','stopAhead','rampSpeedAdvisory20',... 'rampSpeedAdvisory45','truckSpeedLimit55','rampSpeedAdvisory50',... 'turnLeft','rampSpeedAdvisoryUrdbl','turnRight','rightLaneMustTurn',... 'yield','yieldAhead','school','schoolSpeedLimit25','zoneAhead45',... 'signalAhead'}; outputImage = insertShape(im,'Rectangle',boundingBoxes,'LineWidth',3); for i = 1:size(boundingBoxes,1) ymin = boundingBoxes(i,2); xmin = boundingBoxes(i,1); xmax = xmin+boundingBoxes(i,3); % inserting class as text at YOLO detection classRec = classNames{classIndices(i)}; outputImage = insertText(outputImage,[xmax ymin-20],classRec,... 'FontSize',20,'TextColor','red'); end outputImage = insertText(outputImage,... round(([size(outputImage,1) 40]/2)-20),... ['Frame Rate: ',num2str(fps)],'FontSize',20,'TextColor','red'); imshow(outputImage); end