2016-11-18 52 views
1

我阅读了关于cv2.createTrackbar的文档。它说,cv2.createTrackbar将用户数据参数传入回调

onChange – Pointer to the function to be called every time the slider changes position. This function should be prototyped as void Foo(int,void*); , where the first parameter is the trackbar position and the second parameter is the user data (see the next parameter). If the callback is the NULL pointer, no callbacks are called, but only value is updated.

但我不知道如何将用户数据传递到Python中的onChange回调。

我定义我的回调函数:

def callback(value,cur_img): 
    cv2.GaussianBlur(cur_img, (5, 5), value) 

我得到了错误:

callback() takes exactly 2 arguments (1 given) 

,因为它仅通过酒吧值参数步入回调。
但我真的需要cur_img为cv2.GaussianBlur函数。我怎样才能将cur_img参数传递给回调函数?

+0

你能不能声明cur_img的输入(在回调被调用之前)并将其作为全局变量在回调中? –

回答

1

您可以使用lambda表达式作为回调函数来创建函数闭包。在课堂中包装玩家时,我遇到了同样的问题,并希望使用我的课程实例的属性。下面的类方法的片段。

def play(self): 
    ... other code... 
    cv2.namedWindow('main', cv2.WINDOW_NORMAL) 
    cv2.createTrackbar('trackbar', 'main', 0, 
     100, 
     lambda x: self.callback(x, self) 
     ) 
    ... other code... 

def callback(tb_pos, self): 
    #tb_pos receives the trackbar position value 
    #self receives my class instance, but could be 
    #whatever you want