76 lines
3.1 KiB
Python
76 lines
3.1 KiB
Python
"""图片智能抠图/切分 — auto cutout / split image.
|
||
|
||
tripocli img-split -a <asset_id> --wait -o ./cutout.png
|
||
tripocli img-split (自动取最新一张参考图抠图)
|
||
|
||
实测流程(页面上剪刀图标抓到的请求):
|
||
POST /v2/studio/image/split
|
||
{"asset_id": "...", "resource_key": "generate-image/..."}
|
||
→ {"task_id": "...", "asset_id": "..."}
|
||
|
||
轮询:
|
||
POST /v2/studio/image/get_image_asset {"asset_id": "..."}
|
||
→ status == "success", type == "split_image", output.data[0].url
|
||
"""
|
||
|
||
import os
|
||
import time
|
||
|
||
from ..errors import TripoAPIError, TripoTimeout
|
||
from .image_upscale import resolve_asset_and_key
|
||
|
||
NAME = "img-split"
|
||
HELP = "图片智能抠图/切分:主体背景去除与透明化(对应网页端剪刀按钮)"
|
||
|
||
|
||
def add_arguments(parser):
|
||
parser.add_argument("-a", "--asset", help="图片资产 ID(默认自动取最近生成的一张)")
|
||
parser.add_argument("--key", help="指定图片 resource_key(默认自动解析)")
|
||
parser.add_argument("-w", "--wait", action="store_true", default=True, help="等待抠图完成(默认等待)")
|
||
parser.add_argument("--no-wait", dest="wait", action="store_false", help="不等待,提交后直接退出")
|
||
parser.add_argument("-o", "--output", help="抠图后的图片保存路径")
|
||
parser.add_argument("--timeout", type=int, default=180, help="等待超时秒数(默认 180)")
|
||
|
||
|
||
def run(ctx):
|
||
args = ctx.args
|
||
asset_id, key = resolve_asset_and_key(ctx, args.asset, args.key)
|
||
ctx.out.line(f"✂️ 提交智能抠图任务: asset={asset_id}")
|
||
|
||
resp = ctx.client.get_data("POST", "/v2/studio/image/split", body={
|
||
"asset_id": asset_id,
|
||
"resource_key": key,
|
||
}) or {}
|
||
|
||
new_asset_id = resp.get("asset_id") or resp.get("task_id")
|
||
if not new_asset_id:
|
||
raise TripoAPIError(f"split 未返回 asset_id: {resp}")
|
||
|
||
if not args.wait:
|
||
ctx.out.data(resp, human=lambda: ctx.out.line(f"✅ 任务已提交,asset_id: {new_asset_id}"))
|
||
return resp
|
||
|
||
ctx.out.line(f"⏳ 等待智能抠图完成: {new_asset_id}")
|
||
start = time.time()
|
||
while time.time() - start < args.timeout:
|
||
info = ctx.client.get_data("POST", "/v2/studio/image/get_image_asset", body={"asset_id": new_asset_id}) or {}
|
||
status = info.get("status")
|
||
if status == "success":
|
||
ctx.out.line("🎉 智能抠图完成!")
|
||
out_imgs = (info.get("output") or {}).get("data") or []
|
||
url = out_imgs[0].get("url") if out_imgs else None
|
||
if url:
|
||
ctx.out.line(f"抠图结果地址: {url}")
|
||
if args.output:
|
||
save_path = args.output
|
||
if os.path.isdir(save_path):
|
||
save_path = os.path.join(save_path, f"{new_asset_id}_cutout.webp")
|
||
ctx.client.download_file(url, save_path)
|
||
ctx.out.line(f"💾 已保存到: {save_path}")
|
||
return info
|
||
if status in ("failed", "expired"):
|
||
raise TripoAPIError(f"智能抠图失败: status={status}")
|
||
time.sleep(2)
|
||
|
||
raise TripoTimeout(f"智能抠图超时(超过 {args.timeout} 秒)")
|