【问题标题】:Converting 2D Numpy array of grayscale values to a PIL image将灰度值的二维 Numpy 数组转换为 PIL 图像
【发布时间】:2016-06-01 02:38:33
【问题描述】:

假设我有一个 0 到 1 范围内的 2D Numpy 值数组,它表示灰度图像。然后如何将其转换为 PIL Image 对象?迄今为止的所有尝试都产生了极其奇怪的分散像素或黑色图像。

for x in range(image.shape[0]):
    for y in range(image.shape[1]):
        image[y][x] = numpy.uint8(255 * (image[x][y] - min) / (max - min))

#Create a PIL image.
img = Image.fromarray(image, 'L')

在上面的代码中,numpy 数组图像由 (image[x][y] - min) / (max - min) 归一化,因此每个值都在 0 到 1 的范围内。然后乘以 255 和转换为 8 位整数。理论上,这应该通过具有模式 L 的 Image.fromarray 处理成灰度图像 - 但结果是一组分散的白色像素。

【问题讨论】:

  • 您使用的是最新版本的Pillow,PIL 的维护分支,还是使用原始 PIL?
  • +MattDMo 我使用的是最新版本的 Pillow,尤其是 Python 3.4
  • edit您的问题并发布您迄今为止尝试过的内容,包括示例输入、预期输出、实际输出(如果有)以及全文任何错误或追溯。
  • +MattDMo 我编辑了,但我可以添加的信息并不多。这不是一个具体的问题,而是一个普遍的问题。

标签: python numpy python-imaging-library


【解决方案1】:

我认为答案是错误的。 Image.fromarray( ____ , 'L') 函数似乎只适用于 0 到 255 之间的整数数组。我为此使用 np.uint8 函数。

如果您尝试制作渐变,您可以看到这一点。

import numpy as np
from PIL import Image

# gradient between 0 and 1 for 256*256
array = np.linspace(0,1,256*256)

# reshape to 2d
mat = np.reshape(array,(256,256))

# Creates PIL image
img = Image.fromarray(np.uint8(mat * 255) , 'L')
img.show()

制作干净的渐变

import numpy as np
from PIL import Image

# gradient between 0 and 1 for 256*256
array = np.linspace(0,1,256*256)

# reshape to 2d
mat = np.reshape(array,(256,256))

# Creates PIL image
img = Image.fromarray( mat , 'L')
img.show()

具有相同的神器。

【讨论】:

  • np.uint8 很重要。我以前使用过 .astype(int) ,也通过乘以 255 来缩放 0...1 值,但只得到完全黑色的图像。 uint8 是解决方法。
【解决方案2】:

如果我理解您的问题,您想使用 PIL 获得灰度图像。

如果是这种情况,您不需要将每个像素乘以 255。

以下对我有用

import numpy as np
from PIL import Image

# Creates a random image 100*100 pixels
mat = np.random.random((100,100))

# Creates PIL image
img = Image.fromarray(mat, 'L')
img.show()

【讨论】:

  • 我试过这个并且得到了非常明显的图像伪影 - 每 7 个左右像素就有可见的垂直条。最新版本的 Pillow 是否有可能直接坏掉了?
  • 我也得到了文物。如果我使用 img = Image.fromarray(np.uint8(mat), 'L'),那么一切正常。
【解决方案3】:

im = Image.fromarray(np.uint8(mat), 'L')

im = Image.fromarray(np.uint8(mat))

显然它接受类型 np.uint8(在此处插入数组),也可以为了简洁而删除 'L'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2020-02-20
    • 2017-06-25
    • 2013-06-21
    • 1970-01-01
    • 2021-04-02
    • 2020-02-17
    相关资源
    最近更新 更多