1、在raspi-config中使能攝像頭
開啟樹莓派終端,輸入sudo raspi-config
完成後重啟樹莓派
2、檢查攝像頭執行情況
vcgencmd get_camera
raspistill命令列測試拍照
raspistill -v -o test。jpg
執行後如下圖操作:
3、上面都是設定開啟攝像頭及測試,我們接下來要使用python呼叫攝像頭,完成拍照和直播流的功能。
樹莓派4B安裝opencv:
sudo apt-get install -y libopencv-dev python3-opencv
網路不好的,下載會中斷,多執行以上命令幾次就好了,段點續傳。
安裝完成後
輸入命令:
python3
import cv2
看到以下無錯誤顯示即可
4、使用opencv呼叫樹莓派拍照
(1)、 開啟usb攝像頭讀取一張照片
import cv2
import matplotlib。pyplot as plt
#opencv呼叫csi攝像頭優先0,然後usb按順序排列下去
capture = cv2。VideoCapture(0)
# 獲取一幀
ret, frame = capture。read()
plt。imshow(frame[:,:,::-1])#BGRtoRGB
plt。show()
# 釋放資源
capture。release()
5、Csi排線的可以直接用樹莓派官方系統自帶的picamera庫
(1)、捕捉一個影象輸出至檔案
使用capture方法可以輕鬆將捕捉到的影象輸出至指定檔案。 下面這個例項是捕捉一個解析度為1024*768的影象,並將之輸出到foo。jpg中
import time
import picamera
with picamera。PiCamera() as camera:
camera。resolution = (1024, 768)
camera。start_preview()
#攝像頭預熱2秒
time。sleep(2)
#camera。capture(‘foo。jpg’, resize=(320, 240))#可改變解析度
camera。capture(‘foo。jpg’)
(2)、如果你不想使用有損JPEG編碼,並希望加快這一解碼過程的話,可以使用picamera自帶的picamera。array模組。可以使用PiRGBArray類簡單的捕獲‘brg’格式的資料。(假定RGB與BGR是解析度相同的資料,只是具有相反的顏色)
import time
import picamera
import picamera。array
import cv2
with picamera。PiCamera() as camera:
camera。start_preview()
time。sleep(2)
with picamera。array。PiRGBArray(camera) as stream:
camera。capture(stream, format=‘rgb’)#format型別:bgr\rgb\h264
# 此時就可以獲取到bgr的資料流了
image = stream。array
import matplotlib。pyplot as plt
image_resize = cv2。resize(image,(320, 240)) #opencv改變解析度
plt。imshow(image_resize)
6、使用python做一個簡單的遠端監控攝像頭
使用opencv 和python自帶的http庫就能完成(為什麼不用picamera?因為通用呀,不一定樹莓派,只要裝了opencv的硬體,這程式碼就可以執行),使用瀏覽器,輸入樹莓派地址:8080直接顯示,上程式碼:
import cv2
from http import server
import time
#做一個響應主頁面html
PAGE=“”“\
Video Streaming Demonstration
”“”
# 透過opencv獲取實時影片流
video = cv2。VideoCapture(0)
def get_frame(v):
success, image = v。read()
# 因為opencv讀取的圖片並非jpeg格式,因此要用motion JPEG模式需要先將圖片轉碼成jpg格式圖片
ret, jpeg = cv2。imencode(‘。jpg’, image)
return jpeg。tobytes()
def gen(camera):
while True:
frame = get_frame(camera)
# 使用generator函式輸出影片流, 每次請求輸出的content型別是image/jpeg
yield (b‘——frame\r\n’
b‘Content-Type: image/jpeg\r\n\r\n’ + frame + b‘\r\n\r\n’)
class HTTPHandler(server。BaseHTTPRequestHandler):
def do_GET(self):#get資料處理
if self。path == ‘/’: #跳轉至預設頁面
self。send_response(301)
self。send_header(‘Location’, ‘/index。html’)
self。end_headers()
elif self。path == ‘/index。html’:
content = PAGE。encode(‘utf-8’)
self。send_response(200)
self。send_header(‘Content-Type’, ‘text/html’)
self。send_header(‘Content-Length’, len(content))
self。end_headers()
self。wfile。write(content)
elif self。path == ‘/video_feed’:
self。send_response(200)
self。send_header(‘Content-Type’,‘multipart/x-mixed-replace; boundary=frame’)
self。end_headers()
while True:
self。wfile。write(next(cam)) #必須用next()才能執行生成器
self。wfile。write(b‘\r\n’)
else:
self。send_error(404)
self。end_headers()
cam = gen(video)#生成器
try:
print(“http server start。。。”)
address = (‘’, 8080)
server = server。HTTPServer(address, HTTPHandler)
server。serve_forever()
finally:
print(‘done’)