使用「擴大」功能擴展圖片內容

本頁面說明外繪功能。外擴功能可讓您使用 Imagen 將圖片內容擴展至較大的區域,或擴展至不同尺寸的區域。

外繪範例

外繪是以遮罩為基礎的編輯方法,可擴展基礎圖片的內容,以符合較大或不同尺寸的遮罩畫布。

範例基礎映像檔
原始圖片,並加上圖片邊框間距,以符合遮罩圖片 (目標) 大小。
圖片來源:Kari Shea 發表於 Unsplash
遮罩圖片範例
遮罩圖片的尺寸與目標輸出內容相同,並標示原始圖片的像素尺寸和位置。
輸出圖片範例
外繪輸出圖片 (沒有提示)。

查看「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. 在「外擴」選單中,選取最終圖片的預先定義顯示比例,或按一下「自訂」,為最終圖片定義自訂尺寸。
    5. 在編輯工具列中,選取圖片的放置位置:
      • 靠左對齊
      • 水平置中對齊
      • 靠右對齊
      • 頂端對齊
      • 垂直置中對齊
      • 底部對齊
    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/living_room.png'), reference_id=0)
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=Image.from_file(location='test_resources/living_room_mask.png'),
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_USER_PROVIDED",
            mask_dilation=0.03,
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A chandelier hanging from the ceiling",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_OUTPAINT",
        ),
    )
    
    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 服務地區」。
    • prompt:如要使用圖像外繪功能,可以提供空字串來建立編輯後的圖像。如果選擇提供提示,請使用遮蓋區域的說明,以獲得最佳結果。例如「a blue sky」,而非「insert a blue sky」。
    • referenceTypeReferenceImage 是提供圖片編輯額外背景資訊的圖片。編輯用途需要正常的 RGB 原始參考圖像 (REFERENCE_TYPE_RAW)。一個要求最多只能有一個原始參照圖片。 輸出圖片的高度和寬度與原始參考圖片相同。如要使用遮罩編輯功能,必須提供遮罩參考圖片 (REFERENCE_TYPE_MASK)。如有原始參照圖片,遮罩圖片的高度和寬度必須與原始參照圖片相同。如果遮罩參照圖片為空白,且 maskMode 未設為 MASK_MODE_USER_PROVIDED,系統會根據原始參照圖片計算遮罩。
    • B64_BASE_IMAGE:要編輯或放大畫質的基礎圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • B64_OUTPAINTING_MASK:您要用來做為遮罩圖層的黑白圖片,可編輯原始圖片。遮罩的解析度應與輸入圖片相同。輸出圖片的解析度與輸入圖片相同。 這個遮罩圖片必須指定為 Base64 編碼的位元組字串。大小限制:10 MB。
    • MASK_DILATION - float。遮罩擴張的圖片寬度百分比。建議將外繪值設為 0.03。設定 "dilation": 0.0 可能會在擴充點產生明顯的邊框,或造成白色邊框效果。
    • EDIT_STEPS - 整數。基礎模型的取樣步驟數。如要使用外繪功能,請從步驟 35 開始。如果品質不符合規定,請增加步驟。
    • 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": "",
          "referenceImages": [
            {
              "referenceType": "REFERENCE_TYPE_RAW",
              "referenceId": 1,
              "referenceImage": {
                "bytesBase64Encoded": "B64_BASE_IMAGE"
              }
            },
            {
              "referenceType": "REFERENCE_TYPE_MASK",
              "referenceId": 2,
              "referenceImage": {
                "bytesBase64Encoded": "B64_OUTPAINTING_MASK"
              },
              "maskImageConfig": {
                "maskMode": "MASK_MODE_USER_PROVIDED",
                "dilation": MASK_DILATION
              }
            }
          ]
        }
      ],
      "parameters": {
        "editConfig": {
          "baseSteps": EDIT_STEPS
        },
        "editMode": "EDIT_MODE_OUTPAINT",
        "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. 在編輯工具列中,按一下「外繪」圖示

    5. 選取最終圖片的預先定義顯示比例,或按一下「自訂」,為最終圖片定義自訂尺寸。

    6. (選用步驟) 在編輯工具列中,選取要生成圖片的畫布中,原始圖片的水平位置 (左側、水平置中或右側對齊) 和垂直位置 (頂端、垂直置中或底部對齊)。

    7. (選用步驟) 在「Parameters」(參數) 面板中,調整「Number of results」(結果數量) 或其他參數。

    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_file = "mask-image.png"
    # output_file = "output-image.png"
    # prompt = "" # The optional 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="outpainting",
    )
    
    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

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

    • PROJECT_ID:您的 Google Cloud 專案 ID
    • LOCATION:專案的區域。例如 us-central1europe-west2asia-northeast3。如需可用區域的清單,請參閱「Vertex AI 的生成式 AI 服務地區」。
    • prompt:如要使用圖像外繪功能,可以提供空字串來建立編輯後的圖像。
    • B64_BASE_IMAGE:要編輯或放大畫質的基礎圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • B64_OUTPAINTING_MASK:您要用來做為遮罩圖層的黑白圖片,可編輯原始圖片。遮罩的解析度應與輸入圖片相同。輸出圖片的解析度與輸入圖片相同。 這個遮罩圖片必須指定為 Base64 編碼的位元組字串。大小限制:10 MB。
    • EDIT_IMAGE_COUNT:編輯過的圖片數量。預設值: 4。

    HTTP 方法和網址:

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

    JSON 要求主體:

    {
      "instances": [
        {
          "prompt": "",
          "image": {
              "bytesBase64Encoded": "B64_BASE_IMAGE"
          },
          "mask": {
            "image": {
              "bytesBase64Encoded": "B64_OUTPAINTING_MASK"
            }
          }
        }
      ],
      "parameters": {
        "sampleCount": EDIT_IMAGE_COUNT,
        "editConfig": {
          "editMode": "outpainting"
        }
      }
    }
    

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

    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 上呼叫。服務會傳回編輯後的圖片版本,然後儲存在本機。

    
    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 EditImageOutpaintingMaskSample {
    
      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 optional text prompt describing what you want to see inserted.
    
        editImageOutpaintingMask(projectId, location, inputPath, maskPath, prompt);
      }
    
      // Edit an image using a mask file. Outpainting lets you expand the content of a base image to fit
      // a larger or differently sized mask canvas.
      public static PredictResponse editImageOutpaintingMask(
          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", "outpainting"); // [ "editMode", "outpainting" ]
          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 方法。 這項服務會生成圖片,然後儲存在本機。

    /**
     * TODO(developer): Update these variables before running the sample.
     */
    const projectId = process.env.CAIP_PROJECT_ID;
    const location = 'us-central1';
    const inputFile = 'resources/roller_skaters.png';
    const maskFile = 'resources/roller_skaters_mask.png';
    const prompt = 'city with skyscrapers';
    
    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 editImageOutpaintingMask() {
      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 optional text prompt describing what you want to see inserted
        editMode: 'outpainting',
        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 editImageOutpaintingMask();

    限制

    如果擴展後的圖片比原始圖片大 200% 以上,模型可能會產生扭曲的細節。建議的最佳做法是新增後續處理步驟,對外繪圖片執行 Alpha 混合。

    以下是後續處理的範例程式碼:

    parameters = {
       "editConfig": {
           "outpaintingConfig": {
             "blendingMode": "alpha-blending",
             "blendingFactor": 0.01,
           },
       },
    }
    
    

    後續步驟

    閱讀有關 Imagen 和其他 Vertex AI 生成式 AI 產品的文章: