SuperAPI AI 工具集

clip

智能体与模型

查看项目

更新于 10-30 06:47

技能介绍

CLIP(Contrastive Language-Image Pre-Training)是 OpenAI 开发的模型,能够通过自然语言理解图像,实现视觉与语言的连接。

用途

CLIP 适用于以下场景:

  • 零样本图像分类(无需训练数据)
  • 图像-文本相似度/匹配
  • 语义图像搜索
  • 内容审核(检测 NSFW、暴力内容)
  • 视觉问答
  • 跨模态检索(图像→文本、文本→图像)

主要能力

  • 基于 4 亿对图文数据训练,在 ImageNet 零样本任务上可媲美 ResNet-50。
  • 提供多种模型:RN50(102M 参数,速度快,质量好)、ViT-B/32(151M 参数,速度中等,质量更好,推荐)、ViT-L/14(428M 参数,速度慢,质量最佳)。
  • 支持批量处理图像和文本,可集成向量数据库(如 Chroma、FAISS)进行大规模检索。
  • 性能参考:图像编码在 CPU 上约 200ms,GPU(V100)约 20ms;文本编码 CPU 约 50ms,GPU 约 5ms;相似度计算均小于 1ms。

使用方式

安装:

pip install git+https://github.com/openai/CLIP.git
pip install torch torchvision ftfy regex tqdm

零样本分类示例:

import torch
import clip
from PIL import Image

device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)
image = preprocess(Image.open("photo.jpg")).unsqueeze(0).to(device)
text = clip.tokenize(["a dog", "a cat", "a bird", "a car"]).to(device)
with torch.no_grad():
    image_features = model.encode_image(image)
    text_features = model.encode_text(text)
    logits_per_image, logits_per_text = model(image, text)
    probs = logits_per_image.softmax(dim=-1).cpu().numpy()
labels = ["a dog", "a cat", "a bird", "a car"]
for label, prob in zip(labels, probs[0]):
    print(f"{label}: {prob:.2%}")

图像-文本相似度:

image_features = model.encode_image(image)
text_features = model.encode_text(text)
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)
similarity = (image_features @ text_features.T).item()
print(f"Similarity: {similarity:.4f}")

语义图像搜索:

image_paths = ["img1.jpg", "img2.jpg", "img3.jpg"]
image_embeddings = []
for img_path in image_paths:
    image = preprocess(Image.open(img_path)).unsqueeze(0).to(device)
    with torch.no_grad():
        embedding = model.encode_image(image)
        embedding /= embedding.norm(dim=-1, keepdim=True)
    image_embeddings.append(embedding)
image_embeddings = torch.cat(image_embeddings)
query = "a sunset over the ocean"
text_input = clip.tokenize([query]).to(device)
with torch.no_grad():
    text_embedding = model.encode_text(text_input)
    text_embedding /= text_embedding.norm(dim=-1, keepdim=True)
similarities = (text_embedding @ image_embeddings.T).squeeze(0)
top_k = similarities.topk(3)
for idx, score in zip(top_k.indices, top_k.values):
    print(f"{image_paths[idx]}: {score:.3f}")

内容审核:

categories = ["safe for work", "not safe for work", "violent content", "graphic content"]
text = clip.tokenize(categories).to(device)
with torch.no_grad():
    logits_per_image, _ = model(image, text)
    probs = logits_per_image.softmax(dim=-1)
max_idx = probs.argmax().item()
max_prob = probs[0, max_idx].item()
print(f"Category: {categories[max_idx]} ({max_prob:.2%})")

批量处理:

images = [preprocess(Image.open(f"img{i}.jpg")) for i in range(10)]
images = torch.stack(images).to(device)
with torch.no_grad():
    image_features = model.encode_image(images)
    image_features /= image_features.norm(dim=-1, keepdim=True)
texts = ["a dog", "a cat", "a bird"]
text_tokens = clip.tokenize(texts).to(device)
with torch.no_grad():
    text_features = model.encode_text(text_tokens)
    text_features /= text_features.norm(dim=-1, keepdim=True)
similarities = image_features @ text_features.T
print(similarities.shape)  # (10, 3)

与向量数据库集成:

import chromadb
client = chromadb.Client()
collection = client.create_collection("image_embeddings")
for img_path, embedding in zip(image_paths, image_embeddings):
    collection.add(
        embeddings=[embedding.cpu().numpy().tolist()],
        metadatas=[{"path": img_path}],
        ids=[img_path]
    )
query = "a sunset"
text_embedding = model.encode_text(clip.tokenize([query]))
results = collection.query(
    query_embeddings=[text_embedding.cpu().numpy().tolist()],
    n_results=5
)

适用场景

  • 需要快速进行图像语义理解、以文搜图或内容过滤的应用。
  • 无标注数据下的图像分类与检索。
  • 构建跨模态检索系统或视觉问答原型。

限制

  • 不适用于细粒度任务,更适合宽泛类别。
  • 需要描述性文本,模糊标签效果差。
  • 基于网络数据训练,可能存在数据集偏见。
  • 不提供边界框,仅处理整张图像。
  • 空间理解有限,位置和计数能力弱。

资源

  • GitHub:https://github.com/openai/CLIP (星标 25,300+)
  • 论文:https://arxiv.org/abs/2103.00020
  • Colab:https://colab.research.google.com/github/openai/clip/
  • 许可证:MIT

最佳实践

  • 多数情况使用 ViT-B/32,平衡性好。
  • 归一化嵌入向量,余弦相似度必需。
  • 批量处理更高效。
  • 缓存嵌入,重新计算开销大。
  • 使用描述性标签,提升零样本性能。
  • 推荐使用 GPU,速度提升 10-50 倍。
  • 使用提供的 preprocess 函数预处理图像。