受控自定义

借助受控自定义,您可以根据源图片或源图片信号(Canny 边缘或涂鸦)创建新图片。本页面介绍了如何发送两种类型的受控自定义请求:

  1. Imagen 3 受控自定义(正式版功能)

    查看 Imagen for Editing and Customization 模型卡片

  2. Imagen 2 受控自定义 - Canny 边缘或涂鸦源图片信号(预览版功能)

使用场景

Imagen 3 受控自定义功能可提供自由式提示,这可能会让您觉得该模型能完成的任务比训练时学到的更多。以下部分介绍了 Imagen 3 受控自定义功能的应用场景和示例。

该模型已针对我们提供的应用场景进行训练,因此我们预计您在使用 Imagen 3 受控自定义功能时会获得良好的结果。如果您让模型以意想不到的方式回答问题,我们不保证能获得理想的结果。

预期应用场景示例

以下是 Imagen 3 受控自定义功能经过训练,可生成理想结果的应用场景:

  • 生成符合提示和 Canny 边缘控制图片的图片。

  • 生成符合提示和涂鸦图片的图片。

  • 对人像照片进行风格化处理,同时保留面部表情。

非预期应用场景示例

以下应用场景是 Imagen 3 受控自定义功能未进行针对性训练,可能无法生成理想结果的应用场景:

  • 使用提示中指定的风格生成图片。

  • 根据文本生成图片,且该图片采用通过参考图片提供的特定风格,同时使用控制图片对图片构图进行一定程度的控制。

  • 根据文本生成图片,且该图片采用通过参考图片提供的特定风格,同时使用控制涂鸦对图片构图进行一定程度的控制。

  • 根据文本生成图片,且该图片采用参考图片提供的特定风格,同时使用控制图片对图片构图进行一定程度的控制。图片中的人物具有特定的面部表情。

  • 对包含两个或更多人物的照片进行风格化处理,并保留其面部表情。

  • 对宠物照片进行风格化处理并将其转换为绘画。保留或指定图片的构图(例如水彩)。

准备工作

  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 (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 (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.

    REST

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

      安装 Google Cloud CLI。 安装完成后,运行以下命令来初始化 Google Cloud CLI:

      gcloud init

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

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

    自定义提示撰写

    与 Imagen 3 自定义结合使用的提示可能会影响生成的图片的质量。您可以从以下提示模板入手,撰写自定义提示。您可能需要发送多个请求才能获得所需的输出。

    使用场景 参考图片 提示模板 示例
    受控自定义 涂鸦地图 (1) Generate an image that aligns with the scribble map [1] to match the description: ${STYLE_PROMPT} ${PROMPT}. Generate an image that aligns with the scribble map [1] to match the description: The image should be in the style of an impressionistic oil painting with relaxed brushstrokes. It possesses a naturally-lit ambience and noticeable brushstrokes. A side-view of a car. The car is parked on a wet, reflective road surface, with city lights reflecting in the puddles.
    受控自定义 Canny 控制图片 (1) Generate an image aligning with the edge map [1] to match the description: ${STYLE_PROMPT} ${PROMPT} Generate an image aligning with the edge map [1] to match the description: The image should be in the style of an impressionistic oil painting, with relaxed brushstrokes. It posses a naturally-lit ambience and noticeable brushstrokes. A side-view of a car. The car is parked on a wet, reflective road surface, with city lights reflecting in the puddles.
    使用FaceMesh输入的人物图片风格化处理 主题图片 (1-3)

    FaceMesh 控制图片 (1)
    Create an image about SUBJECT_DESCRIPTION [1] in the pose of the CONTROL_IMAGE [2] to match the description: a portrait of SUBJECT_DESCRIPTION [1] ${PROMPT} Create an image about a woman with short hair [1] in the pose of the control image [2] to match the description: a portrait of a woman with short hair [1] in 3D-cartoon style with a blurred background. A cute and lovely character, with a smiling face, facing the camera, pastel color tone, high quality, 4k, masterpiece, super details, skin texture, texture mapping, soft shadows, soft realistic lighting, vibrant colors
    使用FaceMesh输入的人物图片风格化处理 主题图片 (1-3)

    FaceMesh 控制图片 (1)
    Create a ${STYLE_PROMPT} image about SUBJECT_DESCRIPTION [1] in the pose of the CONTROL_IMAGE [2] to match the description: a portrait of SUBJECT_DESCRIPTION [1] ${PROMPT} Create a 3D-cartoon style image about a woman with short hair [1] in the pose of the control image [2] to match the description: a portrait of a woman with short hair [1] in 3D-cartoon style with a blurred background. A cute and lovely character with a smiling face, facing the camera, pastel color tone, high quality, 4k, masterpiece, super details, skin texture, texture mapping, soft shadows, soft realistic lighting, vibrant colors

    发送 Imagen 3 受控自定义请求

    使用以下示例发送 Imagen 3 受控自定义请求:

    REST

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

    • PROJECT_ID:您的 Google Cloud 项目 ID
    • LOCATION:您的项目的区域。 例如 us-central1europe-west2asia-northeast3。如需查看可用区域的列表,请参阅 Vertex AI 上的生成式 AI 位置
    • TEXT_PROMPT:文本提示可用于指导模型生成的图片。如需使用 Imagen 3 受控自定义,请以 [$referenceId] 格式添加您提供的控制参考图片的 referenceId。例如:
      • Generate an image aligning with the scribble map [1] to match the description: [image description].
    • BASE64_CONTROL_IMAGE:基础控制图片(草图)。图片必须指定为 base64 编码的字节字符串。
      对于 CONTROL_TYPE_SCRIBBLE:预期的涂鸦控制图片具有黑色背景和白色涂鸦线。 涂鸦控制图片示例
      对于 CONTROL_TYPE_CANNY:预期的 Canny 边缘控制图片具有黑色背景和白色 Canny 边缘。 Canny 边缘控制图片示例
    • CONTROL_TYPE:控制信号的类型。将 CONTROL_TYPE_CANNY 用于 Canny 边缘。将 CONTROL_TYPE_SCRIBBLE 用于涂鸦。
    • enableControlImageComputation:如果您提供自己的控制图片,请将其设置为 false。在这种情况下,B64_BASE_IMAGE 应为控制信号图片。如果希望 Imagen 从参考图片计算控制图片,请设置为 true。在这种情况下,B64_BASE_IMAGE 应为原始 RGB 图片。
    • 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_CONTROL",
              "referenceId": 1,
              "referenceImage": {
                "bytesBase64Encoded": "BASE64_CONTROL_IMAGE"
              },
              "controlImageConfig": {
                "controlType": "CONTROL_TYPE",
                "enableControlImageComputation": false
              }
            }
          ]
        }
      ],
      "parameters": {
        "sampleCount": 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"
        }
      ]
    }
    

    Python

    乱涂乱画

    from google import genai
    from google.genai.types import (
        ControlReferenceConfig,
        ControlReferenceImage,
        EditImageConfig,
        Image,
    )
    
    client = genai.Client()
    
    # TODO(developer): Update and un-comment below line
    # output_gcs_uri = "gs://your-bucket/your-prefix"
    
    # Create a reference image out of an existing scribble image signal
    # using https://storage.googleapis.com/cloud-samples-data/generative-ai/image/car_scribble.png
    control_reference_image = ControlReferenceImage(
        reference_id=1,
        reference_image=Image(gcs_uri="gs://cloud-samples-data/generative-ai/image/car_scribble.png"),
        config=ControlReferenceConfig(control_type="CONTROL_TYPE_SCRIBBLE"),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="an oil painting showing the side of a red car[1]",
        reference_images=[control_reference_image],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_CONTROLLED_EDITING",
            number_of_images=1,
            safety_filter_level="BLOCK_MEDIUM_AND_ABOVE",
            person_generation="ALLOW_ADULT",
            output_gcs_uri=output_gcs_uri,
        ),
    )
    
    # Example response:
    # gs://your-bucket/your-prefix
    print(image.generated_images[0].image.gcs_uri)

    Canny 边缘

    from google import genai
    from google.genai.types import (
        ControlReferenceConfig,
        ControlReferenceImage,
        EditImageConfig,
        Image,
    )
    
    client = genai.Client()
    
    # TODO(developer): Update and un-comment below line
    # output_gcs_uri = "gs://your-bucket/your-prefix"
    
    # Create a reference image out of an existing canny edge image signal
    # using https://storage.googleapis.com/cloud-samples-data/generative-ai/image/car_canny.png
    control_reference_image = ControlReferenceImage(
        reference_id=1,
        reference_image=Image(gcs_uri="gs://cloud-samples-data/generative-ai/image/car_canny.png"),
        config=ControlReferenceConfig(control_type="CONTROL_TYPE_CANNY"),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="a watercolor painting of a red car[1] driving on a road",
        reference_images=[control_reference_image],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_CONTROLLED_EDITING",
            number_of_images=1,
            safety_filter_level="BLOCK_MEDIUM_AND_ABOVE",
            person_generation="ALLOW_ADULT",
            output_gcs_uri=output_gcs_uri,
        ),
    )
    
    # Example response:
    # gs://your-bucket/your-prefix
    print(image.generated_images[0].image.gcs_uri)

    发送 Imagen 2 受控自定义请求

    输入图片 其他参数 输出图片
    棋步输入
    输入图片。图片来源:Alec Cutter on Unsplash

    提示:“数字艺术版”

    否定提示:“黑白”

    指南图片类型:标准 RGB

    控制条件:Canny 边缘

    Imagen 控制比例:0.95

    样式化输出
    棋步输入
    输入图片。图片来源:Alec Cutter on Unsplash
    (已应用 Canny 边缘检测)。

    提示:“数字艺术版”

    否定提示:“黑白”

    指南图片类型:Canny 边缘

    Imagen 控制比例:0.95

    样式化输出

    使用以下示例发送 Imagen 2 受控自定义请求:

    控制台

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

      前往 Media Studio

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

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

    4. 参数面板的模式部分中,点击控制

    5. 可选。修改结果数量、提供否定提示或修改高级选项 > 区域

    6. 高级选项部分中,选择指南图片类型标准 RGBCanny 边缘涂鸦

    7. 高级选项部分中,选择控制条件Canny 边缘涂鸦

    8. 在提示字段(写入提示...)中,提供文本提示。

    9. 点击 生成

    REST

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

    • PROJECT_ID:您的 Google Cloud 项目 ID
    • TEXT_PROMPT:用于指导模型生成什么图片的文本提示。生成和修改都需要此字段。
    • B64_BASE_IMAGE:要修改或放大的基础图片。图片必须指定为 base64 编码的字节字符串。大小上限:10 MB。
    • EDIT_IMAGE_COUNT:已修改图片的数量。 默认值:4。
    • NEGATIVE_PROMPT:有助于生成图片的否定提示。例如:“animals”(移除动物)、“blurry”(可使图片更清晰)、“text”(移除文本)或“cropped”(移除剪裁后的图片)。
    • CONDITIONstring。所提供的控制图片信号的类型。值:cannyEdgesscribble
    • CONTROL_SCALEfloat。控制图片信号的强度。值:0.0 - 1.0。默认值:0.95。建议范围:0.9 - 1.0
    • SAMPLING_STEPSinteger。采样步骤数。值:1 - 30。默认值:16
    • COMPUTE_CONDITION_MAPboolean。是否要根据基本输入图片计算条件映射。设置为 false 时,该服务会将输入图片视为涂鸦或 Canny 边缘,并将该图片直接提供给模型。设置为 true 时,该服务会将输入图片视为 RGB 图片,并根据 conditionName 计算输入图片的 Canny 边缘或涂鸦信息。然后,该服务会将处理过的条件映射提供给模型进行图片编辑。提供涂鸦图片时,应使用黑色背景,并用白线描绘要生成的对象。默认值:false

    HTTP 方法和网址:

    POST https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/imagen-2.0-edit-preview-0627:predict

    请求 JSON 正文:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT",
          "image": {
            "bytesBase64Encoded": "B64_BASE_IMAGE"
          }
        }
      ],
      "parameters": {
        "sampleCount": EDIT_IMAGE_COUNT,
        "negativePrompt": "NEGATIVE_PROMPT",
        "controlPluginConfig":  {
          "conditions": [
            {
              "conditionName": "CONDITION",
              "controlScale": CONTROL_SCALE,
              "samplingSteps": SAMPLING_STEPS,
              "computeConditionMap": COMPUTE_CONDITION_MAP
            }
          ]
        }
      }
    }
    

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

    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://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/imagen-2.0-edit-preview-0627: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://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/publishers/google/models/imagen-2.0-edit-preview-0627:predict" | Select-Object -Expand Content
    以下示例响应适用于包含 "sampleCount": 2 的请求。响应返回两个预测对象,其中生成的图片字节采用 base64 编码。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    产品使用

    如需查看与 Imagen on Vertex AI 关联的使用标准和内容限制,请参阅使用指南

    模型版本

    您可以使用多种图片生成模型。如需了解详情,请参阅 Imagen 模型

    后续步骤

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