将大矩阵转换为灰度图像 [英] Turning a Large Matrix into a Grayscale Image
问题描述
我有一个3,076,568个二进制值(1和0)的NumPy数组。我想将其转换为矩阵,然后转换为Python中的灰度图像。
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.
但是,当我尝试将数组重新整形为1,538,284 x 1,538,284矩阵时,我收到内存错误。
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.
推荐答案
你的二进制值数组是一个字节数组?
Your array of "binary values" is an array of bytes?
如果是这样,您可以在调整大小后使用 Pillow ):
If so, you can do (using Pillow) after resizing it:
from PIL import Image
im = Image.fromarray(arr)
然后 im.show()
查看它。
如果你的数组只有0和1(1位深度或黑白)你可能需要将它乘以255
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)
这是一个例子:
>>> arr = numpy.random.randint(0,256, 100*100) #example of a 1-D array
>>> arr.resize((100,100))
>>> im = Image.fromarray(arr)
>>> im.show()
编辑(2018):
这个问题是写于2011年,Pillow因为在加载 fromarray
时需要使用 mode ='L'
参数而改变了。
This question was written in 2011 and Pillow changed ever since requiring to use the mode='L'
parameter when loading with fromarray
.
同样在下面的评论中,也说 arr.astype(np.uint8)
也需要,但我有未经测试
Also on comments below it was said arr.astype(np.uint8)
was needed as well, but I have not tested it
这篇关于将大矩阵转换为灰度图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!