以下是使用milvus进行以图搜图的Python代码示例:

import os
import io
import numpy as np
from PIL import Image

from milvus import Milvus, IndexType, MetricType
from minio import Minio
from minio.error import ResponseError

# Set up Milvus and Minio clients
milvus_client = Milvus(host='localhost', port='19530')
minio_client = Minio(
    "localhost:9000",
    access_key="minioadmin",
    secret_key="minioadmin",
    secure=False
)

# Define the bucket and image prefix to search
bucket_name = "my-bucket"
prefix = "images/"

# Define the index and metric types for Milvus
index_type = IndexType.IVF_FLAT
metric_type = MetricType.L2

# Create the index and collection in Milvus if it doesn't exist
collection_name = "image_collection"
if not milvus_client.has_collection(collection_name):
    milvus_client.create_collection({"collection_name": collection_name, "dimension": 512, "index_file_size": 1024,
                                      "metric_type": metric_type})

if not milvus_client.has_partition(collection_name, "image_partition"):
    milvus_client.create_partition(collection_name, "image_partition")

if not milvus_client.has_index(collection_name):
    milvus_client.create_index(collection_name, index_type, {"nlist": 128})

# Get the vectors and corresponding image IDs from Milvus
query_vectors = []
query_ids = []
search_params = {"nprobe": 16}
results = milvus_client.search(collection_name, top_k=10, query_records=query_vectors, params=search_params)
for result in results:
    query_ids.append(result.id)

# Download the images from Minio and get their vectors using a pre-trained model
vectors = []
for id in query_ids:
    object_name = prefix + str(id) + ".jpg"
    try:
        image_data = minio_client.get_object(bucket_name, object_name)
        image_bytes = io.BytesIO(image_data.data)
        image = Image.open(image_bytes)
        vector = get_vector_from_model(image)
        vectors.append(vector)
    except ResponseError as err:
        print(err)

# Search for similar images in Milvus using the image vectors
search_vectors = np.array(vectors)
search_ids = []
search_results = milvus_client.search(collection_name, top_k=10, query_records=search_vectors, params=search_params)
for result in search_results:
    search_ids.append(result.id)

# Download and display the top 5 similar images
for i in range(5):
    object_name = prefix + str(search_ids[i]) + ".jpg"
    try:
        image_data = minio_client.get_object(bucket_name, object_name)
        image_bytes = io.BytesIO(image_data.data)
        image = Image.open(image_bytes)
        image.show()
    except ResponseError as err:
        print(err)

这段代码的大致流程如下:

  1. 连接Milvus和Minio客户端,并设置要搜索的图像的桶和前缀。
  2. 创建Milvus集合和索引,并检查是否已经存在。如果不存在,则创建。
  3. 使用Milvus从集合中获取要搜索的图像的向量和ID。
  4. 使用Minio从桶中下载图像,并使用预训练模型获取它们的向量。
  5. 使用Milvus搜索相似的图像,使用先前获取的向量作为查询向量。
  6. 下载并显示与查询图像最相似的前5个图像
milvus中以图搜图代码

原文地址: https://www.cveoy.top/t/topic/ePww 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录