使用Flask保存并发送大型numpy数组

问题描述 投票:0回答:1

我正在寻找通过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(为每个图像创建一个数据集会太长)。

有没有人知道如何优化这个?

python numpy flask h5py
1个回答
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)

有三种快速方法可以在发送文件时获得一些速度。

  1. 不要写入磁盘:这个非常简单,只需使用缓冲区存储数据,然后再将其传递给flask.send_file()
  2. 压缩数据:一旦你有二进制数据的缓冲区,有很多压缩选项,但zlib是标准python发行版的一部分。如果您的阵列是图像(或者即使它们不是),png compression也是无损的,有时可以提供比zlib更好的压缩。 Scipy贬值它的内置imreadimwrite所以你现在应该使用imageio.imwrite
  3. 获得性能更高的服务器来实际执行文件发送。当您调用app.run()或直接通过flask调用您的应用程序($flask run$python -m flask run)时调用的内置开发服务器不支持X-Sendfile功能。这是在Apache或Nginx之类的东西背后运行的一个原因。不幸的是,这并没有以相同的方式为每个服务器实现,并且可能需要文件系统中的文件(尽管如果操作系统支持,您可能会使用内存中的文件)。对于您选择的任何部署,这将是rtfm的情况。
© www.soinside.com 2019 - 2024. All rights reserved.