首页 > 解决方案 > 如何将 numpy 数组放入与 open().read() 相同的字节对象中?

问题描述

我最初在这里发布了这个问题: https ://community.plot.ly/t/images-are-not-displayed-after-altering/26521/2 但我觉得它更适合stackoverflow。所以它基本上归结为我试图弄清楚我如何获得当我打开一个 .png 文件时创建的相同字节对象

    with open('temp.png', 'rb') as f:
        encoded=base64.b64encode(f.read())

在我已经将图像打开为 numpy 数组之后。当我只是尝试将 numpy 数组转换为字节对象时,它看起来与我使用 open 得到的完全不同:

(io.BytesIO(imageio.imread(img_path))).getvalue()[0:20]
Out[70]: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

(imageio.imread(img_path)).tobytes()[0:20]
Out[71]: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

(open(img_path, 'rb').read())[0:20]
Out[72]: b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x04\x00'

并且具有不同的长度(np 数组的转换要长一个数量级)。这些方法之间有什么区别,在将图像转换为 np.array 后,如何实现 open.read() 的功能?

标签: pythonimagenumpybyte

解决方案


推荐阅读