背景去除简介

背景去除 - 从原始背景中分离出物体。

使用案例

OctankFashion 想在其零售网站的产品页面上重复使用一些营销图像。他们的网站设计标准要求所有产品图像都必须有一个透明的背景,以免分散衬衫设计的注意力。Nova Canvas 的背景去除功能非常适合这个任务。

要使用这个功能,我们只需要提供图像给模型。模型将自动确定图像中哪些部分应该被视为前景和背景,无需提示!

先决条件: 请先运行 00-prerequisites.ipynb 中的先决条件。

import io
import json
import base64
import boto3
from botocore.config import Config
from PIL import Image
from utils import save_image, plot_images

bedrock_runtime_client = boto3.client(
    "bedrock-runtime",
    region_name="us-east-1",
    config=Config(
        read_timeout=5 * 60
    ),  # 重要: 将读取超时时间增加到5分钟以支持更长的操作。
)
image_generation_model_id = "amazon.nova-canvas-v1:0"
output_dir = "output"

以下参数特定于"BACKGROUND_REMOVAL"任务类型,并封装在请求正文的backgroundRemovalParams字段中。

  • image (必需) - 要修改的 JPEG 或 PNG 图像,编码为 Base64 字符串。 (有关如何将图像编码为 Base64 的代码,请参见下面。)

为了演示,我们将使用下面的图像。运行下面的单元格以去除背景。生成的图像将保存到"output"文件夹。

# 指定要从中删除背景的图像。
reference_image_path = "images/tshirt_palm_tree_wood_bkg.png"
with open(reference_image_path, "rb") as image_file:
    input_image = base64.b64encode(image_file.read()).decode("utf8")

body = json.dumps(
    {
        "taskType": "BACKGROUND_REMOVAL",
        "backgroundRemovalParams": {"image": input_image},
    }
)

print("正在生成图像...")

response = bedrock_runtime_client.invoke_model(
    body=body,
    modelId=image_generation_model_id,
    accept="application/json",
    contentType="application/json",
)

response_body = json.loads(response.get("body").read())

base64_images = response_body.get("images")
image_path = f"{output_dir}/04-background-removal.png"
save_image(base64_images[0], image_path)

print(f"图像已保存到 {image_path}")

response_images = [
    Image.open(io.BytesIO(base64.b64decode(base64_image)))
    for base64_image in base64_images
]

plot_images(
    response_images,
    ref_image_path=reference_image_path,
    original_title="原始图像",
    processed_title="去除背景后的图像",
)

要点

背景去除是一个强大的功能,可以自动检测和分离图像中的物体。这个工具创建了一个透明的背景,只保留主要的主题。通过消除原始背景,用户可以轻松地将隔离的物体放置在新的环境或构图中。