How to build a semantic image search engine with CLIP and Python
DEV Community

How to build a semantic image search engine with CLIP and Python

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 supply another photograph as the query when describing what you want in words is difficult. 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 enables semantic image search

To compare a sentence with a photograph, we first need a representation that makes the two comparable. A conventional image encoder can turn pixels into a vector, and a text encoder can turn words into a vector. Two independently trained encoders can produce vectors of the same dimension while representing information differently.

Contrastive Language-Image Pretraining (CLIP) addresses this problem by training an image encoder and a text encoder together. In the original CLIP paper, OpenAI describes training on 400 million image-text pairs collected from the internet. During training, CLIP learns to give an image and its matching description a higher similarity score than descriptions of other images in the same batch.

Each encoder processes its own input modality. Learned projection layers map their outputs into a shared embedding space. For the openai/clip-vit-base-patch32 checkpoint used here, the projected embedding dimension is 512.

A description such as β€œa person at the beach” and a photograph depicting that scene can have similar vector directions even though the original inputs are completely different. This also gives us a way to search by image. We encode a reference photograph with the same image encoder used for the collection, then compare its vector against the stored image vectors. Both query types can use the same 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 imag

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.