我有一个烧瓶式web应用程序,它读取一个图像并在我的web浏览器中显示它。
app.py
from flask import Response
from flask import Flask
from flask import render_template
import cv2
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
def GetImage():
global img
while True:
yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(img) + b'\r\n')
@app.route("/stream")
def stream():
return Response(GetImage(), mimetype = "multipart/x-mixed-replace; boundary=frame")
if(__name__ == "__main__"):
img = cv2.imread("Cat.jpg", 0)
app.run(debug = True, threaded = True, use_reloader = False)index.html
<html>
<body>
<img src="{{ url_for('stream') }}">
</body>
</html>这个例子不起作用,因为图像没有显示在浏览器中。但是,当我以以下方式更改GetImage时,该图像将在浏览器中显示:
def GetImage():
global img
(flag, encodedImage) = cv2.imencode(".jpg", img)
while True:
yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(encodedImage) + b'\r\n')那么为什么我需要这个imencode呢?图像在我的硬盘上存储为jpg,所以为什么我必须将它再次编码为JPG
发布于 2019-09-02 22:02:13
如果您有JPEG文件,则可以使用标准的open()和read()将其作为原始字节数据读取,而无需将其解压缩为具有所有像素的数组,因此以后不必使用imencode()将其压缩回JPEG数据。
img = open("Cat.jpg", "rb").read()然后你就可以显示了
b'Content-Type: image/jpeg\r\n\r\n'+ img + b'\r\n'我直接以字节模式( open(..., 'rb') )读取它,因此我不必使用bytearray()将字符串转换为字节。此外,在文本模式下,它可以转换一些字符(如“新行”)并创建不正确的数据。
但是要发送单个文件,可以使用send_file()
@app.route("/image")
def image():
return send_file('Cat.jpg')工作的例子。
在Chrome中打开http://127.0.0.1:5000/stream,它显示图像。
我的火狐在显示图像时遇到了问题--它一直在读取数据直到我添加了time.sleep()。
我还添加了添加头Content-Length:的版本
from flask import Flask, Response, send_file
import time
app = Flask(__name__)
@app.route("/")
def index():
return "Hello World"
def get_image():
while True:
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n'+ img + b'\r\n')
time.sleep(0.01) # my Firefox needs some time to display image / Chrome displays image without it
def get_image_with_size():
length = str(len(img)).encode() # convert to bytes
while True:
yield(b'--frame\r\n'
b'Content-Type: image/jpeg\r\n'
b'Content-Length: ' + length + b'\r\n'
b'\r\n'+ img + b'\r\n')
time.sleep(0.01) # my Firefox needs some time to display image / Chrome displays image without it
@app.route("/stream")
def stream():
return Response(get_image(), mimetype="multipart/x-mixed-replace; boundary=frame")
@app.route("/image")
def image():
return send_file('Cat.jpg')
if(__name__ == "__main__"):
img = open('Cat.jpg', 'rb').read()
app.run()https://stackoverflow.com/questions/57762334
复制相似问题