Python Image Window Not Closing Properly on Mac

Viewed 421

I'm working with OpenCV and trying to figure this out. When I want to read and show an image:

import cv2

img = cv2.imread('baboon.jpg', 0)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyWindow('image')

I write this. But whenever the image display window pops up, I'm not able to close it and execute everything after

cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyWindow('image')

because the window will not close unless I quit it.

For example, if I run this code

import cv2

img = cv2.imread('baboon.jpg', 0)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyWindow('image')
#Nothing after this will get executed
print('Hello')

I get no output in my console, but the image window does pop up.

How can I fix this?

(I'm using Pycharm if that helps)

EDIT:

It seems that whenever I press any key the window closes and it works as intended (code after the comment is executed). Not sure why this is happening.

2 Answers

I believe the quit is acting as an interrupt, which quits the entire python program. This is different than pressing a key, which is incorporated into the logic of the actual program and continues to completion:

cv2.waitKey(0) # waits for any key to be pressed to continue the logic of the program
# this is what actually allows you to "display" an image without it immediately disappearing.

I believe you can click on anywhere in the pic and it would return to the code window

Related