使用文字提示來生成圖像

您可以使用 Vertex AI 的 Imagen,根據文字提示生成新圖片。 支援的介面包括 Google Cloud 控制台和 Vertex AI API。

如要進一步瞭解如何編寫文字提示來生成及編輯圖片,請參閱提示指南

查看 Imagen for Generation 模型資訊卡

試用圖片生成功能 (Vertex AI Studio)

在 Colab 中試用 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.

    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」。

    使用文字生成圖像

    你只需要輸入描述性文字,就能生成新穎的圖像。下列範例顯示生成圖像的基本指令。

    控制台

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

      前往媒體工作室

    2. 按一下「Imagen」。系統會顯示 Imagen Media Studio 圖像生成頁面。

    3. 選用:在「設定」窗格中,設定下列選項:

      • 模式:從可用選項中選擇模式。

        如要進一步瞭解可用的模型,請參閱 Imagen 模型

      • 顯示比例:從可用選項中選擇顯示比例。

      • 結果數量:調整滑桿或輸入介於 14 之間的值。

    4. 選用:在「進階選項」部分中,選取要生成圖片的「區域」

    5. 在「撰寫提示」方塊中,輸入文字提示來描述要生成的圖片。例如「清晨水面上的小船,水彩插畫」

      如要進一步瞭解如何撰寫有效的提示,請參閱提示和圖片屬性指南

    6. 按一下「生成」

      系統會自動在生成的圖片中加入數位浮水印。使用 Google Cloud 控制台生成圖片時,無法停用數位浮水印。

      選取圖片即可在「圖片詳細資料」視窗中查看。 有浮水印的圖片會顯示「數位浮水印」徽章。你也可以明確驗證圖片浮水印

      使用文字生成含浮水印的圖像範例
      圖片詳細資料檢視以 Imagen 2 根據提示生成的浮水印圖片:small red boat on water in the morning watercolor illustration muted colors

    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=global
    export GOOGLE_GENAI_USE_VERTEXAI=True

    在這個範例中,您會對 ImageGenerationModel 呼叫 generate_images 方法,並在本機儲存產生的圖片。然後,您可以在筆記本中選擇使用 show() 方法,顯示生成的圖片。如要進一步瞭解模型版本和功能,請參閱 Imagen 模型

    from google import genai
    
    client = genai.Client()
    
    # TODO(developer): Update and un-comment below line
    # output_file = "output-image.png"
    
    image = client.models.generate_images(
        model="imagen-4.0-generate-preview-06-06",
        prompt="A dog reading a newspaper",
    )
    
    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

    如要進一步瞭解 imagegeneration 模型要求,請參閱 imagegeneration 模型 API 參考資料

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID:您的 Google Cloud 專案 ID
    • MODEL_VERSION:要使用的 Imagen 模型版本。如要進一步瞭解可用的模型,請參閱 Imagen 模型

    • LOCATION:專案的區域。例如 us-central1europe-west2asia-northeast3。如需可用區域的清單,請參閱「Vertex AI 的生成式 AI 服務地區」。
    • TEXT_PROMPT:文字提示,引導模型生成圖片。生成和編輯時都必須填寫這個欄位。
    • IMAGE_COUNT:生成的圖片數量。 可接受的整數值:1 到 8 (imagegeneration@002),1 到 4 (所有其他模型版本)。 預設值為 4。
    • 其他選用參數

      請視用途使用下列選用變數。在 "parameters": {} 物件中新增部分或所有下列參數。 這份清單列出常見的選用參數,並非完整清單。如要進一步瞭解選用參數,請參閱 Imagen API 參考資料:生成圖片

      "parameters": {
        "sampleCount": IMAGE_COUNT,
        "addWatermark": ADD_WATERMARK,
        "aspectRatio": "ASPECT_RATIO",
        "enhancePrompt": ENABLE_PROMPT_REWRITING,
        "includeRaiReason": INCLUDE_RAI_REASON,
        "includeSafetyAttributes": INCLUDE_SAFETY_ATTRIBUTES,
        "outputOptions": {
          "mimeType": "MIME_TYPE",
          "compressionQuality": COMPRESSION_QUALITY
        },
        "personGeneration": "PERSON_SETTING",
        "safetySetting": "SAFETY_SETTING",
        "seed": SEED_NUMBER,
        "storageUri": "OUTPUT_STORAGE_URI"
      }
      
      • ADD_WATERMARK:布林值。(選用步驟) 是否為生成的圖片啟用浮水印。 如果將欄位設為 true,系統會為生成的圖片加上 SynthID 數位浮水印,方便您驗證圖片。如果省略這個欄位,系統會使用預設值 true;如要停用這項功能,請將值設為 false。只有在將這個欄位設為 false 時,才能使用 seed 欄位取得確定性輸出內容。
      • ASPECT_RATIO:字串。(選用步驟) 控制長寬比的生成模式參數。支援的比例值及其用途:
        • 1:1 (預設,正方形)
        • 3:4 (廣告、社群媒體)
        • 4:3 (電視、攝影)
        • 16:9 (橫向)
        • 9:16 (直向)
      • ENABLE_PROMPT_REWRITING:布林值。(選用步驟) 這個參數可使用以 LLM 為基礎的提示重寫功能,提供更能反映原始提示意圖的高畫質圖像。停用這項功能可能會影響影像品質和提示遵循率。預設值為 true
      • INCLUDE_RAI_REASON:布林值。(選用步驟) 是否要在輸入或輸出內容遭到封鎖的回覆中,啟用「負責任的 AI 技術篩選理由」代碼。預設值: true
      • INCLUDE_SAFETY_ATTRIBUTES:布林值。(選用步驟) 是否要在未經過濾的輸入內容和輸出內容的回覆中,針對一系列安全屬性啟用四捨五入的負責任 AI 分數。安全屬性類別:"Death, Harm & Tragedy""Firearms & Weapons""Hate""Health""Illicit Drugs""Politics""Porn""Religion & Belief""Toxic""Violence""Vulgarity""War & Conflict"。預設值為 false
      • MIME_TYPE:字串。(選用步驟) 圖片內容的 MIME 類型。可用值:
        • image/jpeg
        • image/gif
        • image/png
        • image/webp
        • image/bmp
        • image/tiff
        • image/vnd.microsoft.icon
      • COMPRESSION_QUALITY:整數。(選用步驟) 僅適用於 JPEG 輸出檔案。模型為以 JPEG 檔案格式生成的圖片保留的細節程度。值:0100,數字越大代表壓縮程度越高。預設值: 75
      • PERSON_SETTING:字串。(選用步驟) 這項安全性設定可控管模型允許生成的人物或臉部類型。可用值:
        • allow_adult (預設):只允許生成成人內容,但名人生成除外。任何設定都不允許生成名人。
        • dont_allow:禁止在生成圖像中加入人物或臉部。
      • SAFETY_SETTING:字串。(選用步驟) 這項設定可控管生成圖像的安全篩選器門檻。可用值:
        • block_low_and_above:安全門檻最高,因此篩除的生成圖像數量最多。先前的值:block_most
        • block_medium_and_above (預設):中等安全門檻,可平衡過濾潛在有害和安全內容。先前的值:block_some
        • block_only_high:安全門檻,可減少因安全篩選機制而遭封鎖的要求數量。這項設定可能會增加 Imagen 生成的不當內容。先前的值:block_few
      • SEED_NUMBER:整數。(選用步驟) 您提供的任何非負整數,可讓輸出圖片具有確定性。提供相同的種子編號一律會產生相同的輸出圖片。如果您使用的模型支援數位浮水印,就必須設定 "addWatermark": false 才能使用這個欄位。可接受的整數值:1 - 2147483647
      • OUTPUT_STORAGE_URI:字串。(選用步驟) 用於儲存輸出圖片的 Cloud Storage bucket。如果未提供,回應中會傳回 base64 編碼的圖片位元組。範例值: gs://image-bucket/output/

    HTTP 方法和網址:

    POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_VERSION:predict

    JSON 要求主體:

    {
      "instances": [
        {
          "prompt": "TEXT_PROMPT"
        }
      ],
      "parameters": {
        "sampleCount": 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/MODEL_VERSION: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/MODEL_VERSION:predict" | Select-Object -Expand Content
    以下是含有 "sampleCount": 2 的要求範例回應。回應會傳回兩個預測物件,其中包含以 base64 編碼產生的圖片位元組。
    {
      "predictions": [
        {
          "bytesBase64Encoded": "BASE64_IMG_BYTES",
          "mimeType": "image/png"
        },
        {
          "mimeType": "image/png",
          "bytesBase64Encoded": "BASE64_IMG_BYTES"
        }
      ]
    }

    如果您使用的模型支援提示強化功能,回應會包含額外的 prompt 欄位,其中含有用於生成內容的強化提示:

    {
      "predictions": [
        {
          "mimeType": "MIME_TYPE",
          "prompt": "ENHANCED_PROMPT_1",
          "bytesBase64Encoded": "BASE64_IMG_BYTES_1"
        },
        {
          "mimeType": "MIME_TYPE",
          "prompt": "ENHANCED_PROMPT_2",
          "bytesBase64Encoded": "BASE64_IMG_BYTES_2"
        }
      ]
    }
    

    後續步驟

    閱讀有關 Imagen 和其他 Vertex AI 生成式 AI 產品的文章: