Transparent Background Image/Video Remover

1.3.4 · active · verified Thu Apr 16

Transparent-background is a Python library that leverages InSPyReNet (ACCV 2022) to remove backgrounds from images and videos, making them transparent. It supports various output modes, including RGBA, green screen, blur, and overlay. The library is actively maintained, with frequent updates addressing performance, dependencies, and new features.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `transparent-background` to remove the background from an image. It creates a dummy image, processes it using the `Remover` class to achieve a transparent background, and then saves the result. The `device` parameter can be set to 'cuda' for GPU acceleration if PyTorch with CUDA is installed.

import os
from PIL import Image
from transparent_background import Remover

# Create a dummy image for demonstration
try:
    img = Image.new('RGB', (200, 200), color = 'red')
    # Add a white circle in the middle
    from PIL import ImageDraw
    draw = ImageDraw.Draw(img)
    draw.ellipse((50, 50, 150, 150), fill='white', outline='white')
    input_image_path = 'input_image.png'
    output_image_path = 'output_transparent_image.png'
    img.save(input_image_path)
    print(f"Dummy image saved to {input_image_path}")

    # Initialize the Remover (downloads model checkpoint on first run)
    # Consider setting TRANSPARENT_BACKGROUND_FILE_PATH if default home directory is an issue
    remover = Remover(fast=False, jit=False, device='cpu') # 'cuda' for GPU if available

    # Load an image
    img = Image.open(input_image_path)

    # Process the image to remove background
    # 'bg_color=(0, 0, 0, 0)' ensures a fully transparent background for RGBA
    out = remover.process(img, type='rgba', threshold=0.5, bg_color=(0,0,0,0))

    # Save the output image
    out.save(output_image_path)
    print(f"Processed image saved to {output_image_path}")

    # Clean up dummy image
    os.remove(input_image_path)
    os.remove(output_image_path)
    print("Cleaned up dummy images.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure PyTorch is installed correctly for your system (e.g., with CUDA support if desired).")
    print("You might also need to install optional dependencies like `flet` or `pyvirtualcam` if using GUI/webcam features.")

view raw JSON →