Search code examples
pythonopencvtrackbaropencv3.1

How to create Trackbars which do not call any function? OpenCV 3.1 with Python 2.7


I'm trying to threshold an image. I have used the cv2.createTrackbar function as-
cv2.createTrackbar('High H','image',0,179, None).
Now the last part is what I'm having trouble with. Further in my code, I use highH = cv2.getTrackbarPos('High H','image') to get my trackbar value and use it in the cv2.inRange function. So it becomes pretty obvious that I do not need to call a function as the last argument of the function. Now the problem is I can't seem to type in the function. I tried removing the last part, I got an error-

cv2.createTrackbar only works with 5 arguements. Only 4 given.

Hmm, okay seems like I can't skip a part.
Next I tried callback and nothing. I got this error:-

When used nothing:- NameError: name 'nothing' is not defined
When used callback:- NameError: name 'callback' is not defined

Okay after a while I tried using None. Got this error:-

TypeError: on_change must be callable

So how do I use the cv2.createTrackbar function without calling a function?

Thanks!


Solution

  • Why not just create a simple function as expected?

    Simple solution is to define a trivial function that returns the trackbar position. It will be called as the trackbar is moved by the user, but nothing will happen.

    import cv2
    def f(x): return x
    win = cv2.namedWindow("MyImage")
    tb = cv2.createTrackbar("MyTrackbar","MyImage",0,179,f)
    #assume you have some cv2 image already loaded
    cv2.imshow("MyImage", img)
    

    You can also use an anonymous lambda function for the callback, which looks like the following:

    import cv2
    win = cv2.namedWindow("MyImage")
    tb = cv2.createTrackbar("MyTrackbar","MyImage",0,179,lambda x:x)
    #assume you have some cv2 image already loaded
    cv2.imshow("MyImage", img)