OpenCV利用鼠标进行矩形ROI选取

在进行图像处理时,往往是对ROI区域进行局部处理,利用鼠标选取ROI区域显然可以更加方便。

OpenCV选取唯一矩形ROI区域的代码如下:

#include 
#include 
#include 
#include 

#pragma comment(lib, "opencv_core245d.lib")
#pragma comment(lib, "opencv_highgui245d.lib")

cv::Mat matInit;
cv::Mat matSrc;
cv::Mat matDst;

cv::Rect	rectSelect;
cv::Point	ptOrigin	= cv::Point(-1, -1);
cv::Point   ptCurrent	= cv::Point(-1, -1);

std::string windowName = "orig";

void onMouse(int event, int x, int y, int flags, void *param)
{
	if (matSrc.data == NULL)
		return;

	if (x > matSrc.cols || y > matSrc.rows)
		return;

	int		fontFace	= CV_FONT_HERSHEY_COMPLEX_SMALL;
	double	fontScale	= 1;
	int     thickness	= 1;
	int     lineType	= CV_AA;

	char	strTemp[16];

	if (event == CV_EVENT_LBUTTONDOWN)	{

		matInit.copyTo(matSrc);
		matInit.copyTo(matDst);

		sprintf(strTemp, "(%d,%d)",x,y);
		ptOrigin = cv::Point(x, y);
		rectSelect = cv::Rect(x, y, 0, 0);

		cv::putText(matSrc, strTemp, ptOrigin, fontFace, fontScale, 
			cv::Scalar(0, 0, 0));
		cv::circle(matSrc, ptOrigin, 3, cv::Scalar(0xFF, 0, 0), 
			CV_FILLED, lineType);

		cv::imshow(windowName, matSrc);
		matSrc.copyTo(matDst);

	}else if (event == CV_EVENT_MOUSEMOVE && 
		(flags & CV_EVENT_FLAG_LBUTTON))	{

			matDst.copyTo(matSrc);

			sprintf(strTemp, "(%d,%d)",x,y);
			ptCurrent = cv::Point(x, y);

			rectSelect.x = MIN(ptOrigin.x, ptCurrent.x);
			rectSelect.y = MIN(ptOrigin.y, ptCurrent.y);
			rectSelect.height = abs(ptOrigin.y - ptCurrent.y);
			rectSelect.width  = abs(ptOrigin.x - ptCurrent.x);
			rectSelect &= cv::Rect(0, 0, matSrc.cols, matSrc.rows);

			cv::putText(matSrc, strTemp, ptCurrent, fontFace, fontScale, 
				cv::Scalar(0, 0, 0));
			cv::rectangle(matSrc, ptOrigin, ptCurrent, cv::Scalar(0, 0xFF, 0), 
				thickness, lineType);
			cv::imshow(windowName, matSrc);

	}else if (event == CV_EVENT_LBUTTONUP)	{

		sprintf(strTemp, "(%d,%d)",x,y);
		ptCurrent = cv::Point(x, y);

		rectSelect.x = MIN(ptOrigin.x, ptCurrent.x);
		rectSelect.y = MIN(ptOrigin.y, ptCurrent.y);
		rectSelect.height = abs(ptOrigin.y - ptCurrent.y);
		rectSelect.width  = abs(ptOrigin.x - ptCurrent.x);
		rectSelect &= cv::Rect(0, 0, matSrc.cols, matSrc.rows);

		cv::putText(matSrc, strTemp, ptCurrent, fontFace, fontScale, 
			cv::Scalar(0, 0, 0));
		cv::circle(matSrc, ptCurrent, 3, cv::Scalar(0xFF, 0, 0), 
			CV_FILLED, lineType);
		cv::rectangle(matSrc, ptOrigin, ptCurrent, cv::Scalar(0, 0xFF, 0), 
			thickness, lineType);
		cv::imshow(windowName, matSrc);

	}

}

int main(int argc, char *argv[])
{
	matInit = cv::imread("lena.jpg");
	if (matInit.data == NULL)
	{
		std::cout << "Opening file failed!" << std::endl;
		return -1;
	}

	matSrc = matInit.clone();
	matDst = matInit.clone();

	cv::namedWindow(windowName);
	cv::setMouseCallback(windowName, onMouse, NULL);
	cv::imshow(windowName, matSrc);

	cv::waitKey(0);

	return 0;
}

效果图:

OpenCV利用鼠标进行矩形ROI选取_第1张图片

 

工程code

点击打开链接

你可能感兴趣的:(OpenCV,鼠标,OpenCV,ROI)