【问题标题】:Grayscale image to NumPy array for Fourier transform灰度图像到 NumPy 数组的傅里叶变换
【发布时间】:2013-01-12 16:12:24
【问题描述】:

目前我正在使用 PIL 和 NumPy。我有一张彩色的png 图片,我想:

  1. 灰度阅读
  2. 转换为 NumPy 数组
  3. 对阵列执行 FFT
  4. 显示图片

这就是我正在尝试的(在带有 --pylab 标志的 IPython 中):

In [1]: import Image

In [2]: img = Image.open('ping.png').convert('LA')

In [3]: img_as_np = np.asarray(img)

In [4]: img_as_np
Out[4]: array(<Image.Image image mode=LA size=1000x1000 at 0x105802950>, dtype=object)

In [5]: img_fft = fft.fft2(img_as_np) // IndexError: index out of range for array

【问题讨论】:

  • 有什么理由使用LA 模式(带alpha 的灰度)?
  • 在您重新考虑之后,stackoverflow.com/a/14472089/1832154 的答案显示了如何正确显示傅里叶变换的结果。
  • 我在某处读到LA 模式可以让我在灰度中使用imshow(),我现在意识到L 也将它置于灰度中,但我只需要向imshow() 添加一个参数以确保它正确显示为灰度。我了解到(从下面的答案)A 正在阻止转换正常发生.. 我的错误 :-) 谢谢!

标签: python image-processing numpy python-imaging-library fft


【解决方案1】:

您使用的似乎是 1.1.6 之前的 PIL 版本,其中they introduced the methods so that numpy would know what to do with an Image。因此,您只是将img_as_np 作为一个包含Image 对象的单元素数组(这是Out[4] 向您展示的内容)。

您需要执行类似np.asarray(img.getdata()) 的操作,这将为您提供一个num_pixels x num_channels 0 到255 之间的整数数组(至少对于我尝试过的png)。你可能想这样做

img_as_np = np.asarray(img.getdata()).reshape(img.size[1], img.size[0], -1)

像图像一样布局(转置)。您可能还想除以 255 以获得介于 0 和 1 之间的浮点值,如果这是您所期望的格式(例如 matplotlib 的 imshow 也是如此)。

【讨论】:

    【解决方案2】:

    您想使用模式“L”而不是“LA”作为 convert() 方法的参数。 'LA' 留下一个 alpha 通道,然后 numpy.asarray 无法按您的预期工作。如果您需要 alpha 通道,那么您将需要一种不同的方法来转换为 numpy 数组。否则,使用模式“L”。

    【讨论】:

      【解决方案3】:

      this 用于图像:

      >>> from PIL import Image
      >>> import numpy as np
      >>> import matplotlib.pyplot as plt
      >>> Image.__version__
      '1.1.7'
      >>> img = Image.open('lena.png').convert('L')
      >>> data = np.asarray(img.getdata()).reshape(img.size)
      >>> fft = np.fft.fft2(data)
      >>> fft[0, 0] = 0 # remove DC component for visualization
      >>> plt.imshow(np.abs(np.fft.fftshift(fft)), interpolation='nearest')
      <matplotlib.image.AxesImage object at 0x046012F0>
      >>> plt.show()
      >>> plt.imshow(np.abs(np.fft.fftshift(fft))[224:288, 224:288], interpolation='nearest')
      <matplotlib.image.AxesImage object at 0x0476ED70>
      >>> plt.show()
      

      【讨论】:

        猜你喜欢
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 2021-07-26
        • 2015-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多