Main Content

Detect Cars Using Gaussian Mixture Models

此示例显示了如何使用基于高斯混合模型(GMM)的前景检测器以视频序列检测和计数汽车。

Introduction

检测和计数汽车可用于分析交通模式。检测也是执行更复杂的任务之前的第一步,例如通过其类型对车辆进行跟踪或分类。

This example shows how to use the foreground detector and blob analysis to detect and count cars in a video sequence. It assumes that the camera is stationary. The example focuses on detecting objects. To learn more about tracking objects, see the example titled基于运动的多个对象跟踪

步骤1-导入视频并初始化前景检测器

Rather than immediately processing the entire video, the example starts by obtaining an initial video frame in which the moving objects are segmented from the background. This helps to gradually introduce the steps used to process the video.

前景检测器需要一定数量的视频帧才能初始化高斯混合模型。该示例使用前50帧在混合模型中初始化三个高斯模式。

前景电视= vision.ForegroundDetector“数字”,3,...'NumTrainingFrames',50);videoreader = videoreader('VisionTraffic.avi');为了i = 1:150帧= readframe(videoreader);%阅读下一个视频框架前景=步骤(前景探测器,框架);结尾

训练后,检测器开始输出更可靠的分割结果。下面的两个图显示了检测器计算的视频帧和前景掩模。

数字;imshow(帧);标题('Video Frame');

数字;Imshow(前景);标题('前景');

Step 2 - Detect Cars in an Initial Video Frame

前景细分过程并不完美,通常包括不良的噪音。该示例使用形态开口来消除噪声并填补检测到的对象中的空白。

se = strel('正方形',3);过滤前景= iMopen(前景,SE);数字;iMshow(过滤前地面);标题('Clean Foreground');

接下来,使用Vision.blobanalysis对象找到与移动汽车相对应的每个连接组件的边界框。该对象通过拒绝少于150个像素的斑点,进一步过滤了检测到的前景。

斑点分析=视觉。布洛巴分析('BoundingBoxOutputPort',,,,true,...“区域输出港”, 错误的,“ Centroidoutputport”, 错误的,...'MinimumBlobArea',,,,150); bbox = step(blobAnalysis, filteredForeground);

为了突出检测到的汽车,我们在它们周围画绿色盒子。

结果=插入形状(帧,'Rectangle',,,,bbox,'Color',,,,'绿色');

边界框的数量对应于视频框架中发现的汽车数量。在处理后的视频框架的左上角显示发现的汽车数量。

numcars = size(bbox,1);结果= insertText(结果,[10 10],数字,“拳击”,1,...'字体大小',14);数字;imshow(结果);标题(“检测到汽车”);

Step 3 - Process the Rest of Video Frames

在最后一步中,我们处理其余的视频帧。

videoplayer = vision.videoplayer('姓名',,,,“检测到汽车”);videoplayer.position(3:4)= [650,400];%窗口大小:[宽度,高度]se = strel('正方形',3);%降噪的形态滤波器whilehasframe(videoreader)frame = readframe(videoreader);%阅读下一个视频框架% Detect the foreground in the current video frame前景=步骤(前景探测器,框架);%利用形态学开去除噪声in the foreground过滤前景= iMopen(前景,SE);%检测具有指定最小面积的连接组件,并且%计算它们的边界盒bbox = step(blobanalysis,过滤前地下);%在检测到的汽车周围绘制边界盒结果=插入形状(帧,'Rectangle',,,,bbox,'Color',,,,'绿色');%显示视频框架中发现的汽车数量numcars = size(bbox,1);结果= insertText(结果,[10 10],数字,“拳击”,1,...'字体大小',14);step(videoPlayer, result);%显示结果结尾

输出视频显示汽车周围的边界框。它还显示了视频左上角的汽车数量。