OpenCV-Python 演習
キー入力を処理する†
ポイント†
- コンソール画面ではなく,cv2.namedWindowによって生成されたウィンドウにフォーカスが当たっている(選択されている)ときにのみキー入力イベントを受け取れる.
- cv2.waitKey(整数)の整数は,1以上のとき,その数(ms)の間だけブロックし(待ち),その間にキー入力があったとき,そのアスキーコードを返す.
- 数ms待ってもキー入力がなかったとき,-1を返し,ブロックから抜ける.
- 【注意】引数を0としたときは,キー入力があるまでブロックする.
- 文字からアスキーコードを得るには,ordを使用する.
- アスキーコードから文字を得るには,chrを使用する.
サンプルコード†
'''
tutorial_007.py
ウィンドウ上のキー入力を処理する
'''
import cv2
import numpy as np
def tutorial_007():
# ウィンドウの表示形式の設定
# 第一引数:ウィンドウを識別するための名前
# 第二引数:ウィンドウの表示形式
# cv2.WINDOW_AUTOSIZE:デフォルト。ウィンドウ固定表示
# cv2.WINDOW_NORMAL:ウィンドウのサイズを変更可能にする
cv2.namedWindow("img", cv2.WINDOW_AUTOSIZE)
cv2.moveWindow("img", 100, 100)
img = np.zeros((480,640,3), np.uint8) # y座標, x座標, チャンネル
img[:,:] = [255, 255, 255]
while True:
cv2.imshow("img", img)
key = cv2.waitKey(0) & 0xff
if key == 0x1b:
break
elif key == ord("r"):
print("Key: \'" + chr(key) + "\' pressed.")
img[:,:] = [0, 0, 255]
elif key == ord("g"):
print("Key: \'" + chr(key) + "\' pressed.")
img[:,:] = [0, 255, 0]
elif key == ord("b"):
print("Key: \'" + chr(key) + "\' pressed.")
img[:,:] = [255, 0, 0]
elif key == ord("w"):
print("Key: \'" + chr(key) + "\' pressed.")
img[:,:] = [255, 255, 255]
elif key == ord("q"):
print("Key: \'" + chr(key) + "\' pressed.")
break
else:
print("Key: \'" + chr(key) + "\' pressed.")
print("Unknown key")
cv2.destroyAllWindows()
if __name__ == "__main__":
tutorial_007()
課題 (exercise_007.py)†
- tutorial_007.pyを拡張し,以下の仕様を持つプログラム(exercise_007.py)を作成しなさい.
- 背景を黒とする.
- 'c'キーが押されたら,画像の中心に,半径120画素,赤色の円を描く.
- 'b'キーが押されたら,画像の中心に,長辺200画素,短辺100画素の青色の矩形を描く.
- 'd'キーが押されたらすべての図形を消去する.
OpenCV-Python 演習