---
comments: true
---
# 人脸识别产线使用教程
## 1. 人脸识别产线介绍
人脸识别任务是计算机视觉领域的重要组成部分,旨在通过分析和比较人脸特征,实现对个人身份的自动识别。该任务不仅需要检测图像中的人脸,还需要对人脸图像进行特征提取和匹配,从而在数据库中找到对应的身份信息。人脸识别广泛应用于安全认证、监控系统、社交媒体和智能设备等场景。
人脸识别产线是专注于解决人脸定位和识别任务的端到端串联系统,可以从图像中快速准确地定位人脸区域、提取人脸特征,并与特征库中预先建立的特征做检索比对,从而确认身份信息。
人脸识别产线中包含了人脸检测模块和人脸特征模块,每个模块中包含了若干模型,具体使用哪些模型,您可以根据下边的 benchmark 数据来选择。如您更考虑模型精度,请选择精度较高的模型,如您更考虑模型推理速度,请选择推理速度较快的模型,如您更考虑模型存储大小,请选择存储大小较小的模型。
👉模型列表详情
人脸检测模块:
| 模型 | 模型下载链接 |
AP (%) Easy/Medium/Hard |
GPU推理耗时 (ms) |
CPU推理耗时 |
模型存储大小 (M) |
介绍 |
| BlazeFace | 推理模型/训练模型 |
77.7/73.4/49.5 |
|
|
0.447 |
轻量高效的人脸检测模型 |
| BlazeFace-FPN-SSH | 推理模型/训练模型 |
83.2/80.5/60.5 |
|
|
0.606 |
BlazeFace的改进模型,增加FPN和SSH结构 |
| PicoDet_LCNet_x2_5_face | 推理模型/训练模型 |
93.7/90.7/68.1 |
|
|
28.9 |
基于PicoDet_LCNet_x2_5的人脸检测模型 |
| PP-YOLOE_plus-S_face | 推理模型/训练模型 |
93.9/91.8/79.8 |
|
|
26.5 |
基于PP-YOLOE_plus-S的人脸检测模型 |
注:以上精度指标是在WIDER-FACE验证集上,以640
*640作为输入尺寸评估得到的。所有模型 GPU 推理耗时基于 NVIDIA Tesla T4 机器,精度类型为 FP32, CPU 推理速度基于 Intel(R) Xeon(R) Gold 5117 CPU @ 2.00GHz,线程数为8,精度类型为 FP32。
人脸特征模块:
| 模型 | 模型下载链接 |
输出特征维度 |
Acc (%) AgeDB-30/CFP-FP/LFW |
GPU推理耗时 (ms) |
CPU推理耗时 |
模型存储大小 (M) |
介绍 |
| MobileFaceNet | 推理模型/训练模型 |
128 |
96.28/96.71/99.58 |
|
|
4.1 |
基于MobileFaceNet在MS1Mv3数据集上训练的人脸特征提取模型 |
| ResNet50_face | 推理模型/训练模型 |
512 |
98.12/98.56/99.77 |
|
|
87.2 |
基于ResNet50在MS1Mv3数据集上训练的人脸特征提取模型 |
注:以上精度指标是分别在 AgeDB-30、CFP-FP 和 LFW 数据集上测得的 Accuracy。所有模型 GPU 推理耗时基于 NVIDIA Tesla T4 机器,精度类型为 FP32, CPU 推理速度基于 Intel(R) Xeon(R) Gold 5117 CPU @ 2.00GHz,线程数为8,精度类型为 FP32。
## 2. 快速开始
PaddleX 所提供的预训练的模型产线均可以快速体验效果,你可以在线体验人脸识别产线的效果,也可以在本地使用命令行或 Python 体验人脸识别产线的效果。
### 2.1 在线体验
暂不支持在线体验
### 2.2 本地体验
> ❗ 在本地使用人脸识别产线前,请确保您已经按照[PaddleX安装教程](../../../installation/installation.md)完成了PaddleX的wheel包安装。
#### 2.2.1 命令行方式体验
暂不支持命令行体验
默认使用内置的的通用图像识别产线配置文件,若您需要自定义配置文件,可执行如下命令获取:
👉点击展开
paddlex --get_pipeline_config face_recognition
执行后,通用图像识别产线配置文件将被保存在当前路径。若您希望自定义保存位置,可执行如下命令(假设自定义保存位置为./my_path):
paddlex --get_pipeline_config face_recognition --save_path ./my_path
#### 2.2.2 Python脚本方式集成
请下载[测试图像](https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/friends1.jpg)进行测试。
在该产线的运行示例中需要预先构建人脸特征库,您可以参考如下指令下载官方提供的demo数据用来后续构建人脸特征库。
您可以参考下面的命令将 Demo 数据集下载到指定文件夹:
```bash
cd /path/to/paddlex
wget https://paddle-model-ecology.bj.bcebos.com/paddlex/data/face_demo_gallery.tar
tar -xf ./face_demo_gallery.tar
```
若您希望用私有数据集建立人脸特征库,可以参考[2.3节 构建特征库的数据组织方式](#23-构建特征库的数据组织方式)。之后通过几行代码即可完成人脸特征库建立和人脸识别产线的快速推理。
```python
from paddlex import create_pipeline
pipeline = create_pipeline(pipeline="face_recognition")
pipeline.build_index(data_root="face_demo_gallery", index_dir="face_gallery_index")
output = pipeline.predict("friends1.jpg", index_dir="face_gallery_index")
for res in output:
res.print()
res.save_to_img("./output/")
```
在上述 Python 脚本中,执行了如下几个步骤:
(1)实例化 `create_pipeline` 实例化 人脸识别 产线对象。具体参数说明如下:
API参考
对于服务提供的主要操作:
- HTTP请求方法为POST。
- 请求体和响应体均为JSON数据(JSON对象)。
- 当请求处理成功时,响应状态码为
200,响应体的属性如下:
| 名称 |
类型 |
含义 |
errorCode |
integer |
错误码。固定为0。 |
errorMsg |
string |
错误说明。固定为"Success"。 |
响应体还可能有result属性,类型为object,其中存储操作结果信息。
| 名称 |
类型 |
含义 |
errorCode |
integer |
错误码。与响应状态码相同。 |
errorMsg |
string |
错误说明。 |
服务提供的主要操作如下:
获取图像OCR结果。
POST /ocr
| 名称 |
类型 |
含义 |
是否必填 |
image |
string |
服务可访问的图像文件的URL或图像文件内容的Base64编码结果。 |
是 |
inferenceParams |
object |
推理参数。 |
否 |
inferenceParams的属性如下:
| 名称 |
类型 |
含义 |
是否必填 |
maxLongSide |
integer |
推理时,若文本检测模型的输入图像较长边的长度大于maxLongSide,则将对图像进行缩放,使其较长边的长度等于maxLongSide。 |
否 |
- 请求处理成功时,响应体的
result具有如下属性:
| 名称 |
类型 |
含义 |
texts |
array |
文本位置、内容和得分。 |
image |
string |
OCR结果图,其中标注检测到的文本位置。图像为JPEG格式,使用Base64编码。 |
texts中的每个元素为一个object,具有如下属性:
| 名称 |
类型 |
含义 |
poly |
array |
文本位置。数组中元素依次为包围文本的多边形的顶点坐标。 |
text |
string |
文本内容。 |
score |
number |
文本识别得分。 |
result示例如下:
{
"texts": [
{
"poly": [
[
444,
244
],
[
705,
244
],
[
705,
311
],
[
444,
311
]
],
"text": "北京南站",
"score": 0.9
},
{
"poly": [
[
992,
248
],
[
1263,
251
],
[
1263,
318
],
[
992,
315
]
],
"text": "天津站",
"score": 0.5
}
],
"image": "xxxxxx"
}
多语言调用服务示例
Python
import base64
import requests
API_URL = "http://localhost:8080/ocr" # 服务URL
image_path = "./demo.jpg"
output_image_path = "./out.jpg"
# 对本地图像进行Base64编码
with open(image_path, "rb") as file:
image_bytes = file.read()
image_data = base64.b64encode(image_bytes).decode("ascii")
payload = {"image": image_data} # Base64编码的文件内容或者图像URL
# 调用API
response = requests.post(API_URL, json=payload)
# 处理接口返回数据
assert response.status_code == 200
result = response.json()["result"]
with open(output_image_path, "wb") as file:
file.write(base64.b64decode(result["image"]))
print(f"Output image saved at {output_image_path}")
print("\nDetected texts:")
print(result["texts"])
C++
#include <iostream>
#include "cpp-httplib/httplib.h" // https://github.com/Huiyicc/cpp-httplib
#include "nlohmann/json.hpp" // https://github.com/nlohmann/json
#include "base64.hpp" // https://github.com/tobiaslocker/base64
int main() {
httplib::Client client("localhost:8080");
const std::string imagePath = "./demo.jpg";
const std::string outputImagePath = "./out.jpg";
httplib::Headers headers = {
{"Content-Type", "application/json"}
};
// 对本地图像进行Base64编码
std::ifstream file(imagePath, std::ios::binary | std::ios::ate);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<char> buffer(size);
if (!file.read(buffer.data(), size)) {
std::cerr << "Error reading file." << std::endl;
return 1;
}
std::string bufferStr(reinterpret_cast<const char*>(buffer.data()), buffer.size());
std::string encodedImage = base64::to_base64(bufferStr);
nlohmann::json jsonObj;
jsonObj["image"] = encodedImage;
std::string body = jsonObj.dump();
// 调用API
auto response = client.Post("/ocr", headers, body, "application/json");
// 处理接口返回数据
if (response && response->status == 200) {
nlohmann::json jsonResponse = nlohmann::json::parse(response->body);
auto result = jsonResponse["result"];
encodedImage = result["image"];
std::string decodedString = base64::from_base64(encodedImage);
std::vector<unsigned char> decodedImage(decodedString.begin(), decodedString.end());
std::ofstream outputImage(outPutImagePath, std::ios::binary | std::ios::out);
if (outputImage.is_open()) {
outputImage.write(reinterpret_cast<char*>(decodedImage.data()), decodedImage.size());
outputImage.close();
std::cout << "Output image saved at " << outPutImagePath << std::endl;
} else {
std::cerr << "Unable to open file for writing: " << outPutImagePath << std::endl;
}
auto texts = result["texts"];
std::cout << "\nDetected texts:" << std::endl;
for (const auto& text : texts) {
std::cout << text << std::endl;
}
} else {
std::cout << "Failed to send HTTP request." << std::endl;
return 1;
}
return 0;
}
Java
import okhttp3.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
public class Main {
public static void main(String[] args) throws IOException {
String API_URL = "http://localhost:8080/ocr"; // 服务URL
String imagePath = "./demo.jpg"; // 本地图像
String outputImagePath = "./out.jpg"; // 输出图像
// 对本地图像进行Base64编码
File file = new File(imagePath);
byte[] fileContent = java.nio.file.Files.readAllBytes(file.toPath());
String imageData = Base64.getEncoder().encodeToString(fileContent);
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode params = objectMapper.createObjectNode();
params.put("image", imageData); // Base64编码的文件内容或者图像URL
// 创建 OkHttpClient 实例
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.Companion.get("application/json; charset=utf-8");
RequestBody body = RequestBody.Companion.create(params.toString(), JSON);
Request request = new Request.Builder()
.url(API_URL)
.post(body)
.build();
// 调用API并处理接口返回数据
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String responseBody = response.body().string();
JsonNode resultNode = objectMapper.readTree(responseBody);
JsonNode result = resultNode.get("result");
String base64Image = result.get("image").asText();
JsonNode texts = result.get("texts");
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
try (FileOutputStream fos = new FileOutputStream(outputImagePath)) {
fos.write(imageBytes);
}
System.out.println("Output image saved at " + outputImagePath);
System.out.println("\nDetected texts: " + texts.toString());
} else {
System.err.println("Request failed with code: " + response.code());
}
}
}
}
Go
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
API_URL := "http://localhost:8080/ocr"
imagePath := "./demo.jpg"
outputImagePath := "./out.jpg"
// 对本地图像进行Base64编码
imageBytes, err := ioutil.ReadFile(imagePath)
if err != nil {
fmt.Println("Error reading image file:", err)
return
}
imageData := base64.StdEncoding.EncodeToString(imageBytes)
payload := map[string]string{"image": imageData} // Base64编码的文件内容或者图像URL
payloadBytes, err := json.Marshal(payload)
if err != nil {
fmt.Println("Error marshaling payload:", err)
return
}
// 调用API
client := &http.Client{}
req, err := http.NewRequest("POST", API_URL, bytes.NewBuffer(payloadBytes))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
res, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return
}
defer res.Body.Close()
// 处理接口返回数据
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
type Response struct {
Result struct {
Image string `json:"image"`
Texts []map[string]interface{} `json:"texts"`
} `json:"result"`
}
var respData Response
err = json.Unmarshal([]byte(string(body)), &respData)
if err != nil {
fmt.Println("Error unmarshaling response body:", err)
return
}
outputImageData, err := base64.StdEncoding.DecodeString(respData.Result.Image)
if err != nil {
fmt.Println("Error decoding base64 image data:", err)
return
}
err = ioutil.WriteFile(outputImagePath, outputImageData, 0644)
if err != nil {
fmt.Println("Error writing image to file:", err)
return
}
fmt.Printf("Image saved at %s.jpg\n", outputImagePath)
fmt.Println("\nDetected texts:")
for _, text := range respData.Result.Texts {
fmt.Println(text)
}
}
C#
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
static readonly string API_URL = "http://localhost:8080/ocr";
static readonly string imagePath = "./demo.jpg";
static readonly string outputImagePath = "./out.jpg";
static async Task Main(string[] args)
{
var httpClient = new HttpClient();
// 对本地图像进行Base64编码
byte[] imageBytes = File.ReadAllBytes(imagePath);
string image_data = Convert.ToBase64String(imageBytes);
var payload = new JObject{ { "image", image_data } }; // Base64编码的文件内容或者图像URL
var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
// 调用API
HttpResponseMessage response = await httpClient.PostAsync(API_URL, content);
response.EnsureSuccessStatusCode();
// 处理接口返回数据
string responseBody = await response.Content.ReadAsStringAsync();
JObject jsonResponse = JObject.Parse(responseBody);
string base64Image = jsonResponse["result"]["image"].ToString();
byte[] outputImageBytes = Convert.FromBase64String(base64Image);
File.WriteAllBytes(outputImagePath, outputImageBytes);
Console.WriteLine($"Output image saved at {outputImagePath}");
Console.WriteLine("\nDetected texts:");
Console.WriteLine(jsonResponse["result"]["texts"].ToString());
}
}
Node.js
const axios = require('axios');
const fs = require('fs');
const API_URL = 'http://localhost:8080/ocr'
const imagePath = './demo.jpg'
const outputImagePath = "./out.jpg";
let config = {
method: 'POST',
maxBodyLength: Infinity,
url: API_URL,
data: JSON.stringify({
'image': encodeImageToBase64(imagePath) // Base64编码的文件内容或者图像URL
})
};
// 对本地图像进行Base64编码
function encodeImageToBase64(filePath) {
const bitmap = fs.readFileSync(filePath);
return Buffer.from(bitmap).toString('base64');
}
// 调用API
axios.request(config)
.then((response) => {
// 处理接口返回数据
const result = response.data["result"];
const imageBuffer = Buffer.from(result["image"], 'base64');
fs.writeFile(outputImagePath, imageBuffer, (err) => {
if (err) throw err;
console.log(`Output image saved at ${outputImagePath}`);
});
console.log("\nDetected texts:");
console.log(result["texts"]);
})
.catch((error) => {
console.log(error);
});
PHP
<?php
$API_URL = "http://localhost:8080/ocr"; // 服务URL
$image_path = "./demo.jpg";
$output_image_path = "./out.jpg";
// 对本地图像进行Base64编码
$image_data = base64_encode(file_get_contents($image_path));
$payload = array("image" => $image_data); // Base64编码的文件内容或者图像URL
// 调用API
$ch = curl_init($API_URL);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// 处理接口返回数据
$result = json_decode($response, true)["result"];
file_put_contents($output_image_path, base64_decode($result["image"]));
echo "Output image saved at " . $output_image_path . "\n";
echo "\nDetected texts:\n";
print_r($result["texts"]);
?>