复制代码
struct MouseParam
{
int m_WinWidth; //窗口大小
int m_WinHeight;
cv::String m_WinName;//窗口名称
cv::Point m_RoiLeftUp; //Roi区域左上角在原图中的坐标,初始值为(0,0)
cv::Mat m_Roi; //最终显示出来的Roi区域的图像矩阵
cv::Mat m_Src; //原始图像
cv::Point m_StartDrag;
cv::Point m_EndDrag;
bool m_Dragging;
cv::Point m_PrevMouse;
};
void onMouse(int event, int x, int y, int flags, void* param)
{
MouseParam * mp = (MouseParam*)param;
cv::Point &prevMouse = mp->m_PrevMouse;
int &roi_width = mp->m_WinWidth;
int &roi_height = mp->m_WinHeight; // 可以根据自己的显示屏分辨率自行设置
cv::Point &roi_lt = mp->m_RoiLeftUp; // roi区域左上角在原图中的坐标,初始值为(0,0)
cv::Mat &roi = mp->m_Roi; // 最终显示出来的roi区域的图像矩阵
cv::Point &startDrag = mp->m_StartDrag;
cv::Point &endDrag = mp->m_EndDrag;
bool &dragging = mp->m_Dragging;
cv::Mat disp = mp->m_Src.clone();
cv::String &winName = mp->m_WinName;
if (event == cv::EVENT_LBUTTONDOWN)
{// 如果鼠标左键按下,则为开始拖动,记录下拖动起始点,并将dragging标志位设为true
startDrag = cv::Point(x, y);
prevMouse = startDrag;
dragging = true;
}
else if (event == cv::EVENT_LBUTTONUP)
{// 如果鼠标左键松开,则为结束拖动,记录下拖动结束点,并将其与拖动起始点的差值加在roi_lt上,并将dragging标志位设为false
//cv::Mat disp = (*(cv::Mat*)param).clone();
endDrag = cv::Point(x, y);
roi_lt += (startDrag - endDrag);
// 判断拖动终点是否超出边界
if (roi_lt.x < 0) roi_lt.x = 0;
if (roi_lt.y < 0) roi_lt.y = 0;
if (roi_lt.x > (disp.cols - roi_width)) roi_lt.x = disp.cols - roi_width;
if (roi_lt.y > (disp.rows - roi_height))roi_lt.y = disp.rows - roi_height;
dragging = false;
// 在原图disp上裁剪出roi区域内的像素并显示
cv::Rect roiRect(roi_lt.x, roi_lt.y, roi_width, roi_height);
roi = disp(roiRect).clone();
cv::imshow(winName, roi);
}
else if (event == cv::EVENT_MOUSEMOVE && dragging)
{// 如果鼠标在按住左键的状态下移动,则一直更新画面
//cv::Mat disp = (*(cv::Mat*)param).clone();
cv::Point mousePos(x, y);
roi_lt += (prevMouse - mousePos);
if (roi_lt.x < 0) roi_lt.x = 0;
if (roi_lt.y < 0) roi_lt.y = 0;
if (roi_lt.x > (disp.cols - roi_width)) roi_lt.x = disp.cols - roi_width;
if (roi_lt.y > (disp.rows - roi_height))roi_lt.y = disp.rows - roi_height;
prevMouse = mousePos;
cv::Rect roiRect(roi_lt.x, roi_lt.y, roi_width, roi_height);
roi = disp(roiRect).clone();
cv::imshow(winName, roi);
}
}
void MatShow(const cv::String &winname,cv::Mat &mat)
{
MouseParam * mp = new MouseParam;
mp->m_WinWidth = 1000;
mp->m_WinHeight= 800;
mp->m_WinName = winname;
mp->m_Src = mat.clone();
cv::Rect roiRect(mp->m_RoiLeftUp.x, mp->m_RoiLeftUp.y, mp->m_WinWidth, mp->m_WinHeight);
mp->m_Roi = mat(roiRect).clone(); // roi
cv::namedWindow(winname);
cv::resizeWindow(winname, cv::Size(mp->m_WinWidth, mp->m_WinHeight));
cv::setMouseCallback(winname, onMouse, mp); // whole display image
cv::imshow(winname, mp->m_Roi);
}