运动物体检测顾名思义就是在视频(视频文件、摄像头获取)中检测运动物体(目标)。
OpenCV中常用的运动物体检测有背景差法、帧差法、光流法,运动物体检测广泛应用于视频安全监控、车辆检测等方面。
本博文主要介绍背景差法与帧差法:
背景差法:就是用原图像减去背景模型,剩下的就是前景图像,即运动目标
帧差法:就是利用相邻的两帧或者三帧图像,利用像素之间的差异性,判断是否有运动目标
(视频就是一帧一帧图像组成的、求图像差异最基本的就是图像减法--suntract,absdiff)
背景减法基本步骤:原图-背景------阈值处理------去除噪声(腐蚀滤波)------膨胀连通-----查找轮廓-----外接矩形(椭圆/圆)
一个摄像头:
#include "opencv2/opencv.hpp"
#include<iostream>
using namespace std;
using namespace cv;
Mat MoveDetect(Mat background, Mat img)
{
//将background和img转为灰度图
Mat result = img.clone();
Mat gray1, gray2;
cvtColor(background, gray1, CV_BGR2GRAY);
cvtColor(img, gray2, CV_BGR2GRAY);
//进行canny边缘检测
Canny(background, background, 0, 30, 3);
//将background和img做差;对差值图diff进行阈值化处理
Mat diff;
absdiff(gray1, gray2, diff);
//imshow("absdiss", diff);
threshold(diff, diff, 50, 255, CV_THRESH_BINARY);
//imshow("threshold", diff);
//腐蚀膨胀消除噪音
/*
Mat element = getStructuringElement(MORPH_RECT, Size(3, 3));
Mat element2 = getStructuringElement(MORPH_RECT, Size(15, 15));
erode(diff, diff, element);
//imshow("erode", diff);
dilate(diff, diff, element2);
//imshow("dilate", diff);
*/
//二值化后使用中值滤波+膨胀
Mat element = getStructuringElement(MORPH_RECT, Size(11, 11));
medianBlur(diff, diff, 5);//中值滤波
//imshow("medianBlur", diff);
dilate(diff, diff, element);
//blur(diff, diff, Size(10, 10)); //均值滤波
//imshow("dilate", diff);
//查找并绘制轮廓
vector<vector<Point>&