Skip to content

How to easily remove the background of images in Python

Learn how you can easily remove the background of images in Python.


Learn how you can easily remove the background of images in Python.

For this, we use the Open Source tool rembg and only need a few lines of code.

Input:

Input

Output:

Output

Install rembg

To use it with a CPU, use the following command:

pip install rembg

If you have a GPU, you can use:

pip install rembg[gpu]

Tip

For a free GPU, you can use a Google Colab.

Make sure the correct Pillow version is installed. It should be >= 9.3.0

import PIL
PIL.__version__

If this is not the case, you can try using this command (I had to use this workaround when using a Google Colab):

pip install --ignore-installed Pillow==9.3.0

Remove the background

Now, you can easily remove the background like so:

from rembg import remove

input_path = 'input.png'
output_path = 'output.png'

with open(input_path, 'rb') as i:
    with open(output_path, 'wb') as o:
        input = i.read()
        output = remove(input)
        o.write(output)

This will load the image, apply the background removal, and write the result to a new output image.

Use it as a CLI

You can also use rembg from the command line:

rembg i path/to/input.png path/to/output.png

FREE VS Code / PyCharm Extensions I Use

鉁 Write cleaner code with Sourcery, instant refactoring suggestions: Link*


PySaaS: The Pure Python SaaS Starter Kit

馃殌 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 馃檹