[opencv]鼠标和键盘的回调方法

来源:互联网 发布:思源网络教学支持 编辑:程序博客网 时间:2024/05/29 02:15

在做行人检测时,我利用帧差法和hog+svm方法扣出了行人的大致图像,但其中有部分图像扣得不太好,或者人重叠在一块。下面实现了一个代码,通过逐一读取文件夹中的图像,利用鼠标进行截图,并保存到指定的文件夹内。下面是我实现的代码,主要是利用了鼠标和键盘的回调方法。

#include"head.h"#include<string.h>/*该程序是读取需要修改(截取)图像的文件夹,逐一读取图像,并利用鼠标进行截图*/CvPoint pt1 = Point(0, 0);CvPoint pt2 = Point(0, 0);bool is_selecting = false;void cvMouseCallback(int mouseEvent, int x, int y, int flags, void* param){switch (mouseEvent){case CV_EVENT_LBUTTONDOWN:pt1 = Point(x, y);pt2 = Point(x, y);is_selecting = true;break;case CV_EVENT_MOUSEMOVE:if (is_selecting)pt2 = Point(x, y);break;case CV_EVENT_LBUTTONUP:pt2 = Point(x, y);is_selecting = false;break;}return;}void _screenshoot(char* strData, char *destData) {vector<string> files;//存储的是当前文件夹下所有的文件名_getFiles(strData, files);Mat strcImg, destImg;string strPath, destPath;int num = 0;char* windowName = "img";bool exitFlag = false;//控制程序离开的标志位namedWindow(windowName, CV_WINDOW_AUTOSIZE);Mat imgShoot;bool shift_on = false;Mat roi;while ((num< files.size()) && !exitFlag) {strPath.assign(strData).append("\\").append(files[num]);strcImg = imread(strPath);//读取的每幅图像Mat imgShoot;//裁剪的图像strcImg.copyTo(imgShoot);setMouseCallback(windowName, cvMouseCallback);strcImg.copyTo(imgShoot);rectangle(imgShoot, pt1, pt2, Scalar(255, 255, 255));imshow(windowName, imgShoot);char key = cvWaitKey(10);switch (key) {case'\t':shift_on = !shift_on; break;//W、A、S、D是控制向上下左右移动的case'A':case 'a':pt1.x--; pt2.x--; break;case'S':case 's':pt1.y++; pt2.y++; break;case'D':case 'd':pt1.x++; pt2.x++; break;case'W':case 'w':pt1.y--; pt2.y--; break;//ROI放大和缩小,主要是对初始设置的ROI区域的边缘进行平移操作case '1':if (shift_on) pt1.x--;else pt2.x--;break;case '2':if (shift_on) pt2.y++;else pt1.y++;break;case '3':if (shift_on) pt2.x++;else pt1.x++;break;case '4':if (shift_on) pt1.y--;else pt2.y--;break;//回车确定最终ROI区域的截取,并将其保存下来case '\r':roi = strcImg(Rect(pt1.x, pt1.y, std::abs(pt2.x - pt1.x), std::abs(pt2.y - pt1.y)));//确定输出的路径destPath.assign(destData).append("\\").append("In_").append(files[num]);imwrite(destPath, roi);cout << "已保存图像: " << destPath << endl;++num;cvDestroyWindow(windowName);pt1 = Point(0, 0);pt2 = Point(0, 0);break;case'N':case 'n'://下一幅图像++num;pt1 = Point(0, 0);pt2 = Point(0, 0);cvDestroyWindow(windowName);break;case'E':case'e'://离开程序cvDestroyWindow(windowName);exitFlag = true;break;}//switch}//while//*/cout << "There is no images" << endl;}
注意:上面是核心代码,并不完全,主函数的话就是单纯地写入原来图像的路径和打算放入图像的路径。_getFiles函数实现的是读取指定路径下的所有文件