将一个大矩阵转换成灰度图像

12

我有一个包含3076568个二进制值(1和0)的NumPy数组。我想将其转换为矩阵,然后在Python中转换为灰度图像。

但是,当我尝试将该数组重新形状为1538284 x 1538284的矩阵时,会出现内存错误。

如何减小矩阵的大小,使其可以成为适合屏幕的图像,同时又不丢失数据的唯一性?

此外,我应该如何将其转换为灰度图像?

如果有任何帮助和建议,将不胜感激。谢谢。


1
嗯... 3,076,568个值将会是一张大约1754x1754的图片,而不是一张1,538,284x1,538,284的图片。 - Amber
4个回答

23

您的“二进制值”数组是一个字节数组?

如果是这样,您可以在调整大小后使用(使用Pillow):

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

然后使用im.show()命令查看。

如果你的数组只有0和1(1位深度或黑白图像),你可能需要将其乘以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'参数。

下面的评论中还说需要arr.astype(np.uint8),但我没有测试过。


4
尝试以上示例时,我遇到了“无法处理此数据类型”的错误。需要像这样传递mode="L"参数:im = Image.fromarray(arr, mode="L")。 - barbolo
@barbolo 我的代码没有报错,只是把整张图片都变成了白色。但是使用“L”模式修复了这个问题,谢谢! - Arthur Dent
1
我不得不使用arr.astype(np.uint8)mode='L'(如上所述),才能获得正确的输出(请参见https://dev59.com/-FYN5IYBdhLWcg3wi4jo)。 - dexteritas

12

使用PIL并不是必须的,你可以直接使用pyplot来绘制数组(请参见下文)。要保存到文件,你可以使用plt.imsave('fname.png', im)

在此输入图片描述

下面是代码。

import numpy as np
import matplotlib.pyplot as plt

x = (np.random.rand(1754**2) < 0.5).astype(int)

im = x.reshape(1754, 1754)
plt.gray()
plt.imshow(im)

你也可以使用plt.show(im)在新窗口中显示图像。


3
您可以使用 scipy.misc.toimageim.save("foobar.png") 来完成此操作:
#!/usr/bin/env python

# your data is "array" - I just made this for testing
width, height = 512, 100
import numpy as np
array = (np.random.rand(width*height) < 0.5).astype(int)
array = array.reshape(height, width)

# what you need
from scipy.misc import toimage

im = toimage(array)
im.save("foobar.png")

这可以提供

这里输入图片描述


1
从scipy 1.0.0开始,此函数已被弃用。您应该使用Image.fromarray代替。 - cnexans

1
如果您在PC上有一个包含某些数据(图像)的txt文件,并且想将此类数据可视化为灰度图像,则可以使用以下方法:
with open("example.txt", "r") as f:
data = [i.strip("\n").split() for i in f.readlines()]
data1 = np.array(data, dtype=float)
plt.figure(1)
plt.gray()
plt.imshow(data1)
plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接