➣ Reading Time: 7 minutes

前言

此為我測試 Raspberry Pi 3 / 樹莓派 照相機模組的筆記

去設定開啟照相機功能

sudo raspi-config

範例程式碼

外接 hdmi 直接顯示於螢幕

如果有外接 hdmi,可以使用這組 (會直接將畫面呈現並覆蓋於螢幕上)
開啟攝影機並顯示 10秒鐘 (使用 python 控制)

from picamera import PiCamera
from time import sleep

camera = PiCamera()

camera.start_preview()
sleep(10)
camera.stop_preview()

透過遠端桌面,搭配 OpenCV 顯示視窗來顯示畫面

上述方法是直接顯示畫面於螢幕上,但如果透過遠端桌面會看不到,
因此我們先將圖片存下來 (tmp.jpg),然後再使用 OpenCV 輸出畫面。

from picamera import PiCamera
from time import sleep
import cv2

wait_time = 1

def close_cv2_window():
    cv2.destroyAllWindows()
    camera.stop_preview()
    exit()


def show_img_OpenCV(img):
    cv2.imshow('test', img)
    #cv2.waitKey(1)

    ch = cv2.waitKey(wait_time)

    if cv2.getWindowProperty('test',1) == -1 :
        close_cv2_window() # break

    if ch & 0xFF == ord('q'): # q
        close_cv2_window()

    if ch == 27: # ESC
        close_cv2_window()        #break


def resize_img(img):
    scale_percent = 50
    width = int(img.shape[1] * scale_percent / 100)
    height = int(img.shape[0] * scale_percent / 100)
    dim = (width, height)
    resize_img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)

    return resize_img

def read_img(path):
    cv2_img = cv2.imread(path)
    return resize_img(cv2_img)

camera = PiCamera()

camera.start_preview()

while(True):
    # sleep(wait_time)
    path = '/home/pi/Desktop/tmp.jpg'
    camera.capture(path)
    cv2_img = read_img(path)
    show_img_OpenCV(cv2_img)

Reference