CompreFace人脸识别应用集成指南:API调用示例
1. 引言
在当今数字化时代,人脸识别技术已广泛应用于安防、考勤、身份验证等多个领域。CompreFace作为一款领先的开源人脸识别系统,提供了强大且易用的API接口,使得开发者能够快速将人脸识别功能集成到自己的应用中。本指南将详细介绍CompreFace的API调用方法,并提供丰富的代码示例,帮助开发者轻松上手。
2. API基础信息
2.1 基础URL
CompreFace的API基础URL为:http://localhost:8000/api/v1/
2.2 请求头
所有API请求都需要包含以下请求头:
Content-Type:根据请求类型设置为application/json或multipart/form-datax-api-key:服务API密钥,由用户创建
3. 人脸识别服务API
3.1 管理主体(Subjects)
3.1.1 添加主体
创建一个新的主体到人脸集合中。
请求示例:
curl -X POST "http://localhost:8000/api/v1/recognition/subjects" \
-H "Content-Type: application/json" \
-H "x-api-key: <service_api_key>" \
-d '{"subject": "<subject_name>"}'
参数说明: | 元素 | 描述 | 类型 | 是否必需 | 备注 | |--------------|-------------|--------|----------|-------------------------------------------------------------------------------| | Content-Type | 请求头 | string | 必需 | application/json | | x-api-key | 请求头 | string | 必需 | 用户创建的人脸识别服务API密钥 | | subject | 请求体参数 | string | 必需 | 主体名称,可以是人名或任何字符串 |
成功响应:
{
"subject": "<subject_name>"
}
3.1.2 重命名主体
重命名现有主体。如果新主体名称已存在,将合并两个主体。
请求示例:
curl -X PUT "http://localhost:8000/api/v1/recognition/subjects/<subject>" \
-H "Content-Type: application/json" \
-H "x-api-key: <service_api_key>" \
-d '{"subject": "<new_subject_name>"}'
成功响应:
{
"updated": "true"
}
3.1.3 删除主体
删除现有主体及所有保存的人脸。
请求示例:
curl -X DELETE "http://localhost:8000/api/v1/recognition/subjects/<subject>" \
-H "Content-Type: application/json" \
-H "x-api-key: <service_api_key>"
成功响应:
{
"subject": "<subject_name>"
}
3.1.4 列出所有主体
返回人脸集合中所有主体。
请求示例:
curl -X GET "http://localhost:8000/api/v1/recognition/subjects/" \
-H "Content-Type: application/json" \
-H "x-api-key: <service_api_key>"
成功响应:
{
"subjects": [
"<subject_name1>",
"<subject_name2>"
]
}
3.2 管理主体示例(Subject Examples)
主体示例是指要保存到人脸集合中的已知人脸图像。
3.2.1 添加主体示例
通过保存图像创建主体示例。图像应只包含一张人脸。
请求示例:
curl -X POST "http://localhost:8000/api/v1/recognition/faces?subject=<subject>&det_prob_threshold=<det_prob_threshold>" \
-H "Content-Type: multipart/form-data" \
-H "x-api-key: <service_api_key>" \
-F file=@<local_file>
参数说明: | 元素 | 描述 | 类型 | 是否必需 | 备注 | |--------------------|-------------|--------|----------|------------------------------------------------------------------------------------------------------| | Content-Type | 请求头 | string | 必需 | multipart/form-data | | x-api-key | 请求头 | string | 必需 | 用户创建的人脸识别服务API密钥 | | subject | URL参数 | string | 必需 | 分配给保存图像的主体名称 | | det_prob_threshold | URL参数 | string | 可选 | 识别到的人脸实际上是人脸的最小置信度,值在0.0到1.0之间 | | file | 请求体 | image | 必需 | 允许的图像格式:jpeg、jpg、ico、png、bmp、gif、tif、tiff、webp,最大大小为5Mb |
成功响应:
{
"image_id": "6b135f5b-a365-4522-b1f1-4c9ac2dd0728",
"subject": "subject1"
}
3.2.2 列出主体的所有示例
检索主体的所有保存示例。
请求示例:
curl -X GET "http://localhost:8000/api/v1/recognition/faces?page=<page>&size=<size>&subject=<subject>" \
-H "x-api-key: <service_api_key>"
成功响应:
{
"faces": [
{
"image_id": "<image_id>",
"subject": "<subject>"
},
...
],
"page_number": 0,
"page_size": 10,
"total_pages": 2,
"total_elements": 12
}
3.2.3 删除主体的所有示例
删除指定主体的所有图像示例。
请求示例:
curl -X DELETE "http://localhost:8000/api/v1/recognition/faces?subject=<subject>" \
-H "x-api-key: <service_api_key>"
成功响应:
{
"deleted": <count>
}
3.3 人脸识别
3.3.1 从图像中识别人脸
识别上传图像中的人脸。
请求示例:
curl -X POST "http://localhost:8000/api/v1/recognition/recognize?limit=<limit>&prediction_count=<prediction_count>&det_prob_threshold=<det_prob_threshold>&face_plugins=<face_plugins>&status=<status>&detect_faces=<detect_faces>" \
-H "Content-Type: multipart/form-data" \
-H "x-api-key: <service_api_key>" \
-F file=<local_file>
参数说明: | 元素 | 描述 | 类型 | 是否必需 | 备注 | |--------------------|-------------|---------|----------|------------------------------------------------------------------------------------------------------------------------------------------------| | Content-Type | 请求头 | string | 必需 | multipart/form-data | | x-api-key | 请求头 | string | 必需 | 用户创建的人脸识别服务API密钥 | | file | 请求体 | image | 必需 | 允许的图像格式:jpeg、jpg、ico、png、bmp、gif、tif、tiff、webp,最大大小为5Mb | | limit | URL参数 | integer | 可选 | 图像上要识别的最大人脸数,优先识别最大的人脸,0表示无限制,默认值为0 | | det_prob_threshold | URL参数 | string | 可选 | 识别到的人脸实际上是人脸的最小置信度,值在0.0到1.0之间 | | prediction_count | URL参数 | integer | 可选 | 每个人脸的最大主体预测数,返回最相似的主体,默认值为1 | | face_plugins | URL参数 | string | 可选 | 人脸插件的逗号分隔slug,如果为空,不返回附加信息 | | status | URL参数 | boolean | 可选 | 如果为true,包括执行时间和插件版本等系统信息,默认值为false | | detect_faces | URL参数 | boolean | 可选 | 如果为false,CompreFace不会运行人脸检测器,而是将图像视为裁剪后的人脸,默认值为true(自1.2版本起) |
成功响应:
{
"result": [
{
"age": {
"probability": 0.9308982491493225,
"high": 32,
"low": 25
},
"gender": {
"probability": 0.9898611307144165,
"value": "female"
},
"mask": {
"probability": 0.9999470710754395,
"value": "without_mask"
},
"embedding": [9.424854069948196E-4, "...", -0.011415496468544006],
"box": {
"probability": 1.0,
"x_max": 1420,
"y_max": 1368,
"x_min": 548,
"y_min": 295
},
"landmarks": [[814, 713], [1104, 829], [832, 937], [704, 1030], [1017, 1133]],
"subjects": [
{
"similarity": 0.97858,
"subject": "subject1"
}
],
"execution_time": {
"age": 28.0,
"gender": 26.0,
"detector": 117.0,
"calculator": 45.0,
"mask": 36.0
}
}
],
"plugins_versions": {
"age": "agegender.AgeDetector",
"gender": "agegender.GenderDetector",
"detector": "facenet.FaceDetector",
"calculator": "facenet.Calculator",
"mask": "facemask.MaskDetector"
}
}
3.3.2 人脸验证
将上传图像中的人脸与保存的图像ID对应的人脸进行比较。
请求示例:
curl -X POST "http://localhost:8000/api/v1/recognition/faces/<image_id>/verify?limit=<limit>&det_prob_threshold=<det_prob_threshold>&face_plugins=<face_plugins>&status=<status>" \
-H "Content-Type: multipart/form-data" \
-H "x-api-key: <service_api_key>" \
-F file=<local_file>
成功响应:
{
"result": [
{
"age": {
"probability": 0.9308982491493225,
"high": 32,
"low": 25
},
"gender": {
"probability": 0.9898611307144165,
"value": "female"
},
"mask": {
"probability": 0.9999470710754395,
"value": "without_mask"
},
"embedding": [-0.049007344990968704, "...", -0.01753818802535534],
"box": {
"probability": 0.9997453093528748,
"x_max": 205,
"y_max": 167,
"x_min": 48,
"y_min": 0
},
"landmarks": [[260, 129], [273, 127], [258, 136], [257, 150], [269, 148]],
"similarity": 0.97858,
"execution_time": {
"age": 59.0,
"gender": 30.0,
"detector": 177.0,
"calculator": 70.0,
"mask": 36.0
}
}
],
"plugins_versions": {
"age": "agegender.AgeDetector",
"gender": "agegender.GenderDetector",
"detector": "facenet.FaceDetector",
"calculator": "facenet.Calculator",
"mask": "facemask.MaskDetector"
}
}
4. 代码示例
4.1 Python示例
以下是使用Python调用CompreFace API的示例代码,包括添加主体示例和识别人脸功能。
import requests
class CompreFaceAPI:
def __init__(self, api_url, api_key):
self.api_url = api_url
self.api_key = api_key
self.headers = {
"x-api-key": self.api_key
}
def add_subject_example(self, subject, image_path, det_prob_threshold=0.5):
"""添加主体示例"""
url = f"{self.api_url}/recognition/faces?subject={subject}&det_prob_threshold={det_prob_threshold}"
files = {"file": open(image_path, "rb")}
response = requests.post(url, headers=self.headers, files=files)
return response.json()
def recognize_faces(self, image_path, limit=0, prediction_count=1, det_prob_threshold=0.5, face_plugins="", status=False):
"""识别人脸"""
url = f"{self.api_url}/recognition/recognize?limit={limit}&prediction_count={prediction_count}&det_prob_threshold={det_prob_threshold}&status={status}"
if face_plugins:
url += f"&face_plugins={face_plugins}"
files = {"file": open(image_path, "rb")}
response = requests.post(url, headers=self.headers, files=files)
return response.json()
# 使用示例
if __name__ == "__main__":
# 配置
API_URL = "http://localhost:8000/api/v1"
API_KEY = "your_api_key_here"
SUBJECT = "person1"
TRAIN_IMAGE_PATH = "train_image.jpg"
TEST_IMAGE_PATH = "test_image.jpg"
# 创建API实例
compre_face = CompreFaceAPI(API_URL, API_KEY)
# 添加主体示例
print("添加主体示例...")
add_result = compre_face.add_subject_example(SUBJECT, TRAIN_IMAGE_PATH)
print("添加结果:", add_result)
# 识别人脸
print("识别人脸...")
recognize_result = compre_face.recognize_faces(TEST_IMAGE_PATH, face_plugins="age,gender,mask", status=True)
print("识别结果:", recognize_result)
4.2 JavaScript示例
以下是使用JavaScript调用CompreFace API的示例代码。
const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
class CompreFaceAPI {
constructor(apiUrl, apiKey) {
this.apiUrl = apiUrl;
this.apiKey = apiKey;
this.headers = {
"x-api-key": this.apiKey
};
}
async addSubjectExample(subject, imagePath, detProbThreshold = 0.5) {
const url = `${this.apiUrl}/recognition/faces?subject=${subject}&det_prob_threshold=${detProbThreshold}`;
const formData = new FormData();
formData.append('file', fs.createReadStream(imagePath));
try {
const response = await axios.post(url, formData, {
headers: {
...this.headers,
...formData.getHeaders()
}
});
return response.data;
} catch (error) {
console.error('添加主体示例失败:', error.response.data);
throw error;
}
}
async recognizeFaces(imagePath, limit = 0, predictionCount = 1, detProbThreshold = 0.5, facePlugins = "", status = false) {
let url = `${this.apiUrl}/recognition/recognize?limit=${limit}&prediction_count=${predictionCount}&det_prob_threshold=${detProbThreshold}&status=${status}`;
if (facePlugins) {
url += `&face_plugins=${facePlugins}`;
}
const formData = new FormData();
formData.append('file', fs.createReadStream(imagePath));
try {
const response = await axios.post(url, formData, {
headers: {
...this.headers,
...formData.getHeaders()
}
});
return response.data;
} catch (error) {
console.error('识别人脸失败:', error.response.data);
throw error;
}
}
}
// 使用示例
async function main() {
// 配置
const API_URL = "http://localhost:8000/api/v1";
const API_KEY = "your_api_key_here";
const SUBJECT = "person1";
const TRAIN_IMAGE_PATH = "train_image.jpg";
const TEST_IMAGE_PATH = "test_image.jpg";
// 创建API实例
const compreFace = new CompreFaceAPI(API_URL, API_KEY);
// 添加主体示例
console.log("添加主体示例...");
const addResult = await compreFace.addSubjectExample(SUBJECT, TRAIN_IMAGE_PATH);
console.log("添加结果:", addResult);
// 识别人脸
console.log("识别人脸...");
const recognizeResult = await compreFace.recognizeFaces(TEST_IMAGE_PATH, 0, 1, 0.5, "age,gender,mask", true);
console.log("识别结果:", JSON.stringify(recognizeResult, null, 2));
}
main();
5. API调用流程
使用CompreFace进行人脸识别的典型流程如下:
- 获取API密钥:在CompreFace系统中创建人脸识别服务,获取对应的API密钥。
- 添加主体示例:上传人脸图像,为每个主体添加一个或多个示例。
- 识别人脸或验证人脸:调用相应的API进行人脸识别或人脸验证。
- 处理识别结果:根据API返回的结果,进行后续的业务逻辑处理。
6. 常见问题及解决方案
6.1 API调用失败
- 检查API密钥:确保使用正确的API密钥,并且该密钥具有相应的权限。
- 检查请求格式:确保请求头和请求体的格式正确,特别是文件上传时的
Content-Type设置。 - 检查服务状态:确保CompreFace服务正常运行,可以通过访问管理界面或基础URL进行验证。
6.2 识别准确率低
- 增加训练样本:为每个主体添加多个不同角度、不同光照条件下的人脸图像。
- 调整检测阈值:适当降低
det_prob_threshold参数的值,以提高检测到人脸的可能性。 - 检查图像质量:确保上传的图像清晰,人脸占据图像的足够比例。
6.3 响应时间长
- 优化图像大小:减小上传图像的尺寸和文件大小。
- 减少插件使用:只使用必要的人脸插件,减少额外的处理时间。
- 考虑GPU加速:如果条件允许,使用GPU版本的CompreFace以提高处理速度。
7. 总结
CompreFace提供了功能丰富且易于使用的API接口,使得开发者能够快速将人脸识别功能集成到自己的应用中。通过本指南介绍的API调用方法和代码示例,您可以轻松实现主体管理、人脸示例添加、人脸识别和验证等功能。
在实际应用中,您可以根据具体需求调整API参数,例如设置合适的检测阈值、选择需要的人脸插件等,以获得最佳的识别效果。同时,结合CompreFace的开源特性,您还可以根据自己的需求进行二次开发和定制。
希望本指南能够帮助您顺利集成CompreFace的人脸识别功能,为您的应用增添强大的身份验证和人脸分析能力。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



