DEV Community

浩

Posted on

Remove Image Backgrounds in Python in 10 Lines of Code

Need to remove backgrounds from images programmatically? Here's the simplest way using Python's rembg library.

The Code

from rembg import remove

# Load and remove background
with open('photo.jpg', 'rb') as f:
    input_data = f.read()
    output_data = remove(input_data)

with open('photo_no_bg.png', 'wb') as f:
    f.write(output_data)
Enter fullscreen mode Exit fullscreen mode

That's literally it. 10 lines including imports and file I/O.

How It Works

rembg uses a U-Net neural network to segment foreground from background. It's built on top of ONNX Runtime, which means it runs on CPU without a GPU. The model was trained on a massive dataset of images with transparent backgrounds.

Installation

pip install rembg pillow
Enter fullscreen mode Exit fullscreen mode

First run will download the model (~200MB). Subsequent runs are instant.

Real-World Use Cases

  • E-commerce: Batch process product photos for white backgrounds
  • Profile pictures: Remove messy backgrounds instantly
  • Design mockups: Extract objects for compositing
  • Document scanning: Clean up photos of documents

Built Something With It

I integrated this into my micro-tools platform. It's literally wrapping those 10 lines in a Flask route with a drag-and-drop UI:

@app.route('/api/bg-remover', methods=['POST'])
def bg_remover():
    file = request.files['image']
    output_data = remove(file.read())
    return send_file(io.BytesIO(output_data), mimetype='image/png')
Enter fullscreen mode Exit fullscreen mode

Try It

If you don't want to write code, you can use the tool I built: https://badge-market-asia-males.trycloudflare.com/tools/bg-remover — first use is free, no signup needed.

What are you using background removal for?

Top comments (0)