Skip to main content
 首页 » 编程设计

python之如何让 matplotlib 的 imshow 生成图像而不被绘制

2025年05月04日23zhengyun_ustc

Matplotlib 的 imshow 可以很好地绘制 numpy 数组。这段代码最能说明这一点:

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) 

及其创建的数字: ,这就是我想要的。我想要的是没有轴的图像,所以通过谷歌搜索我能够组装这个函数:

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) 

它从 numpy 矩阵生成图像。而且它几乎没有情节。它绘制了片刻,但随后图像关闭。我接下来可以保存图像,这是所有这些麻烦的原因。

我想知道是否有更简单的方法可以达到相同的目标。我尝试通过在第一个示例的代码后面添加一些语句来使用枕头:

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

但这会生成一个不全面的图像。可能是由于我的一些错误,但我不知道是哪个。

我不知道如何通过其他方式(例如枕头)获取具有类似输出(如 imshow)的 numpy 数组图像。有人知道我如何以与 matplotlibs imshow() 相同的方式从 numpy 矩阵生成图像而没有闪烁的图吗?并且比我用 create_img 函数编造的方法更简单?

请您参考如下方法:

这个简单的案例最好由 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")