PIL过滤像素和粘贴

时间:2015-11-22 00:07:47

标签: python python-imaging-library

我正在尝试将图片粘贴到另一张图片上。我实际上正在使用Joseph here的第二个答案,因为我正在尝试做一些非常相似的事情:将我的foregroud调整为背景图像,然后仅将前景中的黑色像素复制到背景上。我的前景是带有黑色轮廓的彩色图像,我只想将轮廓粘贴在背景上。这条线

mask = pixel_filter(mask, (0, 0, 0), (0, 0, 0, 255), (0, 0, 0, 0))

返回错误"图像索引超出范围"。

当我不进行此过滤过程以查看粘贴是否至少有效时,我会得到一个错误的掩码透明度错误"。我已经将背景和前景设置为RGB和RGBA,以查看是否有任何组合解决了问题,它没有。

我在mask()行中做错了什么,以及我对粘贴过程缺少什么?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您引用的pixel filter函数似乎有一个小错误。它试图将1维列表索引向后转换为2d索引。它应该是(x,y) => (index/height, index%height)see here)。下面是重写的函数(full attribution to the original author)。

def pixel_filter(image, condition, true_colour, false_colour):
    filtered = Image.new("RGBA", image.size)
    pixels = list(image.getdata())
    for index, colour in enumerate(pixels):
        if colour == condition:
            filtered.putpixel((index/image.size[1],index%image.size[1]), true_colour)
        else:
            filtered.putpixel((index/image.size[1],index%image.size[1]), false_colour)
    return filtered