【计算机视觉】BLIP:源代码示例demo(含源代码)

news2024/10/6 8:32:33

文章目录

  • 一、Image Captioning
  • 二、VQA
  • 三、Feature Extraction
  • 四、Image-Text Matching

一、Image Captioning

首先配置代码:

import sys
if 'google.colab' in sys.modules:
    print('Running in Colab.')
    !pip3 install transformers==4.15.0 timm==0.4.12 fairscale==0.4.4
    !git clone https://github.com/salesforce/BLIP
    %cd BLIP

这段代码用于在Google Colab环境中进行设置。代码首先检查是否在Google Colab环境中运行(‘google.colab’ in sys.modules)。如果是在Colab环境中运行,它会继续使用pip3安装特定版本的Python包。然后,它通过git clone命令克隆名为"BLIP"的GitHub代码仓库。最后,代码使用%cd命令将当前工作目录更改为"BLIP"代码仓库的目录。

这段代码的目的是在Google Colab中设置必要的环境,以便在"BLIP"代码仓库中继续执行其他相关代码。

from PIL import Image
import requests
import torch
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

def load_demo_image(image_size,device):
    img_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg' 
    raw_image = Image.open(requests.get(img_url, stream=True).raw).convert('RGB')   

    w,h = raw_image.size
    display(raw_image.resize((w//5,h//5)))
    
    transform = transforms.Compose([
        transforms.Resize((image_size,image_size),interpolation=InterpolationMode.BICUBIC),
        transforms.ToTensor(),
        transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
        ]) 
    image = transform(raw_image).unsqueeze(0).to(device)   
    return image

这段代码用于加载演示图像并进行预处理,以便用于后续的计算机视觉任务。让我们逐行解读代码:

  1. from PIL import Image: 导入PIL库中的Image模块,用于图像处理。

  2. import requests: 导入requests库,用于从网络上获取图像。

  3. import torch: 导入PyTorch库,用于深度学习任务。

  4. from torchvision import transforms: 从torchvision库中导入transforms模块,用于图像预处理。

  5. from torchvision.transforms.functional import InterpolationMode: 从torchvision.transforms.functional模块中导入InterpolationMode,用于指定图像的插值方式。

  6. device = torch.device(‘cuda’ if torch.cuda.is_available() else ‘cpu’): 判断是否有可用的GPU,如果有则将device设置为cuda,否则设置为cpu。后续计算会在这个设备上执行。

  7. def load_demo_image(image_size, device):: 定义了一个名为load_demo_image的函数,该函数接受图像大小image_size和计算设备device作为输入参数。

  8. img_url = ‘https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg’: 定义了演示图像的URL。

  9. raw_image = Image.open(requests.get(img_url, stream=True).raw).convert(‘RGB’): 从给定的URL下载原始图像,并使用PIL库中的Image模块打开和转换图像格式为RGB。

  10. w, h = raw_image.size: 获取原始图像的宽度和高度。

  11. display(raw_image.resize((w//5, h//5))): 使用display函数显示缩小后的原始图像。

  12. transform = transforms.Compose([…]): 定义一个图像预处理的变换链,包括图像大小调整、图像转换为张量、以及归一化等操作。

  13. image = transform(raw_image).unsqueeze(0).to(device): 对原始图像进行预处理,并将其转换为张量。使用unsqueeze(0)将图像张量的维度从 [C, H, W] 调整为 [1, C, H, W],以匹配网络模型的输入形状。最后,将处理后的图像张量移动到之前设定的计算设备上。

  14. return image: 返回预处理后的图像张量。

这段代码的作用是加载演示图像,并将其预处理成适合用于后续计算机视觉任务的张量数据。在函数调用时,您需要传入所需的图像大小和计算设备,然后可以使用返回的图像张量进行计算机视觉模型的推理和分析。

from models.blip import blip_decoder

image_size = 384
image = load_demo_image(image_size=image_size, device=device)

model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth'
    
model = blip_decoder(pretrained=model_url, image_size=image_size, vit='base')
model.eval()
model = model.to(device)

with torch.no_grad():
    # beam search
    caption = model.generate(image, sample=False, num_beams=3, max_length=20, min_length=5) 
    # nucleus sampling
    # caption = model.generate(image, sample=True, top_p=0.9, max_length=20, min_length=5) 
    print('caption: '+caption[0])
  1. from models.blip import blip_decoder: 导入自定义的blip_decoder模型,这是"BLIP"模型的解码部分。

  2. image_size = 384: 定义图像大小为384x384像素。

  3. image = load_demo_image(image_size=image_size, device=device): 使用之前定义的load_demo_image函数加载演示图像,并对图像进行预处理,以适应模型的输入要求。image是经过预处理后的图像张量。

  4. model_url = ‘https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth’: 定义了预训练模型的URL。

  5. model = blip_decoder(pretrained=model_url, image_size=image_size, vit=‘base’): 使用blip_decoder模型的构造函数创建模型实例。此处的pretrained参数指定了预训练模型的URL,image_size参数指定了图像大小,vit参数指定了使用哪个ViT(Vision Transformer)模型,这里选择了base版本。

  6. model.eval(): 将模型设置为评估模式,这会关闭一些在训练时启用的特定功能,如Dropout。

  7. model = model.to(device): 将模型移动到之前设定的计算设备上。

  8. with torch.no_grad():: 使用torch.no_grad()上下文管理器,以确保在推理时不会计算梯度。

  9. caption = model.generate(image, sample=False, num_beams=3, max_length=20, min_length=5): 使用model.generate()方法生成图像的描述。这里使用了beam search方法来搜索最佳的描述。sample=False表示不使用采样方法,而是使用beam search。num_beams=3表示beam search时使用3个束(beam)。max_length=20表示生成的描述最长为20个词,min_length=5表示生成的描述最短为5个词。

  10. print('caption: '+caption[0]): 输出生成的图像描述。

这段代码的作用是使用预训练的"BLIP"模型对加载的图像进行描述生成。它使用beam search方法在模型中进行推理,并输出生成的图像描述。您可以尝试使用不同的采样方法或调整其他参数,来观察生成描述的变化。

输出结果为:

在这里插入图片描述

load checkpoint from https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model*_base_caption.pth
caption: a woman sitting on the beach with a dog

二、VQA

from models.blip_vqa import blip_vqa

image_size = 480
image = load_demo_image(image_size=image_size, device=device)     

model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth'
    
model = blip_vqa(pretrained=model_url, image_size=image_size, vit='base')
model.eval()
model = model.to(device)

question = 'where is the woman sitting?'

with torch.no_grad():
    answer = model(image, question, train=False, inference='generate') 
    print('answer: '+answer[0])
  1. from models.blip_vqa import blip_vqa: 导入自定义的blip_vqa模型,这是"BLIP"模型的视觉问答部分。

  2. image_size = 480: 定义图像大小为480x480像素。

  3. image = load_demo_image(image_size=image_size, device=device): 使用之前定义的load_demo_image函数加载演示图像,并对图像进行预处理,以适应模型的输入要求。image是经过预处理后的图像张量。

  4. model_url = ‘https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth’: 定义了视觉问答模型的预训练模型的URL。

  5. model = blip_vqa(pretrained=model_url, image_size=image_size, vit=‘base’): 使用blip_vqa模型的构造函数创建模型实例。此处的pretrained参数指定了预训练模型的URL,image_size参数指定了图像大小,vit参数指定了使用哪个ViT(Vision Transformer)模型,这里选择了base版本。

  6. model.eval(): 将模型设置为评估模式,这会关闭一些在训练时启用的特定功能,如Dropout。

  7. model = model.to(device): 将模型移动到之前设定的计算设备上。

  8. question = ‘where is the woman sitting?’: 定义了一个视觉问答问题,这里的问题是"where is the woman sitting?"。

  9. with torch.no_grad():: 使用torch.no_grad()上下文管理器,以确保在推理时不会计算梯度。

  10. answer = model(image, question, train=False, inference=‘generate’): 使用模型的__call__方法进行推理,输入图像和问题,以生成回答。train=False表示在推理过程中不使用训练模式。inference='generate’表示使用生成式推理方法,而不是提供答案的训练模式。

  11. print('answer: '+answer[0]): 输出生成的回答。

这段代码的作用是使用预训练的"BLIP"模型进行视觉问答,根据给定的问题对加载的图像进行回答生成。它使用生成式推理方法来生成回答。您可以尝试提供不同的问题,来观察模型生成的回答。

输出结果:

在这里插入图片描述

load checkpoint from https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model*_vqa.pth
answer: on beach

三、Feature Extraction

from models.blip import blip_feature_extractor

image_size = 224
image = load_demo_image(image_size=image_size, device=device)     

model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base.pth'
    
model = blip_feature_extractor(pretrained=model_url, image_size=image_size, vit='base')
model.eval()
model = model.to(device)

caption = 'a woman sitting on the beach with a dog'

multimodal_feature = model(image, caption, mode='multimodal')[0,0]
image_feature = model(image, caption, mode='image')[0,0]
text_feature = model(image, caption, mode='text')[0,0]

输出结果为:

在这里插入图片描述

load checkpoint from https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base.pth

四、Image-Text Matching

from models.blip_itm import blip_itm

image_size = 384
image = load_demo_image(image_size=image_size,device=device)

model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth'
    
model = blip_itm(pretrained=model_url, image_size=image_size, vit='base')
model.eval()
model = model.to(device='cpu')

caption = 'a woman sitting on the beach with a dog'

print('text: %s' %caption)

itm_output = model(image,caption,match_head='itm')
itm_score = torch.nn.functional.softmax(itm_output,dim=1)[:,1]
print('The image and text is matched with a probability of %.4f'%itm_score)

itc_score = model(image,caption,match_head='itc')
print('The image feature and text feature has a cosine similarity of %.4f'%itc_score)

输出结果为:

在这里插入图片描述

load checkpoint from https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth
text: a woman sitting on the beach with a dog
The image and text is matched with a probability of 0.9960
The image feature and text feature has a cosine similarity of 0.5262

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

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

相关文章

linux(进程)[6]

管理概念 先描述,再组织 进程 启动一个软件就相当于启动了一个进程 Linux下执行一条命令就在系统层面创建了一个进程!! 如何管理 进程对应的代码和数据 进程对应的PCB结构体 PCB(process control block) 在Linu…

Java反射机制的详细讲解

目录 1.反射机制是什么? 2.反射机制能干什么? 3.反射相关的类 ​编辑 4.Class类(反射机制的起源 ) 5.反射机制相关的API 1.(重要)常用获得类相关的方法 2.常用获得类中属性相关的方法(以下方法返回值为Field相关 3.(了解)获得类中注解相关的方法…

iOS开发-实现3DTouch按压App快捷选项shortcutItems及跳转功能

iOS开发-实现3DTouch按压App快捷选项shortcutItems及跳转功能 App的应用图标通过3D Touch按压App图标,会显示快捷选项,点击选项可快速进入到App的特定页面。 这里用到了UIApplicationShortcutItem与UIMutableApplicationShortcutItem 一、效果图 这里…

VS附加到进程调试

操作: 要附加到进程中调试外部可执行文件,您需要使用Visual Studio的“调试附加”功能。以下是附加到进程中调试外部可执行文件的步骤: 打开您要调试的源代码文件或可执行文件。打开Visual Studio。选择“调试”菜单,然后选择“…

三种无监督学习方法用于肿瘤病理图像预测任务

这里写自定义目录标题 BYOLBYOL描述基本思路示意图合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants 创建一个自定义列表如何创建一个注脚注释也是必…

大数据_Hadoop_Parquet数据格式详解

之前有面试官问到了parquet的数据格式,下面对这种格式做一个详细的解读。 参考链接 : 列存储格式Parquet浅析 - 简书 Parquet 文件结构与优势_parquet文件_KK架构的博客-CSDN博客 Parquet文件格式解析_parquet.block.size_davidfantasy的博客-CSDN博…

day16 | 513.找树左下角的值 112.路径总和 106.从中序与后序遍历序列构造二叉树

文章目录 一、找树左下角的值二、路径总和三、从中序与后序遍历序列构造二叉树 一、找树左下角的值 513.找树左下角的值 暴力解法 class Solution { public:int findBottomLeftValue(TreeNode *root){// 第一眼想到的就是层序遍历,取最后一层的第一个值即可queue…

Vue系列第六篇:axios封装,登录逻辑优化,404页面实现,Go语言跨域处理

第五篇利用vue实现了登录页面,用go语言开发了服务端并最后在nginx上进行了部署。本篇将axios封装,登录逻辑优化,404页面实现。 目录 1.前端 1.1代码结构 1.2源码 2.服务端 2.1源码 3.运行效果 4.注意事项 4.1webpack.config.js和vue…

探索自除数:发现区间内的神奇数字

本篇博客会讲解力扣“728. 自除数”的解题思路,这是题目链接。 对于给定的正整数num,我们如何判断它是不是自除数呢?根据定义,我们只需要把num的每一位数字都取出来,判断能不能整除num,如果发现num的某一位…

【虹科案例】使用虹科模块化数字化仪进行车辆测试

引言 模块化仪器比传统仪器的尺寸大大减小,适合安装在电路卡上,同时也可以将多个卡插入具有通用计算机接口、电源和互连的框架中。模块化仪器框架包括使用标准 PCIe 接口的计算机、PXI 测试框架或基于 LXI 的盒子,工程师通常会使用多个卡并将…

git stash clear清空本地暂存代码

git stash clear清空本地暂存代码 git stash 或者 git stash list 查看本地暂存的代码。 清除本地暂存的代码修改: git stash clear git回退代码仓库版本_git回退到之前的版本会影响本地代码嘛_zhangphil的博客-CSDN博客git回退代码版本_git回退到之前的版本会影…

基于opencv的几种图像滤波

一、介绍 盒式滤波、均值滤波、高斯滤波、中值滤波、双边滤波、导向滤波。 boxFilter() blur() GaussianBlur() medianBlur() bilateralFilter() 二、代码 #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> …

01 制作Windows11启动盘及安装 || 包含校验ISO映像的方法

前言 由于空间越来越不够用了&#xff0c;上次为Ubuntu分配了96G的空间依然是快要被用完&#xff0c;连一个数据集都放不下了&#xff0c;因此我不得不选择换硬盘。 由于是离谱的华为Mate book D 15的2021款逆天机型&#xff0c;我没有第二个硬盘位。至于说移动硬盘的解决方案…

python3GUI--我的翻译器By:PyQt5(附下载地址)

文章目录 一&#xff0e;前言二&#xff0e;展示1.主界面2.段落翻译3.单词翻译 三&#xff0e;设计1.UI设计2.软件设计3.参考 四&#xff0e;总结 一&#xff0e;前言 很早之前写过一篇python3GUI–翻译器By:PyQt5&#xff08;附源码&#xff09; &#xff0c;但是发现相关引擎…

LED显示屏技术:数码时代的绚丽舞台

随着信息技术的飞速发展&#xff0c;LED显示屏技术成为现代社会不可或缺的一部分。这种技术以其高亮度、高清晰度和多样化的应用领域&#xff0c;在数字化时代展现出绚丽多彩的画面&#xff0c;为我们带来了前所未有的视觉体验。本文将探讨LED显示屏技术的原理、应用以及对于现…

【JavaEE】简单了解JVM

目录 一、JVM中的内存区域划分 二、JVM的类加载机制 1、类加载的触发时机 2、双亲委派模型 1.1、向上委派 1.2、向下委派 三、JVM中的垃圾回收机制&#xff08;GC&#xff09; 1、确认垃圾 1.1、引用计数&#xff08;Java实际上没有使用这个方案&#xff0c;但是Pytho…

超详细 | 模拟退火算法及其MATLAB实现

模拟退火算法(simulated annealing&#xff0c;SA)是20世纪80年代初期发展起来的一种求解大规模组合优化问题的随机性方法。它以优化问题的求解与物理系统退火过程的相似性为基础&#xff0c;利用Metropolis算法并适当地控制温度的下降过程实现模拟退火&#xff0c;从而达到求解…

RK3588平台开发系列讲解(调试篇)如何进行性能分析

文章目录 一、什么是性能分析呢?二、系统级工具三、源码级工具沉淀、分享、成长,让自己和他人都能有所收获!😄 📢 本篇将介绍性能分析(Performance Profiling) 最简单的性能分析工具是 top,可以快速查看进程的 CPU、内存使用情况;pstack 和 strace 能够显示进程在用…

大数据面试题:HBase的RegionServer宕机以后怎么恢复的?

面试题来源&#xff1a; 《大数据面试题 V4.0》 大数据面试题V3.0&#xff0c;523道题&#xff0c;679页&#xff0c;46w字 可回答&#xff1a;1&#xff09;HBase一个节点宕机了怎么办&#xff1b;2&#xff09;HBase故障恢复 参考答案&#xff1a; 1、HBase常见故障 导…

简要介绍 | 解析模态之间的联系:跨模态学习与多模态学习的区别和联系

注1&#xff1a;本文系“简要介绍”系列之一&#xff0c;仅从概念上对跨模态学习和多模态学习进行非常简要的介绍&#xff0c;不适合用于深入和详细的了解。 解析模态之间的联系&#xff1a;跨模态学习与多模态学习的区别和联系 在人工智能的广泛领域中&#xff0c;跨模态学习…