【RaspberryPi Zero W】カメラモジュールの映像をストリーミングしてブラウザで視聴する

Raspberry Pi Zero Wのカメラ映像をリアルタイムでストリーミングする方法として、以下の手順を実行します。

1: Raspberry Pi Zero Wにカメラモジュールを接続します。接続方法は、モジュールの説明書を参照してください。

2: Raspberry Pi Zero WにOSをインストールし、必要なライブラリやパッケージをインストールします。具体的には、picameraライブラリとflaskパッケージが必要です。インストール方法は、以下のコマンドを実行します。

$ pip install picamera flask

3: ストリーミング用のPythonスクリプトを作成します。以下は、ストリーミング用のスクリプトの例です。この例では、flaskを使用してWebサーバーを起動し、カメラの映像をストリーミングします。

from flask import Flask, render_template, Response
from picamera import PiCamera
import time
import io

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

def gen(camera):
    while True:
        time.sleep(0.1)
        frame = camera.get_frame()
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')

@app.route('/video_feed')
def video_feed():
    return Response(gen(Camera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

class Camera(object):
    def __init__(self):
        self.camera = PiCamera()
        self.camera.resolution = (640, 480)
        self.camera.framerate = 24

    def __del__(self):
        self.camera.close()

    def get_frame(self):
        stream = io.BytesIO()
        self.camera.capture(stream, 'jpeg', use_video_port=True)
        stream.seek(0)
        return stream.read()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, debug=True, threaded=True)

4: templatesフォルダを作成し、index.htmlを作成します。以下は、index.htmlの例です。

<!DOCTYPE html>
<html>
    <head>
        <title>Raspberry Pi Camera Stream</title>
    </head>
    <body>
        <h1>Raspberry Pi Camera Stream</h1>
        <img src="{{ url_for('video_feed') }}">
    </body>
</html>

5: スクリプトを実行します。以下のコマンドを実行します。

$ python streaming.py 
 * Serving Flask app 'streaming'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on all addresses (0.0.0.0)
 * Running on http://127.0.0.1:8000
 * Running on http://192.168.11.247:8000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 535-101-874

実行するとWebサーバーが起動して、リッスン状態になるのでブラウザからアクセスします。

6: ブラウザでhttp://[Raspberry PiのIPアドレス]:8000/にアクセスします。ストリーミング画面が表示されるはずです。