前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >open_clip编码图像和文本 - plus studio

open_clip编码图像和文本 - plus studio

作者头像
plus sign
发布2024-02-29 08:07:19
4110
发布2024-02-29 08:07:19
举报
文章被收录于专栏:个人博客

open_clip是CLIP的开源实现版本,只训练了CLIP效果最好的几个模型。

安装是

代码语言:text
复制
pip install open_clip_torch

首先导入 open_clip,并创建相关模型

代码语言:text
复制
import open_clip
import torch

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
clip_model_name = "ViT-L-14"
clip_model,_,clip_preprocess = open_clip.create_model_and_transforms(clip_model_name
clip_model_name,pretrained = "openai",precision='fp16' if device == 'cuda' else 'fp32',device=device,
)

tokenize = open_clip.get_tokenizer(clip_model_name)

tokenize 是分词器,所有的文本都要先经过分析器才能放入模型进行推理。

编码图像
代码语言:text
复制
def image_to_features(image: Image.Image) -> torch.Tensor:
	images = clip_preprocess(image).unsqueeze(0).to(device)
	with torch.no_grad(), torch.cuda.amp.autocast():
	image_features = clip_model.encode_image(images)
	return image_features
  
img = cv.imread("/path/to/example.png")
img = Image.fromarray(img)

image_feature = image_to_features(img)

/path/to/example.png 替换成自己图片的路径

image_to_features 函数是一个封装过的将图像转成文本的函数,传入的参数是一个image_to_features格式的图片。

image_feature 就是经过CLIP的编码器得到的特征

编码文本
代码语言:text
复制
prompt = "a photo of a cat"
text_tokens = tokenize([prompt]).to(device)
text_features = clip_model.encode_text(text_tokens)

text_features 就是得到的特征。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-7-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 编码图像
  • 编码文本
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档