Raspberry Pi 3 + Camera Module 2 :Video Streaming


測試1:利用Youtube或者Facebook (來源:國外教學)

Step 1 :先開啟樹梅派鏡頭使用(raspi-config)

Step 2 :安裝套件
sudo apt-get install libav-tools

Step 3 :到Youtube或Facebook直播設定的地方取得KEY

Step 4 :Youtube的話打開樹梅派終端機,輸入
raspivid -o - -t 0 -vf -hf -fps 20 -b 600000 -w 1280 -h 720 | ffmpeg -re -ar 44100 -ac 2 -acodec pcm_s16le -f s16le -ac 2 -i /dev/zero -f h264 -i - -vcodec copy -acodec aac -ab 128k -g 10 -strict experimental -f flv rtmp://a.rtmp.youtube.com/live2/你的直播KEY

Step 5 :Facebook的話一樣打開樹梅派終端機,輸入
raspivid -o - -t 0 -vf -hf -fps 10 -b 500000 | ffmpeg -re -ar 44100 -ac 2 -acodec pcm_s16le -f s16le -ac 2 -i /dev/zero -f h264 -i - -vcodec copy -acodec aac -ab 128k -g 50 -strict experimental -f flv rtmp://rtmp-api.facebook.com:80/rtmp/你的直播KEY

Step 6 :實際測試都可以使用,但Youtube延遲較嚴重,可透過參數改變來改善,像是-fps後面的偵數、-b後面的bit rate、-g後面接的是關鍵Frame每隔幾偵加入一個(因為是H.264,如果影像一直變動,建議改小,讓畫面更新快一點)、可在bit rate後面加入-w和-h,這是畫面解析度,不更改的話預設是1920*1080


測試2:利用樹梅派開啟HTTP SERVER來串流(除非樹梅派有實體IP,不然只有區網下可見)

Step 1 :創建一個python檔

Step 2 :輸入以下程式 (來源:國外教學)
import io
import picamera
import logging
import socketserver
from threading import Condition
from http import server

PAGE="""\
<html>
<head>
<title>Raspberry Pi - Surveillance Camera</title>
</head>
<body>
<center><h1>Raspberry Pi - Surveillance Camera</h1></center>
<center><img src="stream.mjpg" width="640" height="480"></center>
</body>
</html>

"""

class StreamingOutput(object):
    def __init__(self):
        self.frame = None
        self.buffer = io.BytesIO()
        self.condition = Condition()
    def write(self, buf):
        if buf.startswith(b'\xff\xd8'):
            # New frame, copy the existing buffer's content and notify all
            # clients it's available
            self.buffer.truncate()
            with self.condition:
                self.frame = self.buffer.getvalue()
                self.condition.notify_all()
            self.buffer.seek(0)
        return self.buffer.write(buf)
class StreamingHandler(server.BaseHTTPRequestHandler):
    def do_GET(self):
        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 == '/stream.mjpg':
            self.send_response(200)
            self.send_header('Age', 0)
            self.send_header('Cache-Control', 'no-cache, private')
            self.send_header('Pragma', 'no-cache')
            self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME')
            self.end_headers()
            try:
                while True:
                    with output.condition:
                        output.condition.wait()
                        frame = output.frame
                    self.wfile.write(b'--FRAME\r\n')
                    self.send_header('Content-Type', 'image/jpeg')
                    self.send_header('Content-Length', len(frame))
                    self.end_headers()
                    self.wfile.write(frame)
                    self.wfile.write(b'\r\n')
            except Exception as e:
                logging.warning(
                    'Removed streaming client %s: %s',
                    self.client_address, str(e))
        else:
            self.send_error(404)
            self.end_headers()
class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer):
    allow_reuse_address = True
    daemon_threads = True
with picamera.PiCamera(resolution='640x480', framerate=24) as camera:
    output = StreamingOutput()
    camera.start_recording(output, format='mjpeg')
    try:
        address = ('', 8000)
        server = StreamingServer(address, StreamingHandler)
        server.serve_forever()
    finally:
        camera.stop_recording()

Step 3 :同個網段下的裝置,只要在瀏覽器輸入"樹梅派IP:8000",就可以瀏覽到即時影像(幾乎0延遲)

留言