【问题标题】:How to create png image file-object from numpy array in python without saving to disk (for http request)如何在python中从numpy数组创建png图像文件对象而不保存到磁盘(用于http请求)
【发布时间】:2018-11-16 14:03:32
【问题描述】:

我需要通过 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)

【问题讨论】:

    标签: python numpy http request png


    【解决方案1】:

    您可以将内存中的 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 关键字。

    【讨论】:

    • 非常感谢您的快速回复! :) 但是我需要将什么变量传递给我的 http 请求?是 tmpFile 还是 not_on_disk?使用 open(...) 我有类型 _io.BufferedReader,所以这就是我想要的。 tmpFile 的类型为 BytesIO,not_on_disk 的类型为 _bytes。有什么方法可以转换?此外,如果我尝试打开 not_on_disk,我会收到“嵌入式空字节”错误。如果我使用 PIL 打开我得到 PngImageFile 对象在我发出请求时没有读取属性。对不起,我的一点理解。
    • 看起来requests.post 需要一个文件句柄,因此您需要传递tmpFile(在调用tmpFile.seek(0) 设置文件开头之后)。
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2018-08-31
    • 2022-01-26
    • 2015-05-10
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多