视觉语言模型 Qwen2-VL

视觉语言模型 Qwen2-VL

flyfish

py 复制代码
from PIL import Image
import requests
import torch
from torchvision import io
from typing import Dict
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from modelscope import snapshot_download

# 下载模型快照并指定保存目录
model_dir = snapshot_download("qwen/Qwen2-VL-7B-Instruct")

# 加载模型到可用设备(CPU或GPU),并使用自动精度(根据设备自动选择)
model = Qwen2VLForConditionalGeneration.from_pretrained(
    model_dir, torch_dtype="auto", device_map="auto"
)

# 加载图像处理器
processor = AutoProcessor.from_pretrained(model_dir)

# 图像的URL
url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"

# 从给定的URL加载图像
image = Image.open(requests.get(url, stream=True).raw)

# 定义对话历史,包括用户输入的文本和图像
conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]

# 使用处理器应用聊天模板,并添加生成提示
text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)

# 预处理输入数据,将文本和图像转换为模型可以接受的格式
inputs = processor(
    text=[text_prompt], images=[image], padding=True, return_tensors="pt"
)

# 将输入数据移动到CUDA设备上(如果可用的话)
inputs = inputs.to("cuda")

# 推理:生成输出文本
output_ids = model.generate(**inputs, max_new_tokens=128)  # 最大新生成token数量为128

# 提取生成的token ID,去掉输入的原始token ID
generated_ids = [
    output_ids[len(input_ids) :]
    for input_ids, output_ids in zip(inputs.input_ids, output_ids)
]

# 解码生成的token ID为人类可读的文本
output_text = processor.batch_decode(
    generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
)

# 打印生成的描述文本
print(output_text)
相关推荐
冬奇Lab1 小时前
OpenClaw 深度解析(八):Skill 系统——让 LLM 按需学习工作流
人工智能·开源·源码阅读
冬奇Lab1 小时前
一天一个开源项目(第45篇):OpenAI Agents SDK Python - 轻量级多 Agent 工作流框架,支持 100+ LLM 与实时语音
人工智能·开源·openai
小兵张健1 小时前
两个配置让 Codex 效率翻倍
人工智能·程序员·github copilot
kymjs张涛3 小时前
OpenClaw 学习小组:初识
android·linux·人工智能
yangpow23 小时前
拆解 OpenClaw 的 Skills 机制:一个为 AI Agent 设计的"包管理器"
人工智能
warm3snow3 小时前
AI 重塑产品管理工具:从 Jira 到智能体项目经理的终极演进
人工智能·ai·excel·项目管理·飞书·产品经理·jira·协同·tapd
吴佳浩3 小时前
OpenClaw macOS 完整安装与本地模型配置教程(实战版)
人工智能·macos·agent
吴佳浩4 小时前
OpenClaw 2026.3.2 — 2026.3.8 权限变更与安全加固
人工智能·openai·agent
左右用AI4 小时前
将openclaw接入飞书:10分钟,让你的AI员工直接操作你的文档和表格!
人工智能