flask上的视频流没有错误,但它只是在运行应用程序,而不是在浏览器上显示



我想在烧瓶框架上播放一段视频。我最初尝试流式传输相机视频。没有错误,但它不起作用。实际上,它并没有在html页面上进行流式传输。它加载html页面,但不显示我想要的视频。

app.py:
import cv2
import numpy as np
from flask import Flask, render_template, Response
app = Flask(__name__)
@app.route('/')
def index():
# return the rendered template
return render_template("view.html")
def gen():
while True:
capture = cv2.VideoCapture(0)
ret, frame = capture.read()
if ret == False:
continue
# encode the frame in JPEG format
encodedImage = cv2.imencode(".jpg", frame)
yield (b'--framern'b'Content-Type: image/jpegrnrn' + bytearray(np.array(encodedImage)) + b'rn')

@app.route('/video_feed')
def video_feed():
return Response(gen(),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(debug = True)

这是我的html代码。

view.html:
<html>
<head>
<title>Pi Video Surveillance</title>
</head>
<body>
<h1>Pi Video Surveillance</h1>
<img src="{{ url_for('video_feed') }}">
</body>
</html>

只需将capture = cv2.VideoCapture(0)写入def gen():中的while True:之外。

以下是修改后的def gen()函数:

def gen():
capture = cv2.VideoCapture(0)
while True:
ret, frame = capture.read()
if ret == False:
continue
# encode the frame in JPEG format
encodedImage = cv2.imencode(".jpg", frame)
yield (b'--framern'b'Content-Type: image/jpegrnrn' + bytearray(np.array(encodedImage)) + b'rn')

使用Mehul Purohit答案将遇到以下问题。

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray

更改以下内容对我来说是可行的。

yield (b'--framern'
b'Content-Type: image/jpegrnrn' + cv2.imencode('.jpg', frame)[1].tobytes() + b'rnrn')

相关内容

最新更新