APIインターフェース仕様書
概要
本システムは完全なRESTful APIインターフェースを提供します。すべてのAPIルートは face_tracker_mcp/api/routes.py に統一的に定義され、FlaskのBlueprintを通じてWebサービスに登録されています。クロスオリジンアクセス(CORS)に対応し、標準的なJSON形式でレスポンスを返します。
ベースURL: http://localhost:5000
顔検出API
顔検出結果の取得
エンドポイント: GET /api/faces
機能: 現在検出されているすべての顔の情報を取得します。
レスポンス例:
{
"faces": [
{
"id": 1,
"confidence": 0.92,
"bbox": {
"x1": 150,
"y1": 100,
"x2": 250,
"y2": 200
},
"center": {
"x": 200,
"y": 150
},
"area": 10000,
"is_tracking": true
}
],
"count": 1,
"timestamp": "2023-12-01T15:30:45.123Z"
}
フィールド説明:
id: 顔ID(追跡システムが割り当て)confidence: 検出信頼度 (0.0-1.0)bbox: バウンディングボックス座標(左上と右下)center: 顔の中心点座標area: 顔のバウンディングボックス面積(ピクセル²)is_tracking: 現在の追跡対象かどうか
パン・チルト雲台制御API
雲台の絶対位置制御
エンドポイント: POST /api/gimbal/control
機能: 雲台を指定した絶対角度位置まで移動させます。
リクエストボディ:
{
"pan": 135.0, // 水平角度 (0-270度)
"tilt": 90.0 // 垂直角度 (0-270度)
}
成功レスポンス (200):
{
"success": true,
"message": "云台已移动到指定位置",
"position": {
"pan": 135.0,
"tilt": 90.0
}
}
エラーレスポンス (400):
{
"success": false,
"error": "角度超出范围",
"error_type": "ANGLE_OUT_OF_RANGE",
"details": {
"valid_range": "0-270度",
"provided_angle": 300.0
}
}
雲台の相対移動
エンドポイント: POST /api/gimbal/relative
機能: 現在位置を基準に相対的な角度調整を行います。
リクエストボディ:
{
"pan_offset": 10.0, // 水平角度偏移量(正值向右)
"tilt_offset": -5.0 // 垂直角度偏移量(正值向上)
}
レスポンス形式: 絶対位置制御APIと同じです。
雲台状態の取得
エンドポイント: GET /api/gimbal/status
機能: 雲台の現在位置と状態情報を取得します。
レスポンス例:
{
"position": {
"pan": 135.0,
"tilt": 90.0
},
"is_connected": true,
"last_update": "2023-12-01T15:30:45.123Z",
"angle_range": {
"pan": [0, 270],
"tilt": [0, 270]
},
"serial_config": {
"port": "/dev/ttyS1",
"baudrate": 115200,
"timeout": 1.0
}
}
雲台位置のリセット
エンドポイント: POST /api/gimbal/reset
機能: 雲台を初期位置(水平135°、垂直135°)にリセットします。
リクエストボディ: 不要
成功レスポンス (200):
{
"success": true,
"message": "云台已重置到初始位置",
"position": {
"pan": 135.0,
"tilt": 135.0
}
}
顔追跡API
自動追跡の開始
エンドポイント: POST /api/tracking/start
機能: 顔の自動追跡機能を開始します。
リクエストボディ:
{
"target_center_threshold": 50 // 可选:目标中心阈值(像素)
}
成功レスポンス (200):
{
"success": true,
"message": "人脸追踪已启动",
"config": {
"target_center_threshold": 50,
"pid_enabled": true,
"kalman_enabled": true
}
}
自動追跡の停止
エンドポイント: POST /api/tracking/stop
機能: 顔の自動追跡機能を停止します。
成功レスポンス (200):
{
"success": true,
"message": "人脸追踪已停止"
}
追跡状態の取得
エンドポイント: GET /api/tracking/status
機能: 現在の追跡システムの状態とパラメーターを取得します。
レスポンス例:
{
"is_enabled": true,
"current_target": {
"id": 1,
"center": {"x": 320, "y": 240},
"confidence": 0.92,
"tracking_duration": 5.2
},
"tracking_stats": {
"targets_detected": 3,
"tracking_switches": 1,
"average_confidence": 0.87
},
"pid_config": {
"kp": 0.6,
"ki": 0.1,
"kd": 0.05
},
"kalman_config": {
"enabled": true,
"prediction_enabled": true
}
}
映像ストリームAPI
リアルタイム映像ストリーム
エンドポイント: GET /video_feed
機能: 顔検出結果を可視化したMJPEG形式のリアルタイム映像ストリームを取得します。
レスポンス: multipart/x-mixed-replace 形式の映像ストリーム
特長:
- 顔検出枠のリアルタイム描画
- 追跡対象の特別表示(オレンジ色の枠+「Tracking」ラベル)
- フレームレート表示
- 検出統計情報
静止画のキャプチャ
エンドポイント: GET /api/capture
機能: 現在のフレームをキャプチャし、Base64エンコードされた画像を返します。
レスポンス例:
{
"success": true,
"image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...",
"timestamp": "2023-12-01T15:30:45.123Z",
"faces_detected": 2
}
システム状態API
システム状態
エンドポイント: GET /api/system/status
機能: システムの稼働状態と設定情報を取得します。
レスポンス例:
{
"status": "running",
"version": "2.0.0",
"uptime": "2h 15m 32s",
"services": {
"web": "active",
"mcp": "active",
"detection": "active",
"tracking": "enabled",
"gimbal": "connected"
},
"hardware": {
"camera": {
"device": "/dev/facecamera",
"resolution": "640x480",
"fps": 30,
"status": "connected"
},
"gimbal": {
"port": "/dev/ttyS1",
"baudrate": 115200,
"status": "connected"
}
},
"performance": {
"detection_fps": 29.5,
"tracking_latency": 15.2,
"memory_usage": "385MB",
"cpu_usage": "12%"
},
"config": {
"model_path": "model/yolo11n_face_detect_bayese_320x320_nv12.bin",
"confidence_threshold": 0.6,
"iou_threshold": 0.45
}
}
ヘルスチェック
エンドポイント: GET /api/health
機能: システムの可用性を監視するための簡易ヘルスチェックです。
レスポンス例:
{
"status": "healthy",
"timestamp": "2023-12-01T15:30:45.123Z",
"checks": {
"model_loaded": true,
"camera_accessible": true,
"gimbal_connected": true,
"services_running": true
}
}
エラー処理
共通エラー形式
すべてのAPIは統一されたエラーレスポンス形式に従います。
{
"success": false,
"error": "错误描述信息",
"error_type": "ERROR_CODE",
"error_code": "FACE_001",
"details": {
"field": "具体错误详情",
"timestamp": "2023-12-01T15:30:45.123Z"
}
}
主なエラーコード
| エラーコード | HTTPステータス | エラー種別 | 説明 |
|---|---|---|---|
INVALID_REQUEST |
400 | リクエストエラー | リクエストパラメーターが無効または不足しています |
ANGLE_OUT_OF_RANGE |
400 | パラメーターエラー | 雲台の角度が有効範囲外です |
GIMBAL_NOT_CONNECTED |
503 | デバイスエラー | 雲台デバイスが未接続、または通信に失敗しました |
GIMBAL_MOVE_ERROR |
500 | 操作エラー | 雲台の移動操作の実行に失敗しました |
CAMERA_NOT_FOUND |
503 | デバイスエラー | カメラデバイスが使用できません |
MODEL_ERROR |
500 | システムエラー | 顔検出モデルの推論に失敗しました |
TRACKING_ERROR |
500 | システムエラー | 追跡システムの内部エラーです |
SYSTEM_ERROR |
500 | システムエラー | 不明なシステム内部エラーです |
エラー処理のベストプラクティス
- HTTPステータスコードの確認: まずレスポンスのHTTPステータスコードを確認します
- エラー情報の解析:
errorフィールドを読み取り、ユーザー向けのエラー説明を取得します - エラー種別の判定:
error_typeを使ってプログラムでエラーを処理します - 詳細情報: より詳しいデバッグ情報は
detailsフィールドを参照します
座標系の説明
画像座標系
- 原点: 画像の左上 (0,0)
- X軸: 右方向が正
- Y軸: 下方向が正
- 単位: ピクセル
- 範囲: X[0-640], Y[0-480](デフォルト解像度)
雲台角度系
- 水平軸(Pan): 0°-270°、135°が中心位置
- 垂直軸(Tilt): 0°-270°、135°が中心位置
- 単位: 度 (°)
- 精度: 1°刻み
相対座標への変換
画像中心に対する顔中心の座標:
# 图像中心坐标
image_center_x = 320 # 640/2
image_center_y = 240 # 480/2
# 相对坐标计算
relative_x = face_center_x - image_center_x # [-320, 320]
relative_y = face_center_y - image_center_y # [-240, 240]
APIクライアントの例
Pythonの例
import requests
import json
# 基础配置
BASE_URL = "http://localhost:5000"
headers = {"Content-Type": "application/json"}
class FaceTrackerAPI:
def __init__(self, base_url=BASE_URL):
self.base_url = base_url
self.session = requests.Session()
def get_faces(self):
"""获取人脸检测结果"""
response = self.session.get(f"{self.base_url}/api/faces")
return response.json()
def control_gimbal(self, pan, tilt):
"""控制云台位置"""
payload = {"pan": pan, "tilt": tilt}
response = self.session.post(
f"{self.base_url}/api/gimbal/control",
json=payload
)
return response.json()
def start_tracking(self, threshold=50):
"""启动人脸追踪"""
payload = {"target_center_threshold": threshold}
response = self.session.post(
f"{self.base_url}/api/tracking/start",
json=payload
)
return response.json()
def get_system_status(self):
"""获取系统状态"""
response = self.session.get(f"{self.base_url}/api/system/status")
return response.json()
# 使用示例
api = FaceTrackerAPI()
# 检查系统状态
status = api.get_system_status()
print(f"系统状态: {status['status']}")
# 获取人脸信息
faces = api.get_faces()
print(f"检测到 {faces['count']} 个人脸")
# 启动追踪
result = api.start_tracking()
print(f"追踪启动: {result['success']}")
# 控制云台
result = api.control_gimbal(150, 120)
print(f"云台控制: {result['success']}")
JavaScript/Node.jsの例
const axios = require('axios');
class FaceTrackerAPI {
constructor(baseURL = 'http://localhost:5000') {
this.client = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {'Content-Type': 'application/json'}
});
}
async getFaces() {
try {
const response = await this.client.get('/api/faces');
return response.data;
} catch (error) {
console.error('获取人脸信息失败:', error.response?.data);
throw error;
}
}
async controlGimbal(pan, tilt) {
try {
const response = await this.client.post('/api/gimbal/control', {
pan: pan,
tilt: tilt
});
return response.data;
} catch (error) {
console.error('云台控制失败:', error.response?.data);
throw error;
}
}
async startTracking(threshold = 50) {
try {
const response = await this.client.post('/api/tracking/start', {
target_center_threshold: threshold
});
return response.data;
} catch (error) {
console.error('启动追踪失败:', error.response?.data);
throw error;
}
}
}
// 使用示例
(async () => {
const api = new FaceTrackerAPI();
try {
// 获取系统状态
const status = await api.client.get('/api/system/status');
console.log('系统状态:', status.data.status);
// 启动追踪
const tracking = await api.startTracking(60);
console.log('追踪启动:', tracking.success);
// 控制云台
const gimbal = await api.controlGimbal(140, 110);
console.log('云台控制:', gimbal.success);
} catch (error) {
console.error('API调用失败:', error.message);
}
})();
curlコマンドの例
# 获取系统状态
curl -X GET http://localhost:5000/api/system/status
# 获取人脸检测结果
curl -X GET http://localhost:5000/api/faces
# 控制云台位置
curl -X POST http://localhost:5000/api/gimbal/control \
-H "Content-Type: application/json" \
-d '{"pan": 135.0, "tilt": 90.0}'
# 启动人脸追踪
curl -X POST http://localhost:5000/api/tracking/start \
-H "Content-Type: application/json" \
-d '{"target_center_threshold": 50}'
# 停止人脸追踪
curl -X POST http://localhost:5000/api/tracking/stop
# 云台相对移动
curl -X POST http://localhost:5000/api/gimbal/relative \
-H "Content-Type: application/json" \
-d '{"pan_offset": 10.0, "tilt_offset": -5.0}'
# 重置云台位置
curl -X POST http://localhost:5000/api/gimbal/reset
# 健康检查
curl -X GET http://localhost:5000/api/health
レート制限
システムの安定性を保つため、APIには以下のレート制限が設けられています。
- 雲台制御API: 1秒あたり最大2リクエスト
- 追跡制御API: 1秒あたり最大1リクエスト
- 状態照会API: 1秒あたり最大10リクエスト
- 映像ストリームAPI: 制限なし
- ヘルスチェックAPI: 1秒あたり最大20リクエスト
認証とセキュリティ
現在のバージョンでは基本的なCORSポリシーを使用し、クロスオリジンアクセスを許可しています。本番環境では以下を推奨します。
- APIキー認証: 機密性の高い操作にAPIキー認証を追加する
- IPホワイトリスト: アクセス元のIPアドレスを制限する
- HTTPS暗号化: TLSで通信を暗号化する
- リクエスト署名: 重要な操作にはリクエスト署名による検証を行う
監視とデバッグ
APIログ
すべてのAPIリクエストは、以下の内容とともにログに記録されます。
- リクエストのタイムスタンプ
- クライアントIP
- リクエストパスとメソッド
- レスポンスステータスコード
- レスポンス時間
デバッグモード
環境変数を設定してデバッグモードを有効にします。
export FACE_TRACKER_LOGGING_CONSOLE_LEVEL=DEBUG
パフォーマンス監視
システムは以下のパフォーマンス指標を提供します。
- APIレスポンス時間
- リクエスト成功率
- システムリソースの使用状況
- ハードウェアデバイスの状態
詳細なパフォーマンスデータは /api/system/status エンドポイントで取得できます。
お問い合わせ
資料のダウンロード・技術サポートについては、HumansX株式会社までお問い合わせください。
ドキュメント