使用 Milvus 搜尋圖像
在本筆記簿中,我們將教您如何使用 Milvus 在資料集中搜尋類似圖像。我們將使用ImageNet資料集的一個子集,然後搜尋一隻阿富汗獵犬的圖像來進行示範。
資料集準備
首先,我們需要載入資料集並解壓縮以進行進一步處理。
!wget https://github.com/milvus-io/pymilvus-assets/releases/download/imagedata/reverse_image_search.zip
!unzip -q -o reverse_image_search.zip
先決條件
若要執行本筆記本,您需要安裝下列依賴項目:
- pymilvus>=2.4.2
- timm
- 火炬
- numpy
- sklearn
- 枕頭
為了執行 Colab,我們提供了安裝必要相依性的簡易指令。
$ pip install pymilvus --upgrade
$ pip install timm
如果您使用的是 Google Colab,要啟用剛安裝的相依性,您可能需要重新啟動運行時間。(點擊螢幕頂部的 "Runtime 「菜單,從下拉菜單中選擇 」Restart session")。
定義特徵擷取器
接下來,我們需要定義一個特徵萃取器,使用 timm 的 ResNet-34 模型從影像中萃取嵌入。
import torch
from PIL import Image
import timm
from sklearn.preprocessing import normalize
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
class FeatureExtractor:
def __init__(self, modelname):
# Load the pre-trained model
self.model = timm.create_model(
modelname, pretrained=True, num_classes=0, global_pool="avg"
)
self.model.eval()
# Get the input size required by the model
self.input_size = self.model.default_cfg["input_size"]
config = resolve_data_config({}, model=modelname)
# Get the preprocessing function provided by TIMM for the model
self.preprocess = create_transform(**config)
def __call__(self, imagepath):
# Preprocess the input image
input_image = Image.open(imagepath).convert("RGB") # Convert to RGB if needed
input_image = self.preprocess(input_image)
# Convert the image to a PyTorch tensor and add a batch dimension
input_tensor = input_image.unsqueeze(0)
# Perform inference
with torch.no_grad():
output = self.model(input_tensor)
# Extract the feature vector
feature_vector = output.squeeze().numpy()
return normalize(feature_vector.reshape(1, -1), norm="l2").flatten()
建立 Milvus 集合
接下來,我們需要建立 Milvus 集合來儲存圖像的內嵌。
from pymilvus import MilvusClient
# Set up a Milvus client
client = MilvusClient(uri="example.db")
# Create a collection in quick setup mode
if client.has_collection(collection_name="image_embeddings"):
client.drop_collection(collection_name="image_embeddings")
client.create_collection(
collection_name="image_embeddings",
vector_field_name="vector",
dimension=512,
auto_id=True,
enable_dynamic_field=True,
metric_type="COSINE",
)
至於MilvusClient
的參數:
- 將
uri
設定為本機檔案,例如./milvus.db
,是最方便的方法,因為它會自動利用Milvus Lite 將所有資料儲存在這個檔案中。 - 如果您有大規模的資料,您可以在docker 或 kubernetes 上架設效能更高的 Milvus 伺服器。在此設定中,請使用伺服器的 uri,例如
http://localhost:19530
,作為您的uri
。 - 如果您想使用Zilliz Cloud(Milvus 的完全管理雲端服務),請調整
uri
和token
,與 Zilliz Cloud 的Public Endpoint 和 Api key對應。
將嵌入資料插入 Milvus
我們將使用 ResNet34 模型擷取每張圖片的嵌入資料,並將訓練集中的圖片插入 Milvus。
import os
extractor = FeatureExtractor("resnet34")
root = "./train"
insert = True
if insert is True:
for dirpath, foldername, filenames in os.walk(root):
for filename in filenames:
if filename.endswith(".JPEG"):
filepath = dirpath + "/" + filename
image_embedding = extractor(filepath)
client.insert(
"image_embeddings",
{"vector": image_embedding, "filename": filepath},
)
from IPython.display import display
query_image = "./test/Afghan_hound/n02088094_4261.JPEG"
results = client.search(
"image_embeddings",
data=[extractor(query_image)],
output_fields=["filename"],
search_params={"metric_type": "COSINE"},
)
images = []
for result in results:
for hit in result[:10]:
filename = hit["entity"]["filename"]
img = Image.open(filename)
img = img.resize((150, 150))
images.append(img)
width = 150 * 5
height = 150 * 2
concatenated_image = Image.new("RGB", (width, height))
for idx, img in enumerate(images):
x = idx % 5
y = idx // 5
concatenated_image.paste(img, (x * 150, y * 150))
display("query")
display(Image.open(query_image).resize((150, 150)))
display("results")
display(concatenated_image)
'query'
png
'results'
結果
我們可以看到大部分的圖片都來自與搜尋圖片相同的類別,也就是阿富汗獵犬。這表示我們找到與搜尋圖像相似的圖像。
快速部署
若要瞭解如何利用本教學開始線上演示,請參閱範例應用程式。