对所有提取到的轮廓画其重心

#include "cv.h" 
#include "highgui.h" 

void main( ) 
{ 
	IplImage* src; 
	CvMoments moments; 
	CvMat *region; 
	CvPoint pt1,pt2; 
	double m00 = 0, m10, m01, mu20, mu11, mu02, inv_m00; 
	double a, b, c; 
	int xc, yc; 

	if( (src=cvLoadImage("two.bmp", 0))!= 0) 
	{ 
		IplImage* dst = cvCreateImage( cvGetSize(src), 8, 3 ); 
		CvMemStorage* storage = cvCreateMemStorage(0); 
		CvSeq* contour = 0; 

		cvThreshold( src, src, 100, 255, CV_THRESH_BINARY );//100 is the thredhold 
		cvNot( src, src ); 
		cvNamedWindow( "Source", 1 ); 
		cvShowImage( "Source", src ); 

		cvFindContours( src, storage, &contour, sizeof(CvContour),CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) ); 
		cvZero( dst ); 

		for( ; contour != 0; contour = contour->h_next ) 
		{ 
			CvScalar color = CV_RGB( 255, 0,0 ); 
			/* 用1替代 CV_FILLED 所指示的轮廓外形 */ 
			cvDrawContours( dst, contour, color, color, -1, CV_FILLED, 8,cvPoint(0,0) );//you can change 1 to CV_FILLED 
			contour = cvApproxPoly( contour, sizeof(CvContour), storage, CV_POLY_APPROX_DP, 3, 1 ); 
			region=(CvMat*)contour; 
			cvMoments( region, &moments,0 ); 
			// cvDrawContours( cnt_img, _contours, CV_RGB(255,0,0), CV_RGB(0,255,0), _levels, 3, CV_AA, cvPoint(0,0) ); CV_FILLED 

			m00 = moments.m00; 
			m10 = moments.m10; 
			m01 = moments.m01; 
			mu11 = moments.mu11; 
			mu20 = moments.mu20; 
			mu02 = moments.mu02; 

			//if( fabs(m00) < DBL_EPSILON )break; 

			inv_m00 = 1. / m00; 
			xc = cvRound( m10 * inv_m00 ); 
			yc = cvRound( m01 * inv_m00 ); 
			a = mu20 * inv_m00; 
			b = mu11 * inv_m00; 
			c = mu02 * inv_m00; 
			///////////////// 
			pt1.x=xc-1;pt1.y=yc; 
			pt2.x=xc+1;pt2.y=yc; 
			cvLine( dst, pt1, pt2, CV_RGB(0,255,0), 2, CV_AA, 0 ); 
			pt1.x=xc;pt1.y=yc-1; 
			pt2.x=xc;pt2.y=yc+1; 
			cvLine( dst, pt1, pt2, CV_RGB(0,255,0), 2, CV_AA, 0 ); 
		} 

		cvNamedWindow( "Components", 1 ); 
		cvShowImage( "Components", dst ); 
		cvWaitKey(0); 
	} 
}


你可能感兴趣的:(对所有提取到的轮廓画其重心)