Update image_search.py
Browse files- image_search.py +9 -0
image_search.py
CHANGED
|
@@ -264,6 +264,7 @@ from chromadb.utils.embedding_functions import EmbeddingFunction
|
|
| 264 |
# Optional dataset downloader
|
| 265 |
from download import download_flickr8k_dataset
|
| 266 |
|
|
|
|
| 267 |
|
| 268 |
# -------------------------
|
| 269 |
# HuggingFace CLIP Wrapper
|
|
@@ -427,3 +428,11 @@ def update_custom_image_paths(folder_path):
|
|
| 427 |
global custom_image_paths
|
| 428 |
custom_image_paths = [os.path.join(folder_path, name) for name in os.listdir(folder_path) if name.lower().endswith((".jpg", ".jpeg", ".png"))]
|
| 429 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
# Optional dataset downloader
|
| 265 |
from download import download_flickr8k_dataset
|
| 266 |
|
| 267 |
+
TOP_K = 5
|
| 268 |
|
| 269 |
# -------------------------
|
| 270 |
# HuggingFace CLIP Wrapper
|
|
|
|
| 428 |
global custom_image_paths
|
| 429 |
custom_image_paths = [os.path.join(folder_path, name) for name in os.listdir(folder_path) if name.lower().endswith((".jpg", ".jpeg", ".png"))]
|
| 430 |
|
| 431 |
+
def query_by_image(image_path, nn_model, image_paths):
|
| 432 |
+
image = Image.open(image_path).convert("RGB")
|
| 433 |
+
tensor = clip_preprocess(image).unsqueeze(0).to(device)
|
| 434 |
+
with torch.no_grad():
|
| 435 |
+
image_features = clip_model.encode_image(tensor).cpu().numpy()
|
| 436 |
+
dists, indices = nn_model.kneighbors(image_features, n_neighbors=TOP_K)
|
| 437 |
+
return [image_paths[i] for i in indices[0]]
|
| 438 |
+
|