はじめに
ライブラリのインストール
pip install opencv-python
サンプルコード
import cv2
import os
import datetime
cap = cv2.VideoCapture(0)
os.makedirs('images/', exist_ok=True)
base_path = os.path.join('images', 'example')
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
else:
cv2.imwrite('{}_{}.{}'.format(base_path, datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'), 'jpg'), frame)
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
実行
- 下記のコマンドを実行するとカメラが起動して1秒間に1枚撮影してファイルを保存していきます。
python test.py