【发布时间】:2020-09-01 19:19:48
【问题描述】:
我已经创建了代码以使用烧瓶在真实条件下运行两个产量,但最近我能够创建一些更改它工作正常但它显示连续响应,如下面快照所述
我的原始代码如下所述
from flask import Flask, render_template, Response, jsonify
import cv2
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
class VideoCamera:
def __init__(self):
# Using OpenCV to capture from device 0. If you have trouble capturing
# from a webcam, comment the line below out and use a video file
# instead.
#self.video = cv2.VideoCapture("rtsp://admin:root%40123@10.1.1.1:554/Streaming/Channels/101")
self.video = cv2.VideoCapture(0)
# # If you decide to use video.mp4, you must have this file in the folder
# as the main.py.
# self.video = cv2.VideoCapture('video.mp4')
def __del__(self):
self.video.release()
def get_frame(self):
success, image = self.video.read()
# We are using Motion JPEG, but OpenCV defaults to capture raw images,
# so we must encode it into JPEG in order to correctly display the
# video stream.
ret, jpeg = cv2.imencode('.jpg', image)
return ret, jpeg.tobytes()
camera = VideoCamera()
@app.route('/')
def index():
return render_template('index.html')
def gen():
while True:
_,frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
def gen1():
while True:
print(camera.get_frame()[0])
yield str(camera.get_frame()[0])
@app.route('/ap')
def p2():
#ab_next = next(gen1())
return Response(gen1())
@app.route('/video_fed')
def video_fed():
return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')
# @app.route('/video_fed')
# def video_fed(camera1):
# ret,_ = camera1.get_frame()
# return jsonify(ret)
if __name__ == '__main__':
#from yourapplication import app
#from gevent.pywsgi import WSGIServer
# http_server = WSGIServer(('0.0.0.0', 5000), app)
# http_server.serve_forever()
app.run(host='0.0.0.0', debug=False)
如果我必须改变什么,或者这件事在性能方面会更好还是我应该改变什么?
【问题讨论】:
-
你相当广泛地使用了
while True:。实际上,这是您在 Web 应用程序中应该避免的事情。 -
我对实时视频流了解不多,这似乎是您想要做的。我确实知道 Flask 应用程序是如何工作的,而且您似乎假设每当提供新请求时都会重新加载脚本(就像 PHP 的情况一样)。因此,您似乎依赖于为每个请求运行的
data = frame1()行,我认为这是您获取新帧的方式。但是,此行只会在每个工作进程初始化时运行一次,因此您不会获得新帧。这可能会对您的代码产生不良影响。我没有看到与循环的连接。 -
您是否尝试过删除视频部分,并使用两个产生某些东西(例如整数)的函数运行代码,以查看问题是否与使用 yield 有关?跨度>
-
我做了一些更改,但我不确定它是否工作正常
标签: python python-3.x flask yield-return