skip to Main Content

I can’t seem to be able to stream a video using my webcam on the website using python

@app.route("/Record" , methods=['GET', 'POST'])
def Record():

        cv2.namedWindow("preview")
        vc = cv2.VideoCapture(0)

        if vc.isOpened(): # try to get the first frame
            rval, frame = vc.read()
        else:
            rval = False

        while rval:
            cv2.imshow("preview", frame)
            rval, frame = vc.read()
            key = cv2.waitKey(20)
            if key == 27: # exit on ESC
                break

        vc.release()
        cv2.destroyWindow("preview")
        return render_template('record.html')

I have tried these codes that i have found online but it only allows the video to be streamed by opening a new window. What should I do?

2

Answers


  1. You can modify you API as following,

    from flask import Response, render_template
    import cv2
    
    @app.route("/Record", methods=['GET', 'POST'])
    def Record():
        def generate_frames():
            vc = cv2.VideoCapture(0)
    
            if vc.isOpened():  # try to get the first frame
                rval, frame = vc.read()
            else:
                rval = False
    
            while rval:
                # Encode the frame into JPEG format
                rval, frame = vc.read()
                if rval:
                    ret, buffer = cv2.imencode('.jpg', frame)
                    frame = buffer.tobytes()
                    yield (b'--framern'
                           b'Content-Type: image/jpegrnrn' + frame + b'rn')
                else:
                    break
    
        return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
    

    Here, I have used yield for every frame and used mimetype multipart/x-mixed-replace; boundary=frame to return the response. Now, you can invoke this API from wherever you want and it will return you video frames. You can design separate HTML page to handle it or by directly open in chrome will also work.

    Login or Signup to reply.
  2. You can achieve this by using a web framework like Flask for the server-side and a combination of HTML, JavaScript, and perhaps a library like Flask-SocketIO for real-time communication.

    from flask import Flask, render_template
    from flask_socketio import SocketIO
    import cv2
    import base64
    from io import BytesIO
    
    app = Flask(__name__)
    socketio = SocketIO(app)
    
    def video_stream():
        vc = cv2.VideoCapture(0)
    
        while True:
            rval, frame = vc.read()
    
            if rval:
                _, buffer = cv2.imencode('.jpg', frame)
                jpg_data = base64.b64encode(buffer).decode('utf-8')
                yield f'data:image/jpeg;base64,{jpg_data}'
    
    @socketio.on('connect')
    def handle_connect():
        socketio.emit('video_feed', video_stream())
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    if __name__ == '__main__':
        socketio.run(app)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search