我需要使用 http 请求将 PNG 图像提交到黑盒服务器。我使用 python3 在 numpy 64x64x3 数组中生成图像。我目前做的是:
- 生成图片
- 使用 scipy.misc.toimage 将图像保存到磁盘
- 从磁盘打开保存的图像文件
- 使用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)
最佳答案
您可以将内存 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
关键字。
关于python - 如何在不保存到磁盘的情况下从 python 中的 numpy 数组创建 png 图像文件对象(对于 http 请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53339373/