{"id":3760,"library":"pymatting","title":"PyMatting","description":"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.","status":"active","version":"1.1.15","language":"en","source_language":"en","source_url":"https://github.com/pymatting/pymatting","tags":["image processing","computer vision","alpha matting","matting","foreground extraction"],"install":[{"cmd":"pip install pymatting","lang":"bash","label":"Install PyMatting"}],"dependencies":[{"reason":"Core dependency for numerical operations, especially image data.","package":"numpy","optional":false},{"reason":"Required for image loading and saving functionalities.","package":"pillow","optional":false},{"reason":"Used for performance optimization through JIT compilation.","package":"numba","optional":false},{"reason":"Provides scientific computing tools, likely for linear algebra solvers or sparse matrices.","package":"scipy","optional":false},{"reason":"Optional dependency for GPU-accelerated foreground estimation using CUDA.","package":"cupy-cuda90","optional":true},{"reason":"Optional dependency for GPU-accelerated foreground estimation using OpenCL.","package":"pyopencl","optional":true}],"imports":[{"note":"The primary function for simple, end-to-end alpha matting and foreground extraction.","symbol":"cutout","correct":"from pymatting import cutout"},{"note":"One of several specific alpha estimation methods, often imported directly from the top-level package or 'pymatting.alpha'.","symbol":"estimate_alpha_cf","correct":"from pymatting import estimate_alpha_cf"},{"note":"One of several specific foreground estimation methods, often imported directly from the top-level package or 'pymatting.foreground'.","symbol":"estimate_foreground_ml","correct":"from pymatting import estimate_foreground_ml"}],"quickstart":{"code":"import numpy as np\nfrom PIL import Image\nfrom pymatting import cutout\nimport os\n\n# Create dummy image and trimap files for demonstration\ndef create_dummy_image(path, size=(64, 64), color=(255, 0, 0)):\n    img = Image.new('RGB', size, color)\n    img.save(path)\n\ndef create_dummy_trimap(path, size=(64, 64)):\n    # A simple trimap: top-left foreground (1.0), bottom-right background (0.0), middle unknown (0.5)\n    trimap_data = np.zeros(size, dtype=np.float64)\n    trimap_data[:size[0]//2, :size[1]//2] = 1.0 # Foreground\n    trimap_data[size[0]//2:, size[1]//2:] = 0.0 # Background\n    trimap_data[size[0]//4:size[0]*3//4, size[1]//4:size[1]*3//4] = 0.5 # Unknown\n    \n    # Convert to PIL image and save (e.g., as grayscale PNG)\n    trimap_img = Image.fromarray((trimap_data * 255).astype(np.uint8), mode='L')\n    trimap_img.save(path)\n\ninput_image_path = \"dummy_input.png\"\ninput_trimap_path = \"dummy_trimap.png\"\noutput_cutout_path = \"dummy_cutout.png\"\n\ncreate_dummy_image(input_image_path, color=(100, 150, 200))\ncreate_dummy_trimap(input_trimap_path)\n\nprint(f\"Processing image: {input_image_path} with trimap: {input_trimap_path}\")\n\ntry:\n    # Perform the cutout operation\n    # Note: The first import/call might be slow due to Numba compilation\n    cutout(\n        input_image_path,\n        input_trimap_path,\n        output_cutout_path\n    )\n    print(f\"Cutout saved to: {output_cutout_path}\")\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\nfinally:\n    # Clean up dummy files\n    if os.path.exists(input_image_path):\n        os.remove(input_image_path)\n    if os.path.exists(input_trimap_path):\n        os.remove(input_trimap_path)\n    # Keep output_cutout_path for verification if successful\n    # if os.path.exists(output_cutout_path):\n    #     os.remove(output_cutout_path)\n","lang":"python","description":"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."},"warnings":[{"fix":"Be aware of this initial delay, especially in performance-critical applications or interactive environments. There is no direct fix for the initial compilation, but it's a one-time overhead per session.","message":"The first time PyMatting functions are imported or called, there might be a significant delay due to Numba's Just-In-Time (JIT) compilation. Subsequent calls will be much faster.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure your trimap images are loaded and converted to `numpy.ndarray` with `dtype=np.float64`. Normalize background pixels to 0.0 and foreground pixels to 1.0.","message":"Trimaps must be provided as NumPy arrays of type `np.float64` where values are 0.0 (background), 1.0 (foreground), or anything in between (unknown region). Incorrect data types or value ranges can lead to unexpected results or errors.","severity":"gotcha","affected_versions":"All versions"},{"fix":"If GPU acceleration is critical for alpha estimation, consider alternative libraries or CPU-based methods within PyMatting. For foreground estimation, ensure you install `cupy` or `pyopencl` and relevant GPU drivers, then use the specific GPU-enabled functions.","message":"GPU acceleration for PyMatting currently only supports 'foreground estimation' methods (e.g., `estimate_foreground_ml_cupy`, `estimate_foreground_ml_pyopencl`), not 'alpha estimation'. Additionally, specific GPU-compatible libraries (CuPy, PyOpenCL) and their respective drivers must be installed separately.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Upgrade to PyMatting version 1.1.11 or newer. If you are handling boolean NumPy arrays, prefer `np.bool_` for compatibility.","message":"Prior to version 1.1.11, PyMatting used `np.bool8`. This has been replaced with `np.bool_` to align with newer NumPy conventions. While direct impact on user code might be minimal, it could cause issues if interacting with internal PyMatting types using `np.bool8` in older environments with newer NumPy.","severity":"deprecated","affected_versions":"< 1.1.11"}],"env_vars":null,"last_verified":"2026-04-11T00:00:00.000Z","next_check":"2026-07-10T00:00:00.000Z"}