首页 > 解决方案 > 如何在python中从numpy数组创建png图像文件对象而不保存到磁盘(用于http请求)

问题描述

我需要通过 http 请求将 PNG 图像提交到黑盒服务器。我使用 python3 在 numpy 64x64x3 数组中生成图像。我目前做的是:

  1. 生成图像
  2. 使用 scipy.misc.toimage 将图像保存到磁盘
  3. 从磁盘打开保存的图像文件
  4. 使用 requests 模块发送带有图像打开的图像文件对象的 http 请求

这工作得很好,但我想摆脱第 2 步和第 3 步,所以我不需要先将我的对象保存到磁盘然后再次加载它。相反,我想将我的 numpy 数组转换为与 http 服务器兼容的文件对象并直接发送。(就像你从 open() 得到的一样)

例如,我知道使用 PIL 从 numpy 数组转换为 PNG 图像很容易,但我只发现如何在一个函数中结合保存到磁盘来做到这一点。

非常感谢您的帮助!

到目前为止,这是我的代码:

import numpy as np
import requests
from scipy.misc import toimage

arr = generate64x64x3ImageWithNumpy()
toimage(arr, cmin=0.0, cmax=255.0).save('tmp.png')
d = {'key':API_KEY}
f= {'image': open('tmp.png', 'rb')}
result = requests.post(SERVER_URL, files=f, data=d)

我要这个:

arr = generate64x64x3ImageWithNumpy()

not_on_disk = numpyArrayToPNGImageWithoutSavingOnDisk(arr)

d = {'key':API_KEY}
f = {'image': not_on_disk}
result = requests.post(SERVER_URL, files=f, data=d)

标签: pythonnumpyhttprequestpng

解决方案


您可以将内存中的 iostream 与 savefig 一起使用(https://docs.python.org/3/library/io.html#io.BytesIO

import io
tmpFile = io.BytesIO()
savefig(tmpFile, format='png')

为了验证这是否有效,tmpFile可以将其与保存到磁盘的实际文件进行比较。

# Get contents of tmpFile
tmpFile.seek(0)
not_on_disk = tmpFile.read(-1)

# Save to and load from disk
fname = 'tmp.png'
savefig(fname)
on_disk = open(fname, 'rb').read(-1)

>>>not_on_disk == on_disk
True

编辑您正在考虑使用 scipy 和 pil 而不是 matplotlib,但答案应该相同,包括format用于保存的关键字。


推荐阅读