Как обновить поле данных html-страницы потоком данных из видеообработки - PullRequest
0 голосов
/ 02 ноября 2019

Я обрабатываю видеопоток, используя обработку изображений opencv. В каждом кадре я получаю поле данных под названием статус. Сейчас я транслирую это видео на html-страницу с помощью приложения фляги. Я хочу добавить этот поток данных статуса вместе с видео потоком на html-странице.

app.py:

import cv2
import numpy as np
from imports.vehicleDetection import BoundingBox
from flask import Flask, render_template, Response, session, request, stream_with_context, app

app = Flask(__name__)
app.secret_key = 'mahinsa@12345678'

def stream_template(template_name, **context):
    print('stream_template')
    # http://flask.pocoo.org/docs/patterns/streaming/#streaming-from-templates
    app.update_template_context(context)
    t = app.jinja_env.get_template(template_name)
    rv = t.stream(context)
    # uncomment if you don't need immediate reaction
    ##rv.enable_buffering(5)
    return rv

@app.route('/')
def index():
    # return the rendered template
    return render_template("form.html")


@app.route('/submit', methods = ['POST', 'GET'])
def start():
    if request.method == 'POST':
        inputVideo = request.form['input']
        cameraFocalLength = request.form['cfl']
        session["inputVideo"]=inputVideo
        session["cameraFocalLength"]=cameraFocalLength
        return render_template("view.html")

def gen():
    bb = BoundingBox()
    video=session.get("inputVideo",None)
    cameraFocalLength=session.get("cameraFocalLength",None) 
#    if int(video)==0:
#        capture = cv2.VideoCapture(0)
#    elif int(video)==1:
#        capture = cv2.VideoCapture(1)
#    else:
    capture = cv2.VideoCapture(video+'.mp4')

    def dataPass(status):
        print('datapass')
        def genarate(status):
            yield status
        return Response(stream_template("view.html", status = genarate(status)))


    while True:
        ret, frame = capture.read()
        if ret == False:
            continue
        pro_image, status = bb.getBoundingBox(frame, int(cameraFocalLength))
        dataPass(status)
        resized = cv2.resize(pro_image, (int(pro_image.shape[1]/2), int(pro_image.shape[0]/2)))
        # encode the frame in JPEG format
        encodedImage = cv2.imencode(".jpg", resized)[1].tobytes()
        yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + bytearray(np.array(encodedImage)) + b'\r\n')            

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


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

Ниже приведен HTML-код, и я хочу связать этот статус обгона споток данных о состоянии, который идет с видео потоком.

html:

<html>
<head>
<link rel="stylesheet" href="{{ url_for('static', filename='css/my.css') }}">
</head>
<body>

    <div class="container">

                <div class="container2">
                    <h3>Video Streaming Demonstration</h3>
                    <img src="{{ url_for('video_feed') }}">
                </div>
                <div>
                    <h3>{{ status }}</h3>
                </div>

    </div>

</body>
</html>
...