效果图:
代码:
// FindGravity.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <string> #include "cv.h" #include "highgui.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #pragma comment(lib,"opencv_core2410d.lib") #pragma comment(lib,"opencv_highgui2410d.lib") #pragma comment(lib,"opencv_imgproc2410d.lib") using namespace std; using namespace cv; void FindGravity() { } /** 计算二值图像的重心 * @param[in] src 输入的待处理图像 * @param[out] center 重心坐标 * @retval 0 操作成功 * @retval -1 操作失败 * @note 输入图像是二值化图像 * @note xc=M10/M00, yc=M01/M00, 其中 Mx_order,y_order=SUMx,y(I(x,y)*x^x_order*y^y_order) */ static int aoiGravityCenter(IplImage *src, CvPoint ¢er) { //if(!src) // return GRAVITYCENTER__SRC_IS_NULL; double m00, m10, m01; CvMoments moment; cvMoments( src, &moment, 1); m00 = cvGetSpatialMoment( &moment, 0, 0 ); if( m00 == 0) return 1; m10 = cvGetSpatialMoment( &moment, 1, 0 ); m01 = cvGetSpatialMoment( &moment, 0, 1 ); center.x = (int) (m10/m00); center.y = (int) (m01/m00); return 0; } IplImage* binary_image(IplImage* src) { // cvThreshold( src, src, 100, 255, CV_THRESH_BINARY );//100 is the thredhold IplImage* one_channel = cvCreateImage(cvSize(src->width,src->height),IPL_DEPTH_8U,0); for(int y = 0;y < src->height;y++) { char *ptr= src->imageData + y * src->widthStep; char *p_one_channel = one_channel->imageData + y * one_channel->widthStep; for(int x = 0;x < src->width;x++) { int temp = ptr[3*x]; if (temp != 0)//不是黑色也就是说不是背景 { p_one_channel[x] = 255;//设置为白色 } else { p_one_channel[x] = 0; } //ptr[3*x]= //ptr[3*x+1]= //ptr[3*x+2]=; } } return one_channel; } int _tmain(int argc, _TCHAR* argv[]) { string str_name = "seg_right.bmp"; IplImage* src; IplImage* draw = cvLoadImage(str_name.c_str(),1);//绘制重心的图像 if ((src = cvLoadImage(str_name.c_str(),1))!=0) { //src = binary_image(src); cvNamedWindow( "binary image", 1 ); cvShowImage( "binary image", binary_image(src) ); } CvPoint xy; aoiGravityCenter(binary_image(src),xy); cout<<xy.x<<endl; cout<<xy.y<<endl; cvCircle(draw,cvPoint(xy.x,xy.y),3,CV_RGB(0,0,255),5); cvNamedWindow( "重心", 1 ); cvShowImage( "重心", draw ); cvWaitKey(0); return 0; }
我调试好的工程:点击打开链接
http://download.csdn.net/detail/wangyaninglm/9389338
时间: 2024-10-21 23:13:04