滑动条是我们在OpenCV中经常使用的一个控件,HighGUI提供了滑动条的实现,在OpenCV中滑动条称为trackbar。创建滑动条的函数(这里以C接口为例)cvCreateTrackbar( ),函数原型如下:
int cvCreateTrackbar( const char* trackbar_name, const char* window_name, int* value, int count, CvTrackbarCallback on_change );
前两个参数分别指定了滑动条的名字以及滑动条附属窗口的名字。当滑动条被创建后,会位于窗口的顶部或者底部(由操作系统决定)。滑动条不会遮挡窗口中的图像。
第三个参数value是一个整数指针。当滑动条被拖动时,OpenCV会自动将当前位置所代表的值传递给指针指向的整数。第四个参数count是一个整数数值,为滑动条所能表示的最大值。
最后一个参数是一个指向回调函数的指针。当滑动条被拖动时,回调函数会自动被调用。回调函数必须为CvTrackbarCallback格式,即:
void (*callback) (int position)
不过,这个回调函数不是必须的,所以如果不需要一个回调函数,可以将参数设置为NULL(默认值就是NULL)。没有回调函数,当滑动条被拖动时,唯一的影响就是改变指针value所指向的整数值。
HighGUI还提供了两个函数分别用来读取和设置滚动条的value值,不过前提是必须知道滑动条的名称。
int cvGetTrackbarPos( const char* trackbar_name, const char* window_name ); void cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos );
下面用对《学习OpenCV》书上一个简单的例子进行改进来说明滚动条的具体应用:用滑动条模拟按钮。
#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdio.h> using namespace cv; using namespace std; int g_switch_value = 0; //callback function void switch_callback(int postion); void switch_off_funtion(); void switch_on_function(); int main(int argc, char** argv) { cvNamedWindow("Demo Window", 1); cvCreateTrackbar( "Switch", "Demo Window", &g_switch_value, 1, switch_callback ); while (1) { if (cvWaitKey(15) == 27) { break; } } } void switch_callback(int postion) { if (postion == 0) { switch_off_funtion(); } else { switch_on_function(); } } void switch_on_function() { printf("Switch is On!n"); } void switch_off_funtion() { printf("Switch is off!n"); }
评论已关闭