Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stream python OpenCV output to HTML canvas?

I'm trying to make an web interface for my python OpenCV code using Flask,with the intent of using a canvas HTML element to draw a "crop area" to extract details from the frame stream.Following some examples I've found here on Stackoverflow I was able to stream the output of my OpenCV code to an img element, but not to the canvas nor the video element. Python Code:(Minimal)

import cv2

from flask import Flask, render_template,Response

app = Flask(__name__)

video_capture = cv2.VideoCapture(0)

def gen():    

    while True:
        ret, image = video_capture.read()
        cv2.imwrite('t.jpg', image)
        yield (b'--frame\r\n'
           b'Content-Type: image/jpeg\r\n\r\n' + open('t.jpg', 'rb').read() + b'\r\n')
    video_capture.release()


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

@app.route('/video_feed')
def video_feed():
    """Video streaming route. Put this in the src attribute of an img tag."""
    return Response(gen(),
                mimetype='multipart/x-mixed-replace; boundary=frame')


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

HTML Code:

<html>
<head>
    <title>Video Streaming </title>
</head>
<body>
    <div>
        <h1>Live Video Streaming </h1>
        <img id="img" src = "{{ url_for('video_feed') }}">
    </div>
</body>
</html>
like image 314
Augusto Afonso Avatar asked Jul 20 '26 16:07

Augusto Afonso


1 Answers

For future reference to anyone that bumps into this question,although the answer provided by @furas works as intended, I've found that for my usecase it is also possible to assign the output frame to the canvas background using CSS,allowing to display the video only,and draw freely on top of that.

HTML Code

<html>
<head>
    <title>Video Streaming </title>
</head>
<style>
    .myCanvas{
       background-image: url("{{ url_for('video_feed') }}"); 
    }
</style>
<body>
    <div>
        <h1>Live Video Streaming </h1>
        <img id="img" src = "{{ url_for('video_feed') }}">
        <canvas class="myCanvas" height="600" width="480">
    </div>
</body>
</html>
like image 109
Augusto Afonso Avatar answered Jul 23 '26 04:07

Augusto Afonso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!