zoukankan      html  css  js  c++  java
  • 摄像头中运动物体识别

    #include <opencv2/opencv.hpp>
    #include <cv.h>
    #include <highgui.h>
    #include <iostream>
    
    using namespace std;
    using namespace cv;
    Mat MoveDetect(Mat temp, Mat frame);
    int main()
    {
    	VideoCapture video(1);//定义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
    }
    
  • 相关阅读:
    好的博客
    left join 后边的on条件 小记
    ElasticSearch构建订单服务的博客
    nacos mysql8.0修改
    maven配置
    idea常用配置
    http状态码
    Web Application:Exploded和Web Application:Archive
    将一个简单远程调用的方式例子改为异步调用 -- 2
    将一个简单远程调用的方式例子改为异步调用
  • 原文地址:https://www.cnblogs.com/xingkongcanghai/p/11549430.html
Copyright © 2011-2022 走看看