CodeSampleX

Пример

pymatting 1.1.15: cutout

Проверенный пример — pypi pymatting 1.1.15: cutout. Контракт выполнен на python 3.12 · linux debian/x64 · docker и пройден: pymatting.cutout generates an…

sha256:5229c6a1581c9294b0a3ef973557909404557ff402547dc6eafc7f59fb540050

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда python linux 24 · ubuntu · glibc 2.39 x64 python python pip

Среды запусков проверки

Окружение Контракт Этапы Запуск
python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104…
2026-09-02

Кейс

HOW
Цель
verify pymatting.cutout in pkg:pypi/pymatting@1.1.15
Пакеты
Символы
  • pymatting.cutout
Окружение
python
Создан
2026-09-02T09:25:39Z

Контракт

  1. pymatting.cutout generates an RGBA cutout image file from input image and trimap paths
  2. pymatting.cutout raises ValueError when input image and trimap have mismatched dimensions

Файлы

  • PROMPT.md
  • csx.json
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pymatting.cutout in pkg:pypi/pymatting@1.1.15
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pymatting@1.1.15
Demonstrate these symbols/APIs:
  - pymatting.cutout

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:e74cb83f41c9cf77e0ef54d86f724705666b61cceb08d0335f6bb9a3caed03f8","contract":["pymatting.cutout generates an RGBA cutout image file from input image and trimap paths","pymatting.cutout raises ValueError when input image and trimap have mismatched dimensions"],"goal":"verify pymatting.cutout in pkg:pypi/pymatting@1.1.15","kind":"HOW","packages":["pkg:pypi/pymatting@1.1.15"],"schemaVersion":1,"symbols":["pymatting.cutout"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pymatting@1.1.15"],"schemaVersion":1,"subject":"pkg:pypi/pymatting@1.1.15","symbols":["pymatting.cutout"],"verifierAdapter":"python@1"}
requirements.txt
llvmlite==0.49.0
numba==0.67.0
numpy==2.5.2
pillow==12.3.0
pymatting==1.1.15
scipy==1.18.1
sample.py
"""Sample demonstrating alpha matting and cutout generation with PyMatting."""

import os
from typing import Tuple
import numpy as np
from PIL import Image
import pymatting


def create_synthetic_matting_pair(
    width: int = 32, height: int = 32
) -> Tuple[np.ndarray, np.ndarray]:
    """Generate a synthetic RGB image and corresponding trimap."""
    # Create an RGB image with distinct foreground (top) and background (bottom)
    image = np.zeros((height, width, 3), dtype=np.uint8)
    image[: height // 2, :] = [220, 50, 50]  # Reddish foreground
    image[height // 2 :, :] = [50, 180, 50]  # Greenish background

    # Create trimap: 255 (foreground), 0 (background), 128 (unknown transition zone)
    trimap = np.full((height, width), 128, dtype=np.uint8)
    trimap[: height // 4, :] = 255  # Definite foreground
    trimap[(height * 3) // 4 :, :] = 0  # Definite background

    return image, trimap


def generate_cutout(image_path: str, trimap_path: str, output_path: str) -> None:
    """Extract foreground using PyMatting and save RGBA cutout image."""
    pymatting.cutout(image_path, trimap_path, output_path)


if __name__ == "__main__":
    import tempfile

    with tempfile.TemporaryDirectory() as temp_dir:
        img_file = os.path.join(temp_dir, "input.png")
        trimap_file = os.path.join(temp_dir, "trimap.png")
        cutout_file = os.path.join(temp_dir, "cutout.png")

        img_data, trimap_data = create_synthetic_matting_pair(32, 32)
        Image.fromarray(img_data).save(img_file)
        Image.fromarray(trimap_data).save(trimap_file)

        generate_cutout(img_file, trimap_file, cutout_file)
        print(f"Cutout generated successfully at {cutout_file}")
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pymatting.cutout in pkg:pypi/pymatting@1.1.15",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pymatting@1.1.15"
  ],
  "symbols": [
    "pymatting.cutout"
  ]
}
test/contract.py
"""Contract verification tests for pymatting.cutout."""

import os
import sys
import tempfile
import numpy as np
from PIL import Image
import pymatting

# Ensure project root is on sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sample import create_synthetic_matting_pair, generate_cutout


def test_cutout_generation() -> None:
    """Assertion 1: pymatting.cutout generates an RGBA cutout image file from input image and trimap paths."""
    with tempfile.TemporaryDirectory() as temp_dir:
        img_path = os.path.join(temp_dir, "input.png")
        trimap_path = os.path.join(temp_dir, "trimap.png")
        out_path = os.path.join(temp_dir, "cutout.png")

        img_arr, trimap_arr = create_synthetic_matting_pair(16, 16)
        Image.fromarray(img_arr).save(img_path)
        Image.fromarray(trimap_arr).save(trimap_path)

        generate_cutout(img_path, trimap_path, out_path)

        assert os.path.exists(out_path), "Cutout image was not created"
        with Image.open(out_path) as out_img:
            assert out_img.size == (16, 16), f"Expected size (16, 16), got {out_img.size}"
            assert out_img.mode == "RGBA", f"Expected RGBA mode, got {out_img.mode}"
            arr = np.array(out_img)
            assert arr.shape == (16, 16, 4), f"Expected shape (16, 16, 4), got {arr.shape}"


def test_cutout_dimension_mismatch() -> None:
    """Assertion 2: pymatting.cutout raises ValueError when input image and trimap have mismatched dimensions."""
    with tempfile.TemporaryDirectory() as temp_dir:
        img_path = os.path.join(temp_dir, "input.png")
        mismatched_trimap_path = os.path.join(temp_dir, "mismatched_trimap.png")
        out_path = os.path.join(temp_dir, "cutout.png")

        img_arr = np.zeros((16, 16, 3), dtype=np.uint8)
        trimap_arr = np.zeros((12, 12), dtype=np.uint8)
        Image.fromarray(img_arr).save(img_path)
        Image.fromarray(trimap_arr).save(mismatched_trimap_path)

        try:
            pymatting.cutout(img_path, mismatched_trimap_path, out_path)
            assert False, "Expected ValueError on mismatched input dimensions"
        except ValueError as exc:
            assert "must have same size" in str(exc), f"Unexpected error message: {exc}"


def main() -> None:
    test_cutout_generation()
    test_cutout_dimension_mismatch()
    print("pymatting.cutout contract verification passed.")


if __name__ == "__main__":
    main()

Исходный сидер

аноним