Hah*_*pro 6 python opencv callback python-2.7
我阅读了关于cv2.createTrackbar的文档。它说
onChange – 每次滑块改变位置时要调用的函数的指针。这个函数的原型应该是 void Foo(int,void*); ,其中第一个参数是轨迹栏位置,第二个参数是用户数据(参见下一个参数)。如果回调是 NULL 指针,则不会调用回调,而只会更新值。
但我不知道如何将用户数据传递到 Python 中的 onChange 回调中。
我定义了我的回调函数:
def callback(value,cur_img):
cv2.GaussianBlur(cur_img, (5, 5), value)
Run Code Online (Sandbox Code Playgroud)
我得到了错误:
callback() takes exactly 2 arguments (1 given)
Run Code Online (Sandbox Code Playgroud)
因为它只将 bar 值参数传递到回调中。
但我真的需要 cv2.GaussianBlur 函数的 cur_img 。如何将 cur_img 参数传递到回调中?
您可以使用 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
Run Code Online (Sandbox Code Playgroud)