惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
GbyAI
GbyAI
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
U
Unit 42
Engineering at Meta
Engineering at Meta
aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
Vercel News
Vercel News
美团技术团队
雷峰网
雷峰网
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
D
DataBreaches.Net
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Apple Machine Learning Research
Apple Machine Learning Research
J
Java Code Geeks
罗磊的独立博客
MyScale Blog
MyScale Blog
博客园_首页
IT之家
IT之家
F
Fortinet All Blogs
博客园 - Franky

StudyingLover's Blog

Diffusion Policy笔记 rwkv笔记 act笔记 nanovllm-block_manager opencode多智能体 nanobot-pre-train nanobot-rl nanobot-sft nanobot-checkpoint_manager nanobot-gpt nanobot-mid-train Vision Mamba (Vim)笔记 BPE演示 最后一遍学习Transformer YOLOv5 目标检测笔记 下载根服务器解析记录 Dynaseal A Backend-Controlled LLM API Key Distribution Scheme with Constrained Invocation Parameters 判断链表有环 王道25数据结构勘误 关于perplexity的open-sourcing-r1-1776 AI为什么不像人类一样进行多轮对话 新博客改造日记和功能测试 linuxqq只显示登陆背景图 数字设计和计算机体系结构(机械工业出版社)勘误(自制) Dynaseal:面向未来端侧llm agent的llm api key分发机制 A Definitive Guide to Markdown Style This post is using MDX, Where you can embed JSX and Astro components RT-Patch学习 pydantic实现的LLM ReAct fastapi 和 uvicorn 设置监听 ipv6
open_clip编码图像和文本
About the Author StudyingLover · 2023-07-14 · via StudyingLover's Blog

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

安装是

pip install open_clip_torch

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

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 是分词器,所有的文本都要先经过分析器才能放入模型进行推理。

编码图像

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的编码器得到的特征

编码文本

prompt = "a photo of a cat"
text_tokens = tokenize([prompt]).to(device)
text_features = clip_model.encode_text(text_tokens)

text_features 就是得到的特征。