如何优雅的在MFC中使用cvSetMouseCallback?

MFC与opencv的cvSetMouseCallback用起来感觉很不兼容。

大部分时候,用cvSetMouseCallback也许只是为了获取一个矩形框,或者绘制一个点,或者其它什么简易的图形,通过调用该函数来得到鼠标交互的参数信息。

然而,这么一个简单的要求,在MFC框架中并不是很方便调用。

通过阅读 opencv 官方提供的samples源码,其中在grabcut上面有个GCApplication类,用来控制或者获取绘制信息,我觉得很方便,将其精简一下,如下:

#define GC_BGD 0
#define GC_FGD 1
#define GC_PR_BGD 2
#define GC_PR_FGD 3

const Scalar GREEN = Scalar(0,255,0);

class GCApp
{
public:
	enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 };

public:
	void mouseClick( int event, int x, int y, int flags, void* param );
	void setImageAndWinName( const Mat& _image, const string& _winName);
	void reset();
	void showImage() const;

public:
	Rect rect;
	uchar rectState;
	const Mat* image;
	Mat mask;
	const string* winName;
};

void GCApp::reset()
{
	if( !mask.empty() )
		mask.setTo(Scalar::all(GC_BGD));
	rectState = NOT_SET;
}

void GCApp::setImageAndWinName( const Mat& _image, const string& _winName  )
{
	if( _image.empty() || _winName.empty() )
		return;
	image = &_image;
	winName = &_winName;
	mask.create( image->size(), CV_8UC1);
	reset();
}

void GCApp::showImage() const
{
	if( image->empty() || winName->empty() )
		return;

	Mat res;
	image->copyTo( res );

	if( rectState == IN_PROCESS || rectState == SET )
		rectangle( res, Point( rect.x, rect.y ), Point(rect.x + rect.width, rect.y + rect.height ), GREEN, 2);

	imshow( *winName, res );
}


void GCApp::mouseClick( int event, int x, int y, int flags, void* )
{
	switch( event )
	{
	case CV_EVENT_LBUTTONDOWN: // set rect or GC_BGD(GC_FGD) labels
		{
			if( rectState == NOT_SET )
			{
				rectState = IN_PROCESS;
				rect = Rect( x, y, 1, 1 );
			}
			showImage();
		}
		break;
	case CV_EVENT_MOUSEMOVE:
		if( rectState == IN_PROCESS )
		{
			rect = Rect( Point(rect.x, rect.y), Point(x,y) );
			showImage();
		}
		break;
	case CV_EVENT_LBUTTONUP:
		if( rectState == IN_PROCESS )
		{
			rect = Rect( Point(rect.x, rect.y), Point(x,y) );
			rectState = SET;
			showImage();
		}
		break;
	}

}

由于cvSetMouseCallback需要回调on_mouse函数,声明一个on_mouse函数,注意,得是 static void

GCApp gcapp;
static void on_mouse( int event, int x, int y, int flags, void* param )
{
	gcapp.mouseClick( event, x, y, flags, param );
}

然后,在需要的地方,加上如下的代码,即完成了对鼠标绘制信息的获取,在这里,是针对矩形绘制的获取:

        const string winName = "DrawRegion";
	cvNamedWindow( winName.c_str(), CV_WINDOW_AUTOSIZE );
	cvSetMouseCallback( winName.c_str(), on_mouse, 0 );
	gcapp.setImageAndWinName( img, winName );
	gcapp.showImage();
	for (;;)
	{
		int c = cvWaitKey(0);
		//////  ESC 键 结束
		if (char(c) == 'x1b' && gcapp.rectState == gcapp.SET)
		{
			break;
		}
	}
	Rect rect = gcapp.rect;
原文地址:https://www.cnblogs.com/moondark/p/4227754.html