OpenCV 实现对图片截图小Demo

一个opencv小案例 , 读取一张图片后通过鼠标进行截图; opencv 的配置就不多数了,百度很多;


#include <istream>

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include  <sys/timeb.h>
/*
Demo 显示原始图片,然后鼠标切割获取截取图片
*/
using namespace std;
using namespace cv;
bool cutFlag = false;
bool drawRectFlag = false;
void listenMouse(int event, int x, int y, int flag, void* param);
void drawRect(cv::Mat& img, cv::Rect box);
Rect rect;
RNG c_rand(12345);
string winName_s ;
int winIndex = 1;
int main() 
{
try
{
char * srcWinName = "window";
Mat tempImg;
rect = Rect(10, 10, 200, 200);
//读取原始图片
Mat srcImg = imread("D://logo.png");
//Mat srcImg(320, 568, CV_8UC3), tempImage;
//namedWindow(srcWinName, 0);
//resizeWindow(srcWinName, 320 , 568);
//drawRect(srcImg , rect);
//srcImg.copyTo(tempImg);
imshow(srcWinName, srcImg);
setMouseCallback(srcWinName, listenMouse, (void*)&srcImg);
//tempImg = srcImg(rect);
//imshow("win2", tempImg);
waitKey(0);
}
catch (const std::exception& e)
{
cout << "Exception :: " << e.what() << endl;
}
return 0;
}

/*

* 鼠标回调方法

*/

void listenMouse(int event , int x , int y , int flag , void* param) 
{
Mat& image = *(cv::Mat*) param;
Mat tempImg;
image.copyTo(tempImg);
switch (event)
{
case EVENT_MOUSEMOVE:
{
cout << "鼠标移动" << "x : " << x << "y : " << y << endl;
if (cutFlag)
{
rect.width = x - rect.x;
rect.height = y - rect.y;
}
if (drawRectFlag)
{
drawRect(tempImg, rect);
imshow("window", tempImg);
}
}
break;
case EVENT_LBUTTONDOWN:
{
cout << "鼠标按下" << "x : " << x << "y : " << y << endl;
cutFlag = true;
drawRectFlag = true;
rect = Rect(x, y, 0, 0);
}
break;


case EVENT_LBUTTONUP:
{
cout << "Up" << "x : " << x << "y : " << y << endl;
cutFlag = false;
drawRectFlag = false;
if (rect.width<=0 || rect.height <= 0)
{
break;
}
if (rect.width <= 0)
{
rect.x += rect.width;
rect.width *= -1;
}
if (rect.height <= 0)
{
rect.y += rect.height;
rect.height *= -1;
}
//drawRect(image, rect);
Mat cutTempImg = image(rect);
imshow("window", image);
imshow("window_"+to_string(winIndex), cutTempImg);
winIndex++;
}
default:
break;
}
}


/*

* 画矩形

*/

void drawRect(cv::Mat& img, cv::Rect box)
{
cout << "rectBox" << box << endl;
rectangle(img, box.tl(), box.br(), Scalar(64, 64, 255));

}

运行截图 : window 为原图, window_1 则是利用鼠标进行裁剪图片

1:按下鼠标左键 : 记录坐标

2:移动 : 记录X Y 移动长度

3:松开鼠标左键 : 记录坐标后实现截图并创建新窗口显示

OpenCV 实现对图片截图小Demo