我有一个包含3076568个二进制值(1和0)的NumPy数组。我想将其转换为矩阵,然后在Python中转换为灰度图像。
但是,当我尝试将该数组重新形状为1538284 x 1538284的矩阵时,会出现内存错误。
如何减小矩阵的大小,使其可以成为适合屏幕的图像,同时又不丢失数据的唯一性?
此外,我应该如何将其转换为灰度图像?
如果有任何帮助和建议,将不胜感激。谢谢。
我有一个包含3076568个二进制值(1和0)的NumPy数组。我想将其转换为矩阵,然后在Python中转换为灰度图像。
但是,当我尝试将该数组重新形状为1538284 x 1538284的矩阵时,会出现内存错误。
如何减小矩阵的大小,使其可以成为适合屏幕的图像,同时又不丢失数据的唯一性?
此外,我应该如何将其转换为灰度图像?
如果有任何帮助和建议,将不胜感激。谢谢。
您的“二进制值”数组是一个字节数组?
如果是这样,您可以在调整大小后使用(使用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)
,但我没有测试过。
arr.astype(np.uint8)
和mode='L'
(如上所述),才能获得正确的输出(请参见https://dev59.com/-FYN5IYBdhLWcg3wi4jo)。 - dexteritas使用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)
在新窗口中显示图像。
scipy.misc.toimage
和 im.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")
这可以提供
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()