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)
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.
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?
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.