动态人物识别代码
int main ( )
{ VideoCapture cap ( "vtest.avi" ) ; if ( ! cap. isOpened ( ) ) { std:: cout << "无法打开视频文件或摄像头流" << std:: endl; return - 1 ; } Mat prevFrame, prevGray; cap >> prevFrame; prevGray = Mat ( prevFrame. size ( ) , CV_8UC1, Scalar ( 255 ) ) ; int kk = 0 ; while ( true ) { Mat nextFrame, nextGray; cap >> nextFrame; if ( nextFrame. empty ( ) ) break ; Mat diff; absdiff ( prevFrame, nextFrame, diff) ; Mat gray; cvtColor ( diff, gray, COLOR_BGR2GRAY) ; GaussianBlur ( gray, gray, Size ( 9 , 9 ) , 2 , 2 ) ; threshold ( gray, nextGray, 30 , 255 , THRESH_BINARY) ; Mat currentGray; bitwise_and ( prevGray, nextGray, currentGray) ; Mat dilated; Mat kernel = getStructuringElement ( MORPH_RECT, Size ( 3 , 3 ) ) ; dilate ( currentGray, dilated, kernel, Point ( - 1 , - 1 ) , 3 ) ; RNG rng ( 10086 ) ; Mat out, stats, centroids; int number = connectedComponentsWithStats ( dilated, out, stats, centroids, 8 , CV_16U) ; vector< Vec3b> colors; for ( int i = 0 ; i < number; i++ ) { Vec3b vec3 = Vec3b ( rng. uniform ( 0 , 256 ) , rng. uniform ( 0 , 256 ) , rng. uniform ( 0 , 256 ) ) ; colors. push_back ( vec3) ; } Mat result = Mat :: zeros ( prevFrame. size ( ) , CV_8UC3) ; int w = result. cols; int h = result. rows; for ( int i = 1 ; i < number; i++ ) { int center_x = centroids. at < double > ( i, 0 ) ; int center_y = centroids. at < double > ( i, 1 ) ; int x = stats. at < int > ( i, CC_STAT_LEFT) ; int y = stats. at < int > ( i, CC_STAT_TOP) ; int w = stats. at < int > ( i, CC_STAT_WIDTH) ; int h = stats. at < int > ( i, CC_STAT_HEIGHT) ; int area = stats. at < int > ( i, CC_STAT_AREA) ; if ( area < 500 ) { continue ; } Rect rect ( x, y, w, h) ; rectangle ( prevFrame, rect, colors[ i] , 2 ) ; } imshow ( "Motion Detection" , prevFrame) ; if ( waitKey ( 1 ) == 27 ) break ; prevGray = nextGray; prevFrame = nextFrame; } cap. release ( ) ; destroyAllWindows ( ) ; return 0 ;
}