2013年9月6日 星期五

【OpenCV】Motion History Image 歷史移動資訊檢測




#include "stdafx.h" #include <stdio.h> #include <ctype.h> #include <time.h> #include "opencv2/video/tracking.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" const double MHI_DURATION = 1; const int N = 20;//參考歷史影像張數 IplImage **buf = 0; int last = 0; double t = 0;//偵測速度 IplImage *mhi_img = 0; IplImage *mask = 0; static void MotionHistoryImage( IplImage* img, IplImage* dst, int diff_threshold ) { double timestamp = (double)clock()/CLOCKS_PER_SEC; //取得當下時間 CvSize size = cvSize(img->width, img->height); //取得影像大小 int i, idx1 = last, idx2; IplImage* diff_img;//移動資訊影像 if( !mhi_img || mhi_img->width != size.width || mhi_img->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] ); } cvReleaseImage( &mhi_img ); cvReleaseImage( &mask ); mhi_img = cvCreateImage( size, IPL_DEPTH_32F, 1 ); cvZero( mhi_img ); mask = cvCreateImage( size, IPL_DEPTH_8U, 1 ); } cvCvtColor( img, buf[last], CV_BGR2GRAY ); //將當下影像轉成灰階影像,並存在BUFFER序列影像中 idx2 = (last + 1) % N; last = idx2; //BUFFER影像序列中的INDEX轉換 diff_img = buf[idx2]; cvAbsDiff( buf[idx1], buf[idx2], diff_img ); //計算相鄰畫面移動資訊 cvThreshold( diff_img, diff_img, diff_threshold, 1, CV_THRESH_BINARY ); //利用diff_threshold判斷是否為移動資訊 cvUpdateMotionHistory( diff_img, mhi_img, timestamp, MHI_DURATION ); //更新歷史移動資訊 cvCvtScale( mhi_img, mask, 255./MHI_DURATION, (MHI_DURATION - timestamp)*255./MHI_DURATION ); //根據移動強度計算其像素在時間上的權重給予深淺顏色表示 //時間越近T(當時時間)權重越高 //顏色越深移動能量越強 cvZero( dst ); cvMerge( mask, mask, 0, 0, dst ); } int main(int argc, char** argv) { IplImage* motion_img = 0; CvCapture *capture = cvCaptureFromCAM(-1); if( capture ) { cvNamedWindow( "Motion Image", 1 ); for(;;) { IplImage* image = cvQueryFrame( capture ); if( !image ) break; if( !motion_img )//第一張為背景 { motion_img = cvCreateImage( cvSize(image->width,image->height), 8, 3 ); cvZero( motion_img ); motion_img->origin = image->origin; } MotionHistoryImage( image, motion_img, 30 ); cvShowImage( "Motion Image", motion_img ); if( cvWaitKey(10) >= 0 ) break; } cvReleaseCapture( &capture ); cvDestroyWindow( "Motion Image" ); } return 0; }
相關資訊:OpenCV學習日記

0 意見:

張貼留言