OpenCV 求图形得质心

当窗口显示图像时,使用鼠标在图像上随意画出一个矩形,求出物体在矩形内部的质心坐标。

原始图如下:

OpenCV 求图形得质心_第1张图片

期望的效果图像: 

OpenCV 求图形得质心_第2张图片

OpenCV 求图形得质心_第3张图片

#include "stdio.h"
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#pragma comment (lib,"highgui.lib")
#pragma comment (lib,"cxcore.lib")
#pragma comment (lib,"cv.lib")

IplImage* src= cvLoadImage("arrow.jpg");
IplImage* gray=cvCreateImage(cvGetSize(src),8,1);
CvRect rect;
double ss=0.0,xx=0,yy=0;
void on_mouse(int event,int x,int y,int flags,void* param)
{	
	if(event==CV_EVENT_LBUTTONDOWN)
	{
		rect.x = x;
		rect.y = y;
		rect.width=0;
		rect.height = 0;        
	}
	else if((event == CV_EVENT_MOUSEMOVE) && x>rect.x && y>rect.y && rect.x>0 && rect.y>0&&xwidth&&yheight)
	{
		rect.width = x - rect.x;
		rect.height = y - rect.y;	
		CvPoint pt1,pt2;
		pt1.x = rect.x;
		pt1.y = rect.y;
		pt2.x = x;
		pt2.y = y;	
		IplImage* ImageTemp = cvCreateImage(cvGetSize(src),8,3);
		cvCopy(src,ImageTemp);
		cvRectangle(ImageTemp,pt1,pt2,cvScalar(255,0,0,0),3);
		int m=0,n=0;
		ss=0.0,xx=0,yy=0;
		//根据框选的矩形区域计算矩形内部物体的质心
		for(int i=rect.y;iimageData+gray->widthStep*i))[j]==255)
				{
					xx+=j;
					yy+=i;
					ss++;
				}					
			}		
		if (ss>0)
		{
				xx=xx/ss;
				yy=yy/ss;
			
				cvLine(ImageTemp,cvPoint((int)xx,(int)yy),cvPoint((int)xx,(int)yy),cvScalar(0,0,255,0),5);
		}	
		cvShowImage("center",ImageTemp);
		cvReleaseImage(&ImageTemp);	
	}	
	else if(event == CV_EVENT_LBUTTONUP)
	{
		printf("当前质心为:%f,%f。\n",xx,yy);
		rect.x=0;
		rect.y=0;
		rect.width=0;
		rect.height=0;
	}	
}

int main(int argc, char* argv[])
{
	cvCvtColor(src,gray,CV_BGRA2GRAY);
	cvThreshold(gray,gray,200,255,CV_THRESH_BINARY_INV);	
 	cvNamedWindow("gray",1);	
 	cvShowImage("gray",gray);
	cvNamedWindow("center",1);	
	cvSetMouseCallback("center",&on_mouse);	
	cvShowImage("center",src);
	cvWaitKey(0);	
	cvReleaseImage(&src);
	cvReleaseImage(&gray);
	cvDestroyAllWindows();
	return 0;
}

 

 

 

 

 

 

你可能感兴趣的:(【OpenCV_练习】)