画像の背景を置き換える

このページでは、画像の背景を置き換える方法について説明します。Vertex AI 上の Imagen では、オブジェクトの自動セグメンテーションを使用して、特定の画像コンテンツを維持しながら他のコンテンツを変更できます。Imagen 3 では、独自のマスク領域を指定して、編集時により細かく制御することもできます。

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

商品画像の編集の例

次のユースケースでは、画像の背景を変更して商品画像を強化しながら、画像内の商品の外観を維持する方法について説明します。

コンソールで生成されたサンプル画像
Imagen の商品画像編集機能を使用して次のプロンプトから生成した画像: ブティックのテーブルの上。元の画像の出典: Irene KredenetsUnsplash より。

始める前に

  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.

    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 を使用すると、背景の自動検出で商品画像を編集できます。これは、商品画像の背景を変更しながら、商品の外観を維持する必要がある場合に役立ちます。商品画像の編集では、Google Product Studio(GPS)製品を利用できます。コンソールまたは API を使用して、Imagen の一部として GPS 機能を使用できます。

    コンソールで生成されたサンプル画像
    Imagen の商品画像編集機能を使用して次のプロンプトから生成した画像: ブティックのテーブルの上。元の画像の出典: Irene KredenetsUnsplash より。

    次の手順で、背景の自動検出による商品画像の編集を有効にして使用します。

    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. [送信生成] をクリックします。

    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/suitcase.png'), reference_id=0)
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=None,
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_BACKGROUND",
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A light blue suitcase in front of a window in an airport",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_BGSWAP",
        ),
    )
    
    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: 生成する画像をモデルに指示するテキスト プロンプト。生成と編集のどちらでも必須フィールドです。
    • referenceType: ReferenceImage は、画像編集に追加のコンテキストを提供する画像です。編集のユースケースでは、通常の RGB の元の参照画像(REFERENCE_TYPE_RAW)が必要です。1 つのリクエストに存在できる元の参照画像は 1 つまでです。出力画像の高さと幅は、元の参照画像と同じです。マスク編集のユースケースでは、マスク参照画像(REFERENCE_TYPE_MASK)が必要です。
    • referenceId: 参照画像の整数 ID。この例では、2 つの参照画像オブジェクトのタイプが異なるため、referenceId 値が異なります(12)。
    • B64_BASE_IMAGE: 編集またはアップスケールするベース画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • maskImageConfig.maskMode: マスク編集のマスクモード。MASK_MODE_BACKGROUND は、ユーザーが指定したマスクなしで背景を自動的にマスクするために使用されます。
    • MASK_DILATION - フロート。このマスクを拡大する画像幅の割合。フォアグラウンド プロダクトが拡張されないようにするために、値を 0.00 にすることをおすすめします。最小: 0、最大: 1。デフォルト: 0.03。
    • EDIT_STEPS - 整数。ベースモデルのサンプリング ステップ数。商品画像の編集の場合は、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_BACKGROUND",
                "dilation": MASK_DILATION
              }
            }
          ]
        }
      ],
      "parameters": {
        "editConfig": {
          "baseSteps": EDIT_STEPS
        },
        "editMode": "EDIT_MODE_BGSWAP",
        "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
    次のサンプル レスポンスは、商品の背景の編集リクエストに対するものです。レスポンスは、生成された画像のバイトを base64 でエンコードした 4 つの予測オブジェクトを返します。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        }
      ]
    }
    

    Imagen 2

    次のサンプルを使用して、Imagen 2 モデルまたは Imagen モデルを使用して商品画像編集リクエストを送信します。

    コンソール

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

      Media Studio に移動

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

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

    4. [パラメータ] パネルで、[Enable product style image editing] を選択します。

    5. [Prompt] フィールの「ここにプロンプトを入力します」の部分にプロンプトを入力します。

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

    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"
    # output_file = "output-image.png"
    # prompt = "" # The text prompt describing what you want to see in the background.
    
    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,
        prompt=prompt,
        edit_mode="product-image",
    )
    
    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 リファレンスをご覧ください。

    Imagen 2 バージョン 006 モデル(imagegeneration@006)を使用して商品画像の編集を有効にするには、"editConfig": {} オブジェクトに "editMode": "product-image" フィールドを含めます。このリクエストは常に 4 つの画像を返します。

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

    • PROJECT_ID: 実際の Google Cloud プロジェクト ID
    • LOCATION: プロジェクトのリージョン。たとえば、us-central1europe-west2asia-northeast3 です。使用可能なリージョンの一覧については、Vertex AI の生成 AI のロケーションをご覧ください。
    • TEXT_PROMPT: 生成する画像をモデルに指示するテキスト プロンプト。生成と編集のどちらでも必須フィールドです。
    • B64_BASE_IMAGE: 編集またはアップスケールするベース画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • PRODUCT_POSITION: 省略可。検出された商品またはオブジェクトの元の位置を維持するか、モデルが位置を変更できるようにする設定。使用可能な値: reposition(デフォルト値)は再配置を許可し、fixed は商品の位置を維持します。正方形以外の入力画像の場合、商品の位置は [固定] が設定されていても常に [再配置] になります。

    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": {
        "editConfig": {
          "editMode": "product-image",
          "productPosition": "PRODUCT_POSITION",
        }
      }
    }
    
    

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

    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
    次のサンプル レスポンスは、商品の背景の編集リクエストに対するものです。レスポンスは、生成された画像のバイトを base64 でエンコードした 4 つの予測オブジェクトを返します。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        }
      ]
    }
    

    定義したマスク領域で編集する

    Imagen にマスクを自動的に検出させるのではなく、置き換えられた領域をマスクすることもできます。

    コンソール

    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/suitcase.png'), reference_id=0)
    mask_ref = MaskReferenceImage(
        reference_id=1,
        reference_image=Image.from_file(location='test_resources/suitcase_mask.png'),
        config=MaskReferenceConfig(
            mask_mode="MASK_MODE_USER_PROVIDED",
            mask_dilation=0.0,
        ),
    )
    
    image = client.models.edit_image(
        model="imagen-3.0-capability-001",
        prompt="A light blue suitcase in an airport",
        reference_images=[raw_ref, mask_ref],
        config=EditImageConfig(
            edit_mode="EDIT_MODE_BGSWAP",
        ),
    )
    
    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: 生成する画像をモデルに指示するテキスト プロンプト。生成と編集のどちらでも必須フィールドです。
    • referenceId: 参照画像の整数 ID。この例では、2 つの参照画像オブジェクトのタイプが異なるため、referenceId 値が異なります(12)。
    • B64_BASE_IMAGE: 編集またはアップスケールするベース画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • B64_MASK_IMAGE: 元の画像を編集するためにマスクレイヤとして使用する白黒画像。画像は base64 でエンコードされたバイト文字列として指定する必要があります。サイズの上限: 10 MB。
    • MASK_DILATION - フロート。このマスクを拡大する画像幅の割合。フォアグラウンド プロダクトが拡張されないようにするために、値を 0.00 にすることをおすすめします。最小: 0、最大: 1。デフォルト: 0.03。
    • EDIT_STEPS - 整数。ベースモデルのサンプリング ステップ数。商品画像の編集の場合は、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": [
            {
              "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_BGSWAP",
        "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
    次のサンプル レスポンスは、商品の背景の編集リクエストに対するものです。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        }
      ]
    }
    

    制限事項

    マスクが不完全な場合があるため、境界で非常に小さなビットが欠落していると、モデルは前景オブジェクトを完成させようとする可能性があります。まれな副作用として、フォアグラウンド オブジェクトがすでに完了している場合、モデルがわずかな拡張を作成することがあります。

    この問題を回避するには、モデルの出力をセグメント化してからブレンドします。回避策を示す Python スニペットの例を次に示します。

    blended = Image.composite(out_images[0].resize(image_expanded.size), image_expanded, mask_expanded)
    

    次のステップ

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