使用修復功能在圖片中插入物件

本頁說明如何將物件插入圖片,這也稱為修復。透過 Vertex AI 中的 Imagen,您可以指定遮罩區域,將物件插入圖片。您可以自行提供遮罩,也可以讓 Vertex AI 的 Imagen 為您生成遮罩。

內容插入範例

使用「局部修復」插入內容時,你可以使用基本圖片、圖片遮罩和文字提示,在現有圖片中新增內容。

輸入

要編輯的基礎圖片* 使用 Google Cloud 控制台中的工具指定遮罩區域 文字提示
基本映像檔範例。玻璃罐裝著紅色液體,側邊有檸檬片,還插著吸管。左前景可見檸檬切片 玻璃罐的基礎圖片,現在已在 Cloud 控制台中指定遮罩區域 草莓

* 圖片來源:Alex LvrsUnsplash 上發布。

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

    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.

    Java

    如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 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 驗證說明文件中的「 為本機開發環境設定 ADC」。

    Node.js

    如要在本機開發環境中使用本頁的 Node.js 範例,請安裝並初始化 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 驗證說明文件中的「 為本機開發環境設定 ADC」。

    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 驗證說明文件中的「 為本機開發環境設定 ADC」。

    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 驗證說明文件中的「Authenticate for using REST」。

    插入時定義遮罩區域

    使用下列範例指定修復功能,插入內容。在這些範例中,您會指定基本圖片、文字提示和遮罩區域,藉此修改基本圖片。

    Imagen 3

    使用下列範例,透過 Imagen 3 模型傳送修復要求。

    控制台

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

      前往媒體工作室

    2. 按一下 [上傳]。在顯示的檔案對話方塊中,選取要上傳的檔案。
    3. 按一下「修復」
    4. 執行下列其中一個步驟:

      • 上傳自己的遮罩:
        1. 在電腦上建立遮罩。
        2. 按一下「上傳遮罩」。在顯示的對話方塊中,選取要上傳的遮罩。
      • 定義遮罩: 在編輯工具列中,使用遮罩工具 (方塊、筆刷或masked_transitions反轉工具) 指定要新增內容的區域。
    5. 選用:在「參數」面板中,調整下列選項:
      • 模型:要使用的 Imagen 模型
      • 結果數量:要生成的結果數量
      • 負面提示:避免生成的項目
    6. 在提示欄位中輸入提示,修改圖像。
    7. 按一下「生成」

    Python

    安裝

    pip install --upgrade google-genai

    詳情請參閱 SDK 參考說明文件

    設定環境變數,透過 Vertex AI 使用 Gen AI SDK:

    # 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

    詳情請參閱 Edit images API 參考資料。

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID:您的 Google Cloud 專案 ID
    • LOCATION:專案的區域。例如 us-central1europe-west2asia-northeast3。如需可用區域的清單,請參閱「Vertex AI 的生成式 AI 服務地區」。
    • TEXT_PROMPT:文字提示會引導模型生成圖片。使用提示進行局部修復插入時,請提供遮罩區域的說明,以獲得最佳效果。請避免使用單字提示。舉例來說,請使用「一隻可愛的柯基犬」,而不是「柯基犬」。
    • B64_BASE_IMAGE:要編輯或放大畫質的基礎圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • B64_MASK_IMAGE:要用來做為遮罩圖層的黑白圖片,可編輯原始圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • MASK_DILATION - float。遮罩擴張的圖片寬度百分比。建議使用 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,
              "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": 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 2

    使用下列範例,透過 Imagen 2 模型傳送修復要求。

    控制台

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

      前往媒體工作室

    2. 按一下 [上傳]。在顯示的檔案對話方塊中,選取要上傳的檔案。
    3. 按一下「修復」
    4. 執行下列其中一個步驟:

      • 上傳自己的遮罩:
        1. 在電腦上建立遮罩。
        2. 按一下「上傳遮罩」。在顯示的對話方塊中,選取要上傳的遮罩。
      • 定義遮罩:在編輯工具列中,使用遮罩工具 (方塊、筆刷或 masked_transitions 反轉工具) 指定要新增內容的區域。
    5. (選用步驟) 在「Parameters」面板中,調整下列選項:
      • 模型:要使用的 Imagen 模型
      • 結果數量:要生成的結果數量
      • 負面提示:避免生成的項目
    6. 在提示欄位中輸入新提示,修改圖片。
    7. 按一下「生成」

    Python

    如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 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"
    # mask_file = "mask-image.png"
    # output_file = "output-image.png"
    # prompt = "red hat" # The text prompt describing what you want to see inserted.
    
    vertexai.init(project=PROJECT_ID, location="us-central1")
    
    model = ImageGenerationModel.from_pretrained("imagegeneration@006")
    base_img = Image.load_from_file(location=input_file)
    mask_img = Image.load_from_file(location=mask_file)
    
    images = model.edit_image(
        base_image=base_img,
        mask=mask_img,
        prompt=prompt,
        edit_mode="inpainting-insert",
    )
    
    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 1400814 bytes
    

    REST

    如要進一步瞭解 imagegeneration 模型要求,請參閱 imagegeneration 模型 API 參考資料

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID:您的 Google Cloud 專案 ID
    • LOCATION:專案的區域。例如 us-central1europe-west2asia-northeast3。如需可用區域的清單,請參閱「Vertex AI 的生成式 AI 服務地區」。
    • TEXT_PROMPT:文字提示,引導模型生成圖片。生成和編輯時都必須填寫這個欄位。
    • B64_BASE_IMAGE:要編輯或放大畫質的基礎圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • B64_MASK_IMAGE:要用來做為遮罩圖層的黑白圖片,可編輯原始圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • EDIT_IMAGE_COUNT:編輯過的圖片數量。預設值: 4。
    • GUIDANCE_SCALE_VALUE:參數 (整數),可控制模型遵循文字提示的程度。值越大,文字提示與生成圖片的對齊程度就越高,但可能會影響圖片品質。值: 0 - 500。預設值:60

    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"
          },
          "mask": {
            "image": {
              "bytesBase64Encoded": "B64_MASK_IMAGE"
            }
          }
        }
      ],
      "parameters": {
        "sampleCount": EDIT_IMAGE_COUNT,
        "editConfig": {
          "editMode": "inpainting-insert",
          "guidanceScale": GUIDANCE_SCALE_VALUE
        }
      }
    }
    

    如要傳送要求,請選擇以下其中一個選項:

    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
    以下是要求 "sampleCount": 2 的範例回應。回應會傳回兩個預測物件,其中包含以 base64 編碼的生成圖片位元組。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    Java

    在試用這個範例之前,請先按照Java使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Java API 參考說明文件

    如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

    在本範例中,您會將模型指定為 EndpointName 的一部分。EndpointName 會傳遞至 predict 方法,該方法會在 PredictionServiceClient 上呼叫。服務會傳回編輯後的圖片版本,然後儲存在本機。

    如要進一步瞭解模型版本和功能,請參閱 Imagen 模型

    
    import com.google.api.gax.rpc.ApiException;
    import com.google.cloud.aiplatform.v1.EndpointName;
    import com.google.cloud.aiplatform.v1.PredictResponse;
    import com.google.cloud.aiplatform.v1.PredictionServiceClient;
    import com.google.cloud.aiplatform.v1.PredictionServiceSettings;
    import com.google.gson.Gson;
    import com.google.protobuf.InvalidProtocolBufferException;
    import com.google.protobuf.Value;
    import com.google.protobuf.util.JsonFormat;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.Base64;
    import java.util.Collections;
    import java.util.HashMap;
    import java.util.Map;
    
    public class EditImageInpaintingInsertMaskSample {
    
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "my-project-id";
        String location = "us-central1";
        String inputPath = "/path/to/my-input.png";
        String maskPath = "/path/to/my-mask.png";
        String prompt =
            ""; // The text prompt describing what you want to see inserted in the mask area.
    
        editImageInpaintingInsertMask(projectId, location, inputPath, maskPath, prompt);
      }
    
      // Edit an image using a mask file. Inpainting can insert the object designated by the prompt
      // into the masked area.
      public static PredictResponse editImageInpaintingInsertMask(
          String projectId, String location, String inputPath, String maskPath, String prompt)
          throws ApiException, IOException {
        final String endpoint = String.format("%s-aiplatform.googleapis.com:443", location);
        PredictionServiceSettings predictionServiceSettings =
            PredictionServiceSettings.newBuilder().setEndpoint(endpoint).build();
    
        // Initialize client that will be used to send requests. This client only needs to be created
        // once, and can be reused for multiple requests.
        try (PredictionServiceClient predictionServiceClient =
            PredictionServiceClient.create(predictionServiceSettings)) {
    
          final EndpointName endpointName =
              EndpointName.ofProjectLocationPublisherModelName(
                  projectId, location, "google", "imagegeneration@006");
    
          // Encode image and mask to Base64
          String imageBase64 =
              Base64.getEncoder().encodeToString(Files.readAllBytes(Paths.get(inputPath)));
          String maskBase64 =
              Base64.getEncoder().encodeToString(Files.readAllBytes(Paths.get(maskPath)));
    
          // Create the image and image mask maps
          Map<String, String> imageMap = new HashMap<>();
          imageMap.put("bytesBase64Encoded", imageBase64);
    
          Map<String, String> maskMap = new HashMap<>();
          maskMap.put("bytesBase64Encoded", maskBase64);
          Map<String, Map> imageMaskMap = new HashMap<>();
          imageMaskMap.put("image", maskMap);
    
          Map<String, Object> instancesMap = new HashMap<>();
          instancesMap.put("prompt", prompt); // [ "prompt", "<my-prompt>" ]
          instancesMap.put(
              "image", imageMap); // [ "image", [ "bytesBase64Encoded", "iVBORw0KGgo...==" ] ]
          instancesMap.put(
              "mask",
              imageMaskMap); // [ "mask", [ "image", [ "bytesBase64Encoded", "iJKDF0KGpl...==" ] ] ]
          instancesMap.put("editMode", "inpainting-insert"); // [ "editMode", "inpainting-insert" ]
          Value instances = mapToValue(instancesMap);
    
          // Optional parameters
          Map<String, Object> paramsMap = new HashMap<>();
          paramsMap.put("sampleCount", 1);
          Value parameters = mapToValue(paramsMap);
    
          PredictResponse predictResponse =
              predictionServiceClient.predict(
                  endpointName, Collections.singletonList(instances), parameters);
    
          for (Value prediction : predictResponse.getPredictionsList()) {
            Map<String, Value> fieldsMap = prediction.getStructValue().getFieldsMap();
            if (fieldsMap.containsKey("bytesBase64Encoded")) {
              String bytesBase64Encoded = fieldsMap.get("bytesBase64Encoded").getStringValue();
              Path tmpPath = Files.createTempFile("imagen-", ".png");
              Files.write(tmpPath, Base64.getDecoder().decode(bytesBase64Encoded));
              System.out.format("Image file written to: %s\n", tmpPath.toUri());
            }
          }
          return predictResponse;
        }
      }
    
      private static Value mapToValue(Map<String, Object> map) throws InvalidProtocolBufferException {
        Gson gson = new Gson();
        String json = gson.toJson(map);
        Value.Builder builder = Value.newBuilder();
        JsonFormat.parser().merge(json, builder);
        return builder.build();
      }
    }
    

    Node.js

    在試用這個範例之前,請先按照Node.js使用用戶端程式庫的 Vertex AI 快速入門中的操作說明進行設定。 詳情請參閱 Vertex AI Node.js API 參考說明文件

    如要向 Vertex AI 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

    在這個範例中,您會在 PredictionServiceClient 上呼叫 predict 方法。 這項服務會生成圖片,然後儲存在本機。如要進一步瞭解模型版本和功能,請參閱「Imagen 模型」。

    /**
     * TODO(developer): Update these variables before running the sample.
     */
    const projectId = process.env.CAIP_PROJECT_ID;
    const location = 'us-central1';
    const inputFile = 'resources/woman.png';
    const maskFile = 'resources/woman_inpainting_insert_mask.png';
    const prompt = 'hat';
    
    const aiplatform = require('@google-cloud/aiplatform');
    
    // Imports the Google Cloud Prediction Service Client library
    const {PredictionServiceClient} = aiplatform.v1;
    
    // Import the helper module for converting arbitrary protobuf.Value objects
    const {helpers} = aiplatform;
    
    // Specifies the location of the api endpoint
    const clientOptions = {
      apiEndpoint: `${location}-aiplatform.googleapis.com`,
    };
    
    // Instantiates a client
    const predictionServiceClient = new PredictionServiceClient(clientOptions);
    
    async function editImageInpaintingInsertMask() {
      const fs = require('fs');
      const util = require('util');
      // Configure the parent resource
      const endpoint = `projects/${projectId}/locations/${location}/publishers/google/models/imagegeneration@006`;
    
      const imageFile = fs.readFileSync(inputFile);
      // Convert the image data to a Buffer and base64 encode it.
      const encodedImage = Buffer.from(imageFile).toString('base64');
    
      const maskImageFile = fs.readFileSync(maskFile);
      // Convert the image mask data to a Buffer and base64 encode it.
      const encodedMask = Buffer.from(maskImageFile).toString('base64');
    
      const promptObj = {
        prompt: prompt, // The text prompt describing what you want to see inserted
        editMode: 'inpainting-insert',
        image: {
          bytesBase64Encoded: encodedImage,
        },
        mask: {
          image: {
            bytesBase64Encoded: encodedMask,
          },
        },
      };
      const instanceValue = helpers.toValue(promptObj);
      const instances = [instanceValue];
    
      const parameter = {
        // Optional parameters
        seed: 100,
        // Controls the strength of the prompt
        // 0-9 (low strength), 10-20 (medium strength), 21+ (high strength)
        guidanceScale: 21,
        sampleCount: 1,
      };
      const parameters = helpers.toValue(parameter);
    
      const request = {
        endpoint,
        instances,
        parameters,
      };
    
      // Predict request
      const [response] = await predictionServiceClient.predict(request);
      const predictions = response.predictions;
      if (predictions.length === 0) {
        console.log(
          'No image was generated. Check the request parameters and prompt.'
        );
      } else {
        let i = 1;
        for (const prediction of predictions) {
          const buff = Buffer.from(
            prediction.structValue.fields.bytesBase64Encoded.stringValue,
            'base64'
          );
          // Write image content to the output file
          const writeFile = util.promisify(fs.writeFile);
          const filename = `output${i}.png`;
          await writeFile(filename, buff);
          console.log(`Saved image ${filename}`);
          i++;
        }
      }
    }
    await editImageInpaintingInsertMask();

    插入時自動偵測遮罩

    使用下列範例指定修復功能,插入內容。在這些範例中,您會指定基礎圖片和文字提示。Imagen 會自動偵測並建立遮罩區域,以修改基本圖片。

    Imagen 3

    使用下列範例,透過 Imagen 3 模型傳送修復要求。

    控制台

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

      前往媒體工作室

    2. 按一下 [上傳]。在顯示的檔案對話方塊中,選取要上傳的檔案。
    3. 按一下「修復」
    4. 在編輯工具列中,按一下 background_replace擷取遮罩
    5. 選取其中一個遮罩擷取選項:

      • 背景元素:偵測背景元素,並在周圍建立遮罩。
      • 前景元素:偵測前景物件,並在周圍建立遮罩。
      • background_replacePeople: 偵測人物並建立遮罩。
    6. 選用:在「參數」面板中,調整下列選項:
      • 模型:要使用的 Imagen 模型
      • 結果數量:要生成的結果數量
      • 負面提示:避免生成的項目
    7. 在提示欄位中輸入新提示,修改圖片。
    8. 按一下「傳送」生成

    Python

    安裝

    pip install --upgrade google-genai

    詳情請參閱 SDK 參考說明文件

    設定環境變數,透過 Vertex AI 使用 Gen AI SDK:

    # 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

    詳情請參閱「編輯圖片」API 參考資料。

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID:您的 Google Cloud 專案 ID
    • LOCATION:專案的區域。例如 us-central1europe-west2asia-northeast3。如需可用區域的清單,請參閱「Vertex AI 的生成式 AI 服務地區」。
    • TEXT_PROMPT:文字提示會引導模型生成圖片。使用提示進行局部修復插入時,請提供遮罩區域的說明,以獲得最佳效果。請避免使用單字提示。舉例來說,請使用「一隻可愛的柯基犬」,而不是「柯基犬」。
    • 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 - float。遮罩擴張的圖片寬度百分比。建議使用 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 2

    使用下列範例,透過 Imagen 2 模型傳送修復要求。

    控制台

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

      前往媒體工作室

    2. 在下方工作面板中,按一下「編輯圖片」

    3. 按一下「上傳」,選取要編輯的本機圖片。

    4. 在編輯工具列中,依序點選「background_replace」background_replace「擷取」

    5. 選取其中一個遮罩擷取選項:

      • 背景元素:偵測背景元素,並在周圍建立遮罩。
      • 前景元素:偵測前景物件,並在周圍建立遮罩。
      • background_replacePeople - Detects people and creates a mask around them.
    6. 選用:在「參數」面板中,調整「結果數量」、「負面提示」、「文字提示指引」或其他參數。

    7. 在提示欄位中輸入提示,修改圖片。

    8. 按一下「生成」

    Python

    如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 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"
    # mask_mode = "background" # 'background', 'foreground', or 'semantic'
    # output_file = "output-image.png"
    # prompt = "beach" # The text prompt describing what you want to see inserted.
    
    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,
        mask_mode=mask_mode,
        prompt=prompt,
        edit_mode="inpainting-insert",
    )
    
    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 參考資料

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID:您的 Google Cloud 專案 ID
    • LOCATION:專案的區域。例如 us-central1europe-west2asia-northeast3。如需可用區域的清單,請參閱「Vertex AI 的生成式 AI 服務地區」。
    • TEXT_PROMPT:文字提示,引導模型生成圖片。生成和編輯時都必須填寫這個欄位。
    • B64_BASE_IMAGE:要編輯或放大畫質的基礎圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • EDIT_IMAGE_COUNT:編輯過的圖片數量。預設值: 4。
    • MASK_TYPE:提示模型生成遮罩,不必由您提供。因此,提供這個參數時,請省略 mask 物件。可用值:
      • background:自動為圖片中主要物件、人物或主體以外的所有區域生成遮罩。
      • foreground:自動為圖片中的主要物體、人物或主題生成遮罩。
      • semantic:使用自動區隔功能,為一或多個區隔類別建立遮罩區域。使用 classes 參數和對應的 class_id 值設定區隔類別。最多可指定 5 個類別。使用語意遮罩類型時,maskMode 物件應如下所示:
        "maskMode": {
          "maskType": "semantic",
          "classes": [class_id1, class_id2]
        }
    • GUIDANCE_SCALE_VALUE:參數 (整數),可控制模型遵循文字提示的程度。值越大,文字提示與生成圖片的對齊程度就越高,但可能會影響圖片品質。值: 0 - 500。預設值:60

    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": {
        "sampleCount": EDIT_IMAGE_COUNT,
        "editConfig": {
          "editMode": "inpainting-insert",
          "maskMode": {
            "maskType": "MASK_TYPE"
          },
          "guidanceScale": GUIDANCE_SCALE_VALUE
        }
      }
    }
    

    如要傳送要求,請選擇以下其中一個選項:

    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
    以下是要求 "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 產品的文章: