我的 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 的红色像素。