更換圖片背景

本頁說明如何更換圖片背景。Vertex AI 的 Imagen 可讓您使用自動物件分割功能,在修改其他圖片內容時保留該內容。使用 Imagen 3 時,你也可以提供自己的遮罩區域,在編輯時進一步控管。

查看「Imagen for Editing and Customization」模型資訊卡

產品圖片編輯範例

以下用例著重於修改圖片背景,但保留圖片中產品的外觀,藉此強化產品圖片。

主控台中生成的圖片範例
使用 Imagen 產品圖片編輯功能,根據提示生成的圖片: 精品店桌上的產品。原始圖片來源: Irene Kredenets 發表於 Unsplash

事前準備

  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 驗證說明文件中的「Authenticate for using REST」。

    使用自動偵測到的背景遮罩編輯

    Imagen 可自動偵測背景,並編輯產品圖片。如果您需要修改產品圖片的背景,但想保留產品外觀,這項功能就非常實用。產品圖片編輯功能採用 Google Product Studio (GPS) 服務。您可以使用控制台或 API,透過 Imagen 使用 GPS 功能。

    主控台中生成的圖片範例
    使用 Imagen 產品圖片編輯功能,根據提示生成的圖片: 精品店桌上的產品。原始圖片來源: Irene Kredenets 發表於 Unsplash

    請按照下列操作說明啟用產品圖片編輯功能,並使用自動背景偵測功能。

    Imagen 3

    使用下列範例,透過 Imagen 3 模型傳送產品圖片編輯要求。

    控制台

    1. 在 Google Cloud 控制台中,前往「Vertex AI」>「Media Studio」 頁面。

      前往媒體工作室

    2. 按一下 [上傳]。在顯示的檔案對話方塊中,選取要上傳的檔案。
    3. 按一下「修復」
    4. 在「Parameters」面板中,按一下「Product Background」
    5. 在編輯工具列中,依序按一下 background_replace「擷取」
    6. 選取其中一個遮罩擷取選項:

      • 背景元素:偵測背景元素,並在周圍建立遮罩。
      • 前景元素:偵測前景物件,並在周圍建立遮罩。
      • background_replacePeople: 偵測人物並建立遮罩。
    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:文字提示,引導模型生成圖片。生成和編輯時都必須填寫這個欄位。
    • referenceTypeReferenceImage 是提供圖片編輯額外背景資訊的圖片。編輯用途需要正常的 RGB 原始參考圖像 (REFERENCE_TYPE_RAW)。一個要求最多只能有一個原始參照圖片。 輸出圖片的高度和寬度與原始參考圖片相同。如要使用遮罩編輯,必須提供遮罩參考圖片 (REFERENCE_TYPE_MASK)。
    • referenceId:參考圖片的整數 ID。在這個範例中,兩個參照圖片物件的類型不同,因此具有不同的 referenceId 值 (12)。
    • B64_BASE_IMAGE:要編輯或放大畫質的基礎圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • maskImageConfig.maskMode:遮罩編輯的遮罩模式。 MASK_MODE_BACKGROUND 可自動遮蓋背景,不需使用者提供遮罩。
    • MASK_DILATION - float。遮罩擴張的圖片寬度百分比。建議使用 0.00 值,避免延長前景產品。最小值:0,最大值:1。 預設值:0.03。
    • EDIT_STEPS - 整數。基礎模型的取樣步驟數。如要編輯產品圖片,請從 75 步驟開始。
    • EDIT_IMAGE_COUNT - 編輯過的圖片數量。接受的整數值:1 到 4。 預設值:4。

    HTTP 方法和網址:

    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 編碼產生的圖片位元組。
    {
      "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」 頁面。

      前往媒體工作室

    2. 在下方工作面板中,按一下「編輯圖片」

    3. 按一下「上傳」,選取要編輯的本機產品圖片。

    4. 在「參數」面板中,選取「啟用產品樣式圖片編輯」

    5. 在「提示詞」欄位 (「在這裡撰寫提示詞」) 輸入提示。

    6. 點按「生成」

    Python

    如要瞭解如何安裝或更新 Python 適用的 Vertex AI SDK,請參閱「安裝 Python 適用的 Vertex AI SDK」。 詳情請參閱 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 方法和網址:

    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 編碼的生成圖片位元組。
    {
      "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」 頁面。

      前往媒體工作室

    2. 按一下 [上傳]。在顯示的檔案對話方塊中,選取要上傳的檔案。
    3. 按一下「修復」
    4. 在「Parameters」面板中,按一下「Product Background」
    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。在這個範例中,兩個參照圖片物件的類型不同,因此具有不同的 referenceId 值 (12)。
    • B64_BASE_IMAGE:要編輯或放大畫質的基礎圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • B64_MASK_IMAGE:要用來做為遮罩圖層的黑白圖片,可編輯原始圖片。圖片必須指定為 base64 編碼的位元組字串。大小限制:10 MB。
    • MASK_DILATION - float。遮罩擴張的圖片寬度百分比。建議使用 0.00 值,避免延長前景產品。最小值:0,最大值:1。 預設值:0.03。
    • EDIT_STEPS - 整數。基礎模型的取樣步驟數。如要編輯產品圖片,請從 75 步驟開始。
    • EDIT_IMAGE_COUNT - 編輯過的圖片數量。接受的整數值:1 到 4。 預設值:4。

    HTTP 方法和網址:

    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 產品的文章: