clip_vectorizer.py
1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/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)))