Elffuss BraidHub

kikocis/lancedb public

e822b4e34fb7 · 7.0 KiBRenderedRawPermalink
1# How to Load Image Embeddings into LanceDB
2
3With the rise of Large Multimodal Models (LMMs) such as [GPT-4 Vision](https://blog.roboflow.com/gpt-4-vision/), the need for storing image embeddings is growing. The most effective way to store text and image embeddings is in a vector database such as LanceDB. Vector databases are a special kind of data store that enables efficient search over stored embeddings.
4
5[CLIP](https://blog.roboflow.com/openai-clip/), a multimodal model developed by OpenAI, is commonly used to calculate image embeddings. These embeddings can then be used with a vector database to build a semantic search engine that you can query using images or text. For example, you could use LanceDB and CLIP embeddings to build a search engine for a database of folders.
6
7In this guide, we are going to show you how to use Roboflow Inference to load image embeddings into LanceDB. Without further ado, let’s get started!
8
9## Step #1: Install Roboflow Inference
10
11[Roboflow Inference](https://inference.roboflow.com) enables you to run state-of-the-art computer vision models with minimal configuration. Inference supports a range of models, from fine-tuned object detection, classification, and segmentation models to foundation models like CLIP. We will use Inference to calculate CLIP image embeddings.
12
13Inference provides a HTTP API through which you can run vision models.
14
15Inference powers the Roboflow hosted API, and is available as an open source utility. In this guide, we are going to run Inference locally, which enables you to calculate CLIP embeddings on your own hardware. We will also show you how to use the hosted Roboflow CLIP API, which is ideal if you need to scale and do not want to manage a system for calculating embeddings.
16
17To get started, first install the Inference CLI:
18
19```
20pip install inference-cli
21```
22
23Next, install Docker. Refer to the official Docker installation instructions for your operating system to get Docker set up. Once Docker is ready, you can start Inference using the following command:
24
25```
26inference server start
27```
28
29An Inference server will start running at ‘http://localhost:9001’.
30
31## Step #2: Set Up a LanceDB Vector Database
32
33Now that we have Inference running, we can set up a LanceDB vector database. You can run LanceDB in JavaScript and Python. For this guide, we will use the Python API. But, you can take the HTTP requests we make below and change them to JavaScript if required.
34
35For this guide, we are going to search the [COCO 128 dataset](https://universe.roboflow.com/team-roboflow/coco-128), which contains a wide range of objects. The variability in objects present in this dataset makes it a good dataset to demonstrate the capabilities of vector search. If you want to use this dataset, you can download [COCO 128 from Roboflow Universe](https://universe.roboflow.com/team-roboflow/coco-128). With that said, you can search whatever folder of images you want.
36
37Once you have a dataset ready, install LanceDB with the following command:
38
39```
40pip install lancedb
41```
42
43We also need to install a specific commit of `tantivy`, a dependency of the LanceDB full text search engine we will use later in this guide:
44
45```
46pip install tantivy
47```
48
49Create a new Python file and add the following code:
50
51```python
52import cv2
53import supervision as sv
54import requests
55
56import lancedb
57
58db = lancedb.connect("./embeddings")
59
60IMAGE_DIR = "images/"
61API_KEY = os.environ.get("ROBOFLOW_API_KEY")
62SERVER_URL = "http://localhost:9001"
63
64results = []
65
66for i, image in enumerate(os.listdir(IMAGE_DIR)):
67 infer_clip_payload = {
68 #Images can be provided as urls or as base64 encoded strings
69 "image": {
70 "type": "base64",
71 "value": base64.b64encode(open(IMAGE_DIR + image, "rb").read()).decode("utf-8"),
72 },
73 }
74
75 res = requests.post(
76 f"{SERVER_URL}/clip/embed_image?api_key={API_KEY}",
77 json=infer_clip_payload,
78 )
79
80 embeddings = res.json()['embeddings']
81
82 print("Calculated embedding for image: ", image)
83
84 image = {"vector": embeddings[0], "name": os.path.join(IMAGE_DIR, image)}
85
86 results.append(image)
87
88tbl = db.create_table("images", data=results)
89
90tbl.create_fts_index("name")
91```
92
93To use the code above, you will need a Roboflow API key. [Learn how to retrieve a Roboflow API key](https://docs.roboflow.com/api-reference/authentication#retrieve-an-api-key). Run the following command to set up your API key in your environment:
94
95```
96export ROBOFLOW_API_KEY=""
97```
98
99Replace the `IMAGE_DIR` value with the folder in which you are storing the images for which you want to calculate embeddings. If you want to use the Roboflow CLIP API to calculate embeddings, replace the `SERVER_URL` value with `https://infer.roboflow.com`.
100
101Run the script above to create a new LanceDB database. This database will be stored on your local machine. The database will be called `embeddings` and the table will be called `images`.
102
103The script above calculates all embeddings for a folder then creates a new table. To add additional images, use the following code:
104
105```python
106def make_batches():
107 for i in range(5):
108 yield [
109 {"vector": [3.1, 4.1], "name": "image1.png"},
110 {"vector": [5.9, 26.5], "name": "image2.png"}
111 ]
112
113tbl = db.open_table("images")
114tbl.add(make_batches())
115```
116
117Replacing the `make_batches()` function with code to load embeddings for images.
118
119## Step #3: Run a Search Query
120
121We are now ready to run a search query. To run a search query, we need a text embedding that represents a text query. We can use this embedding to search our LanceDB database for an entry.
122
123Let’s calculate a text embedding for the query “cat”, then run a search query:
124
125```python
126infer_clip_payload = {
127 "text": "cat",
128}
129
130res = requests.post(
131 f"{SERVER_URL}/clip/embed_text?api_key={API_KEY}",
132 json=infer_clip_payload,
133)
134
135embeddings = res.json()['embeddings']
136
137df = tbl.search(embeddings[0]).limit(3).to_list()
138
139print("Results:")
140
141for i in df:
142 print(i["name"])
143```
144
145This code will search for the three images most closely related to the prompt “cat”. The names of the most similar three images will be printed to the console. Here are the three top results:
146
147```
148dataset/images/train/000000000650_jpg.rf.1b74ba165c5a3513a3211d4a80b69e1c.jpg
149dataset/images/train/000000000138_jpg.rf.af439ef1c55dd8a4e4b142d186b9c957.jpg
150dataset/images/train/000000000165_jpg.rf.eae14d5509bf0c9ceccddbb53a5f0c66.jpg
151```
152
153Let’s open the top image:
154
155![Cat](https://media.roboflow.com/cat_lancedb.jpg)
156
157The top image was a cat. Our search was successful.
158
159## Conclusion
160
161LanceDB is a vector database that you can use to store and efficiently search your image embeddings. You can use Roboflow Inference, a scalable computer vision inference server, to calculate CLIP embeddings that you can store in LanceDB.
162
163You can use Inference and LanceDB together to build a range of applications with image embeddings, from a media search engine to a retrieval-augmented generation pipeline for use with LMMs.
164
165To learn more about Inference and its capabilities, refer to the Inference documentation.