问题描述
Matplotlib 的 imshow
在绘制 numpy 数组方面做得很好.这段代码最好地说明了这一点:
Matplotlib's imshow
does a nice job of plotting a numpy array. 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)
它从一个 numpy 矩阵生成一个图像.它没有情节,几乎.绘图一会儿,然后图像关闭.我接下来可以保存图像,这一切麻烦的原因是什么.
It generates an image from a numpy matrix. 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.
我不知道如何通过其他方式(例如通过枕头)获取具有类似 imshow
之类输出的numpy数组的图像.有人知道我如何以与 matplotlibs imshow()
相同的方式从 numpy 矩阵生成图像而没有闪烁的图?并且以一种比我使用 create_img
函数构想的方式更简单的方式?
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. Does someone know how I can generate an image from a numpy matrix in the same way as matplotlibs imshow()
without the flashing plots? And in a simpler way than I have concocted with the create_img
function?
推荐答案
这个简单的案例可能最好由 plt.imsave
.
This simple case can probably best be handled by 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")
这篇关于如何让 matplotlib 的 imshow 生成图像而不被绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!