clip_vectorizer.py 1.12 KB
#!/usr/bin/env python3
"""
CLIP 图片语义向量化
用法:python3 clip_vectorizer.py <image_path>
返回:JSON 数组(512维向量)

依赖:torch, clip(pip install torch git+https://github.com/openai/CLIP.git)
未安装时返回空数组。
"""
import sys
import json
import os


def vectorize(image_path):
    try:
        import torch
        import clip
        from PIL import Image

        device = "cpu"
        model, preprocess = clip.load("ViT-B/32", device=device)

        image = preprocess(Image.open(image_path)).unsqueeze(0).to(device)
        with torch.no_grad():
            features = model.encode_image(image)
            features = features / features.norm(dim=-1, keepdim=True)
        return features[0].tolist()
    except ImportError:
        return []
    except Exception as e:
        return {'error': str(e)}


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print(json.dumps([]))
        sys.exit(0)

    path = sys.argv[1]

    if not os.path.exists(path):
        print(json.dumps({'error': f'File not found: {path}'}))
        sys.exit(1)

    print(json.dumps(vectorize(path)))