2016-11-18 53 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