简体   繁体   中英

Python Opencv2 imshow is closing immediately even with waitKey(0)

I'm using wsl2 and VScode as the editor. The code in question is simply:

image = cv2.imread('sample.png')
cv2.imshow('image', image)
cv2.waitKey(0)

The first run goes smoothly and lets me inspect the image until I press a button. However after the first run the picture shows up for a quarter of a sec and then disappears. Any idea what could be causing this?

However after the first run the picture shows up for a quarter of a sec and then disappears.

This appears to be a problem triggered by the first run. Could it be that you'll need to add cv2.destroyAllWindows() to the end of your code?

import cv2

image = cv2.imread('sample.png')
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

I don't know the problem but a workaround worked for me.

I don't press any key to close the OpenCV window. I kill the terminal using the 🗑️ button in the VSCode terminal.

Please consider if even 1 time you press any key to close the OpenCV window, then you have to restart your WSL. So, from the beginning, just kill the terminal instead of pressing any key.

But this is just a temporary workaround. I hope other people can help to find the root cause.

我遇到了同样的问题,并且能够通过在此处更新我的WSL version来解决它:

aka.ms/wslstorepage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM