Removing an Image Background

Python has a library called rembgfor using AI to remove an image’s background to produce a new image with a transparent background.

https://github.com/danielgatis/rembg

Before the first time you use this, it will need to be installed from a terminal window.
(You also need PIL / pillow installed)

pip install rembg

Next you need a suitable image. Your image should have a clear subject in the foreground so that the AI can find the boundary between the subject and the background. Put this image in your working directory and try something like this:

from rembg import remove
from PIL import Image
original = Image.open('guyoutside.png')
output = remove(original)
output.save('guyoutside_transparent.png')

Change your filename to match the real file, and choose your own output filename. Do save it as a “.png” file, because you will need a file type capable of saving in “RGBA” format. This will not work as a “.jpg” file.

Example original image:

Example output image:

Tip:
Don’t run the code to remove the background every time you run your code.

Removing the background is a slow operation if you run it on a large image. You only need to create the transparent background image once, so comment out that code after you’ve created the transparent background image file.

Once you have the transparent file, your next program can simply open this file and paste it onto a background image using something like this:

from PIL import Image
# original = Image.open('guyoutside.png')
# output = remove(original)
# output.save('guyoutside_transparent.png')
guy = Image.open('guyoutside_transparent.png')
background = image.open('background.jpg')
background.paste(guy, (100, 100), guy)
background.save('output.png')