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.
If you have as example a txt file in your PC with some data (an image), in order to visualize such data as gray scale image you can use this:
Your array of "binary values" is an array of bytes?
If so, you can do (using Pillow) after resizing it:
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
Here an example:
Edit (2018):
This question was written in 2011 and Pillow changed ever since requiring to use the
mode='L'
parameter when loading withfromarray
.Also on comments below it was said
arr.astype(np.uint8)
was needed as well, but I have not tested itYou can do so with
scipy.misc.toimage
andim.save("foobar.png")
:which gives
Using PIL is not really needed, you can plot the array directly with pyplot (see below). To save to a file, you could use
plt.imsave('fname.png', im)
.Code below.
You can also use
plt.show(im)
to display image in new window.