我正在寻找通过Flask发送大型Numpy数组(主要由图像组成)的最佳方法。
现在,我正在做这样的事情:
服务器端:
np.save(matrix_path, my_array)
return send_file(matrix_path+'.npy')
客户端:
with open('test_temp', 'wb') as f:
f.write(r.content)
my_array = np.load('test_temp')
但是.npy文件很大,因此花费的时间太长。
我考虑过使用h5py,但是由于图像的大小不同(array.shape = (200,)
),因此我无法使用h5py(为每个图像创建数据集都太长了。)
有人知道如何优化它吗?
答案 0 :(得分:0)
由于评论部分实际上才刚刚开始成为一个答案,因此,我将其全部写在这里。
编辑:numpy具有一种内置方法,可以将多个数组压缩到一个文件中,以整齐地打包它们以便发送。结合使用缓冲区而不是磁盘上的文件,这可能是提高速度的最快,最简单的方法。这是一个numpy.savez_compressed
将一些数据保存到缓冲区的快速示例,this question显示了使用flask.send_file
import numpy as np
import io
myarray_1 = np.arange(10) #dummy data
myarray_2 = np.eye(5)
buf = io.BytesIO() #create our buffer
#pass the buffer as you would an open file object
np.savez_compressed(buf, myarray_1, myarray_2, #etc...
)
buf.seek(0) #This simulates closing the file and re-opening it.
# Otherwise the cursor will already be at the end of the
# file when flask tries to read the contents, and it will
# think the file is empty.
#flask.sendfile(buf)
#client receives buf
npzfile = np.load(buf)
print(npzfile['arr_0']) #default names are given unless you use keywords to name your arrays
print(npzfile['arr_1']) # such as: np.savez(buf, x = myarray_1, y = myarray_2 ... (see the docs)
有3种快速方法可以加快文件发送速度。
flask.send_file()
zlib
是标准python发行版的一部分。如果您的数组是图像(或者即使不是),则png compression是无损的,有时可以提供比zlib更好的压缩效果。 Scipy正在对其内置imread
和imwrite
进行折旧,因此您现在应该使用imageio.imwrite
。app.run()
或直接通过flask($flask run
或$python -m flask run
来调用应用程序时被调用的内置开发服务器不支持X-Sendfile功能。这是在烧瓶之类的Apache或Nginx之后运行flask的原因之一。不幸的是,对于每个服务器而言,实现方式并不相同,并且可能需要在文件系统中使用一个文件(尽管如果操作系统支持,您可以使用内存中的文件)。无论您选择哪种部署,这都是rtfm的情况。