PiCameraをOpenCVでキャプチャ

2019/08/12

Raspbian10.0,Python2.7.16,picamera1.13,OpenCV3.2

# -*- coding: utf-8 -*-
import time
import numpy as np
import cv2
import picamera

size = (320,240)

camera = picamera.PiCamera()
camera.resolution = size
buff = np.empty((size[0]*size[1]*3,),dtype=np.uint8)

time.sleep(2)
camera.capture(buff,'bgr')
img = buff.reshape((size[1], size[0], 3))

cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()


連続的にモニタリングする場合

# -*- coding: utf-8 -*-
import numpy as np
import cv2
import picamera

camera = picamera.PiCamera()
camera.resolution = (320,240)
camera.framerate = 30
buff = np.empty((240*320*3,),dtype=np.uint8)

for ret in camera.capture_continuous(buff,'bgr',True):
    image = buff.reshape((240, 320, 3))
    cv2.imshow('frame',image)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()

qボタンで終了

第3引数のuse_video_portをTrueにすると早くなる、けどラズパイzeroでは指定FPSの半分以下でした。解像度をあげるともっと低くなります。ドキュメントのサンプルコードでは、プレビューしているけど、しなくても変わらないはず。

Whileやタイマーで使いたい場合

buff = np.empty((240*320*3,),dtype=np.uint8)
stream = camera.capture_continuous(buff,'bgr',True)
while True:
    next(stream)
    image = buff.reshape((240, 320, 3))



Capturing to an OpenCV object
https://picamera.readthedocs.io/en/release-1.13/recipes2.html#capturing-to-an-opencv-object

PiCamera.capture()
https://picamera.readthedocs.io/en/release-1.13/api_camera.html#picamera.PiCamera.capture

PiCamera.capture_continuous()
https://picamera.readthedocs.io/en/release-1.13/api_camera.html#picamera.PiCamera.capture_continuous