【问题标题】:How can I get the uint8 type image from the plot (Matplotlib)?如何从绘图(Matplotlib)中获取 uint8 类型的图像?
【发布时间】:2017-11-23 11:21:45
【问题描述】:

考虑这段代码:

fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.gca()

ax.text(0.0,0.0,"Test", fontsize=45)
ax.axis('off')
canvas.draw()       # draw the canvas, cache the renderer
width, height = fig.get_size_inches() * fig.get_dpi()
images = np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3)

所以我遇到的问题是它保存了带有文本“测试”的情节。但是假设我有一个图,确切地说是“AxesImages”matplotlib,我怎样才能转换图像图而不是文本?我试图用 ax.imshow(axesImage) 更改 ax.text(...) 但它抛出错误。

有什么建议吗?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以将图像保存到文件中,然后使用 PIL 将文件加载到数组中:

    from PIL import Image
    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.text(0.0,0.0,"Test", fontsize=45)
    ax.axis('off')
    ax.imshow(np.random.random((3,3)))
    filename = '/tmp/out.png'
    fig.savefig(filename)
    img = Image.open(filename).convert('RGB')
    arr = np.asarray(img)
    img.show()
    

    如果你想避免磁盘 I/O,你可以save the image to a BytesIO object instead:

    import io
    from PIL import Image
    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.text(0.0,0.0,"Test", fontsize=45)
    ax.axis('off')
    ax.imshow(np.random.random((3,3)))
    
    with io.BytesIO() as memf:
        fig.savefig(memf, format='PNG')
        memf.seek(0)
        img = Image.open(memf)
        arr = np.asarray(img)
        img.show()
    

    【讨论】:

    • 是的,我知道这种方法,但问题是我需要为 NN 转换 51k 图像,并且首先保存它们需要很长时间。节省 BytesIO 有什么好处?它的计算速度更快吗?
    • 磁盘 I/O 可以是orders of magnitude slower,而不是内存 I/O。所以使用BytesIO 会更快,尽管处理 51K 图像可能仍然需要很多时间。
    • 我明白了,这是有道理的。那么保存后在哪里可以获得这些图像呢?对不起,我没有使用 ByteIO 的经验,想知道它到底保存在哪里。此外,arr 显示所有值都是 255,对吗?
    • 那个很有趣:-)
    • @ImportanceOfBeingErnest 好笑吗?
    猜你喜欢
    • 2021-10-24
    • 2018-01-25
    • 2018-04-02
    • 2021-02-12
    • 2013-10-04
    • 2015-11-01
    • 1970-01-01
    • 2012-10-29
    • 2021-01-22
    相关资源
    最近更新 更多