アウトペイントを使用して画像のコンテンツを拡大する

このページでは、アウトペインティングについて説明します。アウトペインティングでは、Imagen を使用して、より大きな領域または異なる寸法の領域に画像コンテンツを拡大できます。

アウトペインティングの例

アウトペインティングはマスクベースの編集方法で、サイズの大きいマスク キャンバスやサイズの異なるマスク キャンバスに合わせてベース画像のコンテンツを拡大できます。

サンプルのベース画像
マスク画像(ターゲット)のサイズに合わせてパディングが設定された元の画像。
画像の出典: Kari SheaUnsplash より
サンプルのマスク画像
元の画像サイズ(ピクセル)と位置をマークして、ターゲット出力のサイズで画像をマスク。
サンプルの出力画像
アウトペインティングの出力画像(プロンプトなし)。

編集とカスタマイズ用 Imagen のモデルカードを表示する

始める前に

  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. Verify 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. Verify 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 をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

      Google Cloud CLI をインストールします。

      外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して 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 認証ドキュメントのローカル開発環境の ADC の設定をご覧ください。

    Node.js

    ローカル開発環境でこのページの Node.js サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

      Google Cloud CLI をインストールします。

      外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して 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 認証ドキュメントのローカル開発環境の ADC の設定をご覧ください。

    Python

    ローカル開発環境でこのページの Python サンプルを使用するには、gcloud CLI をインストールして初期化し、ユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定します。

      Google Cloud CLI をインストールします。

      外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して 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 認証ドキュメントのローカル開発環境の ADC の設定をご覧ください。

    REST

    このページの REST API サンプルをローカル開発環境で使用するには、gcloud CLI に指定した認証情報を使用します。

      Google Cloud CLI をインストールします。

      外部 ID プロバイダ(IdP)を使用している場合は、まず連携 ID を使用して gcloud CLI にログインする必要があります。

    詳細については、 Google Cloud 認証ドキュメントの REST を使用して認証するをご覧ください。

    画像のコンテンツを拡大する

    次のコードサンプルを使用して、既存の画像のコンテンツを拡大します。

    Imagen 3

    次のサンプルを使用して、Imagen 3 モデルを使用してアウトペインティング リクエストを送信します。

    コンソール

    1. Google Cloud コンソールで、[Vertex AI] > [Media Studio] ページに移動します。

      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: 画像のアウトペインティングの場合は、空の文字列を指定して、編集した画像を作成できます。プロンプトを指定する場合は、最適な結果を得られるようにするために、マスクされた領域の説明を使用してください。たとえば、「青い空」ではなく「青い空を挿入」とします。
    • referenceType: ReferenceImage は、画像編集に追加のコンテキストを提供する画像です。編集のユースケースでは、通常の RGB の元の参照画像(REFERENCE_TYPE_RAW)が必要です。1 つのリクエストに存在できる元の参照画像は 1 つまでです。出力画像の高さと幅は、元の参照画像と同じです。マスク編集のユースケースでは、マスク参照画像(REFERENCE_TYPE_MASK)が必要です。元の参照画像が存在する場合、マスク画像の幅と高さは元の参照画像と同じにする必要があります。マスク参照画像が空で、maskModeMASK_MODE_USER_PROVIDED に設定されていない場合、マスクは元の参照画像に基づいて計算されます。
    • B64_BASE_IMAGE: 編集またはアップスケールするベース画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • B64_OUTPAINTING_MASK: 元の画像の編集でマスクレイヤとして使用する白黒画像。マスクは入力画像と同じ解像度にする必要があります。出力画像の解像度は入力画像と同じになります。このマスク画像は、base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • MASK_DILATION - フロート。このマスクを拡大する画像幅の割合。アウトペインティングの場合は、0.03 の値をおすすめします。"dilation": 0.0 を設定すると、拡張ポイントに目立つ枠線が表示される場合や、白い枠線効果が発生する場合があります。
    • EDIT_STEPS - 整数。ベースモデルのサンプリング ステップ数。アウトペインティングの場合は、35 の手順から始めます。品質が要件を満たしていない場合は、ステップを増やします。
    • EDIT_IMAGE_COUNT - 編集された画像の数。指定できるのは整数値(1~4)です。デフォルト値: 4。

    HTTP メソッドと URL:

    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 でエンコードした 2 つの予測オブジェクトを返します。
    {
      "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] ページに移動します。

      Media Studio に移動

    2. 下部のタスクパネルで [画像を編集] をクリックします。

    3. [アップロード] をクリックして、編集する商品画像をローカルに保存されている画像から選択します。

    4. 編集ツールバーで [アウトペイント] をクリックします。

    5. 最終画像に既定のアスペクト比のいずれかを選択します。または、[カスタム] をクリックして、最終画像にカスタム ディメンションを定義します。

    6. 省略可。編集ツールバーで、生成される画像のキャンパス内での元画像の横位置(左詰め、中央揃え、右詰め)と縦位置(上詰め、中央揃え、下詰め)を選択します。

    7. 省略可。[パラメータ] パネルで、[検索結果の表示件数] などのパラメータを調整します。

    8. [生成] をクリックします。

    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"
    # 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 メソッドと URL:

    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 でエンコードした 2 つの予測オブジェクトを返します。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }
    

    Java

    このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。詳細については、Vertex AI Java API のリファレンス ドキュメントをご覧ください。

    Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

    このサンプルでは、モデルを EndpointName の一部として指定します。EndpointName は、PredictionServiceClient で呼び出される predict メソッドに渡されます。このサービスは、編集されたバージョンの画像を返します。この画像はローカルに保存されます。

    
    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

    このサンプルを試す前に、Vertex AI クイックスタート: クライアント ライブラリの使用にある Node.js の設定手順を完了してください。詳細については、Vertex AI Node.js API のリファレンス ドキュメントをご覧ください。

    Vertex AI に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

    このサンプルでは、PredictionServiceClientpredict メソッドを呼び出します。このサービスは画像を生成し、ローカルに保存します。

    /**
     * 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% 以上拡大されると、モデルによっては詳細が歪んで生成されることがあります。ベスト プラクティスとして、アウトペイントされた画像でアルファ ブレンディングを実行する後処理ステップを追加することをおすすめします。

    次のコードは後処理の例です。

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

    次のステップ

    Imagen や Vertex AI のその他の生成 AI プロダクトに関する次の記事を読む。