PIL从图像中删除背景图像 [英] PIL remove background image from image

查看:355
本文介绍了PIL从图像中删除背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有了背景图片,我能否从另一张图片中删除该背景并获得所有差异?例如:

With a background image, would I be able to remove that background from another image and get all of the discrepancies? For example:

假装我保存了这两张图像.我如何在保留所有猫的同时从第二张照片中删除第一张照片?

Pretend I have these two images saved. How could I remove the first picture from the second picture while keeping all of the cats?

推荐答案

根据

According to the PIL handbook, the ImageChops module has a subtract operation:

ImageChops.subtract(image1, image2, scale, offset) => image
Subtracts two images, dividing the result by scale and adding the offset.
If omitted, scale defaults to 1.0, and offset to 0.0.
out = (image1 - image2) / scale + offset

您可以将生成的图像用作猫的图像的蒙版:将像素保留为非零的蒙版,否则使它们成为所需的背景色.

You can use the resulting image as a mask for the image with the cats: Keep the pixels where the mask is non-zero, otherwise make them the desired background colour.

下面的示例代码:

from PIL import Image
from PIL import ImageChops
image1 = Image.open("image1.jpg") # no cats
image2 = Image.open("image2.jpg") # with cats

image = ImageChops.subtract(image2, image1)

mask1 = Image.eval(image, lambda a: 0 if a <= 24 else 255)
mask2 = mask1.convert('1')

blank = Image.eval(image, lambda a: 0)

new = Image.composite(image2, blank, mask2) 
new.show()

几乎可以使用:-)

两个图像之间的差异比看上去要多.因为图像存储为JPG,所以它们是有损的.它们的渲染会略有不同,因此对于相同区域中的像素,减法运算将不会始终导致零(即黑色).

There is a bit more difference between the two images than it seems. Because the images are stored as JPGs, they are lossy. They will be rendered slightly differently, so the subtract operation will not always result in zero (i.e. black) for the pixels in the areas that are the same.

由于这个原因,我必须对eval函数使用lambda a: 0 if a <= 24 else 255才能获得合理的结果.

For this reason, I had to use lambda a: 0 if a <= 24 else 255 for the eval function to get a reasonable result.

如果使用无损图像,它应该可以正常工作.然后,您应该使用0 if a == 0 else 255创建遮罩.

If you use loss-less images it should work properly. You should then use 0 if a == 0 else 255 to create the mask.

请注意,如果某些猫"像素偶然与背景像素相同,它们将显示为黑色像素.

Note that if some 'cat' pixels accidentally are the same as the background pixel, they will show up as black pixels.

这篇关于PIL从图像中删除背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆