简体   繁体   English

删除图像背景并使用Python的PIL创建透明图像

[英]Remove Image background and create a transparent Image using Python's PIL

I'm working on a project in which I need to remove the background of an Image, the only Information we have is that it's an Image which has some (one or more) objects in it, and I need to remove the background and make it a transparent image. 我正在一个项目中,我需要删除图像的背景,我们仅有的信息是它是其中包含一些(一个或多个)对象的图像,我需要删除背景并进行它是透明的图像。

Here's a sample Image: 这是一个示例图像:

在此处输入图片说明

And, here's what I have tried using PIL: 而且,这是我尝试使用PIL的方法:

img = Image.open(url)
img = img.convert("RGBA")
datas = img.getdata()
print('Old Length is: {}'.format(len(datas)))
# print('Exisitng Data is as: {}'.format(datas))
newData = []
for item in datas:
    # print(item)
    if item[0] == 255 and item[1] == 255 and item[2] == 255:
        newData.append((255, 255, 255, 0))
    else:
        newData.append(item)
img.putdata(newData)
print('New Length is: {}'.format(len(datas)))
img.show()
img.save("/Users/abdul/PycharmProjects/ImgSeg/img/new.png", "PNG")
print('Done')

It saves the same image as input with the name as new.png , nothing has been removed from the image. 它将与输入相同的图像保存为new.png ,未从图像中删除任何内容。

When I printed the datas and newData it prints the same values: 当我打印datasnewData它打印相同的值:

Old Length is: 944812
New Length is: 944812

Thanks in advance! 提前致谢!

You are filtering out all white pixels: 您正在过滤掉所有白色像素:

item[0] == 255 and item[1] == 255 and item[2] == 255

but that does not mean that: 但这并不意味着:

  • all white pixels (255, 255, 255) belong to the background and 所有白色像素(255, 255, 255)属于背景,

  • all background contains only white pixels. 所有背景仅包含白色像素。

A heuristic method (partially applicable to your sample image) would be to increase the threshold of your background pixel definition: 启发式方法(部分适用于您的示例图像)将增加背景像素定义的阈值:

if 50 <= item[0] <= 80 and 60 <= item[1] <= 100 and 80 <= item[2] < 140:

filters out much more pixels. 过滤掉更多像素。

Do you really want your background pixels being white is also a question to be answered. 您是否真的希望背景像素为白色也是要回答的问题。

Also, your test for checking the output of your filtering won't work since both images will contain the same number of pixels anyway, regardless of their transparency. 另外,用于检查过滤输出的测试将无法进行,因为无论图像的透明度如何,无论如何,这两个图像都将包含相同数量的像素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM