python - 如何在python中从numpy数组创建png图像文件对象而不保存到磁盘(用于http请求)
问题描述
我需要通过 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
用于保存的关键字。
推荐阅读
- rocket-chip - 如何解决问题“Makefrag:68:目标'simv-freechips.rocketchip.system-DefaultConfig'的配方失败”
- javascript - 很好奇逐步了解涉及let和var的for循环过程
- reactjs - 一次更新多个孩子的状态
- spark-submit - 用于处理每秒 60K 事件的事件负载的 spark-submit 配置
- python - 例外:范围超出网格限制。最大行数:1001,最大列数:20",\n "status": "INVALID_ARGUMENT"
- excel - 从 href 下载文件并循环所有文件以保存在 C 驱动器工作簿中的单独选项卡中
- oracle - 如何修复“警告:使用编译错误创建的函数”?
- android - 即使在卸载应用程序后如何记住登录firebase手机身份验证?
- python - 在内置模块的相对导入和绝对导入之间切换
- mysql - 如何使用查找表产生可读的输出