选择您的 Cookie 首选项

我们使用必要 Cookie 和类似工具提供我们的网站和服务。我们使用性能 Cookie 收集匿名统计数据,以便我们可以了解客户如何使用我们的网站并进行改进。必要 Cookie 无法停用,但您可以单击“自定义”或“拒绝”来拒绝性能 Cookie。

如果您同意,AWS 和经批准的第三方还将使用 Cookie 提供有用的网站功能、记住您的首选项并显示相关内容,包括相关广告。要接受或拒绝所有非必要 Cookie,请单击“接受”或“拒绝”。要做出更详细的选择,请单击“自定义”。

Amazon Titan 图像生成器 G1 模型

聚焦模式
Amazon Titan 图像生成器 G1 模型 - Amazon Bedrock

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

Amazon Titan Image Generator G1 V1 以及 Titan Image Generator G1 V2 模型在执行模型推理时支持以下推理参数和模型响应。

推理参数

当您使用 Amazon Titan 图像生成器模型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) 来定义掩膜覆盖区域。

    • 定义为 (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.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 字段的定义如下。

  • images(必要)– 要生成变体的图片列表。您可以包含 1 到 5 张图像。图像被定义为 base64 编码的图像字符串。有关如何将图像编码为 base64 以及如何对 base64 编码的字符串进行解码并将其转换为图像的示例,请参阅代码示例

  • text(可选)– 定义图像中要保留什么内容、要更改什么内容的文本提示。

  • similarityStrength(可选)-指定生成的图像应与输入图像的相似程度。范围介于 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(仅限 Optional-V2)— 用于指导生成图像的布局和构图的单个输入调节图像。图像被定义为 base64 编码的图像字符串。有关如何将图像编码为 base64 以及如何对 base64 编码的字符串进行解码并将其转换为图像的示例。

  • controlMode(仅限 Optional-V2)— 指定应使用哪种类型的调节模式。支持两种类型的调节模式:CANNY_ EDGE 和SEGMENTATION。默认值为 CANNY _ EDGE。

  • controlStrength(仅限 Optional-V2)— 指定生成的图像的布局和构图应与的相似程度。conditioningImage范围介于 0 到 1.0 之间,使用较低的值可引入更多的随机性。默认值为 0.7。

注意

如果提供了 controlMode 或 controlStrength ,则还 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(必要)– 用于生成图像的文本提示。

  • colors(必要)– 最多 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。

    允许使用以下尺寸。

    宽度 高度 纵横比 价格相当于
    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 1 280 3:5 1024 x 1024
    384 640 3:5 512 x 512
    1 280 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 SDK Titan 图像生成器模型。选择一个选项卡查看每个用例的示例。每个示例最后都显示了图像。

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. 或其附属公司。保留所有权利。