eコマース商品画像の切り抜きと標準化されたエージェントスキルを共有する

product-cutout-normalize エージェント スキルの目的、動作モード、パラメータを紹介し、SKILL.md および scripts/run_pipeline.py の完全なソース コードを保持します。

product-cutout-normalize は、商品画像に使用されるエージェント スキルです。

元画像を統一仕様の下透明正方形画像に加工します。デフォルトのルールは次のとおりです。

  • 1024x1024 キャンバス
  • 透明な背景
  • 件名は可能な限り完全なものにしてください
  • 縦長の被写体を横長に自動変換
  • センターボディ
  • メインの表示幅は820pxに統一

電子商取引資料、製品ライブラリ、詳細ページの画像の前処理に適しています。

このスキルはどのような問題を解決しますか?

多くの製品画像には、基本的な切り抜き後も次の問題が発生します。

  • 白い枠または薄い灰色の背景が残る
  • 被写体の水平方向と垂直方向が一致しない
  • キャンバスのサイズが不安定です
  • 被写体のサイズは大きいものから小さいものまでさまざまです
  • 透明部分に小さなノイズがある

このスキルは一定のプロセスに従って処理されます。

  1. ジェミニのカットアウト
  2. 明るい背景のエッジをクリーンアップ
  3. ノイズの小さな断片を除去する
  4. 縦長画像を横長画像に変換
  5. ターゲットの幅に合わせて拡大縮小する
  6. 均一なサイズの透明なキャンバスの中央に配置します。

この方法でエクスポートされた画像はよりきれいになり、バッチ使用に適しています。

該当するシナリオ

以下のニーズに適しています。

  • 商品写真をバッチ処理する
  • 下透過PNGの統合出力
  • メインビジュアルのサイズを統一する
  • 安定した反復可能な処理手順が必要

少数の画像のみを扱う場合、または各画像のレイアウトを個別に調整する必要がある場合には、これは適さない可能性があります。

クイックスタート

最も直接的な実行方法:

1
& ".\.venv\Scripts\python.exe" ".codex\skills\product-cutout-normalize\scripts\run_pipeline.py" "input_dir" "output_dir" --overwrite

実行前に必須:

  • GEMINI_API_KEY
  • google-genai
  • Pillow

依存関係をインストールします。

1
.\.venv\Scripts\python.exe -m pip install google-genai pillow

環境変数を設定します。

1
$env:GEMINI_API_KEY="your_api_key"

出力ルール

デフォルトの出力:

  • 透明な背景 PNG
  • 1024x1024 キャンバス
  • 身幅820px
  • センターボディ
  • 小さなノイズもクリーンアップされます

つまり、これは単なるスクリプトの暗記ではなく、製品イメージを整理するスクリプトのようなものです。

主なパラメータの説明

一般的に使用されるパラメータ:

  • --model デフォルト gemini-2.5-flash-image
  • --canvas-size 出力正方形キャンバス サイズ、デフォルト 1024
  • --target-width 本体の表示幅、デフォルトは 820
  • --min-component-pixels このピクセル数より小さい透明なフラグメントは削除されます (デフォルトは 500)
  • --overwrite 出力ファイルがすでに存在する場合は、出力ファイルを直接上書きします

例えば:

1
& ".\.venv\Scripts\python.exe" ".codex\skills\product-cutout-normalize\scripts\run_pipeline.py" ".\input" ".\output" --canvas-size 1280 --target-width 960 --overwrite

処理の流れ

処理フローは簡単です。

  1. ジェミニのカットアウト
  2. 明るい背景のエッジをクリーンアップ
  3. ノイズの小さな断片を除去する
  4. 縦長画像を横長画像に変換
  5. ターゲットの幅に合わせて拡大縮小する
  6. 均一なサイズの透明なキャンバスの中央に配置します。

通常の切り抜きスクリプトとの違い

通常の暗記スクリプトと比較して、次の問題もさらに処理します。

  • 主な方向性は統一されています
  • 均一なボディサイズ
  • 均一なキャンバスサイズ
  • 小さな破片やノイズ​​のクリーンアップ
  • 結果はマテリアル ライブラリに直接入れるのに適しています。

SKILL.md ソースコード

SKILL.md の完全なソース コードは以下に保持されており、内容は変更されていません。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
---
name: product-cutout-normalize
description: Run a reusable Gemini product-image pipeline that removes backgrounds, preserves the full subject, rotates tall products to a horizontal orientation, centers them on a 1024x1024 transparent canvas, and normalizes the visible subject width to 820px. Use when the user wants a repeatable cutout-and-normalize workflow for product photos or asks to batch-process product images into standardized square PNG assets.
---

# Product Cutout Normalize

Use this skill when product photos need the same deterministic finishing pipeline:

- Gemini cutout from the original photo
- border cleanup to transparent
- preserve the full subject
- rotate to horizontal when the subject is taller than it is wide
- center on a `1024x1024` transparent canvas
- normalize the visible subject width to `820px`

## Quick Start

Run the bundled script:

```powershell
& ".\.venv\Scripts\python.exe" ".codex\skills\product-cutout-normalize\scripts\run_pipeline.py" "input_dir" "output_dir" --overwrite
```

Required environment:

- `GEMINI_API_KEY`
- `google-genai`
- `Pillow`

## Workflow

1. Confirm the request matches this standard pipeline. If the user asks for a different canvas size, subject width, or layout rule, pass explicit flags instead of changing the script.
2. Run the bundled script on the input directory.
3. If a result looks misaligned, inspect the alpha bounding box and small detached artifacts first; this pipeline already removes tiny alpha components by default.
4. Report the exact input and output directories used, plus any non-default flags.

## Script

Primary entry point:

- `scripts/run_pipeline.py`

Key flags:

- `--model`: Gemini image model, default `gemini-2.5-flash-image`
- `--canvas-size`: output square size, default `1024`
- `--target-width`: visible subject width after normalization, default `820`
- `--min-component-pixels`: remove detached alpha specks smaller than this, default `500`
- `--overwrite`: replace existing outputs in the destination directory

## Repo Integration

If the current project already has [`scripts/nano_banana_cutout.py`](/c:/Work/my_shop/scripts/nano_banana_cutout.py), prefer that repo script when the user wants the same pipeline inside this repository. Use the bundled skill script when the task is cross-project reuse or when you want the workflow to stay self-contained inside the skill.

スクリプト/run_pipeline.py ソース コード

scripts/run_pipeline.py の完全なソース コードは以下に保持されており、内容は変更されていません。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
from __future__ import annotations

import argparse
import os
from collections import deque
from pathlib import Path

from PIL import Image

try:
    from google import genai
except ImportError as exc:  # pragma: no cover
    raise SystemExit(
        "Missing dependency: google-genai. Install it with "
        r"'.\.venv\Scripts\python.exe -m pip install google-genai'."
    ) from exc


PROMPT = (
    "Remove the entire background from this product photo and return only the product "
    "on a fully transparent background as a PNG. Keep the full product intact, preserve "
    "thin cable details, clean the inner loops and holes, and do not add any new objects "
    "or shadows."
)
DEFAULT_CANVAS_SIZE = 1024
DEFAULT_TARGET_WIDTH = 820
DEFAULT_MIN_COMPONENT_PIXELS = 500
SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}


def is_light_background_pixel(r: int, g: int, b: int) -> bool:
    brightness = (r + g + b) / 3
    spread = max(r, g, b) - min(r, g, b)
    return brightness >= 170 and spread <= 35


def to_pil_image(image_obj) -> Image.Image:
    if isinstance(image_obj, Image.Image):
        return image_obj
    pil_image = getattr(image_obj, "_pil_image", None)
    if isinstance(pil_image, Image.Image):
        return pil_image
    as_pil = getattr(image_obj, "pil_image", None)
    if isinstance(as_pil, Image.Image):
        return as_pil
    raise TypeError(f"Unsupported image object type: {type(image_obj)!r}")


def make_transparent_from_borders(image: Image.Image) -> Image.Image:
    rgba = image.convert("RGBA")
    width, height = rgba.size
    pixels = rgba.load()

    visited: set[tuple[int, int]] = set()
    queue: deque[tuple[int, int]] = deque()

    def push_if_bg(x: int, y: int) -> None:
        if (x, y) in visited:
            return
        r, g, b, _ = pixels[x, y]
        if is_light_background_pixel(r, g, b):
            visited.add((x, y))
            queue.append((x, y))

    for x in range(width):
        push_if_bg(x, 0)
        push_if_bg(x, height - 1)
    for y in range(height):
        push_if_bg(0, y)
        push_if_bg(width - 1, y)

    while queue:
        x, y = queue.popleft()
        for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
            if 0 <= nx < width and 0 <= ny < height:
                push_if_bg(nx, ny)

    for x, y in visited:
        pixels[x, y] = (0, 0, 0, 0)

    return rgba


def remove_small_components(image: Image.Image, min_component_pixels: int) -> Image.Image:
    if min_component_pixels <= 0:
        return image

    rgba = image.convert("RGBA")
    alpha = rgba.getchannel("A")
    width, height = rgba.size
    alpha_pixels = alpha.load()
    rgba_pixels = rgba.load()
    visited: set[tuple[int, int]] = set()

    for y in range(height):
        for x in range(width):
            if alpha_pixels[x, y] == 0 or (x, y) in visited:
                continue

            queue: deque[tuple[int, int]] = deque([(x, y)])
            visited.add((x, y))
            component: list[tuple[int, int]] = []

            while queue:
                cx, cy = queue.popleft()
                component.append((cx, cy))
                for nx, ny in ((cx - 1, cy), (cx + 1, cy), (cx, cy - 1), (cx, cy + 1)):
                    if 0 <= nx < width and 0 <= ny < height:
                        if alpha_pixels[nx, ny] == 0 or (nx, ny) in visited:
                            continue
                        visited.add((nx, ny))
                        queue.append((nx, ny))

            if len(component) < min_component_pixels:
                for px, py in component:
                    r, g, b, _ = rgba_pixels[px, py]
                    rgba_pixels[px, py] = (r, g, b, 0)

    return rgba


def normalize_product_image(
    image: Image.Image,
    canvas_size: int,
    target_width: int,
) -> Image.Image:
    rgba = image.convert("RGBA")
    bbox = rgba.getchannel("A").getbbox()
    if bbox is None:
        return Image.new("RGBA", (canvas_size, canvas_size), (0, 0, 0, 0))

    subject = rgba.crop(bbox)
    if subject.height > subject.width:
        subject = subject.rotate(-90, expand=True, resample=Image.Resampling.BICUBIC)
        rotated_bbox = subject.getchannel("A").getbbox()
        if rotated_bbox is not None:
            subject = subject.crop(rotated_bbox)

    scale = target_width / subject.width
    subject = subject.resize(
        (target_width, max(1, int(round(subject.height * scale)))),
        Image.Resampling.LANCZOS,
    )

    canvas = Image.new("RGBA", (canvas_size, canvas_size), (0, 0, 0, 0))
    offset_x = (canvas_size - subject.width) // 2
    offset_y = (canvas_size - subject.height) // 2
    canvas.alpha_composite(subject, (offset_x, offset_y))
    return canvas


def finalize_product_image(
    image: Image.Image,
    canvas_size: int,
    target_width: int,
    min_component_pixels: int,
) -> Image.Image:
    transparent = make_transparent_from_borders(image)
    cleaned = remove_small_components(transparent, min_component_pixels)
    return normalize_product_image(cleaned, canvas_size=canvas_size, target_width=target_width)


def save_first_image_part(
    response,
    dst: Path,
    canvas_size: int,
    target_width: int,
    min_component_pixels: int,
) -> None:
    parts = getattr(response, "parts", None)
    if parts is None and getattr(response, "candidates", None):
        parts = response.candidates[0].content.parts

    if not parts:
        raise RuntimeError("Model returned no content parts.")

    for part in parts:
        inline_data = getattr(part, "inline_data", None)
        if inline_data is None and isinstance(part, dict):
            inline_data = part.get("inline_data")

        if inline_data is None:
            continue

        if hasattr(part, "as_image"):
            image = to_pil_image(part.as_image())
            dst.parent.mkdir(parents=True, exist_ok=True)
            finalize_product_image(
                image,
                canvas_size=canvas_size,
                target_width=target_width,
                min_component_pixels=min_component_pixels,
            ).save(dst)
            return

        data = getattr(inline_data, "data", None)
        if data:
            dst.parent.mkdir(parents=True, exist_ok=True)
            with open(dst, "wb") as handle:
                handle.write(data)
            with Image.open(dst) as image:
                processed = finalize_product_image(
                    image,
                    canvas_size=canvas_size,
                    target_width=target_width,
                    min_component_pixels=min_component_pixels,
                )
                processed.save(dst.with_suffix(".png"))
            if dst.suffix.lower() != ".png":
                dst.unlink(missing_ok=True)
            return

    raise RuntimeError("Model returned text only and no edited image.")


def process_image(
    src: Path,
    dst: Path,
    client,
    model: str,
    canvas_size: int,
    target_width: int,
    min_component_pixels: int,
) -> None:
    with Image.open(src).convert("RGBA") as image:
        response = client.models.generate_content(
            model=model,
            contents=[PROMPT, image],
        )

    save_first_image_part(
        response,
        dst,
        canvas_size=canvas_size,
        target_width=target_width,
        min_component_pixels=min_component_pixels,
    )


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Cut out product images with Gemini and normalize them to square transparent PNGs."
    )
    parser.add_argument("input_dir", type=Path)
    parser.add_argument("output_dir", type=Path)
    parser.add_argument("--model", default="gemini-2.5-flash-image")
    parser.add_argument("--canvas-size", type=int, default=DEFAULT_CANVAS_SIZE)
    parser.add_argument("--target-width", type=int, default=DEFAULT_TARGET_WIDTH)
    parser.add_argument("--min-component-pixels", type=int, default=DEFAULT_MIN_COMPONENT_PIXELS)
    parser.add_argument("--overwrite", action="store_true")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    api_key = os.environ.get("GEMINI_API_KEY")
    if not api_key:
        raise SystemExit("Missing GEMINI_API_KEY environment variable.")
    if not args.input_dir.is_dir():
        raise SystemExit(f"Input directory does not exist: {args.input_dir}")
    if args.canvas_size <= 0:
        raise SystemExit("--canvas-size must be positive.")
    if args.target_width <= 0 or args.target_width > args.canvas_size:
        raise SystemExit("--target-width must be positive and no larger than --canvas-size.")
    if args.min_component_pixels < 0:
        raise SystemExit("--min-component-pixels must be >= 0.")

    args.output_dir.mkdir(parents=True, exist_ok=True)
    client = genai.Client(api_key=api_key)

    for src in sorted(args.input_dir.iterdir()):
        if not src.is_file() or src.suffix.lower() not in SUPPORTED_EXTENSIONS:
            continue
        dst = args.output_dir / f"{src.stem}.png"
        if dst.exists() and not args.overwrite:
            print(f"skip {dst}")
            continue
        process_image(
            src,
            dst,
            client,
            args.model,
            canvas_size=args.canvas_size,
            target_width=args.target_width,
            min_component_pixels=args.min_component_pixels,
        )
        print(dst)


if __name__ == "__main__":
    main()

添付ファイルをダウンロード: product-cutout-normalize.7z

记录并分享
Hugo で構築されています。
テーマ StackJimmy によって設計されています。