LoginSignup
3
3

More than 3 years have passed since last update.

OpenCVのimshow画面でバツを押すとプロセスだけが残る問題の解決方法

Posted at

環境

 Python 3.7.8
 OpenCV 3.4.2

問題

 例えばこのレナさんの画像。
lena.jpeg

 通常であれば以下のコードで画像を表示し、適当なキーを押すとウィンドウが閉じます。しかし、閉じるボタン押した場合、ウィンドウは閉じるのですがpythonのプロセスは実行されたままになります。

open.py
import cv2 

img = cv2.imread("lena.jpg")

#画像を表示
cv2.imshow("img", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

解決方法

 他の方の手法と基本的には同じなのですが、コードを少しだけ短くしたのと、従来通りすべてのキー入力にも対応させたのがオリジナリティです。

import cv2

img = cv2.imread("lena.jpg")

while(1):
    cv2.imshow('img', img)
    key = cv2.waitKey(100) & 0xff
    if key != 255 or cv2.getWindowProperty('img', cv2.WND_PROP_AUTOSIZE) == -1:
        cv2.destroyAllWindows()
        exit()

 同じことで困っている方の助けになればと思います。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3