Home:ALL Converter>Try to broadcast video to multiple clients using cheroot flask and opencv

Try to broadcast video to multiple clients using cheroot flask and opencv

Ask Time:2019-06-23T05:27:41         Author:Anagnostou John

Json Formatter

I am trying to create a video streaming from my Raspberry Pi to multiple clients. Flask does not support WSGI server so i use the cheroot.wsgi Server. i have created a ddns server using noip in order to broadcast the video stream over the internet. Till now i manage to serve the video only to one client even if i use a wsgi server.

Here is the video feeder

from flask import Flask, render_template, Response
from camera import VideoCamera
import RPi.GPIO as gpio


gpio.setmode(gpio.BCM)  
gpio.setup(21, gpio.OUT)


app = Flask(__name__)

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')


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



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

@app.route('/background_process_test')
def background_process_test():
    gpio.output(21, gpio.HIGH)

    print ("Hello")
    return ("nothing")

@app.route('/background_process_test2')
def background_process_test2():
    gpio.output(21, gpio.LOW)

    print ("Hello")
    return ("nothing")

if __name__ == '__main__':
    app.run()

here is the wsgi server using cheroot

try: from cheroot.wsgi import Server as WSGIServer, PathInfoDispatcher except ImportError: print("OK") from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer, WSGIPathInfoDispatcher as PathInfoDispatcher

from main import app
d = PathInfoDispatcher({'/': app})
server = WSGIServer(('0.0.0.0', 5000), d)
if __name__ == '__main__':
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()

The opencv module that captures the camera frames

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)
        self.video.set(cv2.CAP_PROP_FRAME_WIDTH, 160)
        self.video.set(cv2.CAP_PROP_FRAME_HEIGHT, 200)
        # 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()

finally the web page that serves the video feed

<!doctype html>

<html>
<head>
<!--    <link rel="shortcut icon" href="1.ico" type="image/x-icon" />-->

    <title>jindeath</title>



</head>
<body>



hello
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
        $(function() {
          $('a#test').bind('click', function() {
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
                $(function() {
          $('a#test2').bind('click', function() {
            $.getJSON('/background_process_test2',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
</script>

<div class='container'>
    <h3>Test</h3>
        <form>
            <img id="bg" src="{{ url_for('video_feed') }}">
            <a href=# id=test><button class='btn btn-default'>Test</button></a>
            <a href=# id=test2><button class='btn btn-default'>Test</button></a>

        </form>
</body>
</html>

Further more when more than one devices connect to the page my rpi uses 100% of its cpu. any suggestions

Author:Anagnostou John,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56719293/try-to-broadcast-video-to-multiple-clients-using-cheroot-flask-and-opencv
yy