mcpField
C
clip

clip

github.com/kalarislabsその他7344 回インストール4 日前に更新
リポジトリ

clip について

視覚データを扱う開発者向けに、OpenAIのCLIPモデルで画像と自然言語テキストを比較する方法を解説します。ゼロショット分類、類似度計算、セマンティック検索、クロスモーダル検索を扱います。

主な機能

  1. 01ゼロショット画像分類
  2. 02画像とテキストの類似度計算
  3. 03セマンティック画像検索
  4. 04クロスモーダル検索
  5. 05画像埋め込みのバッチ生成

活用シーン

  1. 01学習データなしで画像を分類
  2. 02テキストクエリで画像を検索
  3. 03画像とテキスト記述を照合

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/kalarislabs/research-agent-skills --skill clip

インストール後、Claude Code で/clipを入力して読み込まれたか確認します。

同梱ファイルreferences/applications.md

詳細

CLIP - Contrastive Language-Image Pre-Training

自然言語から画像を理解するOpenAIのモデルです。

CLIPを使用する場面

次の用途に適しています:

  • ゼロショット画像分類(トレーニングデータは不要)
  • 画像とテキストの類似度判定/マッチング
  • 意味に基づく画像検索
  • コンテンツモデレーション(NSFWや暴力の検出)
  • 視覚的な質問応答
  • クロスモーダル検索(画像→テキスト、テキスト→画像)

指標:

  • 4億組の画像とテキストのペアでトレーニング
  • ImageNetでResNet-50と同等の性能(ゼロショット)
  • MIT License

代替モデルを使用してください:

  • BLIP-2:キャプション生成に優れています
  • LLaVA:視覚と言語を使ったチャット
  • Segment Anything:画像セグメンテーション

クイックスタート

インストール
pip install git+https://github.com/openai/CLIP.git
pip install torch torchvision ftfy regex tqdm
ゼロショット分類
import torch
import clip
from PIL import Image

# Load model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load("ViT-B/32", device=device)

# Load image
image = preprocess(Image.open("photo.jpg")).unsqueeze(0).to(device)

# Define possible labels
text = clip.tokenize(["a dog", "a cat", "a bird", "a car"]).to(device)

# Compute similarity
with torch.no_grad():
    image_features = model.encode_image(image)
    text_features = model.encode_text(text)

    # Cosine similarity
    logits_per_image, logits_per_text = model(image, text)
    probs = logits_per_image.softmax(dim=-1).cpu().numpy()

# Print results
labels = ["a dog", "a cat", "a bird", "a car"]
for label, prob in zip(labels, probs[0]):
    print(f"{label}: {prob:.2%}")

利用可能なモデル

# Models (sorted by size)
models = [
    "RN50",           # ResNet-50
    "RN101",          # ResNet-101
    "ViT-B/32",       # Vision Transformer (recommended)
    "ViT-B/16",       # Better quality, slower
    "ViT-L/14",       # Best quality, slowest
]

model, preprocess = clip.load("ViT-B/32")
モデルパラメーター数速度品質
RN50102M高速良好
ViT-B/32151M中速より良好
ViT-L/14428M低速最高

画像とテキストの類似度

# Compute embeddings
image_features = model.encode_image(image)
text_features = model.encode_text(text)

# Normalize
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)

# Cosine similarity
similarity = (image_features @ text_features.T).item()
print(f"Similarity: {similarity:.4f}")

意味に基づく画像検索

# Index images
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)

# Search with text query
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)

# Find most similar images
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}")

コンテンツモデレーション

# Define categories
categories = [
    "safe for work",
    "not safe for work",
    "violent content",
    "graphic content"
]

text = clip.tokenize(categories).to(device)

# Check image
with torch.no_grad():
    logits_per_image, _ = model(image, text)
    probs = logits_per_image.softmax(dim=-1)

# Get classification
max_idx = probs.argmax().item()
max_prob = probs[0, max_idx].item()

print(f"Category: {categories[max_idx]} ({max_prob:.2%})")

バッチ処理

# Process multiple images
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)

# Batch text
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)

# Similarity matrix (10 images × 3 texts)
similarities = image_features @ text_features.T
print(similarities.shape)  # (10, 3)

ベクトルデータベースとの連携

# Store CLIP embeddings in Chroma/FAISS
import chromadb

client = chromadb.Client()
collection = client.create_collection("image_embeddings")

# Add 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 with text
query = "a sunset"
text_embedding = model.encode_text(clip.tokenize([query]))
results = collection.query(
    query_embeddings=[text_embedding.cpu().numpy().tolist()],
    n_results=5
)

ベストプラクティス

  1. ほとんどの場合、ViT-B/32を使用する - バランスに優れています
  2. 埋め込みを正規化する - コサイン類似度の計算に必要です
  3. バッチ処理を行う - より効率的です
  4. 埋め込みをキャッシュする - 再計算にはコストがかかります
  5. 説明的なラベルを使用する - ゼロショット性能が向上します
  6. GPUの使用を推奨 - 10~50倍高速です
  7. 画像を前処理する - 提供されているpreprocess関数を使用します

パフォーマンス

処理CPUGPU(V100)
画像エンコード~200ms~20ms
テキストエンコード~50ms~5ms
類似度計算<1ms<1ms

制限事項

  1. 細かな分類タスクには不向きです - 大まかなカテゴリに最適です
  2. 説明的なテキストが必要です - 曖昧なラベルでは性能が低下します
  3. ウェブデータに起因するバイアスがあります - データセットのバイアスが含まれる場合があります
  4. バウンディングボックスは出力しません - 画像全体のみを扱います
  5. 空間理解に限界があります - 位置や数の把握は不得意です

リソース

エージェントの作業手順

  1. 環境を確認します。 GPUメモリ、モデルのチェックポイントとライセンス、フレームワークのバージョン、入力形式を確認します。
  2. 入力を明確にします。 データまたはユーザーから形式、識別子、パラメーターを確認します。結果に影響する値は推測せず、質問してください。
  3. まず小規模に実行します。 最初に、単一のサンプルを低解像度または短い長さで推論します。
  4. 上記の手順と参考情報を使用して、タスク全体を実行します。
  5. 結果を検証します。 出力を定性的に確認し、タスクの指標で評価します。生成コンテンツに関するライセンス上の制限も確認してください。
  6. 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、まだ不確かな点を伝えます。
発生した問題対処方法
大きな入力でメモリ不足になる解像度またはシーケンス長を下げる、半精度を使う、または入力をタイルに分割します。
これらの手順に記載された関数、フラグ、エンドポイントがインストール済みのバージョンに存在しないインストール済みバージョンのドキュメント(help()、--help、公式ドキュメント)を確認して対応し、ユーザーに伝えてください。APIを捏造してはいけません。
必須の入力、識別子、パラメーターが曖昧であるユーザーに質問するか、実行前に仮定を明示します。

インテグリティに関するルール

  • 結果、パラメーター、識別子、引用、統計情報を捏造してはいけません。実行または検証できない場合は、その旨を明確に伝えてください。
  • 商用利用または公開に際して、モデルとデータセットのライセンスを確認してください。
  • ここに記載されているバージョン固有の情報は古くなっている可能性があります。インストール済みバージョンの公式ドキュメントで確認してください。
  • 費用が発生する操作、共有GPUやクラウドのクォータを消費する操作、個人データや患者データを扱う操作、または取り消せない操作を行う前に、ユーザーに確認してください。

関連スキル

  • llava:大規模言語・ビジョンアシスタントです。
  • blip-2-vision-language:HuggingFace Trans…を通じて、Salesforce BLIP-2(凍結された画像エンコーダーとOPTやFlanT5などのLLMをつなぐQ-Former)の使用方法を説明します。
  • segment-anything-model:ゼロショット転移が可能な画像セグメンテーションの基盤モデルです。

コメント