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

Time:09-30

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?

CodePudding user response:

Maybe if you try cv2.waitKey(1). This worked for me. I also use & 0xFF == 3rd("q"): break after that. So my code, waites for the 'q' key to be pressed to quit the program.

CodePudding user response:

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()
  • Related