【问题标题】:saving a numpy array as a io.BytesIO with jpg format将 numpy 数组保存为 io.BytesIO 与 jpg 格式
【发布时间】:2017-01-31 04:22:27
【问题描述】:

我正在使用 xlsxwriter 在 python 代码中将图像插入到 excel 中。

现在,我在 opencv 处理后得到了图像数据(numpy 数组)。我想将此图像数据插入到 Excel 中。但是 xlswriter 只支持 io.BytesIO 流。

问题:我不知道如何将 numpy 数组转换为 jpg 格式的io.BytesIO

我尝试了 numpy.tostring 但没有 jpg 格式。

代码在下面运行良好: _f = open('test.jpg') # I would like to insert test.jpg worksheet.insert_image('E2', 'abc.jpg', {'image_data': _f.read()})

有人可以帮助我吗?非常感谢。

【问题讨论】:

  • jpeg 格式不是专用的,使用对角线扫描和压缩吗?如果是这样,则需要自定义 jpeg 转换器(可能已获得许可)。

标签: python excel opencv numpy


【解决方案1】:

使用cv2.imencode 函数将numpy 数组转换为jpg 格式。

【讨论】:

    【解决方案2】:

    将 numpy 数组转换为 PIL Image 结构,然后使用 BytesIO 存储编码后的图像。

    img_crop_pil = Image.fromarray(numpy_image)
    byte_io = BytesIO()
    img_crop_pil.save(byte_io, format="JPG")
    jpg_buffer = byte_io.getvalue()
    byte_io.close()
    

    【讨论】:

    • dzieki, Radek ;)
    猜你喜欢
    • 2012-07-20
    • 2020-05-17
    • 2010-10-28
    • 2018-11-03
    • 2011-01-17
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多