LoginSignup
2
5

More than 3 years have passed since last update.

Jupyter notebook上でWebカメラから取得した映像をリアルタイム表示する (Python3)

Posted at

参考 (Python2)

  1. OpenCVでWebカメラから映像を取得
  2. 色空間をBGRからRGBに変換
  3. PILでjpegバイナリを得る
  4. IPython.display.displayで画像表示

pngにするとかなり遅いらしい.(参考サイト参照)

from io import BytesIO
import os

import IPython
from PIL import Image
import cv2

# 画像をjpegバイナリに変換してIpythonで表示する
def show(a, fmt='jpeg'):
    f = BytesIO()
    Image.fromarray(a).save(f, fmt) # (3)
    IPython.display.display(IPython.display.Image(data=f.getvalue())) # (4)

cap = cv2.VideoCapture(0)
assert cap.isOpened(), 'Could not open video device'

try:
    while(True):
        ret, frame = cap.read() # (1)

        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # (2)
            show(frame) # (3-4)
            IPython.display.clear_output(wait=True)

except KeyboardInterrupt:
    cap.release()
    print('Stream stopped')
2
5
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
2
5