環境
- Windows 10
- Python 3.8
- pip
- numpy
インストール
pip install opencv-contrib-python
pythonインタプリタ上からimport cv2
が通ればインストール成功
サンプルコードの実行
注意:閉じるボタンではなく'q'キーで抜ける
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
やっていること
cap = cv2.VideoCapture(0)
cv2.VideoCaptureクラスのインスタンスを取得。インデックス0を指定するとPC搭載カメラになるらしい
# Capture frame-by-frame
ret, frame = cap.read()
無限ループ内でさっきとったcapインスタンスに対し readメソッドを実行
retには取得できたかの True/Falseが、frameにはnumpy.ndarrayが返ってくる
このframeに対して画像処理等をする
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
さっきとってきたframeに対してcv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)とすると色の変換ができる。ここではグレイスケールにしている
他にも cv2.COLOR_BGR2HSV(輝度)などある
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imshow()という関数で'frame'というウィンドウに、gray(配列)を入れて表示する
cv2.waitKey(1)は1 ms表示している間キー入力を待ち受け、取得結果を0xFFでマスクして
'q'と入力されていたら無限ループを抜ける