首页 > 解决方案 > 如何在 Dash (Plotly) 中使用本地网络摄像头在登录页面中显示直播?

问题描述

我想使用本地网络摄像头在 html 页面上实时显示 cam 输出。如果可用,网络浏览器最好使用登陆用户的默认网络摄像头。这是否有可能在 Python 中实现?我考虑过使用 Dash 并尝试了以下代码段:

import dash
import dash_core_components as dcc
import dash_html_components as html

from flask import Flask, Response
import cv2

class VideoCamera(object):
    def __init__(self):
        self.video = cv2.VideoCapture(0)

    def __del__(self):
        self.video.release()
        cv2.destroyAllWindows()

    def get_frame(self):
        success, image = self.video.read()
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()


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

server = Flask(__name__)
app = dash.Dash(__name__, server=server)

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

app.layout = html.Div([
    html.H1("Webcam Test"),
    html.Img(src="/video_feed")
])

if __name__ == '__main__':
    app.run_server(debug=True)

不幸的是,当服务器运行时,它没有在页面上显示所需的本地网络摄像头输出。我该如何解决这个问题?

标签: pythonpython-3.xplotlyplotly-dash

解决方案


推荐阅读