简体   繁体   中英

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

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?

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()

不幸的是fromarray没有文档字符串,但是如果您的“矩阵”是一个numpy数组(或者以其他方式实现了数组接口),并且您另外将模式设置为“ L”(作为fromarray的第二个参数),则您尝试的方法应该可以工作。

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.

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