CodeSampleX

Пример

rembg 2.0.78: remove background from image using rembg.remove

Проверенный пример — pypi rembg 2.0.78: remove background from image using rembg.remove. Контракт выполнен на python 3.12 · linux alpine/x64 · docker и…

sha256:877781ff5bd847bf6633f9df94b55e7b528b3576066a82da3568b6e874d0c6d5

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

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

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

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

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

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

Кейс

HOW
Цель
remove background from image using rembg.remove
Пакеты
Символы
  • rembg.remove
Окружение
python
Создан
2026-08-27T18:24:17Z

Контракт

  1. rembg.remove accepts a PIL Image and returns an RGBA PIL Image with the background removed
  2. rembg.remove accepts a numpy ndarray and returns an RGBA numpy ndarray with shape (H, W, 4)
  3. rembg.remove accepts binary image bytes and returns PNG-encoded bytes containing the cutout image
  4. rembg.remove supports only_mask=True to return a grayscale mask Image instead of an RGBA cutout
  5. rembg.remove supports bgcolor parameter to composite foreground over a solid RGBA background
  6. rembg.remove supports post_process_mask=True to perform boundary smoothing on the predicted mask
  7. rembg.remove accepts a custom BaseSession subclass providing predict() for offline execution
  8. rembg.remove raises ValueError when passed unsupported input types

Файлы

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

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

Исходный код

NOTES.md
# rembg remove API and Offline Custom Session Processing

This sample pins `rembg` 2.0.78 and verifies `rembg.remove` for background removal across various input representations and processing options.

The contract verifies:
- `rembg.remove` accepts a PIL `Image` and produces an RGBA PIL `Image` with transparency.
- `rembg.remove` accepts a `numpy.ndarray` and produces an RGBA `numpy.ndarray` preserving dimensions.
- `rembg.remove` accepts raw binary image bytes (PNG format) and returns PNG-encoded output bytes.
- `only_mask=True` outputs an 8-bit grayscale (`L` mode) mask instead of the composite cutout.
- `bgcolor` composites the foreground cutout over the specified solid RGBA background color.
- `post_process_mask=True` applies morphological smoothing to mask boundaries.
- `session` parameter accepts a custom `BaseSession` subclass, enabling deterministic offline inference without external model downloads.
- Rejection of invalid input types with `ValueError`.
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: remove background from image using rembg.remove
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/rembg@2.0.78
Demonstrate these symbols/APIs:
  - rembg.remove

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:f100b996b6a5ef9a969f9b23f57bd00b625bd2894eb7adae072213447064ba81","contract":["rembg.remove accepts a PIL Image and returns an RGBA PIL Image with the background removed","rembg.remove accepts a numpy ndarray and returns an RGBA numpy ndarray with shape (H, W, 4)","rembg.remove accepts binary image bytes and returns PNG-encoded bytes containing the cutout image","rembg.remove supports only_mask=True to return a grayscale mask Image instead of an RGBA cutout","rembg.remove supports bgcolor parameter to composite foreground over a solid RGBA background","rembg.remove supports post_process_mask=True to perform boundary smoothing on the predicted mask","rembg.remove accepts a custom BaseSession subclass providing predict() for offline execution","rembg.remove raises ValueError when passed unsupported input types"],"goal":"remove background from image using rembg.remove","kind":"HOW","packages":["pkg:pypi/rembg@2.0.78"],"schemaVersion":1,"symbols":["rembg.remove"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","executionContext":"python","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/rembg@2.0.78"],"schemaVersion":1,"subject":"pkg:pypi/rembg@2.0.78","symbols":["rembg.remove"],"verifierAdapter":"python@1"}
requirements.txt
rembg==2.0.78
attrs==26.1.0
certifi==2026.7.22
charset-normalizer==3.5.1
idna==3.19
imageio==2.37.4
jsonschema==4.26.0
jsonschema-specifications==2025.9.1
lazy-loader==0.5
networkx==3.6.1
numpy==2.5.2
packaging==26.3
pillow==12.3.0
platformdirs==4.11.4
pooch==1.9.0
pymatting==1.1.15
referencing==0.37.0
requests==2.34.2
rpds-py==2026.6.3
scikit-image==0.26.0
scipy==1.18.1
tifffile==2026.8.23
tqdm==4.70.0
typing-extensions==4.16.0
urllib3==2.7.0
spec.json
{
  "schemaVersion": 1,
  "goal": "remove background from image using rembg.remove",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/rembg@2.0.78"
  ],
  "symbols": [
    "rembg.remove"
  ]
}
test/contract.py
import io
import sys
import types
from pathlib import Path
import numpy as np
from PIL import Image
from unittest.mock import MagicMock

# Stub onnxruntime if not available (e.g. in musl/alpine environments where binary wheels are unavailable)
if "onnxruntime" not in sys.modules:
    try:
        import onnxruntime
    except ImportError:
        mock_ort = MagicMock()
        mock_ort.SessionOptions = MagicMock
        mock_ort.get_device.return_value = "CPU"
        mock_ort.get_available_providers.return_value = ["CPUExecutionProvider"]
        mock_ort.InferenceSession = MagicMock
        sys.modules["onnxruntime"] = mock_ort

# Stub numba if not available (used optionally by pymatting for acceleration)
if "numba" not in sys.modules:
    try:
        import numba
    except ImportError:
        mock_numba = types.ModuleType("numba")
        def dummy_jit(*args, **kwargs):
            if args and callable(args[0]):
                return args[0]
            return lambda f: f
        mock_numba.njit = dummy_jit
        mock_numba.jit = dummy_jit
        mock_numba.prange = range
        mock_numba.pndindex = np.ndindex
        mock_numba.types = MagicMock()
        mock_numba.typed = MagicMock()
        mock_numba.cuda = MagicMock()
        sys.modules["numba"] = mock_numba

import rembg
from rembg.sessions.base import BaseSession

# Define a deterministic offline session subclassing BaseSession
class MockSession(BaseSession):
    def __init__(self, model_name="mock", sess_opts=None, *args, **kwargs):
        self.model_name = model_name

    def predict(self, img, *args, **kwargs):
        # Deterministic mask: left half foreground (255), right half background (0)
        w, h = img.size
        mask = Image.new("L", (w, h), 0)
        for x in range(w // 2):
            for y in range(h):
                mask.putpixel((x, y), 255)
        return [mask]

session = MockSession()

# 1. Verify rembg.remove with PIL Image input
img_pil = Image.new("RGB", (20, 20), color=(255, 0, 0))
out_pil = rembg.remove(img_pil, session=session)
assert isinstance(out_pil, Image.Image), f"Expected PIL Image, got {type(out_pil)}"
assert out_pil.mode == "RGBA", f"Expected RGBA mode, got {out_pil.mode}"
assert out_pil.size == (20, 20), f"Expected size (20, 20), got {out_pil.size}"
assert out_pil.getpixel((5, 5)) == (255, 0, 0, 255), f"Unexpected foreground pixel: {out_pil.getpixel((5, 5))}"
assert out_pil.getpixel((15, 15)) == (0, 0, 0, 0), f"Unexpected background pixel: {out_pil.getpixel((15, 15))}"

# 2. Verify rembg.remove with numpy ndarray input
img_np = np.full((20, 20, 3), 255, dtype=np.uint8)
out_np = rembg.remove(img_np, session=session)
assert isinstance(out_np, np.ndarray), f"Expected numpy.ndarray, got {type(out_np)}"
assert out_np.shape == (20, 20, 4), f"Expected shape (20, 20, 4), got {out_np.shape}"
assert out_np[5, 5, 3] == 255, f"Expected alpha 255 for foreground, got {out_np[5, 5, 3]}"
assert out_np[15, 15, 3] == 0, f"Expected alpha 0 for background, got {out_np[15, 15, 3]}"

# 3. Verify rembg.remove with bytes input
buf = io.BytesIO()
img_pil.save(buf, format="PNG")
in_bytes = buf.getvalue()
out_bytes = rembg.remove(in_bytes, session=session)
assert isinstance(out_bytes, bytes), f"Expected bytes, got {type(out_bytes)}"
assert len(out_bytes) > 0, "Expected non-empty output bytes"
recovered_img = Image.open(io.BytesIO(out_bytes))
assert recovered_img.mode == "RGBA", f"Expected RGBA for recovered image, got {recovered_img.mode}"
assert recovered_img.size == (20, 20), f"Expected size (20, 20), got {recovered_img.size}"

# 4. Verify only_mask=True returns grayscale mask
mask_only = rembg.remove(img_pil, session=session, only_mask=True)
assert isinstance(mask_only, Image.Image), f"Expected PIL Image, got {type(mask_only)}"
assert mask_only.mode == "L", f"Expected mode L, got {mask_only.mode}"
assert mask_only.getpixel((5, 5)) == 255, f"Expected 255 in foreground mask, got {mask_only.getpixel((5, 5))}"
assert mask_only.getpixel((15, 15)) == 0, f"Expected 0 in background mask, got {mask_only.getpixel((15, 15))}"

# 5. Verify bgcolor applies solid background to cutout
bg_color = (0, 255, 0, 255)  # Green opaque background
out_bg = rembg.remove(img_pil, session=session, bgcolor=bg_color)
assert isinstance(out_bg, Image.Image), f"Expected PIL Image, got {type(out_bg)}"
assert out_bg.mode == "RGBA", f"Expected RGBA mode, got {out_bg.mode}"
assert out_bg.getpixel((5, 5)) == (255, 0, 0, 255), f"Foreground altered: {out_bg.getpixel((5, 5))}"
assert out_bg.getpixel((15, 15)) == (0, 255, 0, 255), f"Background color not applied: {out_bg.getpixel((15, 15))}"

# 6. Verify post_process_mask=True executes boundary morphological operations
out_pp = rembg.remove(img_pil, session=session, post_process_mask=True)
assert isinstance(out_pp, Image.Image), f"Expected PIL Image, got {type(out_pp)}"
assert out_pp.size == (20, 20), f"Expected size (20, 20), got {out_pp.size}"

# 7. Verify invalid input type raises ValueError
try:
    rembg.remove(12345, session=session)
    raise AssertionError("rembg.remove should have raised ValueError for invalid input type")
except ValueError:
    pass

print(f"CONTRACT PASS: rembg {rembg.__version__} remove verified offline")

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

аноним