摄像头中运动物体识别

#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
}

转载于:https://www.cnblogs.com/xingkongcanghai/p/11549430.html

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值