其他分享
首页 > 其他分享> > OpenCV使用BSM统计视频中移动的对象

OpenCV使用BSM统计视频中移动的对象

作者:互联网

一、概述

  案例:使用BackgroundSubstractor实现视频中移动对象统计

  实现步骤:

    1.实例化VideoCapture

    2.创建BackgroundSubstractor

    3.while循环读取视频帧

    4.使用BS->apply获取mask

    5.对mask进行二值化及形态学操作

    6.使用findContours执行轮廓发现

    7.统计最大外接矩形

    8.输出结果

 

  ps:这个算法的抗干扰能力比较差,要相出正确的结果,必须要对frame进行预处理。或者提升视频的质量才行。不然只能得到一个错误的结果

二、代码示例

Move_Video_Object_Tracking::Move_Video_Object_Tracking(QWidget *parent)
    : MyGraphicsView{parent}
{
    this->setWindowTitle("视频中移动对象统计");
    QPushButton *btn = new QPushButton(this);
    btn->setText("选择视频");
    connect(btn,&QPushButton::clicked,[=](){
        choiceVideo();
    });

}


void Move_Video_Object_Tracking::choiceVideo(){
    path = QFileDialog::getOpenFileName(this,"请选择视频","/Users/yangwei/Downloads/",tr("Image Files(*.mp4 *.avi)"));
    qDebug()<<"视频路径:"<<path;
    showMoveVideoObjectTracking(path.toStdString().c_str());
}

void Move_Video_Object_Tracking::showMoveVideoObjectTracking(const char* filePath){
    VideoCapture capture;
    capture.open(filePath);

    if(!capture.isOpened()){
        qDebug()<<"无法加载视频文件";
        return;
    }
    Ptr<BackgroundSubtractor> mogSubstractor = createBackgroundSubtractorMOG2();
    Mat frame,gauss,mask;
    Mat kernel = getStructuringElement(MORPH_RECT,Size(3,3));
    int count=0;
    char text[8];
    while(capture.read(frame)){
        GaussianBlur(frame,gauss,Size(5,5),0,0);
        mogSubstractor->apply(gauss,mask);//获取mask
        threshold(mask,mask,0,255,THRESH_BINARY|cv::THRESH_OTSU);
        //执行形态学操作
        morphologyEx(mask,mask,MORPH_OPEN,kernel);
        dilate(mask,mask,kernel,Point(-1,-1));
        imshow("mask",mask);

        //找到最大轮廓定位外接矩形
        vector<vector<Point>> contours;
        vector<Vec4i> heri;
        //寻找最大外接矩形
        findContours(mask,contours,RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
        count = 0;
        for(size_t i = 0;i<contours.size();i++){
            double area = contourArea(contours[i]);
            if(area<5000){
                continue;
            }
            Rect rect = boundingRect(contours[i]);
            qDebug()<<rect.width<<":"<<rect.height;
            if (rect.width < 200 || rect.height < 100) continue;
            count++;
            rectangle(frame,rect,Scalar(0,0,255),3,8);
            sprintf(text,"%d",count);
            putText(frame,text,Point(rect.x+rect.width/2,rect.y+rect.height/2),FONT_ITALIC, FONT_HERSHEY_PLAIN,Scalar(0,255,0),2,8);
        }


        imshow("frame",frame);

        int c = waitKey(1);
        if(c==27){
            break;
        }
    }
    capture.release();

}

 

三、演示图片

 

标签:视频,Tracking,OpenCV,frame,Object,mask,BSM,Move
来源: https://www.cnblogs.com/tony-yang-flutter/p/16192471.html