import torch
import numpy as np
from transformers import CLIPProcessor, CLIPModel
from PIL import Image
import time
import os
import redis
# 连接 Redis 数据库,地址换成你自己的 Redis 地址
client = redis.Redis(host="redis-server", port=6379, decode_responses=True)
res = client.ping()
print("redis connected:", res)
model_name_or_local_path = "openai/clip-vit-base-patch16"
model = CLIPModel.from_pretrained(model_name_or_local_path)
processor = CLIPProcessor.from_pretrained(model_name_or_local_path)
image_directory = "images"
png_files = [filename for filename in os.listdir(image_directory) if filename.endswith(".png")]
sorted_png_files = sorted(png_files, key=lambda x: int(x.split('-')[-1].split('.')[0]))
# 初始化 Redis Pipeline
pipeline = client.pipeline()
for i, png_file in enumerate(sorted_png_files, start=1):
# 初始化 Redis,先使用 PNG 文件名作为 Key 和 Value,后续再更新为图片特征向量
pipeline.json().set(png_file, "$", png_file)
batch_size = 1
with torch.no_grad():
for idx, png_file in enumerate(sorted_png_files, start=1):
print(f"{idx}: {png_file}")
start = time.time()
image = Image.open(f"{image_directory}/{png_file}")
inputs = processor(images=image, return_tensors="pt", padding=True)
image_features = model.get_image_features(inputs.pixel_values)[batch_size-1]
embeddings = image_features.numpy().astype(np.float32).tolist()
print('image_features:', embeddings)
vector_dimension = len(embeddings)
print('vector_dimension:', vector_dimension)
end = time.time()
print('%s Seconds'%(end-start))
# 更新 Redis 数据库中的文件向量
pipeline.json().set(png_file, "$", embeddings)
res = pipeline.execute()
print('redis set:', res)
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
图片搜索引擎,很简单。三步构建属于你自己的图片搜索引擎,掌握向量数据库和以图搜图、文本搜索图片 教程 准备数据:开源软件 FFmpeg 生成模型使用图片数据集 处理图片数据,构建向量索引:使用 Redis 构建轻量的向量数据库应用:图片搜索引擎(一) 实现向量搜索、图片检索:使用 Redis 构建轻量的向量数据库应用:图片搜索引擎(二)
资源推荐
资源详情
资源评论
收起资源包目录
simple-image-search-engine-main.zip (18个子文件)
simple-image-search-engine-main
.github
detective.jpg 80KB
steps
2.get-all-sorted-images
app.py 473B
5.save-all-embeddings-to-redis
app.py 2KB
test-store.py 258B
7.search-images-by-image
app.py 2KB
ball-8576.jpg 95KB
8.use-clip-detect-element
app.py 1KB
ball-8576.jpg 95KB
6.build-vector-indexes
app.py 1KB
check-indexes.py 552B
9.search-images-by-text
app.py 2KB
3.how-to-embeddings-all-images
app.py 1KB
4.save-embeddings-to-redis
app.py 1KB
ball-8576.jpg 95KB
1.how-to-embeddings
app.py 1KB
ball-8576.jpg 95KB
docker
Dockerfile 251B
docker-compose.yml 415B
共 18 条
- 1
资源评论
博士僧小星
- 粉丝: 1884
- 资源: 5877
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功