Skip to content

Instantly share code, notes, and snippets.

@seraphy
Created February 23, 2019 01:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save seraphy/f36e04aa4379e465ff41266319b5238a to your computer and use it in GitHub Desktop.
Save seraphy/f36e04aa4379e465ff41266319b5238a to your computer and use it in GitHub Desktop.
opencv-pythonでimshowで開いたWindowをcloseボタンで閉じたことを検出する実装例。http://louis-needless.hatenablog.com/entry/how_to_close_opencv_window_by_mouse
import cv2
# pip install opencv-python
# でopenvcを入れて、imshowで画像を表示できるが、
# 1. Windowのcloseボタンを押すとウィンドウは閉じるがハングする。
# 2. destroyAllWindowsで閉じたあとハングする可能性がある
# ... という問題がある。
# 解決策がいくつか提示されている。
# http://louis-needless.hatenablog.com/entry/how_to_close_opencv_window_by_mouse
# https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
BackendError = type('BackendError', (Exception,), {})
def _is_visible(winname):
try:
ret = cv2.getWindowProperty(
winname, cv2.WND_PROP_VISIBLE
)
if ret == -1:
raise BackendError('Use Qt as backend to check whether window is visible or not.')
return bool(ret)
except cv2.error:
return False
ORD_ESCAPE = 0x1b
def closeable_imshow(winname, img, *, break_key=ORD_ESCAPE):
while True:
cv2.imshow(winname, img)
key = cv2.waitKey(10)
if key == break_key:
break
if not _is_visible(winname):
break
for i in range(1,10):
cv2.destroyAllWindows()
cv2.waitKey(1)
cv2.startWindowThread()
img = cv2.imread("assets/imori.jpg")
closeable_imshow("imori", img)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment