【问题标题】:Turning a Large Matrix into a Grayscale Image将大矩阵变成灰度图像
【发布时间】:2011-12-03 10:22:25
【问题描述】:

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

但是,当我尝试将数组重塑为 1,538,284 x 1,538,284 矩阵时,出现内存错误。

如何减小矩阵的大小,使其变成适合屏幕的图像而不会丢失唯一性/数据?

另外,如何把它变成灰度图?

任何帮助或建议将不胜感激。谢谢。

【问题讨论】:

  • 呃... 3,076,568 个值将是 ~1754x1754 图像,而不是 1,538,284x1,538,284 图像。
  • 啊……太晚了,我的错。 :-) 感谢您指出这一点。

标签: python image matrix grayscale


【解决方案1】:

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

如果是这样,您可以在调整大小后(使用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' 参数。

下面的 cmets 也说需要 arr.astype(np.uint8),但我没有测试过

【讨论】:

  • 我在尝试上面的示例时收到错误“无法处理此数据类型”。我需要通过 mode="L" 像:im = Image.fromarray(arr, mode="L")
  • @barbolo mine 没有引发错误,它只是使整个图片变白。但是使用模式“L”修复了它,谢谢!
  • 我必须使用arr.astype(np.uint8)mode='L'(如上所述)才能获得正确的输出(参见stackoverflow.com/questions/47290668/…)。
【解决方案2】:

其实并不需要使用 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")
    

    给了

    【讨论】:

      【解决方案4】:

      如果您的 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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-03
        相关资源
        最近更新 更多