インペイントを使用して画像からオブジェクトを削除する

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

コンテンツの削除の例

次の例では、インペインティングを使用して、画像マスクを使用して既存の画像からコンテンツを削除します。

入力

編集対象のベース画像*

Google Cloud コンソールのツールで指定したマスク領域

テキスト プロンプト

右側にレモンの袋、左隅にクッションが置かれた赤いソファのベース画像の例。ソファは斜めに配置され、1 本の脚が白いラグの上に置かれています。ソファの前のラグの上にレモンが 2 個置かれています。 赤いソファのサンプルベース画像が描かれています。ソファのレモンの袋とラグの 2 つのレモンに対して、マスク領域が定義されています。

プロンプト: (プロンプトなし)

* 画像クレジット: Inside WeatherUnsplash より

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

編集されたサンプル画像には、入力例のソファとラグがレモンなしで描かれています。 編集されたサンプル画像には、入力例のソファとラグがレモンなしで描かれています。 編集されたサンプル画像には、入力例のソファとラグがレモンなしで描かれています。

編集とカスタマイズ用 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. 次のいずれかを行います。

      • 独自のマスクをアップロードする:
        1. パソコンでマスクを作成します。
        2. [マスクをアップロード] をクリックします。表示されたダイアログで、アップロードするマスクを選択します。
      • 独自のマスクを定義する: 編集ツールバーからマスクツール( ボックス、 ブラシ、masked_transitions 反転ツール)を選択して、コンテンツを追加する領域を指定します。
    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=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="",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_INPAINT_REMOVAL",
        ),
    )
    
    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: 最良の結果を得るには、除去にインペインティングを使用するときにプロンプトと negativePrompt を省略してください。
    • B64_BASE_IMAGE: 編集またはアップスケールするベース画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • B64_MASK_IMAGE: 元の画像の編集でマスクレイヤとして使用する白黒画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • MASK_DILATION - フロート。このマスクを拡大する画像幅の割合。不完全な入力マスクを補正するには、値を 0.01 にすることをおすすめします。
    • EDIT_STEPS - 整数。ベースモデルのサンプリング ステップ数。インペインティングの削除の場合は、12 の手順から始めます。品質が要件を満たしていない場合は、ステップを 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": "",
          "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_REMOVAL",
        "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. 編集ツールバーからマスクツール(ボックス、ブラシ、masked_transitions反転ツール)を選択して、コンテンツを削除する領域を指定します(複数の領域を指定できます)。

    5. 省略可: [パラメータ] パネルで、[検索結果の表示件数]、[ネガティブ プロンプト](削除の場合は省略可)、[テキスト プロンプト ガイダンス] などのパラメータを調整します。

    6. プロンプト フィールドは空のままにします。

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

    REST

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

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID
    • LOCATION: プロジェクトのリージョン。たとえば、us-central1europe-west2asia-northeast3 です。使用可能なリージョンの一覧については、Vertex AI の生成 AI のロケーションをご覧ください。
    • B64_BASE_IMAGE: 編集またはアップスケールするベース画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • B64_MASK_IMAGE: 元の画像の編集でマスクレイヤとして使用する白黒画像。画像は 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_MASK_IMAGE"
            }
          }
        }
      ],
      "parameters": {
        "sampleCount": EDIT_IMAGE_COUNT,
        "editConfig": {
          "editMode": "inpainting-remove"
        }
      }
    }
    

    リクエストを送信するには、次のいずれかのオプションを選択します。

    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"
        }
      ]
    }
    

    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 = "outpur-image.png"
    # prompt = "" # The text prompt describing the entire image.
    
    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-remove",
        # Optional parameters
        # negative_prompt="", # Describes the object being removed (i.e., "person")
    )
    
    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 12345678 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 EditImageInpaintingRemoveMaskSample {
    
      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 the entire image.
    
        editImageInpaintingRemoveMask(projectId, location, inputPath, maskPath, prompt);
      }
    
      // Edit an image using a mask file. Inpainting can remove an object from the masked area.
      public static PredictResponse editImageInpaintingRemoveMask(
          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-remove"); // [ "editMode", "inpainting-remove" ]
          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/volleyball_game.png';
    const maskFile = 'resources/volleyball_game_inpainting_remove_mask.png';
    const prompt = 'volleyball game';
    
    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 editImageInpaintingRemoveMask() {
      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 the entire image
        editMode: 'inpainting-remove',
        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 editImageInpaintingRemoveMask();

    自動マスク検出で削除する

    次のサンプルを使用して、コンテンツを削除するインペインティングを指定します。これらのサンプルでは、ベースイメージとテキスト プロンプトを指定します。Imagen は、ベース画像を変更するマスク領域を自動的に検出して作成します。

    Imagen 3

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

    コンソール

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

      Media Studio に移動

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

      • 背景要素: 背景要素を検出し、その周囲にマスクを作成します。
      • 前景要素: 前景のオブジェクトを検出し、その周囲にマスクを作成します。
      • background_replace人物: 人物を検出し、その周囲にマスクを作成します。
    7. 省略可: [パラメータ] パネルで、次のオプションを調整します。
      • モデル: 使用する Imagen モデル
      • 検索結果の表示件数: 生成する結果の数
      • ネガティブ プロンプト: 生成を回避するアイテム
    8. 画像を変更するために、プロンプトのフィールドに新しいプロンプトを入力します。
    9. [send生成] をクリックします。

    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",
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_INPAINT_REMOVAL",
        ),
    )
    
    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: 最良の結果を得るには、除去にインペインティングを使用するときにプロンプトと negativePrompt を省略してください。
    • 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 - 整数。ベースモデルのサンプリング ステップ数。インペインティングの削除の場合は、12 の手順から始めます。品質が要件を満たしていない場合は、ステップを 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": "",
          "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_REMOVAL",
        "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. [生成] をクリックします。

    REST

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

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID
    • LOCATION: プロジェクトのリージョン。たとえば、us-central1europe-west2asia-northeast3 です。使用可能なリージョンの一覧については、Vertex AI の生成 AI のロケーションをご覧ください。
    • 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]
        }

    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"
          }
        }
      ],
      "parameters": {
        "sampleCount": EDIT_IMAGE_COUNT,
        "editConfig": {
          "editMode": "inpainting-remove",
          "maskMode": {
            "maskType": "MASK_TYPE"
          }
        }
      }
    }
    

    リクエストを送信するには、次のいずれかのオプションを選択します。

    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"
        }
      ]
    }
    

    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 = "foreground" # 'background', 'foreground', or 'semantic'
    # output_file = "output-image.png"
    # prompt = "sports car" # The text prompt describing what you want to see in the edited image.
    
    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-remove",
    )
    
    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 1279948 bytes
    

    制限事項

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

    変更されたピクセル

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

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

    削除の制限

    マスクに隣接する小さなオブジェクトも削除されることがあります。ベスト プラクティスとして、マスクをできるだけ正確にすることをおすすめします。

    屋外画像の空の領域で大きな領域を削除すると、不要なアーティファクトが発生する可能性があります。ベスト プラクティスとして、プロンプトを指定することをおすすめします。

    次のステップ

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