運動檢測與跟蹤之動態背景的更新
阿新 • • 發佈:2019-01-04
#include "core/core.hpp" #include "highgui/highgui.hpp" #include "imgproc/imgproc.hpp" #include "iostream" using namespace std; using namespace cv; int main(int argc,char *argv[]) { VideoCapture videoCap(argv[1]); if(!videoCap.isOpened()) { return -1; } Mat image; Mat imageBackground; //動態背景模型 Mat imageFront; //前景 double videoFPS=videoCap.get(CV_CAP_PROP_FPS); //獲取幀率 double videoPause=1000/videoFPS; videoCap>>imageBackground; //第一幀作為初始背景模型 cvtColor(imageBackground,imageBackground,CV_RGB2GRAY); Mat element=getStructuringElement(0,Size(3,3)); //腐蝕核 while(true) { videoCap>>image; if(image.empty()||waitKey(videoPause)==27) //視訊播放完成,或Esc鍵退出 { break; } Mat image1; cvtColor(image,image1,CV_RGB2GRAY); absdiff(image1,imageBackground,imageFront); imageBackground.convertTo(imageBackground,CV_32FC1); //擴充套件至32位做運算 accumulateWeighted(image1,imageBackground,0.6,imageFront); imageBackground.convertTo(imageBackground,CV_8UC1); //轉換回8位 threshold(imageFront,imageFront,0,255,CV_THRESH_OTSU); //閾值分割 morphologyEx(imageFront,imageFront,CV_MOP_OPEN,element); //消除孤立的點 //膨脹操作,消除孔洞 dilate(imageFront,imageFront,element); dilate(imageFront,imageFront,element); dilate(imageFront,imageFront,element); dilate(imageFront,imageFront,element); dilate(imageFront,imageFront,element); vector> contours; vector hierarchy; findContours(imageFront,contours,hierarchy,RETR_EXTERNAL,CHAIN_APPROX_NONE,Point()); for(int i=0;i