替换图片的背景

本页介绍了如何替换图片背景。借助 Imagen on Vertex AI,您可以使用自动对象细分功能保留部分内容,同时修改其他图片内容。借助 Imagen 3,您还可以提供自己的蒙版区域,以便在修改时更好地控制。

查看 Imagen for Editing and Customization 模型卡片

产品图片修改示例

以下使用情形重点介绍了如何通过修改图片的背景来美化商品图片,同时保留图片中商品的外观。

控制台中生成的图片示例
使用 Imagen 产品图片修改功能根据以下提示生成的图片:在精品商店的桌子上。原始图片来源:Unsplash 用户 Irene Kredenets

准备工作

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Enable the API

  8. 为您的环境设置身份验证。

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    Python

    如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Google Cloud

    REST

    如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭证。

      After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

    使用自动检测的背景蒙版进行编辑

    借助 Imagen,您可以修改产品图片,并自动检测背景。如果您需要修改商品图片的背景,但保留商品的外观,此功能会很有帮助。产品图片修改功能使用 Google Product Studio (GPS) 产品。您可以使用控制台或 API 将此 GPS 功能用作 Imagen 的一部分。

    控制台中生成的图片示例
    使用 Imagen 产品图片修改功能根据以下提示生成的图片:在精品商店的桌子上。原始图片来源:Unsplash 用户 Irene Kredenets

    按照以下说明启用并使用具有自动检测背景功能的产品图像修改。

    Imagen 3

    使用以下示例,通过 Imagen 3 模型发送产品图片修改请求。

    控制台

    1. 在 Google Cloud 控制台中,前往 Vertex AI > Media Studio 页面。

      前往媒体工作室

    2. 点击上传。在显示的文件对话框中,选择要上传的文件。
    3. 点击涂抹修复
    4. 参数面板中,点击商品背景
    5. 在修改工具栏中,点击 background_replace提取
    6. 选择其中一个蒙版提取选项:

      • 背景元素:检测背景元素并创建一个围绕它们的蒙版。
      • 前景元素:检测前景对象并创建一个围绕它们的蒙版。
      • background_replace人员:检测人员并创建一个围绕他们的蒙版。
    7. 可选:在参数侧边栏中,调整以下选项:
      • 模型:要使用的 Imagen 模型
      • 结果数量:要生成的结果数量
      • 否定提示:要避免生成的内容
    8. 在提示字段中,输入用于修改图片的提示。
    9. 点击发送生成

    Python

    安装

    pip install --upgrade google-genai

    如需了解详情,请参阅 SDK 参考文档

    设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=us-central1
    export GOOGLE_GENAI_USE_VERTEXAI=True

    from google import genai
    from google.genai.types import RawReferenceImage, MaskReferenceImage, MaskReferenceConfig, EditImageConfig
    
    client = genai.Client()
    
    # TODO(developer): Update and un-comment below line
    # output_file = "output-image.png"
    
    raw_ref = RawReferenceImage(
        reference_image=Image.from_file(location='test_resources/suitcase.png'), reference_id=0)
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=None,
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_BACKGROUND",
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A light blue suitcase in front of a window in an airport",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_BGSWAP",
        ),
    )
    
    image.generated_images[0].image.save(output_file)
    
    print(f"Created output image using {len(image.generated_images[0].image.image_bytes)} bytes")
    # Example response:
    # Created output image using 1234567 bytes
    

    REST

    如需了解详情,请参阅修改图片 API 参考文档。

    在使用任何请求数据之前,请先进行以下替换:

    • PROJECT_ID:您的 Google Cloud 项目 ID
    • LOCATION:您的项目的区域。 例如 us-central1europe-west2asia-northeast3。如需查看可用区域的列表,请参阅 Vertex AI 上的生成式 AI 位置
    • TEXT_PROMPT:用于指导模型生成什么图片的文本提示。生成和修改都需要此字段。
    • referenceTypeReferenceImage 是一种图片,可为图片修改提供更多上下文。修改应用场景需要使用常规 RGB 原始参考图片 (REFERENCE_TYPE_RAW)。一次请求中最多只能存在一张原始参考图片。 输出图片的高度和宽度与原始参考图片相同。蒙版修改应用场景需要蒙版参考图片 (REFERENCE_TYPE_MASK)。
    • referenceId:参考图片的整数 ID。在此示例中,这两个参考图片对象的类型不同,因此具有不同的 referenceId 值(12)。
    • B64_BASE_IMAGE:要修改或放大的基础图片。图片必须指定为 base64 编码的字节字符串。大小上限:10 MB。
    • maskImageConfig.maskMode:用于进行蒙版修改的蒙版模式。 MASK_MODE_BACKGROUND 用于在没有用户提供的蒙版的情况下自动对背景进行蒙版处理。
    • MASK_DILATION - 浮点数。将此蒙版扩大的图像宽度的百分比。建议使用值 0.00,以免扩展前景产品。最小值:0,最大值:1。 默认:0.03。
    • EDIT_STEPS - 整数。基本模型的采样步数。如需修改产品图片,请从 75 步数开始。
    • EDIT_IMAGE_COUNT - 已修改图片的数量。接受的整数值:1-4。默认值:4。

    HTTP 方法和网址:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict

    请求 JSON 正文:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT",
          "referenceImages": [
            {
              "referenceType": "REFERENCE_TYPE_RAW",
              "referenceId": 1,
              "referenceImage": {
                "bytesBase64Encoded": "B64_BASE_IMAGE"
              }
            },
            {
              "referenceType": "REFERENCE_TYPE_MASK",
              "referenceId": 2,
              "maskImageConfig": {
                "maskMode": "MASK_MODE_BACKGROUND",
                "dilation": MASK_DILATION
              }
            }
          ]
        }
      ],
      "parameters": {
        "editConfig": {
          "baseSteps": EDIT_STEPS
        },
        "editMode": "EDIT_MODE_BGSWAP",
        "sampleCount": EDIT_IMAGE_COUNT
      }
    }
    

    如需发送请求,请选择以下方式之一:

    curl

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict"

    PowerShell

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict" | Select-Object -Expand Content
    以下示例回答适用于产品背景修改请求。该响应会返回四个预测对象,其中生成的图片字节采用 base64 编码。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        }
      ]
    }
    

    Imagen 2

    使用以下示例,通过 Imagen 2 或 Imagen 模型发送产品图片修改请求。

    控制台

    1. 在 Google Cloud 控制台中,前往 Vertex AI > Media Studio 页面。

      前往媒体工作室

    2. 在下层任务面板中,点击 修改图片

    3. 点击上传以选择要修改的本地存储的产品图片。

    4. 参数面板中,选择启用产品风格图片修改

    5. 提示字段中(在此处写入提示),输入提示。

    6. 点击生成

    Python

    如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python API 参考文档

    
    import vertexai
    from vertexai.preview.vision_models import Image, ImageGenerationModel
    
    # TODO(developer): Update and un-comment below lines
    # PROJECT_ID = "your-project-id"
    # input_file = "input-image.png"
    # output_file = "output-image.png"
    # prompt = "" # The text prompt describing what you want to see in the background.
    
    vertexai.init(project=PROJECT_ID, location="us-central1")
    
    model = ImageGenerationModel.from_pretrained("imagegeneration@006")
    base_img = Image.load_from_file(location=input_file)
    
    images = model.edit_image(
        base_image=base_img,
        prompt=prompt,
        edit_mode="product-image",
    )
    
    images[0].save(location=output_file, include_generation_parameters=False)
    
    # Optional. View the edited image in a notebook.
    # images[0].show()
    
    print(f"Created output image using {len(images[0]._image_bytes)} bytes")
    # Example response:
    # Created output image using 1234567 bytes
    

    REST

    如需详细了解 imagegeneration 模型请求,请参阅 imagegeneration 模型 API 参考文档

    如需启用使用 Imagen 2 版本 006 模型 (imagegeneration@006) 修改产品图片,请在 "editConfig": {} 对象中添加以下字段:"editMode": "product-image"。此请求始终会返回 4 张图片。

    在使用任何请求数据之前,请先进行以下替换:

    • PROJECT_ID:您的 Google Cloud 项目 ID
    • LOCATION:您的项目的区域。 例如 us-central1europe-west2asia-northeast3。如需查看可用区域的列表,请参阅 Vertex AI 上的生成式 AI 位置
    • TEXT_PROMPT:用于指导模型生成什么图片的文本提示。生成和修改都需要此字段。
    • B64_BASE_IMAGE:要修改或放大的基础图片。图片必须指定为 base64 编码的字节字符串。大小上限:10 MB。
    • PRODUCT_POSITION:可选。该设置用于保持所检测产品或对象的原始位置,或允许模型调整其位置。可用值:reposition(默认值),允许调整位置,或 fixed,用于保持产品位置。对于非方形输入图片,产品位置行为始终为“调整位置”,即使设置了“固定”也是如此。

    HTTP 方法和网址:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagegeneration@006:predict

    请求 JSON 正文:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT",
          "image": {
              "bytesBase64Encoded": "B64_BASE_IMAGE"
          },
        }
      ],
      "parameters": {
        "editConfig": {
          "editMode": "product-image",
          "productPosition": "PRODUCT_POSITION",
        }
      }
    }
    
    

    如需发送请求,请选择以下方式之一:

    curl

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagegeneration@006:predict"

    PowerShell

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagegeneration@006:predict" | Select-Object -Expand Content
    以下示例回答适用于产品背景修改请求。该响应会返回四个预测对象,其中生成的图片字节采用 base64 编码。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        }
      ]
    }
    

    使用定义的蒙版区域进行修改

    您可以选择遮盖要替换的区域,而不是让 Imagen 自动检测遮罩。

    控制台

    1. 在 Google Cloud 控制台中,前往 Vertex AI > Media Studio 页面。

      前往媒体工作室

    2. 点击上传。在显示的文件对话框中,选择要上传的文件。
    3. 点击涂抹修复
    4. 参数面板中,点击商品背景
    5. 执行下列其中一项操作:

      • 上传您自己的遮罩
        1. 在电脑上创建遮罩。
        2. 点击上传遮罩。在显示的对话框中,选择要上传的蒙版。
      • 自行定义蒙版:在修改工具栏中,使用蒙版工具(方框、画笔或 masked_transitions 反转工具)指定要添加内容的一个或多个区域。
    6. 可选:在参数面板中,调整以下选项:
      • 模型:要使用的 Imagen 模型
      • 结果数量:要生成的结果数量
      • 否定提示:要避免生成的内容
    7. 在提示字段中,输入用于修改图片的提示。
    8. 点击 生成

    Python

    安装

    pip install --upgrade google-genai

    如需了解详情,请参阅 SDK 参考文档

    设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

    # Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
    # with appropriate values for your project.
    export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
    export GOOGLE_CLOUD_LOCATION=us-central1
    export GOOGLE_GENAI_USE_VERTEXAI=True

    from google import genai
    from google.genai.types import RawReferenceImage, MaskReferenceImage, MaskReferenceConfig, EditImageConfig
    
    client = genai.Client()
    
    # TODO(developer): Update and un-comment below line
    # output_file = "output-image.png"
    
    raw_ref = RawReferenceImage(
        reference_image=Image.from_file(location='test_resources/suitcase.png'), reference_id=0)
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=Image.from_file(location='test_resources/suitcase_mask.png'),
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_USER_PROVIDED",
            mask_dilation=0.0,
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A light blue suitcase in an airport",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_BGSWAP",
        ),
    )
    
    image.generated_images[0].image.save(output_file)
    
    print(f"Created output image using {len(image.generated_images[0].image.image_bytes)} bytes")
    # Example response:
    # Created output image using 1234567 bytes
    

    REST

    如需了解详情,请参阅修改图片 API 参考文档。

    在使用任何请求数据之前,请先进行以下替换:

    • PROJECT_ID:您的 Google Cloud 项目 ID
    • LOCATION:您的项目的区域。 例如 us-central1europe-west2asia-northeast3。如需查看可用区域的列表,请参阅 Vertex AI 上的生成式 AI 位置
    • TEXT_PROMPT:用于指导模型生成什么图片的文本提示。生成和修改都需要此字段。
    • referenceId:参考图片的整数 ID。在此示例中,这两个参考图片对象的类型不同,因此具有不同的 referenceId 值(12)。
    • B64_BASE_IMAGE:要修改或放大的基础图片。图片必须指定为 base64 编码的字节字符串。大小上限:10 MB。
    • B64_MASK_IMAGE:您要用作蒙版层来修改原始图片的黑白图片。图片必须指定为 base64 编码的字节字符串。大小上限:10 MB。
    • MASK_DILATION - 浮点数。将此蒙版扩大的图像宽度的百分比。建议使用值 0.00,以免扩展前景产品。最小值:0,最大值:1。 默认:0.03。
    • EDIT_STEPS - 整数。基本模型的采样步数。如需修改产品图片,请从 75 步数开始。
    • EDIT_IMAGE_COUNT - 已修改图片的数量。接受的整数值:1-4。默认值:4。

    HTTP 方法和网址:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict

    请求 JSON 正文:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT": [
            {
              "referenceType": "REFERENCE_TYPE_RAW",
              "referenceId": 1,
              "referenceImage": {
                "bytesBase64Encoded": "B64_BASE_IMAGE"
              }
            },
            {
              "referenceType": "REFERENCE_TYPE_MASK",
              "referenceId": 2,
              "referenceImage": {
                "bytesBase64Encoded": "B64_MASK_IMAGE"
              },
              "maskImageConfig": {
                "maskMode": "MASK_MODE_USER_PROVIDED",
                "dilation": MASK_DILATION
              }
            }
          ]
        }
      ],
      "parameters": {
        "editConfig": {
          "baseSteps": EDIT_STEPS
        },
        "editMode": "EDIT_MODE_BGSWAP",
        "sampleCount": EDIT_IMAGE_COUNT
      }
    }
    

    如需发送请求,请选择以下方式之一:

    curl

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict"

    PowerShell

    将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

    $cred = gcloud auth print-access-token
    $headers = @{ "Authorization" = "Bearer $cred" }

    Invoke-WebRequest `
    -Method POST `
    -Headers $headers `
    -ContentType: "application/json; charset=utf-8" `
    -InFile request.json `
    -Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/imagen-3.0-capability-001:predict" | Select-Object -Expand Content
    以下示例回答适用于产品背景修改请求。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        }
      ]
    }
    

    限制

    由于遮罩有时不完整,因此当边界处缺少极小的位时,模型可能会尝试补全前景对象。作为一种罕见的副作用,当前景对象已完成时,模型可能会创建轻微的扩展。

    一种解决方法是对模型输出进行分段,然后进行混合。以下是一个 Python 代码段示例,展示了解决方法:

    blended = Image.composite(out_images[0].resize(image_expanded.size), image_expanded, mask_expanded)
    

    后续步骤

    阅读有关 Imagen 和其他 Vertex AI 上的生成式 AI 产品的文章: