视觉语言模型
视觉语言模型是能够理解和处理图像信息的大语言模型,它们可以分析图像内容、回答关于图像的问题,并生成与图像相关的文本描述。
概述
视觉语言模型结合了计算机视觉和自然语言处理的能力,使模型能够:
- 理解图像内容
- 回答关于图像的问题
- 生成图像描述
- 执行图像相关的推理任务
支持的模型
平台支持多种视觉语言模型,包括但不限于:
- GPT-4V
- Qwen-VL 系列
- Claude 3 Vision
- LLaVA
使用方法
基本用法
python
import openai
client = openai.OpenAI(
api_key="your_api_key",
base_url="https://realmrouter.cn/v1"
)
response = client.chat.completions.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "请描述这张图片的内容"
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg"
}
}
]
}
],
max_tokens=500
)
print(response.choices[0].message.content)使用 Base64 编码图像
python
import base64
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
base64_image = encode_image("path/to/your/image.jpg")
response = client.chat.completions.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "这张图片里有什么?"
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
],
max_tokens=500
)多图像对比分析
python
response = client.chat.completions.create(
model="qwen/qwen2.5-vl-72b-instruct",
messages=[
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://example.com/product1.jpg"
}
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/product2.jpg"
}
},
{
"type": "text",
"text": "请对比一下这两个产品的主要区别。"
}
]
}
],
stream=True
)
for chunk in response:
print(chunk.choices[0].delta.content or "", end="", flush=True)参数说明
重要参数
model: 指定使用的视觉语言模型messages: 包含图像和文本的消息数组max_tokens: 生成文本的最大长度temperature: 控制输出的随机性(0-2)stream: 是否使用流式输出
图像格式支持
- 支持的格式:PNG, JPEG, GIF, WebP
- 图像大小限制:建议不超过 10MB
- Base64 编码:支持 data:image/jpeg;base64, 格式
常见问题与说明
- 图像分辨率与清晰度会影响模型识别准确率,推荐使用清晰图源。
- Base64 编码体积较大,建议图片不超过 1MB。
- 如遇问题请参考平台开发者文档或提交工单获取支持。
最佳实践
- 图像质量:使用高清晰度、构图清晰的图像
- 问题明确:提供具体、明确的问题或指令
- 上下文丰富:在文本中提供足够的上下文信息
- 批量处理:对于大量图像,考虑使用批量 API
- 错误处理:实现适当的错误处理和重试机制
限制和注意事项
- 不同模型对图像的理解能力可能有差异
- 某些模型可能对特定类型的图像处理效果更好
- 建议在生产环境中进行充分的测试