0

我正在尝试使许多白色像素透明,但是我做错了。

我可以更改像素的颜色,但是我的代码似乎忽略了我对 alpha 值所做的任何更改。我对 PIL 和 Python 很陌生,所以这可能是一个相对简单的错误。

这是代码:

image_two = Image.open ("image_two.bmp")
image_two = image_two.convert ("RGBA")

pixels = image_two.load()

for y in xrange (image_two.size[1]):
    for x in xrange (image_two.size[0]):
        if pixels[x, y] == (0, 0, 0, 255):
            pixels[x, y] = (0, 0, 0, 255)
        else:
            pixels[x, y] = (255, 255, 255, 0)

image_two.save("image_two")
4

1 回答 1

0

我的 PIL 版本不支持 BMP 文件中的 alpha 通道。我能够使用您的代码加载带有 alpha 的 PNG 文件。当我尝试将其写回 BMP 文件时,我得到一个 python 异常,告诉我“IOError:无法将模式 RGBA 写为 BMP”。

你的代码说:

    if pixels[x, y] == (0, 0, 0, 255):  #black with alpha of 255
        pixels[x, y] = (0, 0, 0, 255)   #black with alpha of 255
    else:
        pixels[x, y] = (255, 255, 255, 0) #white with alpha of 255

白色像素将 r、g 和 b 设置为“255”。所以可能你想要做的是这样的:

if pixels[x,y] == (255,255,255,255):
    pixels[x,y] = (pixels[x,y][0], pixels[x,y][1], pixels[x,y][2], 0)  #just set this pixel's alpha channel to 0

您可能不需要 else ,因为如果像素不是白色且 alpha 为 255,您可能不想触摸它们。

我像这样修改了你的代码:

import Image

image_two = Image.open ("image_two.png")
image_two = image_two.convert ("RGBA")

pixels = image_two.load()

for y in xrange (image_two.size[1]):
    for x in xrange (image_two.size[0]):
        if pixels[x, y][3] == 255:
            pixels[x, y] = (255, 0, 0, 255)
        else:
            pixels[x, y] = (255, 255, 255, 255)

image_two.save("image_two2.png")

此代码获取我的图像并写出一个蒙版 - alpha 为 0 的白色像素和 alpha 为 255 的红色像素。

于 2013-10-09T03:12:07.017 回答