0

OpenCV comes with cv.setMouseCallback(window, callback_function) method allowing to register a function handling mouse events, so handling mouse events does not require a while loop asking for the events.

Is there an OpenCV method or another approach which will allow to register a function handling keyboard events, so that there is no need for a while True: key = cv.waitKey() ...?

And, yes, I am aware of https://stackoverflow.com/questions/52010883/opencv-set-a-vcallback-for-keyboard-event#52011455 question here on stackoverflow, but it relates to C++ and doesn't have an accepted answer, so my question isn't a duplicate of that one. And I have searched the Internet, but haven't yet found anything helpful to see if there is a way to achieve what I am asking for or not.

Claudio
  • 7,474
  • 3
  • 18
  • 48

1 Answers1

0

There is not.

Not really anyway. For some backends (or maybe none right now) there once was some effort to have a startWindowThread(), which would serve your purpose. Notice that it is not documented at all. Do not depend on it. If it's even still implemented for any backend at all, it might not be a backend that's available on your system, and this functionality may be on the chopping block.

You may (or may not) be able to get away with your own thread that spins the event loop. Then you'll have to take care to ferry those keyboard events back into your program. Simply discarding/ignoring them is usually a bad idea. Whether this works, depends on the specific GUI toolkits that is being used. Some do not like getting called into from multiple different threads, i.e. if you spawn a thread for this, you can no longer (safely) do any GUI operations from the main thread.

For easier experimentation, as long as you're only dealing with still pictures instead of moving pictures, I'd recommend Jupyter notebooks and something that acts like the Colab shim cv2_imshow that basically uses IPython.display.Image to show images in-line. That could even be extended to have some "video" characteristics to it (create IPython widget, replace content to update). Matplotlib plots are less suitable for image display because the output is a plot, containing a resampled image, with a lot of white space and axes around it.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36