PIL过滤像素并粘贴
PIL filter pixels and paste
我正在尝试将一张图片粘贴到另一张图片上。我实际上使用了 Joseph here 的第二个答案,因为我正在尝试做一些非常相似的事情:将前景调整为背景图像,然后仅将前景中的黑色像素复制到背景中。我的前景是带有黑色轮廓的彩色图像,我只想将轮廓粘贴到背景上。该行
mask = pixel_filter(mask, (0, 0, 0), (0, 0, 0, 255), (0, 0, 0, 0))
returns 错误 "image index out of range"。
当我不执行此过滤过程以查看粘贴是否至少有效时,我得到 "bad mask transparency error"。我已将背景和前景都设置为 RGB 和 RGBA,以查看是否有任何组合可以解决问题,但事实并非如此。
我在 mask() 行中做错了什么,我在粘贴过程中遗漏了什么?感谢您的帮助。
您引用的 pixel filter
函数似乎有一个小错误。它试图将一维列表索引反向转换为二维索引。应该是 (x,y)
=> (index/height, index%height)
(see here). Below is the function (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
我正在尝试将一张图片粘贴到另一张图片上。我实际上使用了 Joseph here 的第二个答案,因为我正在尝试做一些非常相似的事情:将前景调整为背景图像,然后仅将前景中的黑色像素复制到背景中。我的前景是带有黑色轮廓的彩色图像,我只想将轮廓粘贴到背景上。该行
mask = pixel_filter(mask, (0, 0, 0), (0, 0, 0, 255), (0, 0, 0, 0))
returns 错误 "image index out of range"。
当我不执行此过滤过程以查看粘贴是否至少有效时,我得到 "bad mask transparency error"。我已将背景和前景都设置为 RGB 和 RGBA,以查看是否有任何组合可以解决问题,但事实并非如此。
我在 mask() 行中做错了什么,我在粘贴过程中遗漏了什么?感谢您的帮助。
您引用的 pixel filter
函数似乎有一个小错误。它试图将一维列表索引反向转换为二维索引。应该是 (x,y)
=> (index/height, index%height)
(see here). Below is the function (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