【问题标题】:Converting image to grayscale returned a weird image将图像转换为灰度返回了一个奇怪的图像
【发布时间】:2023-03-16 20:57:01
【问题描述】:

我尝试使用加权和公式将 rgb 图像转换为灰度图像

Y' = 0.299 R' + 0.587 G' + .114 B'

它没有给出任何错误,但我无法理解输出。 代码如下:

img = Image.open("dog.jpg")
img = img.resize((256, 256), resample=Image.BILINEAR)
img = np.array(img)
bw = np.zeros((256,256))
for i in range(256):
    for j in range(256):
        bw[i,j] = (.299*img[i,j,0])+(.587*img[i,j,1])+(.114*img[i,j,2])
i = Image.fromarray(bw,'L')

这是我得到的输出图片:

【问题讨论】:

    标签: python image-processing python-imaging-library grayscale


    【解决方案1】:

    您在bw[i,j] 中的计算结果为浮点数。图像需要 uint8 类型,即 0-255 范围内的整数。修复此更改

    bw = np.zeros((256,256))
    

    bw = np.zeros((256,256), dtype=np.uint8)
    

    这会将 0-0.999... 中的每个数字剪裁为 0。

    >>> bw[0,0] = 0.3
    >>> bw[0,0]
    0
    >>> bw[0,0] = 0.6
    >>> bw[0,0]
    0
    

    如果您更关心舍入到最接近的整数而不是总是向下舍入,那么您也可以将该计算包装在 np.round() 中。

    >>> bw[0,0] = np.round(0.3)
    >>> bw[0,0]
    0
    >>> bw[0,0] = np.round(0.6)
    >>> bw[0,0]
    1
    

    Numpy 支持向量化,因此您无需编写显式循环(也更慢)。

    img = np.array(img)
    bw = np.round(.299 * img[...,0] + .587 * img[...,1] + .114 * img[...,2]).astype(np.uint8)
    

    【讨论】:

    • 如果我运行你的代码,我会收到错误“TypeError: 'Image' object is not subscriptable”
    • @Shreyas 你仍然需要先做img = np.array(img)。就在上面。
    • 所以如果我会这样做: bw[i,j] = np.round((.299*img[i,j,0])+(.587*img[i ,j,1])+(.114*img[i,j,2]))。会有用吗?
    • @Shreyas 没错。我想你可以省略 (.299*img[i,j,0]) 中的括号,因为乘法优先于加法,但这并不会改变这个想法。
    【解决方案2】:

    据我了解,PIL 图像以uint8 格式存储,因此您可以将i = Image.fromarray(bw,'L') 替换为i = Image.fromarray(np.uint8(bw),'L')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-28
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多