'Serving local webcam video stream to web with "multipart mixed replace" HTTP response
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)
Solution 1:[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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Basj |