视觉语言模型 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)
相关推荐
美狐美颜SDK开放平台1 小时前
美颜SDK性能优化实战:GPU加速与AI人脸美型的融合开发
人工智能·音视频
AI浩2 小时前
VSSD:具有非因果状态空间对偶性的视觉Mamba模型
人工智能·目标检测·计算机视觉
lqqjuly2 小时前
Lidar调试记录Ⅳ之Ubuntu22.04+ROS2+Livox_SDK2环境下编译Livox ROS Driver 2
人工智能·机器人·自动驾驶
qq_436962182 小时前
数据中台:打破企业数据孤岛,实现全域资产化的关键一步
数据库·人工智能·信息可视化·数据挖掘·数据分析
宇若-凉凉3 小时前
BERT 完整教程指南
人工智能·深度学习·bert
JD技术委员会3 小时前
如何在跨部门沟通失误后进行协调与澄清
人工智能
PcVue China4 小时前
PcVue X 工控——工厂数字化转型与落地巡回研讨会圆满举行
人工智能·软件工程·scada·监控平台·工控网
StarPrayers.4 小时前
自蒸馏学习方法
人工智能·算法·学习方法
咚咚王者4 小时前
人工智能之编程进阶 Python高级:第十一章 过渡项目
开发语言·人工智能·python
深度学习lover4 小时前
<数据集>yolo航拍斑马线识别数据集<目标检测>
人工智能·深度学习·yolo·目标检测·计算机视觉·数据集·航拍斑马线识别