OpenCV學習——基於輪廓尋找的視頻流運動檢測

來源:互聯網
上載者:User

原文出處:http://blog.csdn.net/gnuhpc/article/details/4286183

#include "cv.h"#include "highgui.h"#include <time.h>#include <math.h>#include <ctype.h>#include <stdio.h>#include <string.h>// various tracking parameters (in seconds) //跟蹤的參數(單位為秒)const double MHI_DURATION = 0.5;//0.5s為動作追蹤的持續時間上限const double MAX_TIME_DELTA = 0.5;const double MIN_TIME_DELTA = 0.05;const int N = 3;//const int CONTOUR_MAX_AERA = 1000;// ring image buffer 圈出映像緩衝IplImage **buf = 0;//指標的指標int last = 0;// temporary images臨時映像IplImage *mhi = 0; // MHI: motion history imageCvFilter filter = CV_GAUSSIAN_5x5;CvConnectedComp *cur_comp, min_comp;CvConnectedComp comp;CvMemStorage *storage;CvPoint pt[4];//  參數://  img – 輸入視訊框架//  dst – 檢測結果void  update_mhi( IplImage* img, IplImage* dst, int diff_threshold ){    double timestamp = clock()/100.; // get current time in seconds 時間戳記    CvSize size = cvSize(img->width,img->height);    // get current frame size,得到當前幀的尺寸    int i, idx1, idx2;    IplImage* silh;    IplImage* pyr = cvCreateImage( cvSize((size.width & -2)/2, (size.height & -2)/2), 8, 1 );    CvMemStorage *stor;    CvSeq *cont;    /*先進行資料的初始化*/    if( !mhi || mhi->width != size.width || mhi->height != size.height )    {        if( buf == 0 ) //若尚沒有初始化則分配記憶體給他        {            buf = (IplImage**)malloc(N*sizeof(buf[0]));            memset( buf, 0, N*sizeof(buf[0]));        }                for( i = 0; i < N; i++ )        {            cvReleaseImage( &buf[i] );            buf[i] = cvCreateImage( size, IPL_DEPTH_8U, 1 );            cvZero( buf[i] );// clear Buffer Frame at the beginning        }        cvReleaseImage( &mhi );        mhi = cvCreateImage( size, IPL_DEPTH_32F, 1 );        cvZero( mhi ); // clear MHI at the beginning    } // end of if(mhi)    /*將當前要處理的幀轉化為灰階放到buffer的最後一幀中*/    cvCvtColor( img, buf[last], CV_BGR2GRAY ); // convert frame to grayscale    /*設定幀的序號*/    /*    last---->idx1     ^     |     |     |    idx2<-----(last+1)%3    */        idx1 = last;    idx2 = (last + 1) % N; // index of (last - (N-1))th frame    last = idx2;    // 做幀差    silh = buf[idx2];//差值的指向idx2 |idx2-idx1|-->idx2(<-silh)    cvAbsDiff( buf[idx1], buf[idx2], silh ); // get difference between frames        // 對差映像做二值化    cvThreshold( silh, silh, 30, 255, CV_THRESH_BINARY ); //threshold it,二值化        cvUpdateMotionHistory( silh, mhi, timestamp, MHI_DURATION ); // update MHI     cvConvert( mhi, dst );//將mhi轉化為dst,dst=mhi           // 中值濾波,消除小的雜訊    cvSmooth( dst, dst, CV_MEDIAN, 3, 0, 0, 0 );            cvPyrDown( dst, pyr, CV_GAUSSIAN_5x5 );// 向下採樣,去掉雜訊,映像是原映像的四分之一    cvDilate( pyr, pyr, 0, 1 );  // 做膨脹操作,消除目標的不連續空洞    cvPyrUp( pyr, dst, CV_GAUSSIAN_5x5 );// 向上採樣,恢複映像,映像是原映像的四倍    //    // 下面的程式段用來找到輪廓    //    // Create dynamic structure and sequence.    stor = cvCreateMemStorage(0);    cont = cvCreateSeq(CV_SEQ_ELTYPE_POINT, sizeof(CvSeq), sizeof(CvPoint) , stor);        // 找到所有輪廓    cvFindContours( dst, stor, &cont, sizeof(CvContour),                    CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));    // 直接使用CONTOUR中的矩形來畫輪廓    for(;cont;cont = cont->h_next)    {              CvRect r = ((CvContour*)cont)->rect;              if(r.height * r.width > CONTOUR_MAX_AERA) // 面積小的方形拋棄掉              {                  cvRectangle( img, cvPoint(r.x,r.y),                          cvPoint(r.x + r.width, r.y + r.height),                          CV_RGB(255,0,0), 1, CV_AA,0);              }    }    // free memory    cvReleaseMemStorage(&stor);    cvReleaseImage( &pyr );}int main(int argc, char** argv){    IplImage* motion = 0;    CvCapture* capture = 0;        if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0])))        capture = cvCaptureFromCAM( argc == 2 ? argv[1][0] - '0' : 0 );//網路攝影機為視頻來源    else if( argc == 2 )        capture = cvCaptureFromAVI( argv[1] );//AVI為視頻來源    if( capture )    {        cvNamedWindow( "Motion", 1 );//建立視窗        for(;;)        {            IplImage* image;            if( !cvGrabFrame( capture ))//捕捉一楨                break;            image = cvRetrieveFrame( capture );//取出這個幀            if( image )//若取到則判斷motion是否為空白            {                if( !motion )                {                    motion = cvCreateImage( cvSize(image->width,image->height), 8, 1 );                    //建立motion幀,八位,一通道                    cvZero( motion );                    //零填充motion                    motion->origin = image->origin;                    //記憶體儲存的順序和取出的幀相同                }            }            update_mhi( image, motion, 60 );//更新歷史映像            cvShowImage( "Motion", image );//顯示處理過的映像            if( cvWaitKey(10) >= 0 )//10ms中按任意鍵退出                break;        }        cvReleaseCapture( &capture );//釋放裝置        cvDestroyWindow( "Motion" );//銷毀視窗    }    return 0;} 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.