Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

python - Turning a Large Matrix into a Grayscale Image

I have a NumPy array of 3,076,568 binary values (1s and 0s). I would like to convert this to a matrix, and then to a grayscale image in Python.

However, when I try to reshape the array into a 1,538,284 x 1,538,284 matrix, I get a memory error.

How can I reduce the size of the matrix so that it will turn into an image that will fit on a screen without losing the uniqueness/data?

Furthermore, how would I turn it into a grayscale image?

Any help or advice would be appreciated. Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your array of "binary values" is an array of bytes?

If so, you can do (using Pillow) after resizing it:

from PIL import Image
im = Image.fromarray(arr)

And then im.show() to see it.

If your array has only 0's and 1's (1-bit depth or b/w) you may have to multiply it to 255

im = Image.fromarray(arr * 255)

Here an example:

>>> arr = numpy.random.randint(0,256, 100*100) #example of a 1-D array
>>> arr.resize((100,100))
>>> im = Image.fromarray(arr)
>>> im.show()

Random image

Edit (2018):

This question was written in 2011 and Pillow changed ever since requiring to use the mode='L' parameter when loading with fromarray.

Also on comments below it was said arr.astype(np.uint8) was needed as well, but I have not tested it


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...