M
M
mcrack2020-02-15 13:18:52
Python
mcrack, 2020-02-15 13:18:52

Python - camera broadcast stops if there are multiple users, how to fix?

Hello everyone, I found several scripts on the Internet for displaying an image from the camera on the page and redid it a little, but they all do not work correctly.

For example, I launched the server, opened the browser and see myself, but as soon as I go to the same page from the phone, the video on the computer freezes, as soon as I reload the page on the computer, the video on the phone freezes. I don't understand what the problem is.

# camera.py

import cv2

class VideoCamera(object):
    def __init__(self):
        # Using OpenCV to capture from device 0. If you have trouble capturing
        # from a webcam, comment the line below out and use a video file
        # instead.
        self.video = cv2.VideoCapture(0)
        # If you decide to use video.mp4, you must have this file in the folder
        # as the main.py.
        # self.video = cv2.VideoCapture('video.mp4')

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

    def get_frame(self):
        success, image = self.video.read()
        # We are using Motion JPEG, but OpenCV defaults to capture raw images,
        # so we must encode it into JPEG in order to correctly display the
        # video stream.
        ret, jpeg = cv2.imencode('.jpg', image)
        return jpeg.tobytes()


# app.py

#!/usr/bin/env python
from flask import Flask, render_template, Response

# emulated camera
from camera import VideoCamera

app = Flask(__name__)

@app.route('/')
def index():
    """Video streaming home page."""
    return render_template('index.html')

def gen(camera):
    """Video streaming generator function."""
    while True:
        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():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(VideoCamera()),
                    mimetype='multipart/x-mixed-replace; boundary=frame')

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


index.html
<html>
  <head>
    <title>Video Streaming Demonstration</title>
  </head>
  <body>
    <h1>Video Streaming Demonstration</h1>
    <img src="{{ url_for('video_feed') }}">
  </body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-02-15
@mcrack

Flask is synchronous and single-threaded, so it can handle as many connections at the same time as there are workers running by the wsgi server. Simply put, it is not suitable for video broadcasts.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question