選取您的 Cookie 偏好設定

我們使用提供自身網站和服務所需的基本 Cookie 和類似工具。我們使用效能 Cookie 收集匿名統計資料,以便了解客戶如何使用我們的網站並進行改進。基本 Cookie 無法停用,但可以按一下「自訂」或「拒絕」以拒絕效能 Cookie。

如果您同意,AWS 與經核准的第三方也會使用 Cookie 提供實用的網站功能、記住您的偏好設定,並顯示相關內容,包括相關廣告。若要接受或拒絕所有非必要 Cookie,請按一下「接受」或「拒絕」。若要進行更詳細的選擇,請按一下「自訂」。

Amazon Titan Image Generator G1 模型

焦點模式
Amazon Titan Image Generator G1 模型 - Amazon Bedrock

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

Amazon Titan Image Generator G1 V1 以及 Titan Image Generator G1 V2 模型在執行模型推論時支援下列推論參數和模型回應。

推論參數

當您使用 Amazon Titan Image Generator 模型進行InvokeModel呼叫時,請將請求body的欄位取代為符合使用案例的格式。所有任務都共用 imageGenerationConfig 物件,但是每個任務都有一個特定於該項任務的參數物件。支援下列使用案例。

taskType 任務參數欄位 任務類型 定義
TEXT_IMAGE textToImageParams 產生

使用文字提示產生影像。

TEXT_IMAGE textToImageParams 產生

(僅限 Image conditioning-V2) 提供額外的輸入調節影像以及文字提示,以產生遵循調節影像配置和組成的影像。

INPAINTING inPaintingParams 編輯

透過變更遮罩內部以符合周圍背景來修改影像。

OUTPAINTING outPaintingParams 編輯 透過無縫延伸遮罩定義的區域來修改影像。
IMAGE_VARIATION imageVariationParams 編輯 透過產生原始影像的變體來修改影像。
COLOR_GUIDED_GENERATION (V2 only) colorGuidedGenerationParams 產生 提供十六進位顏色代碼清單以及文字提示,以產生色彩調色盤之後的影像。
BACKGROUND_REMOVAL (V2 only) backgroundRemovalParams 編輯 透過識別多個物件並移除背景、輸出具有透明背景的影像來修改映像。

編輯任務時,在輸入中需要一個 image 欄位。此欄位由定義影像中的像素的字串所組成。每個像素由 3 個RGB頻道定義,每個頻道的範圍從 0 到 255 (例如 (255 255 0) 代表黃色)。這些色頻均以 base64 編碼。

您使用的映像必須是 JPEG或 PNG 格式。

如果您執行修圖或擴圖,也需定義遮罩,這是定義要修改之影像部分的區域。您有兩種方式可以定義遮罩:

  • maskPrompt – 撰寫文字提示以描述要遮罩的影像部分。

  • maskImage – 輸入以 base64 編碼的字串,透過將輸入影像中的每個像素標記為 (0 0 0) 或 (255 255 255 255) 來定義遮罩區域。

    • 定義為 (0 0 0) 的像素是遮罩內的像素。

    • 定義為 (255 255 255) 的像素是指遮罩外部的像素。

    您可以使用相片編輯工具繪製遮罩。然後,您可以將輸出JPEG或PNG映像轉換為 base64 編碼,以輸入此欄位。否則,請改用 maskPrompt 欄位來允許模型推論遮罩。

選取標籤以檢視不同影像產生使用案例的API請求內文,以及欄位的說明。

Text-to-image generation (Request)

產生映像的文字提示必須 <= 512 個字元。較長端的解析度 <= 1,408。 negativeText (選用) – 文字提示,用於定義不包含在 <= 512 個字元的影像中。如需完整的解析度清單,請參閱下表。

{ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "string", "negativeText": "string" }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float, "seed": int } }

這些 textToImageParams 欄位如下所述。

  • text (必要) — 用於產生影像的文字提示。

  • negativeText (選用) – 文字提示,用於定義影像中不包含的內容。

    注意

    不要在 negativeText 提示中使用否定性字詞。例如,若您不想在影像中包含鏡像,請在 negativeText 提示中輸入 mirrors。請勿輸入 no mirrors

Inpainting (Request)

text (選用) — 文字提示,用來定義遮罩內要變更的內容。如果未包含此欄位,則模型會嘗試將整個遮罩區域取代為背景。必須 <= 512 個字元。 negativeText (選用) – 文字提示,用於定義影像中不包含的內容。必須 <= 512 個字元。輸入影像和輸入遮罩的大小限制,在影像的較長端為 <= 1,408。輸出大小與輸入大小相同。

{ "taskType": "INPAINTING", "inPaintingParams": { "image": "base64-encoded string", "text": "string", "negativeText": "string", "maskPrompt": "string", "maskImage": "base64-encoded string", "returnMask": boolean # False by default }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float } }

這些 inPaintingParams 欄位如下所述。遮罩定義您要修改的影像部分。

  • image (必要) – 要修改、格式化為指定像素序列的字串的 JPEG或 PNG映像,每個都以RGB值定義,並在 base64 中編碼。有關如何將影像編碼為 base64 並解碼 base64 編碼的字串,再將其轉換為影像的範例,請參閱程式碼範例

  • 您必須定義下列其中一個欄位 (不是兩個) 才能定義。

    • maskPrompt – 定義遮罩的文字提示。

    • maskImage – 透過指定與 大小相同的像素序列來定義遮罩的字串image。每個像素會變成 (0 0 0) (遮罩內的像素) 或 (255 255 255) (遮罩外的像素) RGB的值。有關如何將影像編碼為 base64 並解碼 base64 編碼的字串,再將其轉換為影像的範例,請參閱程式碼範例

  • text (選用) — 文字提示,用來定義遮罩內要變更的內容。如果未包含此欄位,則模型會嘗試將整個遮罩區域取代為背景。

  • negativeText (選用) – 文字提示,用於定義影像中不包含的內容。

    注意

    不要在 negativeText 提示中使用否定性字詞。例如,若您不想在影像中包含鏡像,請在 negativeText 提示中輸入 mirrors。請勿輸入 no mirrors

Outpainting (Request)

text (必要) — 文字提示,用來定義遮罩外要變更的內容。必須 <= 512 個字元。 negativeText (選用) – 文字提示,用於定義影像中不包含的內容。必須 <= 512 個字元。輸入影像和輸入遮罩的大小限制,在影像的較長端為 <= 1,408。輸出大小與輸入大小相同。

{ "taskType": "OUTPAINTING", "outPaintingParams": { "text": "string", "negativeText": "string", "image": "base64-encoded string", "maskPrompt": "string", "maskImage": "base64-encoded string", "returnMask": boolean, # False by default "outPaintingMode": "DEFAULT | PRECISE" }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float } }

outPaintingParams 欄位定義如下。遮罩定義您不想要修改的影像區域。產生無縫延伸您定義的區域。

  • image (必要) – 要修改、格式化為指定像素序列的字串的 JPEG或 PNG映像,每個都以RGB值定義,並在 base64 中編碼。有關如何將影像編碼為 base64 並解碼 base64 編碼的字串,再將其轉換為影像的範例,請參閱程式碼範例

  • 您必須定義下列其中一個欄位 (不是兩個) 才能定義。

    • maskPrompt – 定義遮罩的文字提示。

    • maskImage – 透過指定與 大小相同的像素序列來定義遮罩的字串image。每個像素會變成 (0 0 0) (遮罩內的像素) 或 (255 255 255) (遮罩外的像素) RGB的值。有關如何將影像編碼為 base64 並解碼 base64 編碼的字串,再將其轉換為影像的範例,請參閱程式碼範例

  • text (必要) — 文字提示,用來定義遮罩外要變更的內容。

  • negativeText (選用) – 文字提示,用於定義影像中不包含的內容。

    注意

    不要在 negativeText 提示中使用否定性字詞。例如,若您不想在影像中包含鏡像,請在 negativeText 提示中輸入 mirrors。請勿輸入 no mirrors

  • outPaintingMode – 指定是否允許修改遮罩內的像素。可能的值如下。

    • DEFAULT – 使用此選項可允許修改遮罩內的映像,使其與重建的背景保持一致。

    • PRECISE – 使用此選項可防止修改遮罩內的映像。

Image variation (Request)

影像變化可讓您根據參數值建立原始影像的變化。輸入影像的大小限制在影像較長端 <= 1,408。如需完整的解析度清單,請參閱下表。

  • text (選用) — 文字提示,可定義影像中要保留以及要變更的內容。必須 <= 512 個字元。

  • negativeText (選用) – 文字提示,用於定義影像中不包含的內容。必須 <= 512 個字元。

  • text (選用) — 文字提示,可定義影像中要保留以及要變更的內容。必須 <= 512 個字元。

  • similarityStrength (選用) – 指定產生的映像與輸入映像的相似程度 (使用較低的值),在世代中引入更多隨機性。可接受的範圍介於 0.2 和 1.0 (兩者皆包含) 之間,如果請求中缺少此參數,則會使用預設值 0.7。

{ "taskType": "IMAGE_VARIATION", "imageVariationParams": { "text": "string", "negativeText": "string", "images": ["base64-encoded string"], "similarityStrength": 0.7, # Range: 0.2 to 1.0 }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float } }

imageVariationParams 欄位定義如下。

  • 影像 (必要) - 為其產生變體的影像清單。您可以包含 1 到 5 個影像。影像定義為 base64 編碼的影像字串。有關如何將影像編碼為 base64 並解碼 base64 編碼的字串,再將其轉換為影像的範例,請參閱程式碼範例

  • text (選用) — 文字提示,可定義影像中要保留以及要變更的內容。

  • similarityStrength (選用) – 指定產生的映像與輸入映像 (s) 的相似程度。範圍介於 0.2 到 1.0 之間,而用於引入更多隨機性的數值較低。

  • negativeText (選用) – 文字提示,用於定義影像中不包含的內容。

    注意

    不要在 negativeText 提示中使用否定性字詞。例如,若您不想在影像中包含鏡像,請在 negativeText 提示中輸入 mirrors。請勿輸入 no mirrors

Conditioned Image Generation (Request) V2 only

條件化影像產生任務類型可讓客戶透過提供「條件影像」來增強 text-to-image產生,以對產生的影像實現更精細的控制。

  • Canny 邊緣偵測

  • 區段對應

產生映像的文字提示必須 <= 512 個字元。較長端的解析度 <= 1,408。 negativeText (選用) 是文字提示,用於定義不包含在影像中的項目,且為 <= 512 個字元。如需完整的解析度清單,請參閱下表。

{ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "string", "negativeText": "string", "conditionImage": "base64-encoded string", # [OPTIONAL] base64 encoded image "controlMode": "string", # [OPTIONAL] CANNY_EDGE | SEGMENTATION. DEFAULT: CANNY_EDGE "controlStrength": float # [OPTIONAL] weight given to the condition image. DEFAULT: 0.7 }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float, "seed": int } }
  • text (必要) — 用於產生影像的文字提示。

  • negativeText (選用) – 文字提示,用於定義不包含在映像中的內容。

    注意

    不要在 negativeText 提示中使用否定性字詞。例如,若您不想在影像中包含鏡像,請在 negativeText 提示中輸入 mirrors。請勿輸入 no mirrors

  • conditionImage (僅限選用 V2) – 引導所產生影像之配置和構成的單一輸入調節影像。影像定義為 base64 編碼的影像字串。如需如何將影像編碼為 base64 並解碼 base64 編碼字串並將其轉換為影像的範例。

  • controlMode (僅限選用 V2) – 指定應使用的調節模式類型。支援兩種類型的調節模式:CANNY_EDGE 和 SEGMENTATION。預設值為 CANNY_EDGE。

  • controlStrength (僅限選用 V2) – 指定所產生映像的配置和組成與 的相似程度conditioningImage。範圍介於 0 到 1.0 之間,而用於引入更多隨機性的數值較低。預設值為 0.7。

注意

如果提供 controlStrength controlMode 或 ,則 conditionImage 也必須提供 。

Color Guided Content (Request) V2 only

提供十六進位顏色代碼清單以及文字提示,以產生色彩調色盤之後的影像。產生映像時需要文字提示,必須 <= 512 個字元。較長端的解析度上限為 1,408。需要 1 到 10 個十六進位顏色代碼的清單,才能在產生的映像中指定顏色。 negativeText 選用 文字提示,以定義影像中不包含的內容 <= 512 個字元。 referenceImage 選用額外的參考映像,以引導產生映像中的調色盤。使用者上傳的RGB參考影像大小限制在較長邊 <= 1,408。

{ "taskType": "COLOR_GUIDED_GENERATION", "colorGuidedGenerationParams": { "text": "string", "negativeText": "string", "referenceImage" "base64-encoded string", # [OPTIONAL] "colors": ["string"] # list of color hex codes }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float, "seed": int } }

colorGuidedGeneration參數欄位如下所述。請注意,此參數僅適用於 V2。

  • text (必要) — 用於產生影像的文字提示。

  • color (必要) – 最多 10 個十六進位顏色代碼的清單,用於在產生的映像中指定顏色。

  • negativeText (選用) – 文字提示,用於定義影像中不包含的內容。

    注意

    不要在 negativeText 提示中使用否定性字詞。例如,若您不想在影像中包含鏡像,請在 negativeText 提示中輸入 mirrors。請勿輸入 no mirrors

  • referenceImage (選用) – 單一輸入參考影像,可引導產生影像的調色盤。影像定義為 base64 編碼的影像字串。

Background Removal (Request)

背景移除任務類型會自動識別輸入映像中的多個物件,並移除背景。輸出映像具有透明背景。

請求格式

{ "taskType": "BACKGROUND_REMOVAL", "backgroundRemovalParams": { "image": "base64-encoded string" } }

回應格式

{ "images": [ "base64-encoded string", ... ], "error": "string" }

backgroundRemovalParams 欄位如下所述。

  • image (必要) – 要修改、格式化為指定像素序列的字串的 JPEG或 PNG映像,每個都以RGB值定義,並在 base64 中編碼。

Response body
{ "images": [ "base64-encoded string", ... ], "error": "string" }

回應主體是包含下列其中一個欄位的串流物件。

  • images – 如果請求成功,則會傳回此欄位 base64 編碼字串的清單,每個字串都會定義產生的影像。每個影像的格式都是指定像素序列的字串,每個像素都以RGB值定義,並在 base64 中編碼。有關如何將影像編碼為 base64 並解碼 base64 編碼的字串,再將其轉換為影像的範例,請參閱程式碼範例

  • error – 如果在下列其中一種情況下,請求違反內容管制政策,則會在此欄位中傳回訊息。

    • 如果輸入文字、影像或遮罩影像已由內容管制政策加上旗標。

    • 如果內容管制政策在至少一個輸出影像加上旗標

產生映像的文字提示必須 <= 512 個字元。較長端的解析度 <= 1,408。 negativeText (選用) – 文字提示,用於定義不包含在 <= 512 個字元的影像中。如需完整的解析度清單,請參閱下表。

{ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "string", "negativeText": "string" }, "imageGenerationConfig": { "numberOfImages": int, "height": int, "width": int, "cfgScale": float, "seed": int } }

這些 textToImageParams 欄位如下所述。

  • text (必要) — 用於產生影像的文字提示。

  • negativeText (選用) – 文字提示,用於定義影像中不包含的內容。

    注意

    不要在 negativeText 提示中使用否定性字詞。例如,若您不想在影像中包含鏡像,請在 negativeText 提示中輸入 mirrors。請勿輸入 no mirrors

共享和選用的 imageGenerationConfig 包含下列欄位。如果您未包含此物件,則使用預設組態。

  • numberOfImages (選用) – 要產生的映像數量。

    下限 最大 預設
    1 5 1
  • cfgScale (選用) – 指定產生的映像應遵循提示的程度。使用較低的值可在產生時導入更多隨機性。

    下限 最大 預設
    1.1 10.0 8.0
  • 以下參數定義您希望的輸出影像大小。如需有關按照影像大小定價的詳細資訊,請參閱 Amazon Bedrock 定價

    • height (選用) – 影像的高度 (以像素為單位)。預設值為 1408。

    • width (選用) – 影像的寬度 (以像素為單位)。預設值為 1408。

    以下是允許的尺寸。

    寬度 Height (高度) 長寬比 價格等於
    1024 1024 1:1 1024 x 1024
    768 768 1:1 512 x 512
    512 512 1:1 512 x 512
    768 1152 2:3 1024 x 1024
    384 576 2:3 512 x 512
    1152 768 3:2 1024 x 1024
    576 384 3:2 512 x 512
    768 1280 3:5 1024 x 1024
    384 640 3:5 512 x 512
    1280 768 5:3 1024 x 1024
    640 384 5:3 512 x 512
    896 1152 7:9 1024 x 1024
    448 576 7:9 512 x 512
    1152 896 9:7 1024 x 1024
    576 448 9:7 512 x 512
    768 1408 6:11 1024 x 1024
    384 704 6:11 512 x 512
    1408 768 11:6 1024 x 1024
    704 384 11:6 512 x 512
    640 1408 5:11 1024 x 1024
    320 704 5:11 512 x 512
    1408 640 11:5 1024 x 1024
    704 320 11:5 512 x 512
    1152 640 9:5 1024 x 1024
    1173 640 16:9 1024 x 1024
  • seed (選用) — 用來控制和重現結果。決定初始雜訊設定。使用與先前執行相同的種子和相同的設定,以允許推論建立相似的影像。

    下限 最大 預設
    0 2,147,483,646 42

範例

下列範例示範如何在 Python 中使用隨需輸送量叫用 Amazon Titan Image Generator 模型SDK。選取標籤以檢視每個使用案例的範例。每個範例都會在最後顯示影像。

Text-to-image generation
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image from a text prompt with the Amazon Titan Image Generator G1 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator G1" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator G1 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator G1 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator G1 example. """ logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v1' prompt = """A photograph of a cup of coffee from the side.""" body = json.dumps({ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": prompt }, "imageGenerationConfig": { "numberOfImages": 1, "height": 1024, "width": 1024, "cfgScale": 8.0, "seed": 0 } }) try: image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.") if __name__ == "__main__": main()
Inpainting
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to use inpainting to generate an image from a source image with the Amazon Titan Image Generator G1 model (on demand). The example uses a mask prompt to specify the area to inpaint. """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator G1" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator G1 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator G1 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator G1 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v1' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "INPAINTING", "inPaintingParams": { "text": "Modernize the windows of the house", "negativeText": "bad quality, low res", "image": input_image, "maskPrompt": "windows" }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.") if __name__ == "__main__": main()
Outpainting
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to use outpainting to generate an image from a source image with the Amazon Titan Image Generator G1 model (on demand). The example uses a mask image to outpaint the original image. """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator G1" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator G1 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator G1 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator G1 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v1' # Read image and mask image from file and encode as base64 strings. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') with open("/path/to/mask_image", "rb") as mask_image_file: input_mask_image = base64.b64encode( mask_image_file.read()).decode('utf8') body = json.dumps({ "taskType": "OUTPAINTING", "outPaintingParams": { "text": "Draw a chocolate chip cookie", "negativeText": "bad quality, low res", "image": input_image, "maskImage": input_mask_image, "outPaintingMode": "DEFAULT" }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } } ) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.") if __name__ == "__main__": main()
Image variation
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image variation from a source image with the Amazon Titan Image Generator G1 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator G1" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator G1 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator G1 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator G1 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v1' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "IMAGE_VARIATION", "imageVariationParams": { "text": "Modernize the house, photo-realistic, 8k, hdr", "negativeText": "bad quality, low resolution, cartoon", "images": [input_image], "similarityStrength": 0.7, # Range: 0.2 to 1.0 }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.") if __name__ == "__main__": main()
Image conditioning (V2 only)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate image conditioning from a source image with the Amazon Titan Image Generator G1 V2 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator V2" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator V2 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator V2 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator V2 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator V2 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v2:0' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "A robot playing soccer, anime cartoon style", "negativeText": "bad quality, low res", "conditionImage": input_image, "controlMode": "CANNY_EDGE" }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator V2 model {model_id}.") if __name__ == "__main__": main()
Color guided content (V2 only)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image from a source image color palette with the Amazon Titan Image Generator G1 V2 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator V2" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator V2 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator V2 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator V2 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator V2 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v2:0' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "COLOR_GUIDED_GENERATION", "colorGuidedGenerationParams": { "text": "digital painting of a girl, dreamy and ethereal, pink eyes, peaceful expression, ornate frilly dress, fantasy, intricate, elegant, rainbow bubbles, highly detailed, digital painting, artstation, concept art, smooth, sharp focus, illustration", "negativeText": "bad quality, low res", "referenceImage": input_image, "colors": ["#ff8080", "#ffb280", "#ffe680", "#ffe680"] }, "imageGenerationConfig": { "numberOfImages": 1, "height": 512, "width": 512, "cfgScale": 8.0 } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator V2 model {model_id}.") if __name__ == "__main__": main()
Background removal (V2 only)
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image with background removal with the Amazon Titan Image Generator G1 V2 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator V2" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator V2 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator V2 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator V2 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator V2 example. """ try: logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v2:0' # Read image from file and encode it as base64 string. with open("/path/to/image", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode('utf8') body = json.dumps({ "taskType": "BACKGROUND_REMOVAL", "backgroundRemovalParams": { "image": input_image, } }) image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator V2 model {model_id}.") if __name__ == "__main__": main()
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate an image from a text prompt with the Amazon Titan Image Generator G1 model (on demand). """ import base64 import io import json import logging import boto3 from PIL import Image from botocore.exceptions import ClientError class ImageError(Exception): "Custom exception for errors returned by Amazon Titan Image Generator G1" def __init__(self, message): self.message = message logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_image(model_id, body): """ Generate an image using Amazon Titan Image Generator G1 model on demand. Args: model_id (str): The model ID to use. body (str) : The request body to use. Returns: image_bytes (bytes): The image generated by the model. """ logger.info( "Generating image with Amazon Titan Image Generator G1 model %s", model_id) bedrock = boto3.client(service_name='bedrock-runtime') accept = "application/json" content_type = "application/json" response = bedrock.invoke_model( body=body, modelId=model_id, accept=accept, contentType=content_type ) response_body = json.loads(response.get("body").read()) base64_image = response_body.get("images")[0] base64_bytes = base64_image.encode('ascii') image_bytes = base64.b64decode(base64_bytes) finish_reason = response_body.get("error") if finish_reason is not None: raise ImageError(f"Image generation error. Error is {finish_reason}") logger.info( "Successfully generated image with Amazon Titan Image Generator G1 model %s", model_id) return image_bytes def main(): """ Entrypoint for Amazon Titan Image Generator G1 example. """ logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s") model_id = 'amazon.titan-image-generator-v1' prompt = """A photograph of a cup of coffee from the side.""" body = json.dumps({ "taskType": "TEXT_IMAGE", "textToImageParams": { "text": prompt }, "imageGenerationConfig": { "numberOfImages": 1, "height": 1024, "width": 1024, "cfgScale": 8.0, "seed": 0 } }) try: image_bytes = generate_image(model_id=model_id, body=body) image = Image.open(io.BytesIO(image_bytes)) image.show() except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) except ImageError as err: logger.error(err.message) print(err.message) else: print( f"Finished generating image with Amazon Titan Image Generator G1 model {model_id}.") if __name__ == "__main__": main()
隱私權網站條款Cookie 偏好設定
© 2025, Amazon Web Services, Inc.或其附屬公司。保留所有權利。