我正在寻找通过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(为每个图像创建一个数据集会太长)。
有没有人知道如何优化这个?
由于评论部分真的刚刚开始成为一个答案本身,我会在这里写出来。
编辑: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)
有三种快速方法可以在发送文件时获得一些速度。
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之类的东西背后运行的一个原因。不幸的是,这并没有以相同的方式为每个服务器实现,并且可能需要文件系统中的文件(尽管如果操作系统支持,您可能会使用内存中的文件)。对于您选择的任何部署,这将是rtfm的情况。