Background Removal from Images using Python

2023

Background Removal

To begin, we need to import the necessary libraries:

from rembg import remove
from PIL import Image

We import remove from the rembg library for background removal and Image from Pillow for image processing.

Next, we specify the input and output file paths:

in_path = "inpath/InputImage.png"
out_path = "outpath/OutputImage.png"

We define in_path as the path to the input image and out_path as the path where the output image will be saved.

We open the input image using Pillow:

image_input = Image.open(in_path)

Now, we perform the background removal using the rembg library:

output = remove(image_input)

The remove function from rembg takes the input image and returns a new image with the background removed.

We save the resulting image to the output path:

output.save(out_path)

Finally, we print a message to indicate that the process is complete:

print("Background removed. Result saved to", out_path)

Example Usage

Here's an example of how to use this code to remove the background from an image:

from rembg import remove
from PIL import Image

in_path = "input.png"
out_path = "output.png"

image_input = Image.open(in_path)
output = remove(image_input)
output.save(out_path)
print("Background removed. Result saved to", out_path)

You can replace "input.png" with the path to your input image and "output.png" with the desired output path.


Final Code

Here's the complete Python code for removing the background from an image:

from rembg import remove
from PIL import Image

in_path = "inpath/InputImage.png"
out_path = "outpath/OutputImage.png"

image_input = Image.open(in_path)
output = remove(image_input)
output.save(out_path)
print("Background removed. Result saved to", out_path)

That's it! You now have a Python code snippet that allows you to remove the background from images using the rembg library. Feel free to modify the code or use it as a starting point for your own projects. Enjoy removing backgrounds from your images!

Back