OpenCV之截图工具的实现

OpenCV之截图工具的实现

一、通过鼠标事件进行截图工具的实现

#include
#include
using namespace std;
using namespace cv;

Mat srcImage;
Rect roirect;
Point startPoint;
Point endPoint;
void MouseEvent(int event, int x, int y, int flags, void*)
{
	//if (event == CV_EVENT_LBUTTONUP||!(flags&CV_EVENT_FLAG_LBUTTON))
	//{
	//	startPoint = Point(-1,-1);
	//}
	if (event == CV_EVENT_LBUTTONDOWN)
	{
		startPoint = Point(x, y);
	}
	else if (event==CV_EVENT_MOUSEMOVE && (flags&CV_EVENT_FLAG_LBUTTON))
	{
		endPoint=Point(x,y);
		Mat tempImage = srcImage.clone();
		//rectangle(src,原点,终点,linecolor,linewidth,linetype,0);
		//rectangle(src,Rect(原点,width,height),linecolor,linewidth,linetype,0);
		rectangle(tempImage,startPoint,endPoint,Scalar(255,0,0),2,8,0);  
		//rectangle(srcImage, startPoint, endPoint, Scalar(255, 0, 0), 2, 8, 0);
		imshow("srcImage",tempImage);
	}
	roirect.width = abs(endPoint.x - startPoint.x);
	roirect.height = abs(endPoint.y - startPoint.y);
	if (roirect.width > 0 && roirect.height > 0)
	{
		roirect.x = min(startPoint.x, endPoint.x);
		roirect.y = min(startPoint.y, endPoint.y);
		Mat roiMat = srcImage(Rect(roirect.x, roirect.y, roirect.width, roirect.height));
		imshow("ROI", roiMat);
		imwrite("E:/Images/nine1.png", roiMat);
	}
}
int main()
{
	srcImage = imread("E:/Images/nine.png");
	//resize(srcImage, srcImage, Size(), 0.25, 0.25);
	if (!srcImage.data)
		return -1;
	namedWindow("srcImage");
	imshow("srcImage", srcImage);
	setMouseCallback("srcImage",MouseEvent,0);
	waitKey(0);
	return 0;
}

这是单纯的单次截图实现
下面可以实现多次的截图实现

二、通过OpenCV中tracking模块中带的selectROI()API进行截图的实现

/**********截图工具selectROI ******************/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

using namespace std;
using namespace cv;
using namespace cv::xfeatures2d;
int main()
{
	Mat Image = imread("E:/Images/ten.jpg");
	if (Image.empty())
		return -1;
	imshow("Image", Image);
	char windowname[100];
	Rect2d rect = selectROI("Image",Image,false,false);   //单次区域截图
	Mat Im = Image(rect);
	imshow("Im", Im);
	//vector rect1;
	//selectROI("picture", Image, rect1, false);    //多次区域截图 ENTER表完成 ESC表退出显示所有截的图
	//vector obj;
	//for (int i = 0; i < rect1.size(); i++)
	//{
	//	sprintf(windowname, "%d.jpg", i);    
	//	obj.push_back(rect1[i]);
	//	Mat Im = Image(rect1[i]);
	//	imshow(windowname, Im);
	//}
	waitKey(0);
	return 0;
}

最后运行结果都为
OpenCV之截图工具的实现_第1张图片

注:多次截图需要截取一次按一次enter键

欢迎指正批评!!!

欢迎关注微信公众号–木木夕算法笔记,与博主交流!
公众号会时不时更新有趣的图像算法哦!!!

你可能感兴趣的:(OpenCV,图像算法)