Skip to content
AI & Vectors

Roboflow

Learn how to integrate Supabase with Roboflow, a tool for running fine-tuned and foundation vision models.

在本指南中,我们将通过两个示例演示如何使用 Roboflow 推断 来运行微调模型和基础模型。我们将使用一个目标检测模型和 CLIP 运行推断并保存预测结果。

🌐 In this guide, we will walk through two examples of using Roboflow Inference to run fine-tuned and foundation models. We will run inference and save predictions using an object detection model and CLIP.

项目设置 #

🌐 Project setup

要创建一个新的 Postgres 数据库,在 Supabase 里新建一个项目:

🌐 To create a new Postgres database, start a new Project in Supabase:

  1. 在 Supabase 仪表板中创建一个新项目。
  2. 输入你的项目详情。记得把密码安全地保存起来。

你的数据库将在不到一分钟内可用。

🌐 Your database will be available in less than a minute.

查找你的凭证:

你可以在仪表板上找到你的项目凭证:

🌐 You can find your project credentials on the dashboard:

保存计算机视觉预测 #

🌐 Save computer vision predictions

一旦你有了训练好的视觉模型,你就需要为你的应用创建业务逻辑。在很多情况下,你会想把推断结果保存到文件里。

🌐 Once you have a trained vision model, you need to create business logic for your application. In many cases, you want to save inference results to a file.

以下步骤将向你展示如何在本地运行视觉模型并将预测结果保存到 Supabase。

🌐 The steps below show you how to run a vision model locally and save predictions to Supabase.

准备:搭建一个模型 #

🌐 Preparation: Set up a model

在你开始之前,你需要一个基于你数据训练的目标检测模型。

🌐 Before you begin, you will need an object detection model trained on your data.

你可以在 Roboflow 上训练模型,利用从数据管理和标注到部署的端到端工具,或者上传自定义模型权重进行部署。

🌐 You can train a model on Roboflow, leveraging end-to-end tools from data management and annotation to deployment, or upload custom model weights for deployment.

所有模型都有一个可以无限扩展的 API,通过它你可以查询你的模型,而且可以在本地运行。

🌐 All models have an infinitely scalable API through which you can query your model, and can be run locally.

在本指南中,我们将使用一个演示的剪刀石头布模型。

🌐 For this guide, we will use a demo rock, paper, scissors model.

步骤 1:安装并启动 Roboflow 推断 #

🌐 Step 1: Install and start Roboflow Inference

你将使用 Roboflow 推断(一种计算机视觉推断服务器)在本地部署我们的模型。

🌐 You will deploy our model locally using Roboflow Inference, a computer vision inference server.

要安装并启动 Roboflow 推断,首先在你的电脑上安装 Docker。

🌐 To install and start Roboflow Inference, first install Docker on your machine.

然后,运行:

🌐 Then, run:

pip install inference inference-cli inference-sdk && inference server start

推断服务器将在 http://localhost:9001 可用。

🌐 An inference server will be available at http://localhost:9001.

步骤 2:对图片进行推断 #

🌐 Step 2: Run inference on an image

你可以对图片和视频进行推断。

🌐 You can run inference on images and videos.

创建一个新的 Python 文件并添加以下代码:

🌐 Create a new Python file and add the following code:

from inference_sdk import InferenceHTTPClient
image = "example.jpg"
MODEL_ID = "rock-paper-scissors-sxsw/11"
client = InferenceHTTPClient(
api_url="http://localhost:9001",
api_key="ROBOFLOW_API_KEY"
)
with client.use_model(MODEL_ID):
predictions = client.infer(image)
print(predictions)

上面,替换:

🌐 Above, replace:

  1. 你想要运行推断的图片的 URL 以及图片的名称。
  2. ROBOFLOW_API_KEY 使用你的 Roboflow API 密钥。了解如何获取你的 Roboflow API 密钥。
  3. 用你的 Roboflow 模型 ID 替换 MODEL_ID。了解如何获取你的模型 ID。

当你运行上面的代码时,一系列预测结果会打印到控制台上:

🌐 When you run the code above, a list of predictions will be printed to the console:

{'time': 0.05402109300121083, 'image': {'width': 640, 'height': 480}, 'predictions': [{'x': 312.5, 'y': 392.0, 'width': 255.0, 'height': 110.0, 'confidence': 0.8620790839195251, 'class': 'Paper', 'class_id': 0}]}

步骤 3:将结果保存到 Supabase #

🌐 Step 3: Save results in Supabase

要在 Supabase 中保存结果,请在你的脚本中添加以下代码:

🌐 To save results in Supabase, add the following code to your script:

import os
from supabase import create_client, Client
url: str = os.environ.get("SUPABASE_URL")
key: str = os.environ.get("SUPABASE_KEY")
supabase: Client = create_client(url, key)
result = supabase.table('predictions') \
.insert({"filename": image, "predictions": predictions}) \
.execute()

然后你可以用以下代码来查询你的预测:

🌐 You can then query your predictions using the following code:

result = supabase.table('predictions') \
.select("predictions") \
.filter("filename", "eq", image) \
.execute()
print(result)

这是一个示例结果:

🌐 Here is an example result:

data=[{'predictions': {'time': 0.08492901099998562, 'image': {'width': 640, 'height': 480}, 'predictions': [{'x': 312.5, 'y': 392.0, 'width': 255.0, 'height': 110.0, 'confidence': 0.8620790839195251, 'class': 'Paper', 'class_id': 0}]}}, {'predictions': {'time': 0.08818970100037404, 'image': {'width': 640, 'height': 480}, 'predictions': [{'x': 312.5, 'y': 392.0, 'width': 255.0, 'height': 110.0, 'confidence': 0.8620790839195251, 'class': 'Paper', 'class_id': 0}]}}] count=None

计算并保存 CLIP 嵌入 #

🌐 Calculate and save CLIP embeddings

你可以使用 Supabase 的向量数据库功能来存储和查询 CLIP 嵌入。

🌐 You can use the Supabase vector database functionality to store and query CLIP embeddings.

Roboflow 推断提供了一个 HTTP 接口,你可以通过它使用 CLIP 计算图片和文本的嵌入。

🌐 Roboflow Inference provides an HTTP interface through which you can calculate image and text embeddings using CLIP.

步骤 1:安装并启动 Roboflow 推断 #

🌐 Step 1: Install and start Roboflow Inference

请参阅上面的步骤 #1:安装并启动 Roboflow 推断 来安装并启动 Roboflow 推断。

🌐 See Step #1: Install and Start Roboflow Inference above to install and start Roboflow Inference.

步骤2:在一张图片上运行CLIP #

🌐 Step 2: Run CLIP on an image

创建一个新的 Python 文件并添加以下代码:

🌐 Create a new Python file and add the following code:

import cv2
import supervision as sv
import requests
import base64
import os
IMAGE_DIR = "images/train/images/"
API_KEY = ""
SERVER_URL = "http://localhost:9001"
results = []
for i, image in enumerate(os.listdir(IMAGE_DIR)):
print(f"Processing image {image}")
infer_clip_payload = {
"image": {
"type": "base64",
"value": base64.b64encode(open(IMAGE_DIR + image, "rb").read()).decode("utf-8"),
},
}
res = requests.post(
f"{SERVER_URL}/clip/embed_image?api_key={API_KEY}",
json=infer_clip_payload,
)
embeddings = res.json()['embeddings']
results.append({
"filename": image,
"embeddings": embeddings
})

这段代码会计算目录中每张图片的 CLIP 嵌入,并把结果打印到控制台。

🌐 This code will calculate CLIP embeddings for each image in the directory and print the results to the console.

上面,替换:

🌐 Above, replace:

  1. IMAGE_DIR 与包含你想要运行推断的图片的目录。
  2. ROBOFLOW_API_KEY 使用你的 Roboflow API 密钥。了解如何获取你的 Roboflow API 密钥。

你也可以通过将 SERVER_URL 设置为 https://infer.roboflow.com 来在云端计算 CLIP 嵌入。

🌐 You can also calculate CLIP embeddings in the cloud by setting SERVER_URL to https://infer.roboflow.com.

步骤 3:将嵌入保存到 Supabase #

🌐 Step 3: Save embeddings in Supabase

你可以使用 Supabase 的 vecs Python 包在 Supabase 中存储你的图片嵌入:

🌐 You can store your image embeddings in Supabase using the Supabase vecs Python package:

首先,安装 vecs:

🌐 First, install vecs:

pip install vecs

接下来,在你的脚本中添加以下代码来创建一个索引:

🌐 Next, add the following code to your script to create an index:

import vecs
DB_CONNECTION = "postgresql://postgres:[password]@[host]:[port]/[database]"
vx = vecs.create_client(DB_CONNECTION)
# create a collection of vectors with 3 dimensions
images = vx.get_or_create_collection(name="image_vectors", dimension=512)
for result in results:
image = result["filename"]
embeddings = result["embeddings"][0]
# insert a vector into the collection
images.upsert(
records=[
(
image,
embeddings,
{} # metadata
)
]
)
images.create_index()

将 DB_CONNECTION 替换为你的数据库认证信息。你可以在 Supabase 仪表板的 Project Settings > Database Settings 中获取它。

🌐 Replace DB_CONNECTION with the authentication information for your database. You can retrieve this from the Supabase dashboard in Project Settings > Database Settings.

然后你可以用以下代码查询你的嵌入:

🌐 You can then query your embeddings using the following code:

infer_clip_payload = {
"text": "cat",
}
res = requests.post(
f"{SERVER_URL}/clip/embed_text?api_key={API_KEY}",
json=infer_clip_payload,
)
embeddings = res.json()['embeddings']
result = images.query(
data=embeddings[0],
limit=1
)
print(result[0])

资源 #

🌐 Resources