Abdul Rehman
Abdul Rehman

Reputation: 5674

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:

enter image description here

And, here's what I have tried using 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.

When I printed the datas and newData it prints the same values:

Old Length is: 944812
New Length is: 944812

Thanks in advance!

Upvotes: 0

Views: 1885

Answers (1)

Eypros
Eypros

Reputation: 5723

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

  • 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.

Upvotes: 1

Related Questions