How to convert grayscale values in matrix to an image in Python?

笑着哭i 提交于 2019-12-11 18:37:42

问题


I have a set of grayscale values in matrix of shape 24x24:

masked=[[149 172 160 166 170 179 180 176 202 190 221 232 125 112 153 132 200 185
  191 231 227 101  85 127] ...

And I try to save this matrix file to a grayscale image as follows:

im = Image.fromarray(masked_crop)
im.save('crop.png')

But instead of having those values in my image, I get a complete dark image of size 24x24. Where am I going wrong?


回答1:


You can display and save an image with matplotlib

import numpy
from matplotlib import pyplot as plt
x = numpy.random.rand(10, 10)*255
plt.imshow(x, cmap='gray', interpolation='nearest', vmin=0, vmax=255)
plt.savefig('text.png')
plt.show()



回答2:


Unfortunately fromarray has no docstring, but what you are trying should work if your "matrix" is a numpy array (or otherwise implements the array interface) and you additionally set the mode to 'L' (as the second argument to fromarray).



来源:https://stackoverflow.com/questions/25019287/how-to-convert-grayscale-values-in-matrix-to-an-image-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!