使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务

使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务

亚马逊基岩 提供来自亚马逊和其他领先人工智能公司的广泛高性能基础模型,包括 人类的, AI21, , 凝聚力稳定人工智能,并涵盖广泛的用例,包括文本和图像生成、搜索、聊天、推理和代理等。新的 亚马逊泰坦图像生成器 模型允许内容创建者使用简单的英文文本提示快速生成高质量、逼真的图像。先进的人工智能模型可以理解多个对象的复杂指令,并返回适合的工作室质量图像 广告, 电子商务, 和 娱乐。主要功能包括通过迭代提示、自动背景编辑以及生成同一场景的多个变体来细化图像的能力。创作者还可以使用自己的数据自定义模型,以特定风格输出品牌图像。重要的是,Titan Image Generator 具有内置的保护措施,例如所有人工智能生成的图像上的隐形水印,以鼓励 负责任地使用 并减少虚假信息的传播。这项创新技术可以大批量生产定制图像 任何行业 更方便、更高效。

新的 Amazon Titan 多模式嵌入 模型通过理解文本、图像或两者来帮助构建更准确的搜索和推荐。它将图像和英文文本转换为语义向量,捕获数据中的含义和关系。您可以结合文本和图像(例如产品描述和照片)来更有效地识别商品。这些矢量提供快速、准确的搜索体验。 Titan Multimodal Embeddings 在向量维度上非常灵活,可以根据性能需求进行优化。异步 API 和 亚马逊开放搜索服务 连接器可以轻松地将模型集成到您的神经搜索应用程序中。

在这篇文章中,我们将介绍如何通过 AWS Python SDK 使用 Titan 图像生成器和 Titan 多模态嵌入模型。

图像生成和编辑

在本部分中,我们将演示使用 AWS 开发工具包生成新图像并对现有图像执行 AI 支持的编辑的基本编码模式。代码示例以 Python 形式提供,JavaScript (Node.js) 也可在此处使用 GitHub存储库.

在编写使用 Amazon Bedrock API 的脚本之前,您需要在您的环境中安装适当版本的 AWS 开发工具包。对于 Python 脚本,您可以使用 适用于Python的AWS开发工具包(Boto3)。 Python 用户可能还想安装 枕头模块,这方便了加载和保存图像等图像操作。有关设置说明,请参阅 GitHub存储库.

此外,还允许访问 Amazon Titan Image Generator 和 Titan Multimodal Embeddings 模型。欲了解更多信息,请参阅 模型访问.

辅助函数

以下函数设置 Amazon Bedrock Boto3 运行时客户端并通过获取不同配置的负载生成图像(我们将在本文后面讨论):

import boto3
import json, base64, io
from random import randint
from PIL import Image bedrock_runtime_client = boto3.client("bedrock-runtime") def titan_image( payload: dict, num_image: int = 2, cfg: float = 10.0, seed: int = None, modelId: str = "amazon.titan-image-generator-v1",
) -> list: # ImageGenerationConfig Options: # - numberOfImages: Number of images to be generated # - quality: Quality of generated images, can be standard or premium # - height: Height of output image(s) # - width: Width of output image(s) # - cfgScale: Scale for classifier-free guidance # - seed: The seed to use for reproducibility seed = seed if seed is not None else randint(0, 214783647) body = json.dumps( { **payload, "imageGenerationConfig": { "numberOfImages": num_image, # Range: 1 to 5 "quality": "premium", # Options: standard/premium "height": 1024, # Supported height list above "width": 1024, # Supported width list above "cfgScale": cfg, # Range: 1.0 (exclusive) to 10.0 "seed": seed, # Range: 0 to 214783647 }, } ) response = bedrock_runtime_client.invoke_model( body=body, modelId=modelId, accept="application/json", contentType="application/json", ) response_body = json.loads(response.get("body").read()) images = [ Image.open(io.BytesIO(base64.b64decode(base64_image))) for base64_image in response_body.get("images") ] return images 

从文本生成图像

从文本提示生成新图像的脚本遵循以下实现模式:

  1. 配置文本提示和可选的否定文本提示。
  2. 使用 BedrockRuntime 客户端调用 Titan Image Generator 模型。
  3. 解析并解码响应。
  4. 将生成的图像保存到磁盘。

文本到图像

以下是Titan Image Generator模型的典型图像生成脚本:

# Text Variation
# textToImageParams Options:
#   text: prompt to guide the model on how to generate variations
#   negativeText: prompts to guide the model on what you don't want in image
images = titan_image( { "taskType": "TEXT_IMAGE", "textToImageParams": { "text": "two dogs walking down an urban street, facing the camera", # Required "negativeText": "cars", # Optional }, }
)

这将产生类似于以下的图像。

响应图像 1 响应图像 2
2只狗在街上行走 2只狗在街上行走

图像变体

图像变体提供了一种生成现有图像的细微变体的方法。以下代码片段使用上一示例中生成的图像之一来创建变体图像:

# Import an input image like this (only PNG/JPEG supported):
with open("<YOUR_IMAGE_FILE_PATH>", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode("utf8") # Image Variation
# ImageVariationParams Options:
#   text: prompt to guide the model on how to generate variations
#   negativeText: prompts to guide the model on what you don't want in image
#   images: base64 string representation of the input image, only 1 is supported
images = titan_image( { "taskType": "IMAGE_VARIATION", "imageVariationParams": { "text": "two dogs walking down an urban street, facing the camera", # Required "images": [input_image], # One image is required "negativeText": "cars", # Optional }, },
)

这将产生类似于以下的图像。

原始图像 响应图像 1 响应图像 2
2只狗在街上行走 使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。 使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。

编辑现有图像

Titan 图像生成器模型允许您添加、删除或替换现有图像中的元素或区域。您可以通过提供以下选项之一来指定要影响的区域:

  • 蒙版图片 – 蒙版图像是二值图像,其中 0 值像素代表要影响的区域,255 值像素代表应保持不变的区域。
  • 面膜提示 – 掩码提示是您想要影响的元素的自然语言文本描述,它使用内部文本到分段模型。

有关更多信息,请参阅 及时的工程指南.

对图像应用编辑的脚本遵循以下实现模式:

  1. 从磁盘加载要编辑的图像。
  2. 将图像转换为 Base64 编码的字符串。
  3. 通过以下方法之一配置掩码:
    1. 从磁盘加载蒙版图像,将其编码为 base64 并将其设置为 maskImage 参数。
    2. 设置 maskText 参数到要影响的元素的文本描述。
  4. 使用以下选项之一指定要生成的新内容:
    1. 要添加或替换元素,请设置 text 参数来描述新内容。
    2. 要删除元素,请省略 text 参数完全。
  5. 使用 BedrockRuntime 客户端调用 Titan Image Generator 模型。
  6. 解析并解码响应。
  7. 将生成的图像保存到磁盘。

对象编辑:使用蒙版图像进行修复

以下是使用 Titan Image Generator 模型的典型图像编辑脚本 maskImage。我们采用之前生成的图像之一并提供蒙版图像,其中 0 值像素渲染为黑色,255 值像素渲染为白色。我们还使用文本提示将图像中的一只狗替换为一只猫。

with open("<YOUR_MASK_IMAGE_FILE_PATH>", "rb") as image_file: mask_image = base64.b64encode(image_file.read()).decode("utf8") # Import an input image like this (only PNG/JPEG supported):
with open("<YOUR_ORIGINAL_IMAGE_FILE_PATH>", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode("utf8") # Inpainting
# inPaintingParams Options:
#   text: prompt to guide inpainting
#   negativeText: prompts to guide the model on what you don't want in image
#   image: base64 string representation of the input image
#   maskImage: base64 string representation of the input mask image
#   maskPrompt: prompt used for auto editing to generate mask images = titan_image( { "taskType": "INPAINTING", "inPaintingParams": { "text": "a cat", # Optional "negativeText": "bad quality, low res", # Optional "image": input_image, # Required "maskImage": mask_image, }, }, num_image=3,
)

这将产生类似于以下的图像。

原始图像 遮罩图像 编辑图像
2只狗在街上行走 使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。 猫和狗在街上行走

对象移除:使用蒙​​版提示进行修复

在另一个例子中,我们使用 maskPrompt 指定图像中要编辑的对象(取自前面的步骤)。通过省略文本提示,该对象将被删除:

# Import an input image like this (only PNG/JPEG supported):
with open("<YOUR_IMAGE_FILE_PATH>", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode("utf8") images = titan_image( { "taskType": "INPAINTING", "inPaintingParams": { "negativeText": "bad quality, low res", # Optional "image": input_image, # Required "maskPrompt": "white dog", # One of "maskImage" or "maskPrompt" is required }, },
)

这将产生类似于以下的图像。

原始图像 响应图像
2只狗在街上行走 一只狗在街上行走

背景编辑:Outpainting

当您想要替换图像的背景时,外画非常有用。您还可以扩展图像的边界以获得缩小效果。在下面的示例脚本中,我们使用 maskPrompt 指定要保留哪个对象;你也可以使用 maskImage。 参数 outPaintingMode 指定是否允许修改蒙版内的像素。如果设置为 DEFAULT,允许修改掩模内部的像素,以便重建图像整体一致。如果 maskImage 提供的并不表示具有像素级精度的对象。如果设置为 PRECISE,防止修改掩模内部的像素。如果使用 maskPrompt 或者 maskImage 以像素级精度表示对象。

# Import an input image like this (only PNG/JPEG supported):
with open("<YOUR_IMAGE_FILE_PATH>", "rb") as image_file: input_image = base64.b64encode(image_file.read()).decode("utf8") # OutPaintingParams Options:
#   text: prompt to guide outpainting
#   negativeText: prompts to guide the model on what you don't want in image
#   image: base64 string representation of the input image
#   maskImage: base64 string representation of the input mask image
#   maskPrompt: prompt used for auto editing to generate mask
#   outPaintingMode: DEFAULT | PRECISE
images = titan_image( { "taskType": "OUTPAINTING", "outPaintingParams": { "text": "forest", # Required "image": input_image, # Required "maskPrompt": "dogs", # One of "maskImage" or "maskPrompt" is required "outPaintingMode": "PRECISE", # One of "PRECISE" or "DEFAULT" }, }, num_image=3,
)

这将产生类似于以下的图像。

原始图像 文本 响应图像
2只狗在街上行走 “海滩” 一只狗在海滩上散步
2只狗在街上行走 “森林” 使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。

另外,不同值的影响 outPaintingMode,一个 maskImage 不以像素级精度勾勒出对象的轮廓,如下所示。

本节概述了可以使用 Titan Image Generator 模型执行的操作。具体来说,这些脚本演示了文本到图像、图像变化、修复和修复任务。您应该能够通过参考这些任务类型的参数详细信息来调整您自己的应用程序的模式 Amazon Titan 图像生成器文档.

多模态嵌入和搜索

您可以使用 Amazon Titan 多模态嵌入模型来执行图像搜索和基于相似性的推荐等企业任务,并且它具有内置的缓解措施,有助于减少搜索结果中的偏差。有多种嵌入维度大小可针对不同需求实现最佳延迟/准确性权衡,并且所有嵌入维度大小都可以使用简单的 API 进行自定义,以适应您自己的数据,同时保持数据安全和隐私。 Amazon Titan Multimodal Embeddings 作为简单的 API 提供,用于实时或异步批量转换搜索和推荐应用程序,并且可以连接到不同的矢量数据库,包括 亚马逊开放搜索服务.

辅助函数

以下函数将图像(以及可选的文本)转换为多模式嵌入:

def titan_multimodal_embedding( image_path: str = None, # maximum 2048 x 2048 pixels description: str = None, # English only and max input tokens 128 dimension: int = 1024, # 1,024 (default), 384, 256 model_id: str = "amazon.titan-embed-image-v1",
): payload_body = {} embedding_config: dict = {"embeddingConfig": {"outputEmbeddingLength": dimension}} # You can specify either text or image or both if image_path: # Maximum image size supported is 2048 x 2048 pixels with open(image_path, "rb") as image_file: payload_body["inputImage"] = base64.b64encode(image_file.read()).decode( "utf8" ) if description: payload_body["inputText"] = description assert payload_body, "please provide either an image and/or a text description" print("n".join(payload_body.keys())) response = bedrock_runtime_client.invoke_model( body=json.dumps({**payload_body, **embedding_config}), modelId=model_id, accept="application/json", contentType="application/json", ) return json.loads(response.get("body").read())

以下函数返回给定查询多模态嵌入的最相似的多模态嵌入。请注意,在实践中,您可以使用托管矢量数据库,例如 OpenSearch Service。以下示例用于说明目的:

from scipy.spatial.distance import cdist
import numpy as np def search(query_emb: np.array, indexes: np.array, top_k: int = 1): dist = cdist(query_emb, indexes, metric="cosine") return dist.argsort(axis=-1)[0, :top_k], np.sort(dist, axis=-1)[:top_k]

综合数据集

为了说明目的,我们使用 亚马逊基岩中的 Anthropic 的 Claude 2.1 模型 使用以下提示随机生成七种不同的产品,每种产品都有三种变体:

Generate a list of 7 items description for an online e-commerce shop, each comes with 3 variants of color or type. All with separate full sentence description.

以下是返回的输出列表:

1. T-shirt
- A red cotton t-shirt with a crew neck and short sleeves.
- A blue cotton t-shirt with a v-neck and short sleeves.
- A black polyester t-shirt with a scoop neck and cap sleeves. 2. Jeans
- Classic blue relaxed fit denim jeans with a mid-rise waist.
- Black skinny fit denim jeans with a high-rise waist and ripped details at the knees.
- Stonewash straight leg denim jeans with a standard waist and front pockets. 3. Sneakers
- White leather low-top sneakers with an almond toe cap and thick rubber outsole.
- Gray mesh high-top sneakers with neon green laces and a padded ankle collar.
- Tan suede mid-top sneakers with a round toe and ivory rubber cupsole. 4. Backpack
- A purple nylon backpack with padded shoulder straps, front zipper pocket and laptop sleeve.
- A gray canvas backpack with brown leather trims, side water bottle pockets and drawstring top closure.
- A black leather backpack with multiple interior pockets, top carry handle and adjustable padded straps. 5. Smartwatch
- A silver stainless steel smartwatch with heart rate monitor, GPS tracker and sleep analysis.
- A space gray aluminum smartwatch with step counter, phone notifications and calendar syncing.
- A rose gold smartwatch with activity tracking, music controls and customizable watch faces. 6. Coffee maker
- A 12-cup programmable coffee maker in brushed steel with removable water tank and keep warm plate.
- A compact 5-cup single serve coffee maker in matt black with travel mug auto-dispensing feature.
- A retro style stovetop percolator coffee pot in speckled enamel with stay-cool handle and glass knob lid. 7. Yoga mat
- A teal 4mm thick yoga mat made of natural tree rubber with moisture-wicking microfiber top.
- A purple 6mm thick yoga mat made of eco-friendly TPE material with integrated carrying strap.
- A patterned 5mm thick yoga mat made of PVC-free material with towel cover included.

将上述响应分配给变量 response_cat。然后我们使用 Titan Image Generator 模型为每个项目创建产品图像:

import re def extract_text(input_string): pattern = r"- (.*?)($|n)" matches = re.findall(pattern, input_string) extracted_texts = [match[0] for match in matches] return extracted_texts product_description = extract_text(response_cat) titles = []
for prompt in product_description: images = titan_image( { "taskType": "TEXT_IMAGE", "textToImageParams": { "text": prompt, # Required }, }, num_image=1, ) title = "_".join(prompt.split()[:4]).lower() titles.append(title) images[0].save(f"{title}.png", format="png")

所有生成的图像都可以在本文末尾的附录中找到。

多模式数据集索引

使用以下代码进行多模式数据集索引:

multimodal_embeddings = []
for image_filename, description in zip(titles, product_description): embedding = titan_multimodal_embedding(f"{image_filename}.png", dimension=1024)["embedding"] multimodal_embeddings.append(embedding)

多模态搜索

使用以下代码进行多模式搜索:

query_prompt = "<YOUR_QUERY_TEXT>"
query_embedding = titan_multimodal_embedding(description=query_prompt, dimension=1024)["embedding"]
# If searching via Image
# query_image_filename = "<YOUR_QUERY_IMAGE>"
# query_emb = titan_multimodal_embedding(image_path=query_image_filename, dimension=1024)["embedding"]
idx_returned, dist = search(np.array(query_embedding)[None], np.array(multimodal_embeddings))

以下是一些搜索结果。

结论

该文章介绍了 Amazon Titan 图像生成器和 Amazon Titan 多模式嵌入模型。 Titan 图像生成器使您能够根据文本提示创建自定义的高质量图像。主要功能包括迭代提示、自动后台编辑和数据定制。它具有隐形水印等保护措施,以鼓励负责任的使用。 Titan 多模态嵌入将文本、图像或两者都转换为语义向量,以支持准确的搜索和推荐。然后,我们提供了使用这些服务的 Python 代码示例,并演示了根据文本提示生成图像并迭代这些图像;通过添加、删除或替换蒙版图像或蒙版文本指定的元素来编辑现有图像;从文本、图像或两者创建多模态嵌入;并搜索与查询类似的多模态嵌入。我们还演示了如何使用使用 Titan Multimodal Embeddings 进行索引和搜索的合成电子商务数据集。这篇文章的目的是让开发人员能够开始在他们的应用程序中使用这些新的人工智能服务。代码模式可以用作自定义实现的模板。

所有代码都可以在 GitHub存储库. 有关详细信息,请参阅 亚马逊基岩用户指南.


作者简介

使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。罗希特·米塔尔 是 Amazon AI 的首席产品经理,负责构建多模式基础模型。他最近领导推出了 Amazon Titan Image Generator 模型,作为 Amazon Bedrock 服务的一部分。他在 AI/ML、NLP 和搜索方面拥有丰富经验,有兴趣构建通过创新技术解决客户痛点的产品。

使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。阿什温·斯瓦米纳坦博士 是一名计算机视觉和机器学习研究员、工程师和经理,拥有 12 年以上行业经验和 5 年以上学术研究经验。扎实的基础知识和经过验证的快速获取知识并为新兴领域做出贡献的能力。

使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。谢玉生博士 是 Amazon AGI 的首席应用科学家。他的工作重点是构建多模式基础模型。在加入 AGI 之前,他在 AWS 领导各种多模式 AI 开发,例如 Amazon Titan Image Generator 和 Amazon Textract Queries。

使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。杨浩博士 是亚马逊的首席应用科学家。他的主要研究兴趣是对象检测和有限注释学习。工作之余,郝喜欢看电影、摄影和户外活动。

使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。达维德·莫多洛博士 是 Amazon AGI 的应用科学经理,致力于构建大型多模式基础模型。在加入 Amazon AGI 之前,他在 AWS AI 实验室(Amazon Bedrock 和 Amazon Rekognition)担任经理/主管 7 年。工作之余,他喜欢旅行和参加任何类型的运动,尤其是足球。

使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。孙百川博士, 目前担任 AWS 的高级 AI/ML 解决方案架构师,专注于生成式 AI,并运用他在数据科学和机器学习方面的知识来提供实用的、基于云的业务解决方案。凭借管理咨询和人工智能解决方案架构方面的经验,他解决了一系列复杂的挑战,包括机器人计算机视觉、时间序列预测和预测性维护等。他的工作建立在项目管理、软件研发和学术追求的坚实背景之上。工作之余,孙博士喜欢旅行以及与家人和朋友共度时光。

使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。朱凯博士 目前在 AWS 担任云支持工程师,帮助客户解决 SageMaker、Bedrock 等 AI/ML 相关服务中的问题。他是 SageMaker 主题专家。他在数据科学和数据工程方面拥有丰富的经验,对构建生成式人工智能驱动的项目感兴趣。

使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。克里斯·舒尔茨 25 年来,我们通过将新兴技术与世界一流的设计相结合,将引人入胜的用户体验变为现实。作为高级产品经理,Kris 帮助设计和构建 AWS 服务,为媒体和娱乐、游戏和空间计算提供支持。


附录

在以下部分中,我们将演示具有挑战性的示例用例,例如文本插入、手和反射,以突出 Titan 图像生成器模型的功能。我们还包括前面示例中生成的示例输出图像。

文本

Titan 图像生成器模型擅长复杂的工作流程,例如将可读文本插入图像中。此示例演示了 Titan 在图像中以一致的风格清晰渲染大写和小写字母的能力。

一只戴着棒球帽的柯基犬,上面写着“genai” 一个快乐的男孩竖起大拇指,身穿印有“生成人工智能”字样的 T 恤
使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。 使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。

Titan Image Generator 模型还能够生成详细的 AI 图像。该图像显示了具有可见细节的真实手和手指,超越了可能缺乏这种特异性的更基本的人工智能图像生成。在以下示例中,请注意姿势和解剖结构的精确描述。

从上面看一个人的手 仔细观察一个人拿着咖啡杯的手
使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。 使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。

镜子

Titan 图像生成器模型生成的图像在空间上排列对象并准确反映镜像效果,如以下示例所示。

一只可爱的毛茸茸的白猫用后腿站立,好奇地凝视着华丽的金色镜子。猫在倒影中看到了自己 美丽的天空湖,水面上的倒影
使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。 使用 Amazon Titan 模型进行图像生成、编辑和搜索 |亚马逊网络服务柏拉图区块链数据智能。垂直搜索。人工智能。

合成产品图像

以下是本文前面为 Titan 多模态嵌入模型生成的产品图像。

时间戳记:

更多来自 AWS机器学习