1

This article shows how to stream a local webcam to the browser with Python + Flask + OpenCV + multipart HTTP response.

After launching the following self-contained code with Python, when opening http://127.0.0.1:5000/ I see the webcam is being read (green LED on), I see that a /video_feed request is done by the browser, but strangely, the print(time.time()) is not displayed and no image is updated on the browser.

Is there something which prevents continuous endless multipart/x-mixed-replace; boundary=frame requests to be successful?

from flask import Flask, render_template, Response
import cv2, time
app = Flask('hello')
camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # CAP_DSHOW because of https://answers.opencv.org/question/234933/opencv-440modulesvideoiosrccap_msmfcpp-682-cvcapture_msmfinitstream-failed-to-set-mediatype-stream-0-640x480-30-mfvideoformat_rgb24unsupported-media/
def gen_frames():  
    while True:
        print(time.time())
        success, frame = camera.read()
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/video_feed')
def video_feed():
    return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/')
def index():
    return """
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-8  offset-lg-2">
            <h3 class="mt-5">Live Streaming</h3>
            <img src="/video_feed" width="100%">
        </div>
    </div>
</div>
</body>        
    """
app.run(debug=True)
Basj
  • 41,386
  • 99
  • 383
  • 673
  • 1
    Works perfectly fine for me with constant real-time image updates and the current timestamp being printed on the console. I changed it to `camera = cv2.VideoCapture(0)` – nathancy May 06 '22 at 08:32
  • @nathancy did it work for you in `app.run(debug=True)` mode? For me it finally worked after disabling this debug mode. I don't know why. – Basj May 06 '22 at 08:49
  • 1
    Yes it worked with `debug=True` didn't change anything else – nathancy May 06 '22 at 09:32

1 Answers1

1

Not sure about the reason, but finally it works if and only if I turn debug mode off:

app.run()

instead of

app.run(debug=True)
Basj
  • 41,386
  • 99
  • 383
  • 673