PyMatting

1.1.15 · active · verified Sat Apr 11

PyMatting is a Python library for alpha matting, a fundamental technique in image processing and computer vision used to accurately extract foreground objects from images. It offers various implementations for alpha matting and foreground estimation methods, leveraging CPU, CUDA, and OpenCL for performance. The current version is 1.1.15, with active development leading to periodic releases for bug fixes and feature enhancements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the simplest way to use PyMatting: the `cutout` function. It takes an input image and a trimap, then generates a new image with the foreground extracted. The example includes creating dummy image and trimap files for immediate runnable demonstration. In a real-world scenario, you would replace these with paths to your actual image and trimap files.

import numpy as np
from PIL import Image
from pymatting import cutout
import os

# Create dummy image and trimap files for demonstration
def create_dummy_image(path, size=(64, 64), color=(255, 0, 0)):
    img = Image.new('RGB', size, color)
    img.save(path)

def create_dummy_trimap(path, size=(64, 64)):
    # A simple trimap: top-left foreground (1.0), bottom-right background (0.0), middle unknown (0.5)
    trimap_data = np.zeros(size, dtype=np.float64)
    trimap_data[:size[0]//2, :size[1]//2] = 1.0 # Foreground
    trimap_data[size[0]//2:, size[1]//2:] = 0.0 # Background
    trimap_data[size[0]//4:size[0]*3//4, size[1]//4:size[1]*3//4] = 0.5 # Unknown
    
    # Convert to PIL image and save (e.g., as grayscale PNG)
    trimap_img = Image.fromarray((trimap_data * 255).astype(np.uint8), mode='L')
    trimap_img.save(path)

input_image_path = "dummy_input.png"
input_trimap_path = "dummy_trimap.png"
output_cutout_path = "dummy_cutout.png"

create_dummy_image(input_image_path, color=(100, 150, 200))
create_dummy_trimap(input_trimap_path)

print(f"Processing image: {input_image_path} with trimap: {input_trimap_path}")

try:
    # Perform the cutout operation
    # Note: The first import/call might be slow due to Numba compilation
    cutout(
        input_image_path,
        input_trimap_path,
        output_cutout_path
    )
    print(f"Cutout saved to: {output_cutout_path}")
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Clean up dummy files
    if os.path.exists(input_image_path):
        os.remove(input_image_path)
    if os.path.exists(input_trimap_path):
        os.remove(input_trimap_path)
    # Keep output_cutout_path for verification if successful
    # if os.path.exists(output_cutout_path):
    #     os.remove(output_cutout_path)

view raw JSON →