インペイントを使用して画像にオブジェクトを挿入する

このページでは、画像へのオブジェクトの挿入(インペインティングとも呼ばれます)について説明します。Vertex AI の Imagen では、マスク領域を指定して画像にオブジェクトを挿入できます。独自のマスクを使用することも、Vertex AI の Imagen でマスクを生成することもできます。

コンテンツ挿入の例

インペインティングでコンテンツを挿入する場合は、ベース画像、画像マスク、テキスト プロンプトを使用して、既存の画像にコンテンツを追加できます。

入力

編集対象のベース画像* Google Cloud コンソールのツールで指定したマスク領域 テキスト プロンプト
ベースイメージの例。ガラス瓶に赤い液体が入っており、横にレモンのスライスが添えられ、ストローが突き出ている。左側の手前にレモンのスライスが見える ガラス瓶のベース画像。Cloud コンソールでマスク領域が指定されている イチゴ

* 画像クレジット: Alex LvrsUnsplash より

Google Cloud コンソールでマスク領域を指定した後の出力

赤い液体が入ったガラス瓶の生成された編集のスクリーンショット。このスクリーンショットでは、画像のフォアグラウンドにあったレモンのスライスが、瓶のすぐ前にある 2 つのイチゴに置き換えられています。 赤い液体が入ったガラス瓶の生成された編集のスクリーンショット。このスクリーンショットでは、以前は画像の前景にあったレモンのスライスが、瓶のすぐ左にある 3 つのイチゴに置き換えられています。 赤い液体が入ったガラス瓶の生成された編集のスクリーンショット。このスクリーンショットでは、画像の前景にあったレモン スライスが、瓶の少し手前左にある 2 つのイチゴに置き換えられています。

編集とカスタマイズ用 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. 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 認証ドキュメントの REST を使用して認証するをご覧ください。

    定義されたマスク領域で挿入する

    次のサンプルを使用して、コンテンツを挿入するインペインティングを指定します。これらのサンプルでは、ベース画像、テキスト プロンプト、マスク領域を指定して、ベース画像を変更します。

    Imagen 3

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

    コンソール

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

      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

    詳細については、画像を編集する API リファレンスをご覧ください。

    リクエストのデータを使用する前に、次のように置き換えます。

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID
    • LOCATION: プロジェクトのリージョン。たとえば、us-central1europe-west2asia-northeast3 です。使用可能なリージョンの一覧については、Vertex AI の生成 AI のロケーションをご覧ください。
    • TEXT_PROMPT: 生成する画像をモデルに指示するテキスト プロンプト。インペインティング挿入にプロンプトを使用する場合は、最良の結果を得るために、マスクされた領域の説明を使用してください。1 語のプロンプトは使用しないでください。たとえば、「コーギー」ではなく「かわいいコーギー」を使用します。
    • B64_BASE_IMAGE: 編集またはアップスケールするベース画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • B64_MASK_IMAGE: 元の画像を編集するためにマスクレイヤとして使用する白黒画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • MASK_DILATION - フロート。このマスクを拡大する画像幅の割合。不完全な入力マスクを補正するには、値を 0.01 にすることをおすすめします。
    • EDIT_STEPS - 整数。ベースモデルのサンプリング ステップ数。インペインティング挿入の場合は、35 ステップから始めます。品質が要件を満たしていない場合は、ステップを上限の 75 まで増やします。ステップを増やすと、リクエストのレイテンシも大きくなります。
    • 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": "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 でエンコードした 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. 次のいずれかを行います。

      • 独自のマスクをアップロードする:
        1. パソコンでマスクを作成します。
        2. [マスクをアップロード] をクリックします。表示されたダイアログで、アップロードするマスクを選択します。
      • マスクを定義する: 編集ツールバーからマスクツール(ボックス、ブラシ、masked_transitions反転ツール)を選択して、コンテンツを追加する領域を指定します。
    5. 省略可。[パラメータ] パネルで、次のオプションを調整します。
      • モデル: 使用する Imagen モデル
      • 結果の数: 生成する結果の数
      • ネガティブ プロンプト: 生成を回避するアイテム
    6. 画像を修正するために、プロンプトのフィールドに新しいプロンプトを入力します。
    7. [生成] をクリックします。

    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 = "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: モデルのテキスト プロンプトに対する適合度を制御するパラメータ(整数)。値を大きくすると、テキスト プロンプトと生成された画像のアライメントが向上しますが、画質が低下する可能性があります。値: 0500。デフォルト: 60

    HTTP メソッドと URL:

    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 でエンコードした 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 メソッドに渡されます。このサービスは、編集されたバージョンの画像を返します。この画像はローカルに保存されます。

    モデルのバージョンと機能の詳細については、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

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

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

    このサンプルでは、PredictionServiceClientpredict メソッドを呼び出します。このサービスは画像を生成し、ローカルに保存します。モデルのバージョンと機能の詳細については、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 ] ページに移動します。

      Media Studio に移動

    2. [アップロード] をクリックします。表示されたファイル ダイアログで、アップロードするファイルを選択します。
    3. [インペイント] をクリックします。
    4. 編集ツールバーで、[background_replaceマスクを抽出] をクリックします。
    5. 次のいずれかのマスク抽出オプションを選択します。

      • 背景要素: 背景要素を検出し、その周囲にマスクを作成します。
      • 前景要素: フォアグラウンドのオブジェクトを検出し、その周囲にマスクを作成します。
      • background_replace人物: 人物を検出し、その周囲にマスクを作成します。
    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: 生成する画像をモデルに指示するテキスト プロンプト。インペインティング挿入にプロンプトを使用する場合は、最良の結果を得るために、マスクされた領域の説明を使用してください。1 語のプロンプトは使用しないでください。たとえば、「コーギー」ではなく「かわいいコーギー」を使用します。
    • B64_BASE_IMAGE: 編集またはアップスケールするベース画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • MASK_MODE - モデルで使用する自動マスク作成のタイプを設定する文字列。使用可能な値:
      • MASK_MODE_BACKGROUND: バックグラウンド セグメンテーションを使用してマスクを自動的に生成します。
      • MASK_MODE_FOREGROUND: フォアグラウンド セグメンテーションを使用してマスクを自動的に生成します。
      • MASK_MODE_SEMANTIC: maskImageConfig.maskClasses 配列で指定したセグメンテーション クラスに基づいて、セマンティック セグメンテーションを使用してマスクを自動的に生成します。例:
                  "maskImageConfig": {
                    "maskMode": "MASK_MODE_SEMANTIC",
                    "maskClasses": [175, 176], // bicycle, car
                    "dilation": 0.01
                  }
                
    • MASK_DILATION - フロート。このマスクを拡大する画像幅の割合。不完全な入力マスクを補正するには、値を 0.01 にすることをおすすめします。
    • EDIT_STEPS - 整数。ベースモデルのサンプリング ステップ数。インペインティング挿入の場合は、35 ステップから始めます。品質が要件を満たしていない場合は、ステップを上限の 75 まで増やします。ステップを増やすと、リクエストのレイテンシも大きくなります。
    • EDIT_IMAGE_COUNT - 編集された画像の数。指定できるのは整数値(1~4)です。デフォルト値: 4。

    HTTP メソッドと 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": "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 でエンコードした 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. 編集ツールバーで、[background_replace抽出] をクリックします。

    5. 次のいずれかのマスク抽出オプションを選択します。

      • 背景要素 - 背景要素を検出し、その周囲にマスクを作成します。
      • 前景要素 - フォアグラウンドのオブジェクトを検出し、その周囲にマスクを作成します。
      • background_replace人 - 人物を検出し、その周囲にマスクを作成します。
    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_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: 自動セグメンテーションを使用して、1 つ以上のセグメンテーション クラスのマスク領域を作成します。classes パラメータとそれに対応する class_id 値を使用して、セグメンテーション クラスを設定します。最大 5 つのクラスを指定できます。セマンティック マスクタイプを使用する場合、maskMode オブジェクトは次のようになります。
        "maskMode": {
          "maskType": "semantic",
          "classes": [class_id1, class_id2]
        }
    • GUIDANCE_SCALE_VALUE: モデルのテキスト プロンプトに対する適合度を制御するパラメータ(整数)。値を大きくすると、テキスト プロンプトと生成された画像のアライメントが向上しますが、画質が低下する可能性があります。値: 0500。デフォルト: 60

    HTTP メソッドと URL:

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

    制限事項

    以降のセクションでは、Imagen のオブジェクト削除機能の制限について説明します。

    変更されたピクセル

    マスクに含まれていないモデルによって生成されたピクセルは、入力と同一であるとは限りません。また、モデルの解像度(1024x1024 など)で生成されます。生成された画像には、ごくわずかな変更が含まれている場合があります。

    画像を完全に保持したい場合は、マスクを使用して、生成された画像を入力画像とブレンドすることをおすすめします。通常、入力画像の解像度が 2K 以上の場合は、生成された画像と入力画像をブレンドする必要があります。

    制限事項を挿入する

    通常、挿入はベースイメージのスタイルに一致します。ただし、写実的な出力を意図していても、特定のキーワードによって漫画風の出力が生成されることがあります。

    特に、色が正確に表示されないという問題が報告されています。たとえば、「黄色いキリン」と入力すると、写真のようなキリンは茶色と黄褐色であるため、漫画のキリンが生成される傾向があります。同様に、フォトリアリスティックでありながら不自然な色を生成することも困難です。

    次のステップ

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