OpenCV:鼠标事件 选取矩形掩膜图像

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sss_369/article/details/86710082

目的:

在图像中选取矩形区域作为ROI,作为掩膜图像。

涉及鼠标操作。

【注】:鼠标操作本质是坐标点的位置。

示例

#include <opencv2/opencv.hpp>
#include <iostream>
#pragma comment(lib,"opencv_world341.lib")
using namespace cv;
using namespace std;

Mat image, img, tmp, dst;

void on_mouse(int event, int x, int y, int flags, void *ustc)
{
	static Point pre_pt = (-1, -1);
	static Point cur_pt = (-1, -1);
	if (event == CV_EVENT_LBUTTONDOWN)//左键按下消息
	{
		image.copyTo(img);
		pre_pt = Point(x, y);
	}
	else if (event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON))//鼠标移动消息 
	{
		img.copyTo(tmp);
		cur_pt = Point(x, y);
		rectangle(tmp, pre_pt, cur_pt, Scalar(0, 255, 0, 0), 1, 8, 0);
		imshow("img", tmp);
	}
	else if (event == CV_EVENT_LBUTTONUP)//左键抬起消息
	{
		image.copyTo(img);
		cur_pt = Point(x, y);
		//rectangle(img, pre_pt, cur_pt, Scalar(255, 255, 255), 1, 8, 0);
		//imshow("img", img);
		int width = abs(pre_pt.x - cur_pt.x);
		int height = abs(pre_pt.y - cur_pt.y);
		if (width == 0 || height == 0)
		{
			return;
		}
		if (width % 4 != 0 || height % 4 != 0)
		{
			width = (width - width % 4);
			height = (height - height % 4);

		}
		int minX = min(cur_pt.x, pre_pt.x);
		int minY = min(cur_pt.y, pre_pt.y);
		//dst = image(Rect(min(cur_pt.x, pre_pt.x), min(cur_pt.y, pre_pt.y), width, height));
		for (int i = minY - 1; i < minY + height; i++)
		{
			for (int j = minX - 1; j < minX + width; j++)
			{
				img.at<uchar>(i, j) = 255;
			}
		}

		for (int i = 0; i < img.rows; i++)
		{
			for (int j = 0; j < img.cols; j++)
			{
				if (img.at<uchar>(i, j) != 255)
				{
					img.at<uchar>(i, j) = 0;
				}
			}
		}

		namedWindow("roi", WINDOW_NORMAL);
		imshow("roi", img);

		//imwrite("roi.bmp",dst);
	}
}


int main()
{

	Mat src_image = imread("1.bmp", 0);
	while (1)
	{
		src_image.copyTo(image);
		image.copyTo(img);
		namedWindow("img", WINDOW_NORMAL);
		setMouseCallback("img", on_mouse, 0);
		imshow("img", img);
		waitKey(0);

		Mat mask_img = img.clone();
		namedWindow("mask", WINDOW_NORMAL);
		imshow("mask", mask_img);
		waitKey(0);		

	}

	return 0;
}

参考文章:

1. https://blog.csdn.net/chenpidaxia/article/details/50975924

2. https://blog.csdn.net/yang332233/article/details/51242817

猜你喜欢

转载自blog.csdn.net/sss_369/article/details/86710082