Logo文件

API 參考

使用 SegmentLens API 進行影像分割的完整指南。

API 參考

SegmentLens 提供了一個強大的 REST API,讓您可以將我們先進的 SAM3 影像分割功能直接整合到您的應用程式中。

官方示範

我們提供了一個完整的 Node.js 示範應用程式,展示如何整合 SAM3 API。該示範包括後端 API 整合以及具有物件視覺化和下載功能的互動式前端。

GitHub 儲存庫segmentany/sam3-nodejs-demo

快速入門

# 複製儲存庫
git clone https://github.com/segmentany/sam3-nodejs-demo.git
cd sam3-nodejs-demo

# 安裝依賴項
npm install

# 配置 API 金鑰
cp .env.example .env
# 編輯 .env 並設定:SAM3_API_KEY=sk_live_your_actual_api_key_here

# 啟動伺服器
npm start
# 開啟 http://localhost:3000

驗證

所有 API 請求都必須使用 API 金鑰進行驗證。您可以在儀表板的 設定 > API 金鑰 部分生成和管理您的 API 金鑰。

請在請求的 Authorization 標頭中包含您的 API 金鑰:

Authorization: Bearer sk_live_...

端點

分割影像

對提供的影像 URL 執行影像分割。此端點支援基於點和基於框的提示。

  • URLhttps://sam3.ai/api/v1/segment
  • 方法POST
  • Content-Typeapplication/json

請求主體

欄位類型必填說明
imagestringBase64 編碼的影像字串。
promptsstring[]用於識別要分割的物件的文字提示陣列(例如 ["cat", "dog"])。

注意

  1. 限制:最大解析度 1024x1024。最大 Base64 負載大小 2MB。超過這些限制的影像將被拒絕。
    • 原因:大型影像處理時間過長,可能會超時。調整大小為 1024x1024 不會影響分割品質。
    • 建議:在發送之前在客戶端調整影像大小。您可以將返回的多邊形座標縮放回原始解析度。
  2. 至少需要一個文字提示。

請求範例

curl -X POST https://sam3.ai/api/v1/segment \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk_live_..." \
  -d '{
    "image": "base64_encoded_image_string...",
    "prompts": ["cat", "sunglasses"]
  }'

Node.js 範例

// server.js - Express 後端範例
const express = require('express');
const fetch = require('node-fetch');

const app = express();
app.use(express.json({ limit: '10mb' }));

const SAM3_API_URL = 'https://sam3.ai/api/v1/segment';
const SAM3_API_KEY = process.env.SAM3_API_KEY;

app.post('/api/segment', async (req, res) => {
  try {
    const response = await fetch(SAM3_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${SAM3_API_KEY}`
      },
      body: JSON.stringify({
        image: req.body.image,
        prompts: req.body.prompts
      })
    });
    
    const data = await response.json();
    res.json(data);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

前端範例

// 客戶端影像處理和 API 調用
const MAX_SIZE = 1024;

async function segmentImage(file, prompts) {
  // 將影像調整為最大 1024x1024
  const resizedImage = await resizeImage(file, MAX_SIZE);
  
  const response = await fetch('/api/segment', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      image: resizedImage.base64,
      prompts: prompts
    })
  });
  
  const data = await response.json();
  
  // 將遮罩座標縮放回原始解析度
  const scaleFactor = resizedImage.scaleFactor;
  data.prompt_results.forEach(result => {
    result.predictions.forEach(pred => {
      pred.masks = pred.masks.map(mask => 
        mask.map(point => [point[0] / scaleFactor, point[1] / scaleFactor])
      );
    });
  });
  
  return data;
}

async function resizeImage(file, maxSize) {
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      let width = img.width;
      let height = img.height;
      let scaleFactor = 1;
      
      if (width > maxSize || height > maxSize) {
        scaleFactor = maxSize / Math.max(width, height);
        width *= scaleFactor;
        height *= scaleFactor;
      }
      
      const canvas = document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0, width, height);
      
      resolve({
        base64: canvas.toDataURL('image/jpeg', 0.9).split(',')[1],
        scaleFactor: scaleFactor
      });
    };
    img.src = URL.createObjectURL(file);
  });
}

回應

API 返回一個包含 prompt_results 陣列中分割結果的 JSON 物件。

{
  "prompt_results": [
    {
      "echo": {
        "text": "cat"
      },
      "predictions": [
        {
          "label": "cat",
          "confidence": 0.98,
          "masks": [
            [
              [100, 100], [150, 100], [150, 150], [100, 150]
            ]
          ]
        }
      ]
    }
  ]
}

速率限制

API 設有速率限制,以確保公平使用和穩定性。

  • 限制:每位使用者每秒 10 個請求。

如果您超過此限制,您將收到 429 Too Many Requests 回應。

錯誤

API 使用標準 HTTP 狀態碼來指示請求的成功或失敗。

狀態碼說明
200OK。請求成功。
400錯誤的請求。缺少必填欄位或格式無效。
401未經授權。API 金鑰無效或遺失。
402需要付款。點數不足。
429請求過多。超過速率限制。
500內部伺服器錯誤。我們的伺服器出現問題。

疑難排解

"Unauthorized" 或 401

  • 驗證 SAM3_API_KEY 是否設定正確
  • 確保金鑰有效且處於啟用狀態
  • 更改環境變數後重新啟動伺服器

"Image too large" 或 413

  • API 強制執行最大影像大小和負載大小
  • 示範已經調整了影像大小,但極大的影像仍可能超過限制
  • 嘗試使用較小的來源影像或減少 MAX_SIZE

"Rate limit exceeded"

  • 您使用相同金鑰發送請求的速度過快
  • 在客戶端新增簡單的節流或佇列

伺服器無法啟動

  • 檢查連接埠 3000 是否已被佔用
  • 嘗試更改 server.js 中的 PORT
  • 確保已使用 npm install 安裝依賴項

找不到物件 (No objects found)

  • 嘗試不同的提示(例如 "person", "car", "tree")
  • 確認上傳的影像實際上包含請求的物件
  • 在瀏覽器開發者工具的網路標籤中檢查 API 錯誤

程式碼結構

示範專案遵循此結構:

sam3-nodejs-demo/
├── server.js          # Express 後端
├── package.json       # 依賴項和腳本
├── .env.example       # 環境變數範本
├── .env               # 本地環境(未提交)
├── .gitignore         # Git 忽略規則
└── public/
    └── index.html     # 前端單頁應用程式
API 參考 | SegmentLens - 基於 SAM 3 的智慧影像平台