OpenCV使用BSM統(tǒng)計視頻中移動的對象
1、概述
案例:使用BackgroundSubstractor實現(xiàn)視頻中移動對象統(tǒng)計
實現(xiàn)步驟:
1.實例化VideoCapture
2.創(chuàng)建BackgroundSubstractor
3.while循環(huán)讀取視頻幀
4.使用BS->apply獲取mask
5.對mask進行二值化及形態(tài)學操作
6.使用findContours執(zhí)行輪廓發(fā)現(xiàn)
7.統(tǒng)計最大外接矩形
8.輸出結(jié)果
ps:這個算法的抗干擾能力比較差,要相出正確的結(jié)果,必須要對frame進行預(yù)處理?;蛘咛嵘曨l的質(zhì)量才行。不然只能得到一個錯誤的結(jié)果
2、代碼示例
Move_Video_Object_Tracking::Move_Video_Object_Tracking(QWidget *parent) : MyGraphicsView{parent} { this->setWindowTitle("視頻中移動對象統(tǒng)計"); 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); //執(zhí)行形態(tài)學操作 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、演示圖片
到此這篇關(guān)于OpenCV使用BSM統(tǒng)計視頻中移動的對象的文章就介紹到這了,更多相關(guān)OpenCV BSM統(tǒng)計視頻移動對象內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++強制類型轉(zhuǎn)換(static_cast、dynamic_cast、const_cast、reinterpret_ca
本文主要介紹了C++強制類型轉(zhuǎn)換,主要介紹了static_cast、dynamic_cast、const_cast、reinterpret_cast的4種方法,感興趣的可以了解一下2021-08-08C++實現(xiàn)統(tǒng)計代碼運行時間的示例詳解
這篇文章主要為大家詳細介紹了C++一個有趣的小項目——統(tǒng)計代碼運行時間,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-05-05