0
0

More than 3 years have passed since last update.

PC搭載Webカメラの画像をOpenCVから読み込む

Posted at

環境

  • Windows 10
  • Python 3.8
  • pip
  • numpy

インストール

pip install opencv-contrib-python
pythonインタプリタ上からimport cv2 が通ればインストール成功

サンプルコードの実行

参考 
https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html

注意:閉じるボタンではなく'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'と入力されていたら無限ループを抜ける

実行結果

image.png

0
0
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
0
0