qwen2 VL 多模态图文模型;图像、视频使用案例

news2024/9/21 0:38:48

参考:
https://huggingface.co/Qwen/Qwen2-VL-2B-Instruct

模型:

export HF_ENDPOINT=https://hf-mirror.com

huggingface-cli download --resume-download --local-dir-use-symlinks False Qwen/Qwen2-VL-2B-Instruct  --local-dir qwen2-vl

安装:
transformers-4.45.0.dev0
accelerate-0.34.2 safetensors-0.4.5

pip install git+https://github.com/huggingface/transformers
pip install 'accelerate>=0.26.0'

代码:

单张图片

from PIL import Image
import requests
import torch
from torchvision import io
from typing import Dict
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, AutoProcessor

# Load the model in half-precision on the available device(s)
model = Qwen2VLForConditionalGeneration.from_pretrained(
    "/ai/qwen2-vl", torch_dtype="auto", device_map="auto"
)
processor = AutoProcessor.from_pretrained("/ai/qwen2-vl")




# Image
url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
image = Image.open(requests.get(url, stream=True).raw)

conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
            },
            {"type": "text", "text": "Describe this image."},
        ],
    }
]


# Preprocess the inputs
text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
# Excepted output: '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe this image.<|im_end|>\n<|im_start|>assistant\n'

inputs = processor(
    text=[text_prompt], images=[image], padding=True, return_tensors="pt"
)
inputs = inputs.to("cuda")

# Inference: Generation of the output
output_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids = [
    output_ids[len(input_ids) :]
    for input_ids, output_ids in zip(inputs.input_ids, output_ids)
]
output_text = processor.batch_decode(
    generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
)
print(output_text)

这是图片:
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

中文问


# Image
url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg"
image = Image.open(requests.get(url, stream=True).raw)

conversation = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
            },
            {"type": "text", "text": "描述下这张图片."},
        ],
    }
]


# Preprocess the inputs
text_prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
# Excepted output: '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>Describe this image.<|im_end|>\n<|im_start|>assistant\n'

inputs = processor(
    text=[text_prompt], images=[image], padding=True, return_tensors="pt"
)
inputs = inputs.to("cuda")
# Inference: Generation of the output
output_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids = [
    output_ids[len(input_ids) :]
    for input_ids, output_ids in zip(inputs.input_ids, output_ids)
]
output_text = processor.batch_decode(
    generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
)
print(output_text)

在这里插入图片描述

多张图片

def load_images(image_info):
    images = []
    for info in image_info:
        if "image" in info:
            if info["image"].startswith("http"):
                image = Image.open(requests.get(info["image"], stream=True).raw)
            else:
                image = Image.open(info["image"])
            images.append(image)
    return images

# Messages containing multiple images and a text query
messages = [
    {
        "role": "user",
        "content": [
            {"type": "image", "image": "/ai/fight.png"},
            {"type": "image", "image": "/ai/long.png"},
            {"type": "text", "text": "描述下这两张图片"},
        ],
    }
]

# Load images
image_info = messages[0]["content"][:2]  # Extract image info from the message
images = load_images(image_info)

# Preprocess the inputs
text_prompt = processor.apply_chat_template(messages, add_generation_prompt=True)

inputs = processor(
    text=[text_prompt], images=images, padding=True, return_tensors="pt"
)
inputs = inputs.to("cuda")

# Inference: Generation of the output
output_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids = [
    output_ids[len(input_ids) :]
    for input_ids, output_ids in zip(inputs.input_ids, output_ids)
]
output_text = processor.batch_decode(
    generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
)
print(output_text)

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

视频
安装

pip install qwen-vl-utils
from qwen_vl_utils import process_vision_info

# Messages containing a images list as a video and a text query
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "video",
                "video": [
                    "file:///path/to/frame1.jpg",
                    "file:///path/to/frame2.jpg",
                    "file:///path/to/frame3.jpg",
                    "file:///path/to/frame4.jpg",
                ],
                "fps": 1.0,
            },
            {"type": "text", "text": "Describe this video."},
        ],
    }
]
# Messages containing a video and a text query
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "video",
                "video": "/ai/血液从上肢流入上腔静脉.mp4",
                "max_pixels": 360 * 420,
                "fps": 1.0,
            },
            {"type": "text", "text": "描述下这个视频"},
        ],
    }
]

# Preparation for inference
text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to("cuda")

# Inference
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)

在这里插入图片描述

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2127858.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

你不得不知的日志级别

前言 写日志是一项具有挑战性的任务&#xff0c;在工作中我们常常面临一些困境&#xff0c;比如&#xff1a; 开发人员在编写代码时常常陷入纠结&#xff0c;不确定在何处打印日志才是最有意义的&#xff1b;SRE人员在调查生产问题时可能因为缺乏必要的日志信息而束手无策&am…

基于SSM的“高校学生社团管理系统”的设计与实现(源码+数据库+文档)

基于SSM的“高校学生社团管理系统”的设计与实现&#xff08;源码数据库文档) 开发语言&#xff1a;Java 数据库&#xff1a;MySQL 技术&#xff1a;SSM 工具&#xff1a;IDEA/Ecilpse、Navicat、Maven 系统展示 系统结构图 首页 注册 登录 后台首页界面 社团公告页面 留…

Engage2024用户大会成功举办,数聚股份携手销售易共绘数字化转型新篇章

2024年9月5日&#xff0c;销售易第六届用户大会Engage2024在上海盛大举行。销售易&#xff0c;作为唯一一家入选Gartner SFA魔力象限、且产品能力全球前四的国产CRM软件&#xff0c;当之无愧是国产CRM软件的龙头&#xff0c;其用户大会自然就是CRM领域盛会&#xff0c;汇聚了众…

生命周期函数

所有继承MonoBehavior的脚本 最终都会挂载到Gameobiject游戏对象上 1.生命周期西数 就是该脚本对象依附的Gameobject对象从出生到消亡整个生命周期中 会通过反射自动调用的一些特殊函数 2.Unity帮助我们记录了一个Gameobject对象依附了哪些脚本 会自动的得到这些对象&#x…

视频监控系统中的云镜控制PTZ详细介绍,以及视频监控接入联网平台相关协议对PTZ的支持

目录 一、PTZ概述 二、PTZ 控制的应用场景 1、公共场所 2、安全监控 3、交通监控 4、工业生产环境中的质量监控 5、大型活动的现场直播或录制 三、PTZ摄像的优缺点 1、优点 2、缺点 四、PTZ控制的基本原理 1、云台控制 2、镜头控制 五、 PTZ 控制协议 1. Pelco-…

深度学习时遇到tensor([0.], device=‘cuda:0‘)等输出

更改了数据集后进行训练遇到了以下输出&#xff0c;精度正常提升&#xff0c;训练正常&#xff0c;就是精度和map之间又很多输出&#xff0c;如下&#xff1a; tensor([0.], devicecuda:0), tensor([0.], devicecuda:0), tensor([0.], devicecuda:0), tensor([0.], devicecuda…

NAT技术+代理服务器+内网穿透

NAT技术 IPv4协议中&#xff0c;会存在IP地址数量不充足的问题&#xff0c;所以不同的子网中会存在相同IP地址的主机。那么就可以理解为私有网络的IP地址并不是唯一对应的&#xff0c;而公网中的IP地址都是唯一的&#xff0c;所以NAT&#xff08;Network Address Translation&…

往复密封问题的两个问题

&#x1f3c6;本文收录于《CSDN问答解惑-专业版》专栏&#xff0c;主要记录项目实战过程中的Bug之前因后果及提供真实有效的解决方案&#xff0c;希望能够助你一臂之力&#xff0c;帮你早日登顶实现财富自由&#x1f680;&#xff1b;同时&#xff0c;欢迎大家关注&&收…

使用ChatGPT高质量撰写文献综述全攻略实操指南,五步轻松搞定!

大家好,感谢关注。我是七哥,一个在高校里不务正业,折腾学术科研AI实操的学术人。关于使用ChatGPT等AI学术科研的相关问题可以和作者七哥(yida985)交流,多多交流,相互成就,共同进步,为大家带来最酷最有效的智能AI学术科研写作攻略。 在学术研究中,文献综述很重要,但…

无线感知会议系列【2】【智能无感感知 特征,算法,数据集】

前言&#xff1a; 这篇来自 2022 泛在可信智能感知 论坛 作者&#xff1a; 清华大学杨铮教授 视频&#xff1a; 2.智能无线感知&#xff1a;特征、算法、数据集&#xff1b; 杨峥 清华大学 副教授_哔哩哔哩_bilibili 这篇论文前面有讲过,我前面的博客也有基于提供的数据集做了…

关于打不开SOAMANAGER如何解决

参考文章&#xff1a;https://blog.csdn.net/yannickdann/article/details/115396035 打开SE93

Python字典实战题目练习,巩固知识、检查技术

本文主要是作为Python中列表的一些题目&#xff0c;方便学习完Python的列表之后进行一些知识检验&#xff0c;感兴趣的小伙伴可以试一试&#xff0c;含选择题、判断题、实战题&#xff0c;答案在第四章。 在做题之前可以先学习或者温习一下Python的列表&#xff0c;推荐阅读下面…

沃尔玛测评防关联技术:自养号攻略全面解析

防关联技术 1.使用国外的服务器和防火墙&#xff1a;为了确保测评活动的隐蔽性和安全性&#xff0c;卖家应选择使用国外的服务器&#xff0c;并通过远程搭建一个安全终端防火墙。这样可以阻断硬件参数的关联问题&#xff0c;降低被沃尔玛平台检测到的风险。 2.创建住宅专线IP…

《食品安全导刊》是什么级别的期刊?是正规期刊吗?能评职称吗?

问题解答 问&#xff1a;《食品安全导刊》是不是核心期刊&#xff1f; 答&#xff1a;不是&#xff0c;是知网收录的正规学术期刊。 问&#xff1a;《食品安全导刊》级别&#xff1f; 答&#xff1a;国家级。主管单位&#xff1a; 中国商业联合会 主办单…

解析DNS查询报文,探索DNS工作原理

目录 1. 用 tcpdump工具监听抓包 2. 用 host 工具获取域名对应的IP地址 3. 分析DNS以太网查询数据帧 3.1 linux下查询DNS服务器IP地址 3.2 DNS以太网查询数据帧 &#xff08;1&#xff09;数据链路层 &#xff08;2&#xff09;网络层 &#xff08;3&#xff09;传输层…

NC 和为K的连续子数组

系列文章目录 文章目录 系列文章目录前言 前言 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站&#xff0c;这篇文章男女通用&#xff0c;看懂了就去分享给你的码吧。 描述 给定一个无序…

基于SpringBoot+Vue+MySQL的影院购票系统

系统展示 用户前台界面 管理员后台界面 系统背景 基于SpringBoot、Vue.js与MySQL的影院购票系统&#xff0c;实现了从后端服务到前端展示及数据库管理的全栈开发。该系统通过SpringBoot构建高效稳定的RESTful API&#xff0c;处理用户注册登录、影片信息查询、座位选择、在线购…

无人直播好帮手,视频指定词语消音,消除违禁词,直播视频录制,音视频分离,分段

1.视频消音功能 一键删除或者静音视频中的词语 2.直播视频录制功能 可同时录制多个平台,多个主播,没有数量限制 3.音视频转码 支持多种音视频格式转换 4.视频频分离 分离视频中的音频和视频 5.视频合并分割 合并和按时间分割视屏 目前正在测试中…如有需要可以先使…

【C语言从不挂科到高绩点】16-作用域和自定义头文件

Hello&#xff01;彦祖们&#xff0c;俺又回来了&#xff01;&#xff01;&#xff01;&#xff0c;继续给大家分享 《C语言从不挂科到高绩点》课程!! 本节将为大家讲解C语言中的函数&#xff1a; 本套课程将会从0基础讲解C语言核心技术&#xff0c;适合人群&#xff1a; 大学…

LLM 大模型研习:当下热门 AI 大模型的生成原理与逻辑

前言 在过去数年里&#xff0c;人工智能领域迎来了前所未有的变革&#xff0c;其中大规模预训练模型的崛起尤为引人注目。像GPT系列、BERT、T5、DALLE和CLIP等模型&#xff0c;凭借强大的语言理解与生成能力&#xff0c;在自然语言处理&#xff08;NLP&#xff09;、计算机视觉…