1. Structure
  2. AI & ML
  3. Vector Search
  4. Tutorials
  5. Advanced
  6. Image Search
  • Home
  • What is TileDB?
  • Get Started
  • Explore Content
  • Accounts
    • Individual Accounts
      • Apply for the Free Tier
      • Profile
        • Overview
        • Cloud Credentials
        • Storage Paths
        • REST API Tokens
        • Credits
    • Organization Admins
      • Create an Organization
      • Profile
        • Overview
        • Members
        • Cloud Credentials
        • Storage Paths
        • Billing
      • API Tokens
    • Organization Members
      • Organization Invitations
      • Profile
        • Overview
        • Members
        • Cloud Credentials
        • Storage Paths
        • Billing
      • API Tokens
  • Catalog
    • Introduction
    • Data
      • Arrays
      • Tables
      • Single-Cell (SOMA)
      • Genomics (VCF)
      • Biomedical Imaging
      • Vector Search
      • Files
    • Code
      • Notebooks
      • Dashboards
      • User-Defined Functions
      • Task Graphs
      • ML Models
    • Groups
    • Marketplace
    • Search
  • Collaborate
    • Introduction
    • Organizations
    • Access Control
      • Introduction
      • Share Assets
      • Asset Permissions
      • Public Assets
    • Logging
    • Marketplace
  • Analyze
    • Introduction
    • Slice Data
    • Multi-Region Redirection
    • Notebooks
      • Launch a Notebook
      • Usage
      • Widgets
      • Notebook Image Dependencies
    • Dashboards
      • Dashboards
      • Streamlit
    • Preview
    • User-Defined Functions
    • Task Graphs
    • Serverless SQL
    • Monitor
      • Task Log
      • Task Graph Log
  • Scale
    • Introduction
    • Task Graphs
    • API Usage
  • Structure
    • Why Structure Is Important
    • Arrays
      • Introduction
      • Quickstart
      • Foundation
        • Array Data Model
        • Key Concepts
          • Storage
            • Arrays
            • Dimensions
            • Attributes
            • Cells
            • Domain
            • Tiles
            • Data Layout
            • Compression
            • Encryption
            • Tile Filters
            • Array Schema
            • Schema Evolution
            • Fragments
            • Fragment Metadata
            • Commits
            • Indexing
            • Array Metadata
            • Datetimes
            • Groups
            • Object Stores
          • Compute
            • Writes
            • Deletions
            • Consolidation
            • Vacuuming
            • Time Traveling
            • Reads
            • Query Conditions
            • Aggregates
            • User-Defined Functions
            • Distributed Compute
            • Concurrency
            • Parallelism
        • Storage Format Spec
      • Tutorials
        • Basics
          • Basic Dense Array
          • Basic Sparse Array
          • Array Metadata
          • Compression
          • Encryption
          • Data Layout
          • Tile Filters
          • Datetimes
          • Multiple Attributes
          • Variable-Length Attributes
          • String Dimensions
          • Nullable Attributes
          • Multi-Range Reads
          • Query Conditions
          • Aggregates
          • Deletions
          • Catching Errors
          • Configuration
          • Basic S3 Example
          • Basic TileDB Cloud
          • fromDataFrame
          • Palmer Penguins
        • Advanced
          • Schema Evolution
          • Advanced Writes
            • Write at a Timestamp
            • Get Fragment Info
            • Consolidation
              • Fragments
              • Fragment List
              • Consolidation Plan
              • Commits
              • Fragment Metadata
              • Array Metadata
            • Vacuuming
              • Fragments
              • Commits
              • Fragment Metadata
              • Array Metadata
          • Advanced Reads
            • Get Fragment Info
            • Time Traveling
              • Introduction
              • Fragments
              • Array Metadata
              • Schema Evolution
          • Array Upgrade
          • Backends
            • Amazon S3
            • Azure Blob Storage
            • Google Cloud Storage
            • MinIO
            • Lustre
          • Virtual Filesystem
          • User-Defined Functions
          • Distributed Compute
          • Result Estimation
          • Incomplete Queries
        • Management
          • Array Schema
          • Groups
          • Object Management
        • Performance
          • Summary of Factors
          • Dense vs. Sparse
          • Dimensions vs. Attributes
          • Compression
          • Tiling and Data Layout
          • Tuning Writes
          • Tuning Reads
      • API Reference
    • Tables
      • Introduction
      • Quickstart
      • Foundation
        • Data Model
        • Key Concepts
          • Indexes
          • Columnar Storage
          • Compression
          • Data Manipulation
          • Optimize Tables
          • ACID
          • Serverless SQL
          • SQL Connectors
          • Dataframes
          • CSV Ingestion
      • Tutorials
        • Basics
          • Ingestion with SQL
          • CSV Ingestion
          • Basic S3 Example
          • Running Locally
        • Advanced
          • Scalable Ingestion
          • Scalable Queries
      • API Reference
    • AI & ML
      • Vector Search
        • Introduction
        • Quickstart
        • Foundation
          • Data Model
          • Key Concepts
            • Vector Search
            • Vector Databases
            • Algorithms
            • Distance Metrics
            • Updates
            • Deployment Methods
            • Architecture
            • Distributed Compute
          • Storage Format Spec
        • Tutorials
          • Basics
            • Ingestion & Querying
            • Updates
            • Deletions
            • Basic S3 Example
            • Running Locally
          • Advanced
            • Versioning
            • Time Traveling
            • Consolidation
            • Distributed Compute
            • RAG LLM
            • LLM Memory
            • File Search
            • Image Search
            • Protein Search
          • Performance
        • API Reference
      • ML Models
        • Introduction
        • Quickstart
        • Foundation
          • Basics
          • Storage
          • Cloud Execution
          • Why TileDB for Machine Learning
        • Tutorials
          • Ingestion
            • Data Ingestion
              • Dense Datasets
              • Sparse Datasets
            • ML Model Ingestion
          • Management
            • Array Schema
            • Machine Learning: Groups
            • Time Traveling
    • Life Sciences
      • Single-cell
        • Introduction
        • Quickstart
        • Foundation
          • Data Model
          • Key Concepts
            • Data Structures
            • Use of Apache Arrow
            • Join IDs
            • State Management
            • TileDB Cloud URIs
          • SOMA API Specification
        • Tutorials
          • Data Ingestion
          • Bulk Ingestion Tutorial
          • Data Access
          • Distributed Compute
          • Basic S3 Example
          • Multi-Experiment Queries
          • Appending Data to a SOMA Experiment
          • Add New Measurements
          • SQL Queries
          • Running Locally
          • Shapes in TileDB-SOMA
          • Drug Discovery App
        • Spatial
          • Introduction
          • Foundation
            • Spatial Data Model
            • Data Structures
          • Tutorials
            • Spatial Data Ingestion
            • Access Spatial Data
            • Manage Coordinate Spaces
        • API Reference
      • Population Genomics
        • Introduction
        • Quickstart
        • Foundation
          • Data Model
          • Key Concepts
            • The N+1 Problem
            • Architecture
            • Arrays
            • Ingestion
            • Reads
            • Variant Statistics
            • Annotations
            • User-Defined Functions
            • Tables and SQL
            • Distributed Compute
          • Storage Format Spec
        • Tutorials
          • Basics
            • Basic Ingestion
            • Basic Queries
            • Export to VCF
            • Add New Samples
            • Deleting Samples
            • Basic S3 Example
            • Basic TileDB Cloud
          • Advanced
            • Scalable Ingestion
            • Scalable Queries
            • Query Transforms
            • Handling Large Queries
            • Annotations
              • Finding Annotations
              • Embedded Annotations
              • External Annotations
              • Annotation VCFs
              • Ingesting Annotations
            • Variant Statistics
            • Tables and SQL
            • User-Defined Functions
            • Sample Metadata
            • Split VCF
          • Performance
        • API Reference
          • Command Line Interface
          • Python API
          • Cloud API
      • Biomedical Imaging
        • Introduction
        • Foundation
          • Data Model
          • Key Concepts
            • Arrays
            • Ingestion
            • Reads
            • User Defined Functions
          • Storage Format Spec
        • Quickstart
        • Tutorials
          • Basics
            • Ingestion
            • Read
              • OpenSlide
              • TileDB-Py
          • Advanced
            • Batched Ingestion
            • Chunked Ingestion
            • Machine Learning
              • PyTorch
            • Napari
    • Files
  • API Reference
  • Self-Hosting
    • Installation
    • Upgrades
    • Administrative Tasks
    • Image Customization
      • Customize User-Defined Function Images
      • AWS ECR Container Registry
      • Customize Jupyter Notebook Images
    • Single Sign-On
      • Configure Single Sign-On
      • OpenID Connect
      • Okta SCIM
      • Microsoft Entra
  • Glossary

On this page

  • Setup
  • Store raw images
  • Create vector index
  • Similarity search
  • Clean up
  1. Structure
  2. AI & ML
  3. Vector Search
  4. Tutorials
  5. Advanced
  6. Image Search

Image Search

ai/ml
vector search
tutorials
search
Learn how to perform similarity search over images, generating image embeddings and using TileDB-Vector-Search to add them to vector indexes and query them.
How to run this tutorial

We recommend running this tutorial, as well as the other various tutorials in the Tutorials section, inside TileDB Cloud. This will allow you to quickly experiment avoiding all the installation, deployment, and configuration hassles. Sign up for the free tier, spin up a TileDB Cloud notebook with a Python kernel, and follow the tutorial instructions. If you wish to learn how to run tutorials locally on your machine, read the Tutorials: Running Locally tutorial.

This tutorial is an image search demo, using TileDB-Vector-Search and a dataset of flowers.

Setup

If you are running this tutorial on a local machine, you may have to perform the following installations:

conda install -y -c tiledb -c conda-forge -c anaconda tiledb-vector-search scikit-learn tensorflow-datasets matplotlib efficientnet
# NOTE: `efficientnet` conda package is available on linux only, so
# you can install it from pip on all non-Linux machines

# Or, using pip
#pip install tiledb tiledb-vector-search-scikit-learn tensorflow-datasets efficientnet matplotlib
pip install

Import the necessary packages, set the URIs you will use throughout this tutorial, and delete any past data:

import os
import shutil
import warnings

import numpy as np

warnings.filterwarnings("ignore")
import random

import PIL
import tensorflow as tf
import tensorflow_datasets as tfds
import tiledb
import tiledb.vector_search as vs
from efficientnet.preprocessing import center_crop_and_resize
from tensorflow.keras.applications.resnet_v2 import preprocess_input
from tensorflow_datasets.core import dataset_utils

# URIs you will use in this tutorial
dataset = "tf_flowers"
image_array_uri = "tf_flowers_array"
index_uri = "tf_flowers_index"
features_uri = "features.f32bin"

# Clean up past data
if os.path.exists(image_array_uri):
    shutil.rmtree(image_array_uri)
if os.path.exists(index_uri):
    shutil.rmtree(index_uri)
if os.path.exists(features_uri):
    os.remove(features_uri)

Store raw images

In addition to the vector embeddings you will store using TileDB-Vector-Search, you can use the TileDB array engine to store all the raw images in a 3D TileDB array. This is yet another cool feature of TileDB, which allows you to unify all your data (both “unstructured” and “structured”) under a common data model (i.e., arrays) and database engine.

Create the 3D image array as follows:

# Will be used to define the array domain
crop_image_size = 224

# Define the image array schema, which is a 3D array that will store all images
image_array_schema = tiledb.ArraySchema(
    domain=tiledb.Domain(
        [
            tiledb.Dim(
                name="image_id",
                dtype="uint64",
                domain=(0, np.iinfo(np.uint64).max - 10000),
                tile=10,
            ),
            tiledb.Dim(
                name="d1",
                dtype="uint64",
                domain=(0, crop_image_size - 1),
                tile=crop_image_size,
            ),
            tiledb.Dim(
                name="d2",
                dtype="uint64",
                domain=(0, crop_image_size - 1),
                tile=crop_image_size,
            ),
            tiledb.Dim(name="d3", dtype="uint64", domain=(0, 2), tile=2),
        ]
    ),
    attrs=[
        tiledb.Attr(name="value", dtype=np.uint8),
    ],
    sparse=False,
)

# Physically create the array
tiledb.Array.create(image_array_uri, image_array_schema)

Next, load the images from their source location.

# Load the image dataset.
# NOTE: This could take several minutes depending on your machine configuration.
ds, ds_info = tfds.load(dataset, split="train", with_info=True)

Create a utility function that loads and preprocesses the images and saves them in a TileDB array:

def save_images(ds_info, ds, num_samples, image_key, crop_image_size=-1):
    samples = list(dataset_utils.as_numpy(ds.take(num_samples)))
    images_data = np.array([])
    for i, sample in enumerate(samples):
        if not isinstance(sample, dict):
            raise ValueError(
                "tfds.show_examples requires examples as `dict`, with the same "
                "structure as `ds_info.features`. It is currently not compatible "
                "with `as_supervised=True`. Received: {}".format(type(sample))
            )

        # Preprocess the image
        image = sample[image_key]
        if len(image.shape) != 3:
            raise ValueError(
                "Image dimension should be 3. tfds.show_examples does not support "
                "batched examples or video."
            )
        _, _, c = image.shape
        if c == 1:
            image = image.reshape(image.shape[:2])
        if crop_image_size != -1:
            image = center_crop_and_resize(image, crop_image_size).astype(np.uint8)
        if images_data.any():
            images_data = np.concatenate((images_data, image[None, :]), axis=0)
        else:
            images_data = image[None, :]
    with tiledb.open(image_array_uri, mode="w") as A:
        A[0:image_samples] = {"value": images_data}

Now, save the images in the TileDB array:

image_samples = 3670
save_images(ds_info, ds, image_samples, "image", crop_image_size)

Create vector index

Create a utility function that computes the image embeddings using ResNet50V2:

def calculate_resnet(x: np.ndarray) -> np.ndarray:
    model = tf.keras.applications.ResNet50V2(include_top=False)
    maps = model.predict(preprocess_input(x))
    if np.prod(maps.shape) == maps.shape[-1] * len(x):
        return np.squeeze(maps)
    else:
        return maps.mean(axis=1).mean(axis=1)

Next, generate embeddings for all images and store them in a binary file:

with tiledb.open(image_array_uri, mode="r") as A:
    data = A[0:image_samples]["value"]
    embeddings = calculate_resnet(data)
    with open("features.f32bin", "wb") as f:
        np.array(embeddings.shape, dtype="uint32").tofile(f)
        np.array(embeddings).astype("float32").tofile(f)

Ingest the embeddings into an IVF_FLAT array:

index_ivf_flat = vs.ingest(
    index_type="IVF_FLAT",
    index_uri=index_uri,
    source_uri="features.f32bin",
)

Similarity search

Prepare the index for reading:

index_flat = vs.IVFFlatIndex(index_uri)

Choose a randomly sampled image from the image dataset:

with tiledb.open(image_array_uri, mode="r") as A:
    query_image = A[random.randint(0, image_samples - 1)]["value"]
query_embeding = calculate_resnet(query_image[None, :])
display(PIL.Image.fromarray(query_image))
1/1 [==============================] - 1s 616ms/step

Perform image similarity search using the selected image:

# Retrieve the 5 most similar images to the randomly selected one.
result_d, result_i = index_flat.query(query_embeding, k=5)
with tiledb.open(image_array_uri, mode="r") as A:
    for result in result_i[0]:
        display(PIL.Image.fromarray(A[result]["value"]))

Clean up

Delete all the generated data.

# Clean up
if os.path.exists(image_array_uri):
    shutil.rmtree(image_array_uri)
if os.path.exists(index_uri):
    shutil.rmtree(index_uri)
if os.path.exists(features_uri):
    os.remove(features_uri)
File Search
Protein Search