0

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!

gboffi
  • 22,939
  • 8
  • 54
  • 85
Abdul Rehman
  • 5,326
  • 9
  • 77
  • 150

1 Answers1

1

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.

Eypros
  • 5,370
  • 6
  • 42
  • 75
  • Hi @Eypros, the background will not be the same as always, it's going to vary image by image, how can I set up this code to work for all types of background? – Abdul Rehman Sep 03 '18 at 10:23
  • What do you mean by "all types of background"? If you just check RGB thresholds it will fail certainly. You need a better method for background estimation. – Eypros Sep 03 '18 at 10:26
  • If I try it for a different image, it's totally failed, I'm looking for a solution which works for any image, maybe not 100% correct, but should give some result at least. Any resource will also be very appreciated. – Abdul Rehman Sep 03 '18 at 10:35
  • You haven't specified how is your background defined for example? What method do you have to have to find the background besides RGB values? – Eypros Sep 03 '18 at 11:49