您的位置:首页 > 其它

运动物体的检测--对视频检测的改进

2017-11-23 11:45 405 查看
上次的学习中已经对视频的检测做出来介绍,但是上次用的方法是把视频的第一帧是设为背景,然后后面每一帧依次减去第一帧,这一次采用第二种方法,用每一帧图片与前一帧进行操作,结果消除了很多误差,同时,又对图片进行了形态学操作的开运算,修改了一部分参数,现在的检测误差相对小了很多。接下来将继续对几步运算进行改进与理解。优化程序。

具体代码如下:

#include <opencv2/highgui/highgui.hpp>    

#include <opencv2/imgproc/imgproc.hpp>   

#include <opencv2/core/core.hpp>

#include "opencv2/opencv.hpp"  

using namespace cv;

#include <iostream>  

using namespace std;

void circle(Mat background, Mat frame);

int main()

{
//VideoCapture video(0);
VideoCapture video("bike.mp4");
if (!video.isOpened())  //对video进行异常检测  
{
cout << "video open error!" << endl;
return 0;
}
Mat frame;//存储最新帧 
Mat frame1;//读取帧
Mat frame2;//读取帧
Mat background;//存储背景帧
double framePosition;
int frameCount = video.get(CV_CAP_PROP_FRAME_COUNT);//获取帧数  
double FPS = video.get(CV_CAP_PROP_FPS);//获取FPS 
for(int i=1;i< frameCount;i++)
{
video >> frame1;//读帧进frame
framePosition = video.get(CV_CAP_PROP_POS_FRAMES);//获取帧位置(第几帧)
if (framePosition == 1.0)
{
video >> frame2;//读帧进frame
background = frame1.clone();
frame = frame2.clone();
}
else
frame = frame1.clone();
circle(background, frame);//循环相减
background = frame.clone();
waitKey(30);
}
return 0;

}

void circle(Mat background, Mat frame)

{
Mat diff;//用diff来存储差图
diff.create(frame.size(), frame.type());
absdiff(background, frame, diff);//减
Mat diff_thresh = frame.clone();
//对差值图dif进行阈值化处理 
cvtColor(diff, diff, CV_BGR2GRAY);
threshold(diff, diff, 50, 255, CV_THRESH_BINARY);
// 4.对差值图dif进行腐蚀  
Mat kernel_erode = getStructuringElement(MORPH_RECT, Size(5, 5));
Mat kernel_dilate = getStructuringElement(MORPH_RECT, Size(14, 14));
erode(diff, diff, kernel_erode);
// 5.对差值图dif进行膨胀  
dilate(diff, diff, kernel_dilate);
// 查找轮廓并绘制轮廓  
vector<vector<Point>> contours;//contours被定义成二维浮点型向量,用来存储找到的边界的(x,y)坐标。
vector<Vec4i> hierarchy;
findContours(diff, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
drawContours(diff_thresh, contours, -1, Scalar(0, 255, 0), 1, 8);//在dif_thresh上绘制轮廓 
//7.查找正外接矩形  
int width = 0;
int height = 0;
int x = 0;
int y = 0;
vector<Rect> boundRect(contours.size());
for (int i = 0; i < contours.size(); i++)
{
boundRect[i] = boundingRect(Mat(contours[i]));
//2获得正外接矩形的左上角坐标及宽高  
width = boundRect[i].width;
height = boundRect[i].height;
x = boundRect[i].x;
y = boundRect[i].y;
rectangle(diff_thresh, boundRect[i], Scalar(0, 255, 0), 2);//在dif_thresh上绘制正外接矩形  
}
//显示图片
imshow("差图", diff_thresh);

}

现在对程序使用的一些方法还不是很理解,接下来会深入了解,并开始下一步学习,对摄像头拍出的物体进行实时监测。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: