daniel451
daniel451

Reputation: 10992

OpenCV: wait for different keys?

I am working with OpenCV and I want OpenCV to not wait for any key being pressed (default behaviour of cv2.waitKey()), but to wait for specific keys that I define (and do subsequent actions).

My current solution for this problem is the following recursive one:

def opencv_wait():
    # wait for keypress; capture it
    k = cv2.waitKey(0)

    if k == 27:  # this should be ESC
        return   # e.g. end the program
    elif k == some_key:      # some other keys...
        do_some_function()   # ...and actions to do after key is pressed
    else:
        opencv_wait()        # recursively call opencv_wait() for looping

My question is: is this solution a convenient way to let OpenCV wait for different keys?

Is there a faster / better way to achieve what I want to do?

Basically I want OpenCV to wait (with as little resources wasted as possible) infinitely long until specific keys are pressed that should trigger subsequent actions.

Upvotes: 4

Views: 2773

Answers (1)

Giebut
Giebut

Reputation: 392

If it is not neccessary you could try non-recursive approach:

def is_pressed(key)
    # if statement

def opencv_wait():
    key = 0

    while is_pressed(key) :
        key = cv2.waitKey(0)

Upvotes: 1

Related Questions