将 numpy 数组保存为 io.BytesIO 与 jpg 格式

Bob*_*Liu 3 python excel opencv numpy

我正在使用 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()})

任何人都可以帮助我吗?太感谢了。

Bob*_*Liu 5

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


Rad*_*dek 5

将 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()
Run Code Online (Sandbox Code Playgroud)