一、要在一副图像上加一个滑动条的步骤:
1.先建立一个窗口,该窗口就是而后要把trackba放上去的父窗口。即trackbar属于那个窗口。
2.创建trackbar。要用到函数cvCreateTrackbar函数。
在opencv自带的pdf文件里面可知道该函数的原型如下:
Creates a trackbar and attaches it to the specified window int cvCreateTrackbar( const char* trackbarName, const char* windowName, int* value, int count, CvTrackbarCallback onChange ); trackbarName Name of the created trackbar. windowName Name of the window which will be used as a parent for created trackbar. value Pointer to an integer variable, whose value will reflect the position of the slider. Upon creation, the slider position is defined by this variable. count Maximal position of the slider. Minimal position is always 0. onChange Pointer to the function to be called every time the slider changes position. This function should be prototyped as void Foo(int); Can be NULL if callback is not required. The function cvCreateTrackbar creates a trackbar (a.k.a. slider or range control) with the specified name and range, assigns a variable to be syncronized with trackbar position and speci- fies a callback function to be called on trackbar position change. The created trackbar is displayed on the top of the given window.
trackbarName——就是trackbar的名字,你想给个什么名字就取什么名字
windowName——用于指定trackbar要依附在那个窗口上,注意:该窗口必须先于调用cvCreateTrackbar之前创建,否则trackbar不 会显示在窗口上。
value——自定义一个整数指针变量。trackbar的位置改变的时候,*value就会随着改变。经验:同时*value的值确定了trackbar最一开始时的位置!你大可以把value=10,5;看一看trackbar的初始位置!!实验出真知嘛!!哈哈哈……
count——确定trackbar的范围,最小值默认是0,最大值就是count。滑动条位置取值范围:[0,count]
onChange——trackbar位置改变的时候所调用的函数。该函数的原型必须符合以下原型:void xxxxx( int ) ;函数的名字你随便取。经验:onChange只是一个函数占位符,其实可以改名字是任何你自己定义的函数名!!
3、总之:
1、该函数在名为windowName的窗口上创建一个名为trackbarName的滑动条,滑动条的滑动范围是 [0,count];至于滑动条是在窗口顶部还是底部,这与系统有关。
2、当滑动条位置发生改变的时候同时发生以下两件事,(a)value的值随之改变变为当前的滑动条的位置值,(b)调用名字为onChange的函数。
二、实战例子
对一张灰度图像进行canny边缘检测。用滚动条来确定threshold1、threshold2
//2011/06/14 #include "cv.h" #include "highgui.h" #include <stdio.h> IplImage* src = NULL ; IplImage* dst = NULL ; static const char* wnd_name = "canny" ; static const char* file_name = "lena.jpg" ; static const char* trackbar_name = "threshold" ; void on_track( int pos ) { if( src->nChannels != 1 ) { printf("source image is not gray/n"); } if( pos == 0 ) { cvShowImage(wnd_name,src); } else { cvCanny(src,dst,pos,pos * 3 ,3); cvShowImage(wnd_name,dst); } } int main( int argc,char** argv) { int value = 0 ; src = cvLoadImage( file_name,0 ); dst = cvCreateImage(cvGetSize(src),IPL_DEPTH_8U,1); cvNamedWindow(wnd_name,CV_WINDOW_AUTOSIZE ) ; cvCreateTrackbar( trackbar_name,//const char* trackbarName, wnd_name,//const char* windowName, &value,//int* value, 100,//int count, on_track//CvTrackbarCallback onChange ); on_track(0); cvWaitKey(0); cvDestroyAllWindows(); cvReleaseImage(&src); cvReleaseImage(&dst); return 0 ; }
三、结果
ubuntu+opencv环境下,程序的编译参见鄙人的**学习笔记【1】