回答編集履歴

2

コード修正

2022/06/09 08:33

投稿

can110
can110

スコア38266

test CHANGED
@@ -31,7 +31,14 @@
31
31
  cv2.imshow("image", img)
32
32
 
33
33
  while True:
34
+ # OpenCV Python: How to detect if a window is closed?
35
+ # https://stackoverflow.com/questions/35003476/opencv-python-how-to-detect-if-a-window-is-closed
36
+ if cv2.getWindowProperty('image', cv2.WND_PROP_VISIBLE) < 1:
37
+ print('ユーザーがウインドウを閉じたので終了')
38
+ is_exit = True
39
+ break
40
+
34
- key = cv2.waitKey(-1) # -1=入力あるまで待つ
41
+ key = cv2.waitKey(1000) # 1待つ
35
42
 
36
43
  if key in [49,50,51]:
37
44
  print(f'{chr(key)}の処理をして次の画像へ')
@@ -43,12 +50,8 @@
43
50
  print('何もせず終了')
44
51
  is_exit = True
45
52
  break
46
- elif key < 0: # キー入力なし
47
- print('画像ウインドウがユーザーにより閉じられたので終了')
48
- is_exit = True
49
- break
50
53
  else:
51
- print('無効な入力なので再入力')
54
+ print('未入力or無効な入力なので再入力')
52
55
 
53
56
  cv2.destroyAllWindows()
54
57
  ```

1

コード修正

2022/06/09 08:03

投稿

can110
can110

スコア38266

test CHANGED
@@ -30,7 +30,6 @@
30
30
  img = np.ones((64,48,3), np.uint8) * i * 25
31
31
  cv2.imshow("image", img)
32
32
 
33
- # キー入力処理
34
33
  while True:
35
34
  key = cv2.waitKey(-1) # -1=入力あるまで待つ
36
35
 
@@ -38,10 +37,14 @@
38
37
  print(f'{chr(key)}の処理をして次の画像へ')
39
38
  break
40
39
  elif key == ord('n'):
41
- print('何も処理せず次の画像へ')
40
+ print('何もせず次の画像へ')
42
41
  break
43
42
  elif key == ord('e'):
44
- print('何も処理せず終了')
43
+ print('何もせず終了')
44
+ is_exit = True
45
+ break
46
+ elif key < 0: # キー入力なし
47
+ print('画像ウインドウがユーザーにより閉じられたので終了')
45
48
  is_exit = True
46
49
  break
47
50
  else: