opencv waitKey(0) triggers without keypress

Viewed 459

I have a short python script that shows an image with cv2.imshow() and then waits until a key is pressed with cv2.waitKey(0)

import cv2 as cv

...

cv.imshow("Preview", img)
k = cv.waitKey(0)
print(k)

The first time I run the script, it works fine (waits until a key is pressed, and then closes the window and continues the script). However, the second time I run the script, it detects the key I previously used to close the window even though I'm not pressing it.

My setup:

Im using WSL2 kernel 5.10.16.3 with Ubuntu 20.04 on Windows 10 Pro 21376.1 (insider preview for WSLg). using Windows Terminal as my terminal. I've also tested by running wsl through powershell and the issue is the same.

edit: If i run cv.waitKey(1) in a loop and print the output, it looks equivalent to holding down the corresponding key:

> -1
> -1
> -1
> 106
> -1
> -1
> -1
> -1
> 106
> -1
> -1
> -1
> 106

and so on

edit2: pressing any key physically stops the phantom keypresses. I dont know if there is some way to programmatically press a key at the start of the script.. that might be a viable workaround.

0 Answers
Related