(1)、鼠标操作
创建滑动条并指定回调函数,createTrackbar()原型如下:
指定鼠标操作消息回调函数,setMouseCallback(),原型如下:
wCV_EXPORTS void setMouseCallback(coonst string& winname,MouseCallback onMouse,void* userdate = 0);
inname----窗口名;
onMouse----触发鼠标事件被调用的函数指针;
函数原型:
void Fun(int event,int x,int y,int flags,void * param);
event取值:
enum{
CV_EVENT_MOUSEMOVE = 0,
CV_EVENT_LBUTTONDOWN = 1,
CV_EVENT_RBUTTONDOWN = 2,
CV_EVENT_MBUTTONDOWN = 3,
CV_EVENT_LBUTTONUP = 4,
CV_EVENT_RBUTTONUP = 5,
CV_EVENT_MBUTTONUP = 6,
CV_EVENT_LBUTTONDBLCLK = 7,
CV_EVENT_RBUTTONDBLCLK = 8,
CV_EVENT_MBUTTONDBLCLK = 9,
}
userdata-----用户定义传到回调函数的参数,默认值为0;
(2)、滑动条操作
创建滑动条并指定回调函数,createTrackbar()原型如下:
CV_EXPORTS int creatTrackbar(const string& trackbarname,const string& winname,int* value,int count,TrackbarCallback onChang=0,void* userdate=0);
trackbarname-----滚动条名称
winname-----滚动条所依附的窗口名称(namedWindow创建)
value----指向型指针,表示滑动块位置
count---滑动块最大位置,默认最小为0
onChange----指向回调函数的指针,原型必须为void xxx(int, void*);
userdata -----用户传给回调函数的数据,默认值0
获取滑动条当前位置:
CV_EXPORTS_W int getTrackbarPos(const string& trackbarname,const string& winname);
(3)、例子
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
//Point pt;
//
//void OnMouse(int event, int x, int y, int flags, void* param)
//{
// Mat img = *(Mat*)param;
// switch(event)
// {
// case CV_EVENT_LBUTTONDOWN:
// pt.x = x;
// pt.y = y;
// break;
// case CV_EVENT_LBUTTONUP:
// rectangle(img, pt, Point(x, y), Scalar(0, 255, 0), 2, 8);
// break;
// default:
// break;
// }
// /*if(event == CV_EVENT_LBUTTONDOWN)
// {
// cout<<"Mouse down"<<endl;
// circle(img, Point(x, y), 80, Scalar(255, 255, 0), 2, 8);
// }*/
//
//}
Mat dstImg;
int value = 20;
void OnChange(int, void* param)
{
Mat srcImg = *(Mat*) param;
//threshold(srcImg, dstImg, value, 255, THRESH_BINARY);
Canny(srcImg, dstImg, value, 255);
imshow("TrackBar", dstImg);
}
void main()
{
//Mat img(500, 500, CV_8UC3, Scalar(255, 255, 255));
//namedWindow("Mouse", CV_WINDOW_AUTOSIZE);
//setMouseCallback("Mouse", OnMouse, &img);
//while(1)
//{
// imshow("Mouse", img);
// if(27==waitKey(10)) //按下Esc跳出
// break;
//}
Mat srcImg = imread("1.jpg", 0);
namedWindow("TrackBar", CV_WINDOW_AUTOSIZE);
createTrackbar("Threshold", "TrackBar", &value, 255, OnChange, &srcImg);
//threshold(srcImg, dstImg, value, 255, THRESH_BINARY);
Canny(srcImg, dstImg, value, 255);
imshow("TrackBar", dstImg);
waitKey(0);
}