1

Is it possible to query a webcam from the user in Python using e.g. Plotly Dash and output the frames on the webpage using OpenCV2? How would this work in concrete terms? I have already tried the following code, but the output of the webcam is not displayed.

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)

Unfortunately it didn't show the desired output of the local webcam on the page when the server is running. How might I solve this?

Michel
  • 769
  • 4
  • 19
EchoCache
  • 555
  • 2
  • 8
  • 22

0 Answers0