openCV学习笔记十七:摄像头中运动物体检测
程序员文章站
2022-05-30 12:08:19
...
我们知道视频都是由一帧一帧图像构成的,利用帧差法,相邻两三帧图像像素之间的差异性判断是否有运动目标。
基本步骤
相邻帧相减------阈值处理------去除噪声(腐蚀滤波)------膨胀连通------查找轮廓------外接矩形
// A code block
var foo = 'bar';
帧差法代码如下:
#include <cv.h>
#include <highgui.h>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
VideoCapture video(0);//定义VideoCapture类video
Mat frame;//存储帧
Mat temp;//存储前一帧图像
Mat result;//存储结果图像
video >> temp;//读帧进frame
while (1)
{
video >> frame;//读帧进frame
imshow("frame", frame);
result = MoveDetect(temp, frame);//调用MoveDetect()进行运动物体检测,返回值存入result
imshow("result", result);
waitKey(50);
temp = frame.clone();
}
return 0;
}
Mat MoveDetect(Mat temp, Mat frame)
{
Mat result = frame.clone(); //1.将background和frame转为灰度图
Mat gray1, gray2;
cvtColor(temp, gray1, CV_BGR2GRAY);
cvtColor(frame, gray2, CV_BGR2GRAY);
//2.将background和frame做差
Mat diff;
absdiff(gray1, gray2, diff);
imshow("diff", diff);
//3.对差值图diff_thresh进行阈值化处理
Mat diff_thresh;
threshold(diff, diff_thresh, 50, 255, CV_THRESH_BINARY);
imshow("diff_thresh", diff_thresh);
//4.腐蚀
Mat kernel_erode = getStructuringElement(MORPH_RECT, Size(3, 3));
Mat kernel_dilate = getStructuringElement(MORPH_RECT, Size(18, 18));
erode(diff_thresh, diff_thresh, kernel_erode);
imshow("erode", diff_thresh);
//5.膨胀
dilate(diff_thresh, diff_thresh, kernel_dilate);
imshow("dilate", diff_thresh);
//6.查找轮廓并绘制轮廓
vector<vector<Point>> contours;
findContours(diff_thresh, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
drawContours(result, contours, -1, Scalar(0, 0, 255), 2);//在result上绘制轮廓
//7.查找正外接矩形
vector<Rect> boundRect(contours.size());
for (int i = 0; i < contours.size(); i++)
{
boundRect[i] = boundingRect(contours[i]);
rectangle(result, boundRect[i], Scalar(0, 255, 0), 2);
//在result上绘制正外接矩形
}
return result;//返回result
}
运行结果如下:
上一篇: fastdfs安装配置(整合nginx和fastdfs)
下一篇: JAVA设计模式(四)单例模式