简体   繁体   English

如何让Matplotlib的imshow生成图像而不被绘制

[英]How to have matplotlib's imshow generate an image without being plotted

Matplotlib's imshow does a nice job of plotting a numpy array. Matplotlib的imshow很好地绘制了一个numpy数组。 This is best illustrated by this code: 最好用以下代码说明:

from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
rows, cols = 200, 200
mat = np.zeros ((rows, cols))
for r in range(rows):
    for c in range(cols):
        mat[r, c] = r * c
# Handle with matplotlib
plt.imshow(mat)

and the figure it creates: 它创建的图: 数字 , which is about what I want. ,这是我想要的。 What I want is the image without axes, so by googling around I was able to assemble this function: 我想要的是没有轴的图像,因此通过谷歌搜索,我能够组装此功能:

def create_img (image, w, h):
    fig = plt.figure(figsize=(w, h), frameon=False)
    canvas = FigureCanvas(fig)
    #To make the content fill the whole figure
    ax = plt.Axes(fig, [0., 0., 1., 1.])
    ax.set_axis_off()
    fig.add_axes(ax)
    plt.grid(False)
    ax.imshow(image, aspect='auto', cmap='viridis')
    canvas.draw()
    buf = fig.canvas.tostring_rgb()
    ncols, nrows = fig.canvas.get_width_height()
    a = np.fromstring(buf, dtype=np.uint8).reshape(nrows, ncols, 3)  
    plt.close()
    plt.pause(0.01)
    return Image.fromarray(a)

It generates an image from a numpy matrix. 它从一个numpy矩阵生成图像。 And it does not plot, well almost. 而且它几乎不会绘制。 It plots for a brief moment but then the image closes. 绘图一会儿,然后图像关闭。 I next can save the image what was the reason for all this hassle. 接下来,我可以保存图像,这是所有麻烦的原因。

I wondered whether there was a simpler method to reach the same goal. 我想知道是否有更简单的方法可以达到相同的目标。 I tried to use pillow, by adding some statements behind the code of the first example: 我试图通过在第一个示例的代码后面添加一些语句来使用枕头:

# Handle with pillow.Image
img = Image.fromarray(mat, 'RGB')
img.show()
img.save('/home/user/tmp/figure.png')

But that generates an incomprehensive image. 但这会产生不完整的图像。 Probably due to some mistake of mine but I do not know which. 可能是由于我的一些错误,但我不知道是哪一个。

在此处输入图片说明

I do not know how to get an image of a numpy array with similar output like imshow by other means, for example by pillow. 我不知道如何通过其他方式(例如通过枕头)获得具有类似imshow类输出的numpy数组的图像。 Does someone know how I can generate an image from a numpy matrix in the same way as matplotlibs imshow() without the flashing plots? 有人知道我如何以与matplotlibs imshow()相同的方式从numpy矩阵生成图像而不会出现闪烁的图吗? And in a simpler way than I have concocted with the create_img function? 并且比我用create_img函数create_img方法更简单吗?

This simple case can probably best be handled by plt.imsave . 这种简单的情况可能最好由plt.imsave处理。

import matplotlib.pyplot as plt
import numpy as np

rows, cols = 200, 200
r,c = np.meshgrid(np.arange(rows), np.arange(cols))
mat = r*c

# saving as image
plt.imsave("output.png", mat)
# or in some other format
# plt.imsave("output.jpg", mat, format="jpg")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM