Douzooo
Douzooo

Reputation: 1

Streaming the hosts webcam onto a webpage in Python

I want to record my webcam in python and livestream it per flask to my website When i open the website on the route "/" it doesnt show anything and on "/video_feed" it just gives an img tag that updates but i want a video tag.

index.py

import cv2
from flask import Flask, render_template, Response

app = Flask(__name__)
camera = cv2.VideoCapture(0)

def generate_frames():
    while True:
        success, frame = camera.read()
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
                   
@app.route('/')
def index():
    return render_template('index.html')

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

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

Html page in "./templates":

<!doctype html>
<html>
  <head>
    <title>Webcam Stream</title>
  </head>
  <body>
    <h1>Webcam Stream</h1>
    <video id="video" width="640" height="480" autoplay></video>
    <script>
      var video = document.getElementById('video');
      var source = new EventSource('/video_feed');
      source.onmessage = function(event) {
        video.src = URL.createObjectURL(event.data);
      };
    </script>
  </body>
</html>

Examples: YouTube, Twitch Livestreams, Online-Live-Casinos, etc.

I tried searching github repositories and didnt find anything that comes close to this.

Upvotes: 0

Views: 409

Answers (0)

Related Questions