My Work
My Work

Reputation: 2508

How to change the background of an image using PIL?

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?

Upvotes: 0

Views: 8101

Answers (1)

mhhabib
mhhabib

Reputation: 3121

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

Upvotes: 1

Related Questions