使用修复功能将对象插入图片中

本页面介绍了如何将对象插入图片中,这一过程也称为“修复”。借助 Imagen on Vertex AI,您可以指定蒙版区域,将对象插入图片中的该区域。您可以使用自己的蒙版,也可以让 Imagen 为您生成蒙版。

内容插入示例

借助修复功能,您可以使用基础图片、图片蒙版和文本提示将内容添加到现有图片。

输入

要修改的基础映像* 使用 Google Cloud 控制台中的工具指定的蒙版区域 文本提示
基础图片示例。一个玻璃罐里装有一种红色液体,边上放着一片柠檬,并插着一根吸管。柠檬片显示在左前景中 玻璃罐的基础图片,现在在 Cloud 控制台中指定了一个蒙版区域 草莓

* 图片来源:Unsplash 用户 Alex Lvrs

在 Google Cloud 控制台中指定了一个蒙版区域后的输出

为装有红色液体的玻璃罐生成的修改内容的截图。在这张截图中,之前在图片前景中的柠檬片被玻璃罐正前方的两颗草莓所取代。 为装有红色液体的玻璃罐生成的修改内容的截图。在这张截图中,之前在图片前景中的柠檬片被玻璃罐左侧的三颗草莓所取代。 为装有红色液体的玻璃罐生成的修改内容的截图。在这张截图中,之前在图片前景中的柠檬片被略微位于玻璃罐左前方的两颗草莓所取代。

查看 Imagen for Editing and Customization 模型卡片

准备工作

  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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    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,然后使用您的用户凭证设置应用默认凭证。

      安装 Google Cloud CLI。

      如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI

      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 的凭证。

      安装 Google Cloud CLI。

      如果您使用的是外部身份提供方 (IdP),则必须先使用联合身份登录 gcloud CLI

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

    使用定义的蒙版区域插入内容

    使用以下示例通过 Imagen 3 模型发送修复请求。

    控制台

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

    <a href="https://console.cloud.google.com/vertex-ai/studio/media/generate;tab=image" class="button button-primary"
    target="console" track-name="consoleLink" track-type="task">Go to Media
    Studio</a>
    
    1. 点击上传,然后选择要上传的文件。

    2. 点击修复

      执行下列其中一项操作:

      • 上传您自己的蒙版:

        1. 在电脑上创建蒙版。

        2. 点击上传蒙版,然后选择要上传的蒙版。

      • 定义蒙版:在修改工具栏中,使用蒙版工具(方框画笔masked_transitions 反转 工具)指定要添加内容的一个或多个区域。

    3. 可选:在参数面板中,调整以下选项:

      • 模型:要使用的 Imagen 模型。

      • 结果数量:要生成的结果数量。

      • 排除提示:描述您要从生成的图片中排除的内容。

    4. 在提示字段中,输入提示以修改图片。

    5. 点击 生成

    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/fruit.png"),
        reference_id=0,
    )
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=Image.from_file(location="test_resources/fruit_mask.png"),
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_USER_PROVIDED",
            mask_dilation=0.01,
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A plate of cookies",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_INPAINT_INSERTION",
        ),
    )
    
    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

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

    • REGION:项目所在的区域。如需详细了解支持的区域,请参阅 Vertex AI 上的生成式 AI 位置
    • PROJECT_ID:您的 Google Cloud 项目 ID。
    • TEXT_PROMPT:可选。用于引导模型生成的图片的文本提示。为了获得最佳结果,请使用蒙版区域的说明,并避免使用单个词的提示。例如,请使用“一只可爱的柯基”而不是“柯基”。
    • B64_BASE_IMAGE:被编辑图片的 base64 编码图片,大小不超过 10 MB。如需详细了解 base64 编码,请参阅对文件进行 Base64 编码和解码
    • B64_MASK_IMAGE:base64 编码的黑白蒙版图片,大小不超过 10MB。
    • MASK_DILATION:可选。一个介于 0 和 1 之间的浮点值(含 0 和 1),表示将蒙版扩大的图像宽度的百分比。使用 dilation 有助于补偿不精确的蒙版。我们建议将值设置为 0.01
    • EDIT_STEPS:可选。表示采样步骤数的整数。值越大,图片质量越高;值越小,延迟时间越短。

      建议您先尝试使用 35 个步骤。如果质量不符合您的要求,我们建议您提高此值,但不超过 75

    • SAMPLE_COUNT:可选。一个整数,用于描述要生成的图片数量。接受的值范围为 1-4。默认值为 4

    HTTP 方法和网址:

    POST https://REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/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",
              "referenceImage": {
                "bytesBase64Encoded": "B64_MASK_IMAGE"
              },
              "maskImageConfig": {
                "maskMode": "MASK_MODE_USER_PROVIDED",
                "dilation": MASK_DILATION
              }
            }
          ]
        }
      ],
      "parameters": {
        "editConfig": {
          "baseSteps": EDIT_STEPS
        },
        "editMode": "EDIT_MODE_INPAINT_INSERTION",
        "sampleCount": SAMPLE_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://REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/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://REGION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/REGION/publishers/google/models/imagen-3.0-capability-001:predict" | Select-Object -Expand Content
    以下示例响应适用于包含 "sampleCount": 2 的请求。响应返回两个预测对象,其中生成的图片字节采用 base64 编码。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    通过自动检测蒙版来插入内容

    使用以下示例指定通过修复插入内容。在这些示例中,您需要指定基础图片和文本提示。Imagen 会自动检测并创建蒙版区域来修改基础图片。

    控制台

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

    <a href="https://console.cloud.google.com/vertex-ai/studio/media/generate;tab=image" class="button button-primary"
    target="console" track-name="consoleLink" track-type="task">Go to Media
    Studio</a>
    
    1. 点击上传,然后选择要上传的文件。

    2. 点击修复

    3. 在修改工具栏中,点击 background_replace 提取蒙版

    4. 选择其中一个蒙版提取选项:

      • 背景元素:检测背景元素并创建一个围绕它们的蒙版。

      • 前景元素:检测前景对象并创建一个围绕它们的蒙版。

      • background_replace 人物:检测人物并创建一个围绕他们的蒙版。

    5. 可选:在参数面板中,调整以下选项:

      • 模型:要使用的 Imagen 模型。

      • 结果数量:要生成的结果数量。

      • 排除提示:描述您要从生成的图片中排除的内容。

    6. 在提示字段中,输入提示以修改图片。

    7. 点击发送生成

    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/fruit.png"),
        reference_id=0,
    )
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=None,
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_FOREGROUND",
            mask_dilation=0.1,
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A small white ceramic bowl with lemons and limes",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_INPAINT_INSERTION",
        ),
    )
    
    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

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

    • PROJECT_ID:您的 Google Cloud 项目 ID
    • LOCATION:您的项目的区域。 例如 us-central1europe-west2asia-northeast3。如需查看可用区域的列表,请参阅 Vertex AI 上的生成式 AI 位置
    • TEXT_PROMPT:文本提示可用于指导模型生成的图片。在使用插入修复的提示时,请使用被蒙版区域的说明,以获得最佳结果。避免使用单字词提示。例如,请使用“a cute corgi”而不是“corgi”。
    • B64_BASE_IMAGE:要修改或放大的基础图片。图片必须指定为 base64 编码的字节字符串。大小上限:10 MB。
    • MASK_MODE - 用于设置模型使用的自动蒙版创建类型的字符串。可用的值:
      • MASK_MODE_BACKGROUND:使用背景分割自动生成蒙版。
      • MASK_MODE_FOREGROUND:使用前景分割自动生成蒙版。
      • MASK_MODE_SEMANTIC:根据您在 maskImageConfig.maskClasses 数组中指定的分割类,使用语义分割自动生成蒙版。例如:
                  "maskImageConfig": {
                    "maskMode": "MASK_MODE_SEMANTIC",
                    "maskClasses": [175, 176], // bicycle, car
                    "dilation": 0.01
                  }
                
    • MASK_DILATION - 浮点数。将此蒙版扩大的图像宽度的百分比。建议使用值 0.01 来弥补不完美的输入蒙版。
    • EDIT_STEPS - 整数。基本模型的采样步数。对于修复插入,请从 35 步数开始。如果质量不符合您的要求,请将步数增加到 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",
                "dilation": MASK_DILATION
              }
            }
          ]
        }
      ],
      "parameters": {
        "editConfig": {
          "baseSteps": EDIT_STEPS
        },
        "editMode": "EDIT_MODE_INPAINT_INSERTION",
        "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
    以下示例响应适用于包含 "sampleCount": 2 的请求。响应返回两个预测对象,其中生成的图片字节采用 base64 编码。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    限制

    以下部分将介绍 Imagen 的对象移除功能的一些局限性。

    修改后的像素

    模型会以自己的分辨率(例如 1024x1024)生成像素,这可能与输入图片的分辨率不同。这意味着生成的图片可能与原始图片略有不同。

    为了完美保留图片,建议您使用蒙版将生成的图片与输入图片相融合。通常,如果输入图片的分辨率为 2K 或更高,则需要将生成的图片与输入图片相融合。

    内容插入方面的局限性

    虽然插入的对象通常会与基础图片的风格保持一致,但有些关键字可能会生成卡通风格的结果,而不是写实风格的输出。

    例如,如果提示是“黄色长颈鹿”,则可能会生成卡通风格的图片,因为长颈鹿的自然颜色是褐色和棕色。生成具有不自然色彩的写实风格图片可能很困难。

    后续步骤

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