0

I was trying to find how to remove/change the background of a grayscale image in Python using PIL package but I failed. What I have is an RGB image which has a white background and I would like to load it, resize, change the background from white to black and save. So far I can do the beginning:

from PIL import Image
img = Image.open('my_picture.jpg').convert('LA')
# im1 = img.crop((left, top, right, bottom))

which gives me a grayscale image of a size I want but now I do not know how to change the background. I have found a really good post using cv2 for cropping the image out from a green bg and also another setting the background directly, but I couldn't find it for PIL. Is there such an option?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
My Work
  • 2,143
  • 2
  • 19
  • 47

1 Answers1

1

Convert image into RGB and get the data. Then do follow the step.

from PIL import Image

img = Image.open("test_image.jpg")
img = img.convert("RGB")
datas = img.getdata()
new_image_data = []
for item in datas:
    if item[0] in list(range(190, 256)):
        new_image_data.append((255, 204, 100))
    else:
        new_image_data.append(item)       

img.putdata(new_image_data)
img.save("test_image_altered_background.jpg")
img.show()

You can get some idea from here

mhhabib
  • 2,975
  • 1
  • 15
  • 29
  • Thanks for the answer. I have a question. What are those two limits? `range(190, 256)` and `(255, 204, 100)`. The first should be what I am replacing, if white, then it should be 0s no? And the second should be by what, right? – My Work Nov 23 '20 at 13:39
  • Change all white pixels to yellow – mhhabib Nov 23 '20 at 13:42
  • 1
    There could be some shades hence, I set the range from `190-256' so that everything get change perfectly. – mhhabib Nov 23 '20 at 13:52