Aug*_*nso 2 html javascript python opencv flask
我正在尝试使用 Flask 为我的 python OpenCV 代码制作一个 Web 界面,目的是使用画布 HTML 元素绘制“裁剪区域”以从帧流中提取详细信息。以下是我在此处找到的一些示例Stackoverflow 我能够将 OpenCV 代码的输出流式传输到 img 元素,但不能流式传输到画布或视频元素。Python代码:(最少)
import cv2
from flask import Flask, render_template,Response
app = Flask(__name__)
video_capture = cv2.VideoCapture(0)
def gen():
while True:
ret, image = video_capture.read()
cv2.imwrite('t.jpg', image)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + open('t.jpg', 'rb').read() + b'\r\n')
video_capture.release()
@app.route('/')
def index():
"""Video streaming"""
return render_template('index.html')
@app.route('/video_feed')
def video_feed():
"""Video streaming route. Put this in the src attribute of an img tag."""
return Response(gen(),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run()
Run Code Online (Sandbox Code Playgroud)
HTML 代码:
<html>
<head>
<title>Video Streaming </title>
</head>
<body>
<div>
<h1>Live Video Streaming </h1>
<img id="img" src = "{{ url_for('video_feed') }}">
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
为了将来遇到这个问题的任何人参考,尽管@furas提供的答案按预期工作,但我发现对于我的用例,也可以使用CSS将输出帧分配给画布背景,从而允许显示仅视频,并在此基础上自由绘制。
<html>
<head>
<title>Video Streaming </title>
</head>
<style>
.myCanvas{
background-image: url("{{ url_for('video_feed') }}");
}
</style>
<body>
<div>
<h1>Live Video Streaming </h1>
<img id="img" src = "{{ url_for('video_feed') }}">
<canvas class="myCanvas" height="600" width="480">
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)