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

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

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

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

サンプルのベース画像
マスク画像(ターゲット)のサイズに合わせてパディングが設定された元の画像。
画像の出典: 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.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

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

      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 を使用して認証するをご覧ください。

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

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

    コンソール

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

    <a href="https://console.cloud.google.com/vertex-ai/studio/media/generate;tab=image" class="button button-primary"
    target="console" track-name="consoleLink" track-type="task">Go to Media
    Studio</a>
    
    1. [アップロード] をクリックします。表示されたファイル ダイアログで、アップロードするファイルを選択します。

    2. [アウトペイント] をクリックします。

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

    4. 編集ツールバーで、画像の配置を選択します。

      • 左揃え:

      • 水平方向を中央揃え:

      • 右揃え:

      • 上揃え:

      • 垂直方向を中央揃え:

      • 下揃え: 1 省略可: [パラメータ] パネルで、次のオプションを調整します。

      • モデル: 使用する Imagen モデル

      • 検索結果の表示件数: 生成する結果の数

      • ネガティブ プロンプト: 生成を回避するアイテム

    5. 画像を変更するために、プロンプトのフィールドにプロンプトを入力します。

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

    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

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

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

    制限事項

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

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

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

    次のステップ

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