目录
1、概述
案例:使用BackgroundSubstractor实现视频中挪动对象统计
实现步骤:
1.实例化VideoCapture
2.创建BackgroundSubstractor
3.while循环读取视频帧
4.使用BS->apply获取mask
5.对mask停止二值化及形态学操作
6.使用findContours执行轮廓发现
7.统计最大外接矩形
8.输出结果
ps:这个算法的抗干扰才干比较差,要相出正确的结果,必需要对frame停止预处置。或者提升视频的质量才行。不然只能得到一个错误的结果
2、代码示例
- 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();
- }
复制代码 3、演示图片
到此这篇关于OpenCV使用BSM统计视频中挪动的对象的文章就介绍到这了,更多相关OpenCV BSM统计视频挪动对象内容请搜索网站以前的文章或继续阅读下面的相关文章希望大家以后多多支持网站! |