版权声明:欢迎转载,转载请附上链接 https://blog.csdn.net/chenbeifang/article/details/89678419
#include "pch.h"
#include <iostream>
#include <opencv2\opencv.hpp>
using namespace cv;
using namespace std;
#define Mouse
Point pt;//起始点
Point endPoint;//鼠标移动点
bool IsMouseDown = false;
Mutex mutex;//锁定
void OnMouse(int event, int x, int y,int flags, void *param)//鼠标回调函数
{
Mat img = *(Mat*)param;//*(Mat *)=Mat,
switch (event)
{
case CV_EVENT_MOUSEMOVE:
endPoint.x = x;
endPoint.y = y;
break;
case CV_EVENT_LBUTTONDOWN:
IsMouseDown = true;
pt.x = x;
pt.y = y;
break;
case CV_EVENT_LBUTTONUP:
IsMouseDown = false;
mutex.lock();
if (!(endPoint.x < img.rows&&endPoint.y < img.cols))
{
endPoint.x = img.rows;
endPoint.y = img.cols;
}
if(pt.x!=endPoint.x&&pt.y!=endPoint.y)
imshow("clip", img(Rect(pt,endPoint)));
mutex.unlock();
break;
}
}
int main()
{
#ifdef Mouse
Mat img(500, 500, CV_8UC3, Scalar(255, 255, 255));
namedWindow("mouse", CV_WINDOW_AUTOSIZE);
setMouseCallback("mouse", OnMouse, &img);
char tip[100];//文字显示
while (1)
{
mutex.lock();
{
if (IsMouseDown&&pt != endPoint)
{
img = Mat(500, 500, CV_8UC3, Scalar(255, 255, 255));
rectangle(img, pt, endPoint, Scalar(0, 255, 0), 2, 8);
sprintf(tip, "endx:%d endy:%d",endPoint.x,endPoint.y);
putText(img, tip, pt, CV_FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 0, 0));
}
imshow("mouse", img);
}
mutex.unlock();
if (27 == waitKey(10))
break;
}
#endif // Mouse
}