When using waitKey(0) in a loop with some delays, more key presses are ‘picked up’ before waitKey is ever called for a second time. In case this is OS specific I am using Windows
To illustrate what I mean here’s a small example:
import cv2
import time
import numpy as np
empty = np.zeros((400,400),dtype=np.uint8)
while True:
cv2.imshow('empty', empty)
k = cv2.waitKey(0)
print(k)
time.sleep(3)
print("sleep over")
If I run this and press a key, as expected it will print the keycode and then “sleep over” after 3 seconds. However if I rapidly press many keys after the first one, before “sleep over” is ever printed, the program will continue to (over a long period of time) print every key press that occurred in that short space of time before “sleep over” was printed and subsequently waitKey had a chance to be called for the second time.
What I would expect to happen is that no more key presses are picked up because before the sleep is over waitKey has only been called once, so any additional key presses that occur before then shouldn’t be stored anywhere.
Does anyone know why this happens? Where is this buffer/queue of key presses being stored and can it be manually cleared?
The thing occurs with any other wait times as well, i.e
import cv2
import time
import numpy as np
empty = np.zeros((400,400),dtype=np.uint8)
while True:
cv2.imshow('empty', empty)
k = cv2.waitKey(1)
if k!=-1:
print(k)
time.sleep(3)
print("sleep over")
edit: it’s also worth mentioning this isn’t a scheduling thing either, it is not exclusive to sleep and occurs when sleep is replaced with intensive computation - which is how I came across this issue in the first place.