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

其他教程   发布日期:2023年07月06日   浏览次数:482

本文小编为大家详细介绍“OpenCV如何使用BSM统计视频中移动的对象”,内容详细,步骤清晰,细节处理妥当,希望这篇“OpenCV如何使用BSM统计视频中移动的对象”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1、概述

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

实现步骤:

1.实例化VideoCapture

2.创建BackgroundSubstractor

3.while循环读取视频帧

4.使用BS->apply获取mask

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

6.使用findContours执行轮廓发现

7.统计最大外接矩形

8.输出结果

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

2、代码示例

  1. Move_Video_Object_Tracking::Move_Video_Object_Tracking(QWidget *parent)
  2. : MyGraphicsView{parent}
  3. {
  4. this->setWindowTitle("视频中移动对象统计");
  5. QPushButton *btn = new QPushButton(this);
  6. btn->setText("选择视频");
  7. connect(btn,&QPushButton::clicked,[=](){
  8. choiceVideo();
  9. });
  10. }
  11. void Move_Video_Object_Tracking::choiceVideo(){
  12. path = QFileDialog::getOpenFileName(this,"请选择视频","/Users/yangwei/Downloads/",tr("Image Files(*.mp4 *.avi)"));
  13. qDebug()<<"视频路径:"<<path;
  14. showMoveVideoObjectTracking(path.toStdString().c_str());
  15. }
  16. void Move_Video_Object_Tracking::showMoveVideoObjectTracking(const char* filePath){
  17. VideoCapture capture;
  18. capture.open(filePath);
  19. if(!capture.isOpened()){
  20. qDebug()<<"无法加载视频文件";
  21. return;
  22. }
  23. Ptr<BackgroundSubtractor> mogSubstractor = createBackgroundSubtractorMOG2();
  24. Mat frame,gauss,mask;
  25. Mat kernel = getStructuringElement(MORPH_RECT,Size(3,3));
  26. int count=0;
  27. char text[8];
  28. while(capture.read(frame)){
  29. GaussianBlur(frame,gauss,Size(5,5),0,0);
  30. mogSubstractor->apply(gauss,mask);//获取mask
  31. threshold(mask,mask,0,255,THRESH_BINARY|cv::THRESH_OTSU);
  32. //执行形态学操作
  33. morphologyEx(mask,mask,MORPH_OPEN,kernel);
  34. dilate(mask,mask,kernel,Point(-1,-1));
  35. imshow("mask",mask);
  36. //找到最大轮廓定位外接矩形
  37. vector<vector<Point>> contours;
  38. vector<Vec4i> heri;
  39. //寻找最大外接矩形
  40. findContours(mask,contours,RETR_EXTERNAL,CHAIN_APPROX_SIMPLE);
  41. count = 0;
  42. for(size_t i = 0;i<contours.size();i++){
  43. double area = contourArea(contours[i]);
  44. if(area<5000){
  45. continue;
  46. }
  47. Rect rect = boundingRect(contours[i]);
  48. qDebug()<<rect.width<<":"<<rect.height;
  49. if (rect.width < 200 || rect.height < 100) continue;
  50. count++;
  51. rectangle(frame,rect,Scalar(0,0,255),3,8);
  52. sprintf(text,"%d",count);
  53. 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);
  54. }
  55. imshow("frame",frame);
  56. int c = waitKey(1);
  57. if(c==27){
  58. break;
  59. }
  60. }
  61. capture.release();
  62. }

以上就是OpenCV如何使用BSM统计视频中移动的对象的详细内容,更多关于OpenCV如何使用BSM统计视频中移动的对象的资料请关注九品源码其它相关文章!