上下文:我正在尝试使用Plotly Dash创建一个简单的图像处理应用程序。它必须能够显示图像并在更新图像显示的同时对图像执行一些操作。该图像将即时生成或上传到应用程序。
图像采用numpy ndarray
格式,因为我的处理基于使用这种格式的numpy
和matplotlib
操作。
问题: 什么是可以显示ndarray并通过某些GUI操作对其进行更新的Python代码?
我基本上是在寻找破折号可以为matplotlib.pyplot.imshow()
提供的最接近的东西
研究:在我的研究中,我发现this repository可能包含了我开始工作所需的所有基本功能,但作为Plotly Dash的初学者,我努力提取这些内容。我需要的代码,而且似乎也不使用numpy。
我发现了this question,它非常接近我的要求,但是唯一的答案并不包含numpy数组。
答案 0 :(得分:1)
我找到了一个解决方案,其中使用Flask.Response
和src
的{{1}}参数,并且使用html.Img
进行图像编码:
openCV
结果:
在浏览器中,这些条带正在缓慢移动,我想一个gif会提供更好的演示。
注意不要每秒发送太多图像,否则您将使应用程序和浏览器溢出,并且最终会崩溃。因此,请在生成器循环中使用import dash
import dash_core_components as dcc
import dash_html_components as html
import cv2
from flask import Flask, Response
import numpy as np
import time
def get_image(seed=0):
# strip slide
size = 400
res = np.mod((np.arange(size)[..., None] + np.arange(size)[None, ...]) + seed, [255])
ret, jpeg = cv2.imencode('.jpg', res)
return jpeg.tobytes()
def gen():
i = 0
while True:
time.sleep(0.03333)
frame = get_image(i)
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
i += 1
server = Flask(__name__)
app = dash.Dash(__name__, server=server)
@server.route('/video_feed')
def video_feed():
return Response(gen(),
mimetype='multipart/x-mixed-replace; boundary=frame')
app.layout = html.Div([
html.H1("Webcam Test"),
html.Img(src="/video_feed")
])
if __name__ == '__main__':
app.run_server(debug=True)
或其他等效的限制器。
坚强,我仍然对其他人如何做到这一点很感兴趣。这种解决方案的一个缺点是,我认为用户必须共享在路径time.pause
上定义的同一显示。