I have a folder of photos with filenames like 20251230_141957.JPEG and -7972525063673149628.JPEG. If I wanted to find a photograph of someone at the beach, searching for the word “beach” in File Explorer would not help unless I had already named or tagged the photo accordingly. I know what the photograph contains, but that information is missing from its filename.
Semantic image search lets you use that knowledge as the query. Instead of matching words against filenames, it compares a representation of your description with representations of the images in your collection. You can also use a reference photograph to find visually similar images.
I built a local Python application that supports both approaches. When I searched for “a person at the beach,” it returned the following three photographs, with the beach photo ranked first.
Figure 1: Text-to-image search results for “a person at the beach”.
In this tutorial, you'll build the same application using CLIP, a pretrained vision-language model, and PyTorch. You'll generate and cache image embeddings, implement cosine similarity search, and display the three closest matches in a Matplotlib gallery. You won't need a vector database or a paid inference API. The complete implementation is available in the GitHub repository.
How CLIP works for semantic image search
Contrastive Language–Image Pretraining (CLIP) enables semantic image search by mapping images and text into a shared embedding space. This allows us to compare a photograph with a natural-language description using their vector representations.
Training an image encoder and a text encoder independently does not guarantee that their embeddings are comparable, even when they have the same dimensions. CLIP solves this problem by training both encoders together. In the original CLIP paper, OpenAI describes training on 400 million image-text pairs collected from the internet. During training, CLIP learns to assign higher similarity scores to matching image-text pairs than to mismatched pairs within the same batch.
Each encoder processes its respective input, and learned projection layers map their outputs into a shared embedding space. For the openai/clip-vit-base-patch32 checkpoint we’ll use in this tutorial, both projected embeddings have 512 dimensions. A description like “a person at the beach” and a photograph depicting that scene will ideally have closely aligned vectors.
We can also use CLIP for image-to-image search by passing a reference photograph through the same image encoder used to process our photo collection. Since both search methods produce embeddings in the same space, we only need one ranking function.
Measuring similarity between embeddings
Cosine similarity measures the angle between two nonzero vectors. For an image embedding a and a query embedding b, it is their dot product divided by the product of their Euclidean norms:
cosine_similarity(a, b) = (a · b) / (||a|| × ||b||)
The result ranges from −1 to 1, with larger values indicating closer alignment. The score measures vector alignment rather than the probability of a match. If we normalize both vectors to unit length when encoding them, their norms become 1 and cosine similarity reduces to a dot product. This lets us calculate the scores for an entire collection with one matrix multiplication in PyTorch.
Building a local semantic image search engine
The application has two stages. At startup, it loads CLIP and prepares an embedding for every readable image in the photos directory. It stores those embeddings on disk so that subsequent runs can reuse them. At query time, it encodes the supplied description or reference image, compares the resulting vector with the stored embeddings, and displays the highest-ranked photographs.
Figure 2: Local image indexing, cached embeddings, and multimodal query retrieval.
Prerequisites
You'll need:
Python (I used 3.13.7)
Basic familiarity with Python functions and tensors
A folder of JPG, JPEG, or PNG images. Use photographs you have permission to process and share if you publish your results.
Internet connection for the initial dependency and model downloads.
Step 1: Set up the Python project
Create a project directory, open a terminal inside it, and create a virtual environment. On Windows PowerShell, run:
mkdir ai-photo-search
cd ai-photo-search
python -m venv .venv
.\.venv\Scripts\Activate.ps1
On macOS or Linux, activate the environment with source .venv/bin/activate instead. Create a requirements.txt file containing the versions I used:
torch==2.15.0
transformers==5.23.0
Pillow==13.0.0
matplotlib==3.11.2
Install the dependencies and create a directory for your photographs:
python -m pip install -r requirements.txt
mkdir photos
Create search.py in the project root and copy your images into photos. Your directory should look like this before the first run:
ai-photo-search/
.venv/
photos/
image1.jpg
image2.png
requirements.txt
search.py
Figure 3: The local photo collection with non-descriptive filenames.
PyTorch handles tensor operations and inference, Transformers loads the pretrained CLIP model and its processor, Pillow opens images, and Matplotlib displays the results. We'll build search.py throughout the next steps. You can also clone the complete repository if you prefer to follow along with the finished file.
Step 2: Load the pretrained CLIP model
Import the dependencies and define the paths and model checkpoint. CLIPModel loads both encoders and their projection layers. CLIPProcessor prepares images and text in the formats the model expects, including image preprocessing and text tokenization.
from pathlib import Path
import matplotlib.pyplot as plt
import torch
from PIL import Image
from transformers import CLIPModel, CLIPProcessor
MODEL_NAME = "openai/clip-vit-base-patch32"
PHOTO_DIR = Path("photos")
CACHE_FILE = Path("photo_embeddings.pt")
SUPPORTED_FORMATS = {".jpg", ".jpeg", ".png"}
print("Loading CLIP model...")
model = CLIPModel.from_pretrained(MODEL_NAME)
processor = CLIPProcessor.from_pretrained(MODEL_NAME)
model.eval()
The first call to from_pretrained downloads the checkpoint and configuration from Hugging Face if they are not already cached. Calling model.eval() puts the model into evaluation mode, which is appropriate because we're using pretrained weights for inference rather than training. This implementation leaves the model and tensors on the CPU.
Next, discover the images to index. Filter by file extension and sort the paths so the collection has a stable order. Record file metadata now because we'll use it to determine whether previously saved embeddings still correspond to the current collection.
PHOTO_DIR.mkdir(exist_ok=True)
photo_paths = sorted(
path for path in PHOTO_DIR.iterdir()
if path.is_file() and path.suffix.lower() in SUPPORTED_FORMATS
)
if not photo_paths:
raise SystemExit("Add JPG or PNG images to the photos folder.")
# File metadata helps invalidate the cache when the collection changes.
photo_info = [
(str(path), path.stat().st_mtime_ns, path.stat().st_size)
for path in photo_paths
]
The suffix comparison is case-insensitive, so a file ending in .JPEG is included. The application searches files directly inside photos and skips subdirectories. If the directory contains no supported files, it exits with a message rather than attempting to create an empty embedding matrix.
Step 3: Generate embeddings for the photo collection
We need to encode each photograph only once while building the index. Define encode_image() to open the image, convert it to RGB, and pass it through the processor. RGB conversion gives the model a consistent three-channel input even when the original file uses another image mode.
def encode_image(path):
with Image.open(path) as image:
inputs = processor(images=image.convert("RGB"), return_tensors="pt")
with torch.inference_mode():
features = model.get_image_features(**inputs).pooler_output
return torch.nn.functional.normalize(features, dim=-1)
The processor returns PyTorch tensors because return_tensors is set to pt. The model's get_image_features method extracts the image representation. This implementation accesses the returned pooler_output field using the installed Transformers API. torch.inference_mode() disables autograd bookkeeping for the forward pass. Finally, normalize the features along their last dimension so each nonzero embedding has unit length.
Define the corresponding text encoder now, even though we'll use it only when handling a query later. Both functions return normalized features, so the retrieval code does not need to know which modality produced a query.
def encode_text(query):
inputs = processor(text=[query], return_tensors="pt", padding=True)
with torch.inference_mode():
features = model.get_text_features(**inputs).pooler_output
return torch.nn.functional.normalize(features, dim=-1)
The text processor tokenizes the description and produces model inputs such as token IDs and an attention mask. Unlike an image, the query is represented as a sequence of tokens before it enters the text encoder. The CLIP feature extraction methods provide the representations used for retrieval. The exact return container is version-dependent, so use the pinned Transformers version when following this code.
Now iterate through the collection and accumulate the image embeddings. Keep a second list of paths for images that were successfully encoded.
def create_image_embeddings():
embeddings = []
valid_paths = []
print("Processing photos...")
for path in photo_paths:
try:
embeddings.append(encode_image(path))
valid_paths.append(path)
except Exception as error:
print(f"Skipping {path.name}: {error}")
if not embeddings:
raise SystemExit("No readable photos found.")
return torch.cat(embeddings), valid_paths
The two lists must stay aligned. Row i in the embedding matrix must correspond to valid_paths[i]. If an image cannot be opened or encoded, the exception handler skips it without adding a path. torch.cat() concatenates the individual tensors along the first dimension. For N readable images and 512-dimensional projected embeddings, the resulting matrix has shape (N, 512).
Step 4: Cache image embeddings for subsequent searches
Without persistent storage, closing and reopening the application to search for a different photograph would require running the image encoder on the entire collection again, even if none of the photographs had changed. We can avoid that work by saving the embedding matrix alongside the information needed to validate it.
def load_embeddings():
if CACHE_FILE.exists():
try:
cache = torch.load(CACHE_FILE, map_location="cpu", weights_only=True)
if (
cache["photo_info"] == photo_info
and cache["model_name"] == MODEL_NAME
and len(cache["valid_paths"]) == cache["embeddings"].shape[0]
):
print("Using saved image embeddings.")
return cache["embeddings"], [
Path(path) for path in cache["valid_paths"]
]
except (OSError, KeyError, RuntimeError, ValueError, TypeError):
pass
embeddings, paths = create_image_embeddings()
torch.save(
{
"photo_info": photo_info,
"model_name": MODEL_NAME,
"embeddings": embeddings,
"valid_paths": [str(path) for path in paths],
},
CACHE_FILE,
)
print("Image embeddings saved.")
return embeddings, paths
The cache contains the embedding tensor, the paths associated with its rows, the model name, and the file metadata collected earlier. On startup, load_embeddings() checks that the saved metadata and model name match the current configuration and that the number of paths equals the number of embedding rows. If these checks pass, it returns the stored embeddings and paths. Otherwise, it generates a fresh matrix and overwrites the cache.
The metadata comparison detects changes such as adding or removing a file, renaming it, or modifying its recorded size or timestamp. It is not a content hash, so it cannot detect every possible modification. It also rebuilds the entire collection rather than updating only changed rows. Rebuilding the entire matrix avoids having to track which embedding rows need to be inserted, updated or removed when the photo collection changes.
The weights_only=True argument restricts the objects PyTorch will unpickle when reading the cache. Keep the cache local and avoid loading files from untrusted sources. map_location='cpu' ensures the stored tensors load onto the CPU.
Implementing text-to-image and image-to-image search
We have the functions for representing images and descriptions as vectors and for persisting the image collection. The next step is to connect those representations to a retrieval function and a user interface.
Step 5: Display the matching photographs
A list of filenames and similarity scores is useful for inspecting the ranking, but it does not let us see whether the retrieved images match the query. Define a helper that creates a Matplotlib figure with one subplot per result.
def show_results(paths, scores, heading):
fig, axes = plt.subplots(
1, len(paths), figsize=(5 * len(paths), 5), squeeze=False
)
fig.suptitle(heading, fontsize=16)
for position, (path, score) in enumerate(zip(paths, scores)):
ax = axes[0][position]
with Image.open(path) as image:
ax.imshow(image.convert("RGB"))
ax.set_title(
f"Match {position + 1}\n{path.name}\nSimilarity: {score:.3f}",
fontsize=10,
)
ax.axis("off")
plt.tight_layout()
plt.show()
plt.close(fig)
The function receives already-ranked paths and scores, opens each image, and places its filename and similarity above it. squeeze=False keeps the axes array two-dimensional even when only one image is available. plt.show() opens the gallery, and closing the window allows the terminal interface to continue.
Step 6: Calculate similarity and rank images
Load the cached or newly generated embeddings, then define search_photos(). This function accepts a query embedding from either encoder. An optional exclude argument lets us prevent a reference image from appearing as its own match.
image_embeddings, valid_paths = load_embeddings()
def search_photos(query_embedding, heading, exclude=None):
scores = (image_embeddings @ query_embedding.T).flatten()
# Avoid returning the exact reference file as its own closest match.
if exclude is not None:
for index, path in enumerate(valid_paths):
if path.resolve() == exclude.resolve():
scores[index] = float("-inf")
available = int(torch.isfinite(scores).sum().item())
if not available:
print("No other photos available to compare.")
return
top_scores, top_indices = torch.topk(scores, k=min(3, available))
matching_paths = []
print("\nTop matching photos:\n")
for rank, (score, index) in enumerate(zip(top_scores, top_indices), start=1):
path = valid_paths[index.item()]
matching_paths.append(path)
print(f"{rank}. {path.name} | Cosine similarity: {score.item():.3f}")
show_results(matching_paths, top_scores.tolist(), heading)
The first line inside search_photos() performs the retrieval. If the collection matrix has shape (N, 512) and the query has shape (1, 512), transposing the query produces a (512, 1) tensor. Matrix multiplication returns an (N, 1) tensor containing one dot product per image. flatten() converts it to a one-dimensional score tensor. Normalizing both sets of vectors makes each dot product equivalent to cosine similarity.
For image queries, the function compares resolved filesystem paths and sets the exact reference file's score to negative infinity if it is present in the collection. This excludes that path from the highest finite scores. It does not detect duplicate images stored under different filenames.
torch.topk() returns the largest scores and their indices. We request three results, or fewer if fewer eligible images remain. Each index identifies the corresponding path in valid_paths, which is why preserving the alignment between paths and embeddings earlier was essential. The function prints the ranking and passes it to show_results().
Step 7: Connect both search modes to the CLI
The final part of search.py is an interactive loop. Option 1 passes a description to encode_text(); option 2 opens a reference photograph using encode_image(). Both call the same search_photos() function, so we don't need separate ranking implementations.
while True:
print("\nAI PHOTO SEARCH")
print("1. Search by description")
print("2. Search by image")
print("3. Exit")
choice = input("\nChoose an option (1-3): ").strip()
if choice == "1":
query = input("\nDescribe the photo you're looking for: ").strip()
if not query:
print("Please enter a description.")
continue
print("\nSearching your photos...")
search_photos(encode_text(query), f'Search results for "{query}"')
elif choice == "2":
image_path = input("\nEnter the reference image path: ").strip()
reference = Path(image_path.strip('"').strip("'"))
if not reference.is_file():
print("Image not found. Check the file path.")
continue
try:
print("\nFinding similar photos...")
search_photos(
encode_image(reference),
f"Photos similar to {reference.name}",
exclude=reference,
)
except (OSError, ValueError) as error:
print(f"Could not open the image: {error}")
elif choice == "3":
print("Goodbye!")
break
else:
print("Please choose 1, 2, or 3.")
The loop rejects empty descriptions and checks that a reference path points to a file before encoding it. Stripping surrounding quotation marks also makes it easier to paste a path copied from File Explorer. Option 3 exits the application. With this loop in place, search.py is complete.
Running the semantic image search engine
From the project directory, with the virtual environment active, run:
python search.py
On the first run, the application downloads any missing model files, processes the photographs, and saves photo_embeddings.pt. On subsequent runs with unchanged metadata, it prints “Using saved image embeddings.” The model still loads at startup because we need its encoders to process new queries.
Search by description
Choose option 1 and enter a description of a photograph in your collection. In my demonstration, I entered “a person at the beach.” The terminal returned:
Top matching photos:
1. -7972525063673149628.JPEG | Cosine similarity: 0.254
2. 20251230_141957.JPEG | Cosine similarity: 0.224
3. 20260829_194504.jpg | Cosine similarity: 0.220
Figure 4: Terminal output showing cache reuse and the ranked text query results.
My beach photo ranked first with a cosine similarity of 0.254. Both remaining photos contain people in other outdoor settings. The score of 0.254 measures the alignment between the query and the beach photo embeddings on a scale from −1 to 1. Since the application selects the three highest scores, it can return images that match only part of the description.
Close the gallery to return to the menu and try another description. In a second test, the query “a woman with hair” returned three photographs with scores of 0.244, 0.232 and 0.231. The application reused the saved image embeddings for the search.
Figure 5: Ranked results for a second natural-language query.
Search by reference image
Choose option 2 and paste the path to a reference photograph. It can be inside or outside the photos directory. The application encodes it with the image encoder, then ranks the collection using the same similarity calculation.
In my demo, the reference file was 20261124_121813.jpg. The three returned scores were 0.562, 0.561, and 0.507. The gallery included two photographs of people and a product photograph of an iron. The iron ranked second with a score of 0.561, just 0.001 below the first photograph.
Figure 6: Image-to-image retrieval results from the recorded demonstration.
Use image-to-image search when you have a reference photo and struggle to describe it in words.
What else can you build with CLIP?
You've built a local semantic image search engine that accepts natural-language descriptions and reference photographs, caches image embeddings, and ranks results with cosine similarity. You can extend the same retrieval pattern to product catalogs and multimodal retrieval-augmented generation. Encode the collection, represent the query in a compatible embedding space, and retrieve the closest candidates.
You can find the complete source code and pinned dependencies in the GitHub repository.
FAQs and troubleshooting
Do I need a vector database for semantic image search?
No. This application stores its vectors in a PyTorch tensor and calculates exact similarity scores against every indexed image. With N vectors of dimension d, computing the scores takes O(Nd) arithmetic operations per query, before selecting the top results. For a small collection, this avoids operating a separate database. As the collection grows, consider an approximate nearest-neighbor index for faster retrieval or a vector database if you also need metadata filtering and concurrent access.
Why does the application return photos that don't match my description?
The ranking function selects up to three eligible images regardless of their absolute scores. It does not apply a minimum similarity threshold. You can introduce a threshold before displaying results, but choose it using representative queries and images rather than treating an arbitrary cosine score as a universal relevance cutoff. CLIP can also struggle with fine-grained attributes, counting, and compositional descriptions.
Can I run CLIP without an internet connection?
Once the model and processor files are available locally, the encoding and similarity calculations do not require a remote inference service. The current from_pretrained calls may still contact Hugging Face to resolve files. To explicitly restrict loading to cached files, pass local_files_only=True to both from_pretrained calls after downloading the checkpoint, or load both from a local model directory. See the Hugging Face offline-mode documentation.
Why does the application regenerate my embeddings?
Cache validation compares the current file paths, modification timestamps, sizes, and model name against the saved values. A change in any of these can trigger a rebuild. If you suspect the cache is stale or incompatible after changing the implementation, delete photo_embeddings.pt and restart the application to regenerate it.
What if CLIP feature extraction raises an attribute error?
Check that you're using the pinned Transformers version. The return type of get_image_features() and get_text_features() can differ between releases. Consult the documentation or implementation for your installed version and make sure you're extracting the projected features used for cross-modal similarity, rather than the raw hidden states of either encoder. Equal vector dimensions alone do not establish that two representations share a semantic space.






Top comments (1)
The most honest number in the whole tutorial is 0.254. Your beach photo ranked first with a cosine similarity of 0.254 — correct, but barely above noise — and your FAQ says it plainly: the app returns three results regardless of their absolute scores. That is the gap between a working demo and a tool you would trust with a real photo library. A top-3 list that always has three entries trains you to ignore the scores, and the image-to-image scores show why: 0.562, 0.561, 0.544 are so close together that ranking alone stops telling you anything useful.
The cache design is the part I would steal, though — validating paths, modification times, sizes, and the model name before reusing photo_embeddings.pt, and loading with weights_only=True, is exactly the unglamorous correctness work most tutorials skip. And I like that you answered the vector-database question with a straight no: for a personal folder, one tensor and exact similarity is the right call.
Would you add a minimum similarity threshold, with a "no confident match" state instead of three forced results — and how would you pick that threshold without a labeled set to calibrate against? And at what collection size does the exact scan over one big tensor start to feel slow enough that you would reach for an index?