📄

Background Removal in Python

This article was automatically translated from theJapanese original by AI. It may contain translation errors.

This post was published over 2 years ago. Its content may be outdated.

Introduction

I’ll show how to make an image’s background transparent using a Python library called rembg.

Installation

pip install rembg

Usage

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)

The input image can be webp or other formats. The output image will have a transparent background, so save it as png or a similar format.

Trying it out

Let’s try it with the following images.

OriginalAfter removal
Cat, originalCat, background removed
Man, originalMan, background removed
OriginalBackground removed

You can see that the animal images are cleanly made transparent. You can also see that images with lower contrast have some parts that aren’t quite made transparent.

Conclusion

It’s convenient to be able to remove backgrounds this easily.

Recent Articles

Network(beta)

Drag to move / Ctrl+wheel to zoom