AI Image Similarity Search Project

Artificial Intelligence project 16

AI Image Similarity Search Project

Build a complete image similarity search workflow with reproducible Python code, transparent inputs, reviewable output, and responsible-use limits.

Explore AI training in VizagView all project ideas

AI objective

Find candidate images with the most similar normalised colour distributions.

Data or knowledge source

Four locally generated solid-colour demonstration PNG images; the search also accepts user-supplied local images.

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install numpy Pillow
  • About 45-60 minutes to build and review

How the system works

Convert to RGB, resize consistently, build per-channel histograms, normalise each feature vector, and rank dot-product similarity.

Validation checklist

  • All images use the same colour mode and size
  • Feature vectors are unit normalised
  • The query file is excluded from results
  • Similarity stays between zero and one

Complete Python code

Save the program as ai_image_similarity_search.py. The code runs locally and requires no paid API key or model download.

"""Find visually similar images using normalized colour histograms."""

from __future__ import annotations

from pathlib import Path
import tempfile
import numpy as np
from PIL import Image


def colour_histogram(path: str | Path, bins: int = 16) -> np.ndarray:
    with Image.open(path) as image:
        pixels = np.asarray(image.convert("RGB").resize((128, 128)), dtype=np.uint8)
    features = []
    for channel in range(3):
        histogram, _ = np.histogram(pixels[:, :, channel], bins=bins, range=(0, 256))
        features.extend(histogram.astype(float))
    vector = np.asarray(features)
    norm = np.linalg.norm(vector)
    return vector / norm if norm else vector


def search(query: str | Path, candidates: list[str | Path], limit: int = 3) -> list[tuple[str, float]]:
    query_vector = colour_histogram(query)
    scored = [(str(path), float(np.dot(query_vector, colour_histogram(path)))) for path in candidates if Path(path) != Path(query)]
    return sorted(scored, key=lambda item: item[1], reverse=True)[:limit]


def create_demo_images(folder: str | Path) -> list[Path]:
    folder = Path(folder)
    colours = {"red.png": (220, 40, 40), "warm_red.png": (205, 65, 45), "blue.png": (35, 70, 210), "green.png": (40, 180, 90)}
    paths = []
    for name, colour in colours.items():
        path = folder / name
        Image.new("RGB", (160, 120), colour).save(path)
        paths.append(path)
    return paths


def main() -> None:
    with tempfile.TemporaryDirectory() as folder:
        images = create_demo_images(folder)
        print(search(images[0], images))
    print("Colour histograms compare colour distribution, not objects, meaning, copyright, or identity.")


if __name__ == "__main__":
    main()

Run the project

  1. Create and activate a virtual environment.
  2. Install dependencies with python -m pip install numpy Pillow when packages are required.
  3. Run python ai_image_similarity_search.py.
  4. Review confidence, fallbacks, sources, or error metrics rather than accepting output automatically.
  5. Test additional normal, edge, unsupported, and adversarial inputs.

Expected output

A ranked list of image paths and colour-histogram similarities.

Accuracy, privacy, and responsible-use limits

Colour histograms do not recognise objects, meaning, copyright, people, identity, or image safety. Never use this baseline for facial recognition or high-impact decisions.

Ways to extend the project

Add perceptual hashes, texture features, pretrained embeddings with documented models, duplicate thresholds, evaluation labels, and safe-image handling.

Continue learning Artificial Intelligence

Try the next project, return to the Softenant project library, or explore the AI training in Vizag for guided NLP, retrieval, evaluation, automation, and responsible AI practice.