基于InsightFace的完整人脸识别解决方案,支持人脸检测、特征提取、人脸比较和人员识别。
# 直接运行预构建的Docker镜像
docker run --rm -p 8000:8000 -p 7860:7860 vc123123/face-recognition-api启动后访问:
- API服务: http://localhost:8000/docs
- Web界面: http://localhost:7860
- 🚀 高精度: 基于InsightFace的SOTA人脸识别模型
- 💾 数据库管理: 完整的人脸数据库存储和管理系统
- 🔍 多功能: 支持人脸检测、识别、比较、可视化
- 🛠️ 易于使用: 提供简洁的API和完整的使用示例
- ⚡ GPU加速: 支持GPU加速推理(可选)
- 📊 批量处理: 支持批量图片处理和识别
- 🔒 安全可靠: 支持API密钥认证、请求限制、数据加密
- 🚄 高并发: 异步处理架构,支持大量并发请求
- 🌐 RESTful API: 完整的Web API接口,支持跨平台调用
- Python 3.7+
- OpenCV 4.5+
- ONNX Runtime
- InsightFace
# 运行自动安装脚本,支持选择venv或conda
./setup.sh# 使用conda创建环境
conda env create -f environment.yml
conda activate face_recognition# 创建conda环境
conda create -n face_recognition python=3.8 -y
conda activate face_recognition
# 或创建venv环境
python3 -m venv face_recognition_env
source face_recognition_env/bin/activate
# 安装依赖
pip install -r requirements.txt# 直接运行预构建镜像
docker run --rm -p 8000:8000 -p 7860:7860 vc123123/face-recognition-api
# 后台运行
docker run -d --name face-api -p 8000:8000 -p 7860:7860 vc123123/face-recognition-api# 一键部署脚本
./deployment/deploy.sh
# 或使用Docker Compose
cd deployment && docker-compose up -dfrom src.face_recognition_core import FaceRecognitionCore
from src.face_database import FaceDatabase
# 初始化
face_core = FaceRecognitionCore(use_gpu=False) # 如果有GPU,设置为True
db = FaceDatabase()
# 添加人员到数据库
db.add_person("张三", ["images/zhangsan1.jpg", "images/zhangsan2.jpg"], face_core)
# 识别人脸
result_name, similarity, candidates = db.identify_person("test.jpg", face_core)
print(f"识别结果: {result_name}, 相似度: {similarity:.4f}")python src/example_usage.pytest-face/
├── README.md # 项目说明文档
├── setup.sh # 环境设置脚本
├── .env.example # 环境变量配置模板
├── API_USAGE.md # API使用文档
├── src/ # 核心功能模块
│ ├── face_recognition_core.py # 人脸识别核心功能模块
│ ├── face_database.py # 人脸数据库管理模块
│ └── batch_processing.py # 批量处理脚本
├── api/ # API服务模块
│ ├── simple_api_server.py # 简化版API服务器
│ ├── api_server.py # 基础FastAPI服务器
│ ├── api_server_secure.py # 安全增强版API服务器
│ ├── gradio_app.py # Gradio网页应用
│ └── start_web_app.py # 网页应用启动脚本
├── examples/ # 示例和工具
│ ├── api_client_example.py # API客户端使用示例
│ ├── batch_processing.py # 批量处理示例
│ └── load_test.py # 负载测试工具
├── deployment/ # 部署相关文件
│ ├── deploy.sh # 一键部署脚本
│ ├── Dockerfile # Docker容器配置
│ ├── docker-compose.yml # Docker Compose配置
│ ├── nginx.conf # Nginx负载均衡配置
│ ├── requirements.txt # Python依赖包列表
│ └── start_services.sh # 服务启动脚本
├── face_database/ # 人脸数据库存储目录
│ ├── embeddings.pkl # 人脸特征向量存储文件
│ ├── names.pkl # 人员姓名映射文件
│ └── photos/ # 人员照片存储目录
└── insightface/ # InsightFace模型文件
└── models/
└── buffalo_l/ # 主要使用的人脸识别模型
from face_recognition_core import FaceRecognitionCore
# 初始化
face_core = FaceRecognitionCore(
model_name='buffalo_l', # 模型名称
use_gpu=True, # 是否使用GPU
det_size=(640, 640) # 检测尺寸
)
# 提取人脸特征
embedding = face_core.extract_face_embedding("photo.jpg")
# 比较两张人脸
similarity, is_same = face_core.compare_faces(embedding1, embedding2)
# 可视化检测结果
output_path = face_core.visualize_faces("input.jpg", "output.jpg")from face_database import FaceDatabase
# 初始化数据库
db = FaceDatabase(db_path="./face_database")
# 添加人员
db.add_person("张三", ["photo1.jpg", "photo2.jpg"], face_core)
# 更新人员数据
db.update_person("张三", ["new_photo.jpg"], face_core)
# 识别人员
name, similarity, candidates = db.identify_person("unknown.jpg", face_core)
# 列出所有人员
persons = db.list_all_persons()
# 删除人员
db.remove_person("张三")
# 导出数据库
db.export_database("backup.json")-
创建目录结构:
mkdir -p images/张三 images/李四 images/王五 mkdir -p test_images output
-
将已知人员的照片放入对应目录:
images/ ├── 张三/ │ ├── photo1.jpg │ ├── photo2.jpg │ └── photo3.jpg ├── 李四/ │ ├── photo1.jpg │ └── photo2.jpg └── 王五/ ├── photo1.jpg ├── photo2.jpg └── photo3.jpg
from face_recognition_core import FaceRecognitionCore
from face_database import FaceDatabase
import os
# 初始化
face_core = FaceRecognitionCore(use_gpu=False)
db = FaceDatabase()
# 批量添加人员
for person_name in os.listdir("images"):
person_dir = f"images/{person_name}"
if os.path.isdir(person_dir):
image_files = []
for file in os.listdir(person_dir):
if file.lower().endswith(('.jpg', '.jpeg', '.png')):
image_files.append(os.path.join(person_dir, file))
if image_files:
db.add_person(person_name, image_files, face_core)# 识别单张图片
result_name, similarity, candidates = db.identify_person(
"test_images/unknown.jpg",
face_core,
threshold=0.6
)
if result_name:
print(f"识别结果: {result_name} (相似度: {similarity:.4f})")
else:
print("未识别出已知人员")
# 显示所有候选结果
print("候选结果:")
for name, sim in candidates[:5]: # 显示前5个
print(f" {name}: {sim:.4f}")项目支持多种InsightFace模型:
| 模型名称 | 检测模型 | 识别模型 | 模型大小 | 精度 | 推荐用途 |
|---|---|---|---|---|---|
| buffalo_l | SCRFD-10GF | ResNet50@WebFace600K | 326MB | 高 | 生产环境 |
| buffalo_m | SCRFD-2.5GF | ResNet50@WebFace600K | 313MB | 高 | 平衡性能 |
| buffalo_s | SCRFD-500MF | MBF@WebFace600K | 159MB | 中 | 移动设备 |
| antelopev2 | SCRFD-10GF | ResNet100@Glint360K | 407MB | 最高 | 高精度需求 |
# 使用GPU加速(需要安装onnxruntime-gpu)
face_core = FaceRecognitionCore(
model_name='buffalo_l',
use_gpu=True,
det_size=(640, 640)
)# 使用批量处理脚本
python batch_processing.py --input_dir test_images --output_file results.json# 调整检测尺寸(更大的尺寸可以检测更小的人脸,但速度更慢)
face_core = FaceRecognitionCore(det_size=(1024, 1024))
# 调整相似度阈值
result = db.identify_person("test.jpg", face_core, threshold=0.7) # 更严格
result = db.identify_person("test.jpg", face_core, threshold=0.5) # 更宽松# 在环境变量中设置API密钥
export FACE_API_KEY="your-secret-api-key-here"
# 或在.env文件中配置
FACE_API_KEY=your-secret-api-key-here
ALLOWED_ORIGINS=http://localhost:3000,https://yourdomain.com
RATE_LIMIT_PER_MINUTE=60# 启动API服务器时启用安全模式
python api_server.py --secure --rate-limit 100
# 配置请求大小限制(默认10MB)
MAX_FILE_SIZE=10485760
# IP白名单配置
ALLOWED_IPS=192.168.1.0/24,10.0.0.0/8- 人脸特征向量采用AES-256加密存储
- 支持HTTPS/TLS加密传输
- 敏感日志信息自动脱敏
- 定期清理临时文件和缓存
# 高并发配置启动
uvicorn api_server:app \
--host 0.0.0.0 \
--port 8000 \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--max-requests 1000 \
--max-requests-jitter 100- 数据库连接池:支持最大100个并发连接
- 模型实例池:预加载多个模型实例避免重复初始化
- 内存缓存:Redis缓存热点数据,提升响应速度
- 异步文件I/O:非阻塞文件读写操作
# 启用性能监控
python api_server.py --monitor --metrics-port 9090
# 查看实时性能指标
curl http://localhost:9090/metrics# 使用Apache Bench进行并发测试
ab -n 1000 -c 50 -p test_image.jpg -T image/jpeg http://localhost:8000/recognize
# 使用wrk进行压力测试
wrk -t12 -c400 -d30s --script=post_image.lua http://localhost:8000/recognize所有API请求需要在Header中包含API密钥:
Authorization: Bearer your-api-key-here
Content-Type: application/json1. 人脸识别接口
POST /api/v1/recognize
Content-Type: multipart/form-data
Parameters:
- file: 图片文件 (required)
- threshold: 相似度阈值 (optional, default: 0.6)
- return_face_image: 是否返回检测到的人脸图片 (optional, default: false)2. 添加人员接口(单张图片)
POST /api/v1/persons
Content-Type: multipart/form-data
Parameters:
- name: 人员姓名 (required)
- file: 人脸图片 (required)
- description: 人员描述 (optional)3. 添加人员接口(多张图片)
POST /api/v1/persons/multiple
Content-Type: multipart/form-data
Parameters:
- name: 人员姓名 (required)
- files: 多张人脸图片 (required)
- description: 人员描述 (optional)4. 为现有人员添加图片
POST /api/v1/persons/{name}/images
Content-Type: multipart/form-data
Parameters:
- files: 新增的人脸图片 (required)1. 添加人员(单张图片)
curl -X POST "http://localhost:8000/api/v1/persons" \
-H "Authorization: Bearer your-secret-api-key" \
-F "file=@person_photo.jpg" \
-F "name=张三" \
-F "description=员工"2. 添加人员(多张图片)
curl -X POST "http://localhost:8000/api/v1/persons/multiple" \
-H "Authorization: Bearer your-secret-api-key" \
-F "files=@photo1.jpg" \
-F "files=@photo2.jpg" \
-F "files=@photo3.jpg" \
-F "name=李四" \
-F "description=员工(多张照片)"3. 为现有人员添加更多图片
curl -X POST "http://localhost:8000/api/v1/persons/张三/images" \
-H "Authorization: Bearer your-secret-api-key" \
-F "files=@new_photo1.jpg" \
-F "files=@new_photo2.jpg"4. 人脸识别
curl -X POST "http://localhost:8000/api/v1/recognize" \
-H "Authorization: Bearer your-secret-api-key" \
-F "file=@unknown_person.jpg" \
-F "threshold=0.6"3. 批量识别接口
POST /api/v1/recognize/batch
Content-Type: application/json
Body:
{
"images": ["base64_image1", "base64_image2"],
"threshold": 0.6,
"async": true
}200: 请求成功400: 请求参数错误401: 认证失败403: 权限不足413: 文件过大429: 请求频率超限500: 服务器内部错误
{
"success": true,
"data": {
"faces": [
{
"face_id": 1,
"bbox": [x, y, width, height],
"confidence": 0.99,
"recognition": {
"identified": true,
"name": "张三",
"similarity": 0.85,
"candidates": [
{"name": "张三", "similarity": 0.85},
{"name": "李四", "similarity": 0.72}
]
}
}
]
},
"message": "识别成功",
"timestamp": "2024-01-15T10:30:00Z",
"request_id": "req_123456789"
}# 使用Docker部署
docker build -t face-recognition-api .
docker run -d \
--name face-api \
-p 8000:8000 \
-v ./face_database:/app/face_database \
-e FACE_API_KEY=your-secret-key \
-e WORKERS=4 \
face-recognition-api
# 使用Nginx反向代理
nginx -s reloadupstream face_api {
server 127.0.0.1:8000;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
server_name api.yourface.com;
location / {
proxy_pass http://face_api;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}# 启用日志轮转
logrotate /etc/logrotate.d/face-api
# 监控服务状态
systemctl status face-api
# 查看性能指标
htop
iotop
nvidia-smi # GPU监控# 运行API客户端示例
python examples/api_client_example.py该示例展示了如何:
- 使用API密钥进行身份验证
- 调用各种API接口
- 处理错误和异常
- 进行批量人脸识别
# 基础负载测试
python examples/load_test.py
# 自定义参数测试
python examples/load_test.py --users 20 --requests 10 --api-key your-key参数说明:
--users: 并发用户数--requests: 每用户请求数--api-key: API密钥--url: API服务器地址
镜像信息:
- 镜像名称:
vc123123/face-recognition-api - Docker Hub: https://hub.docker.com/r/vc123123/face-recognition-api
- 支持架构: linux/amd64, linux/arm64
- 镜像大小: ~4.5GB(包含完整的人脸识别模型)
# 拉取最新镜像
docker pull vc123123/face-recognition-api:latest
# 运行容器(临时)
docker run --rm -p 8000:8000 -p 7860:7860 vc123123/face-recognition-api
# 后台运行(持久化数据)
docker run -d --name face-api \
-p 8000:8000 \
-p 7860:7860 \
-v $(pwd)/face_database:/app/face_database \
--restart unless-stopped \
vc123123/face-recognition-api
# 查看容器状态
docker ps
# 查看实时日志
docker logs -f face-api
# 停止容器
docker stop face-api
# 删除容器
docker rm face-api# 构建镜像
docker build -f deployment/Dockerfile -t face-recognition-api .
# 运行容器
docker run --rm -p 8000:8000 -p 7860:7860 face-recognition-api
# 使用Docker Compose
cd deployment && docker-compose up -d
# 查看部署状态
cd deployment && docker-compose ps
# 查看服务日志
cd deployment && docker-compose logs -f部署成功后,可以通过以下地址访问服务:
- API服务: http://localhost:8000
- API文档: http://localhost:8000/docs
- Gradio界面: http://localhost:7860
- 健康检查: http://localhost:8000/health
A:
- 使用多张不同角度、光照的照片建立数据库
- 选择更高精度的模型(如antelopev2)
- 调整相似度阈值
- 确保图片质量良好
A:
# 提取图片中所有人脸
faces_info = face_core.extract_faces_from_image("group_photo.jpg")
for i, face_info in enumerate(faces_info):
embedding = face_info['embedding']
# 对每个人脸进行识别
result = db.find_best_match(embedding, ...)A:
# 导出数据库
db.export_database("backup.json")
# 数据库文件位置
# face_database/embeddings.pkl # 特征向量
# face_database/metadata.json # 元数据A:
- 使用CPU模式:
use_gpu=False - 减小检测尺寸:
det_size=(320, 320) - 使用更小的模型:
model_name='buffalo_s'
- 代码部分:MIT License
- 预训练模型:仅限非商业研究使用
欢迎提交Issue和Pull Request来改进这个项目!
如有问题,请通过GitHub Issues联系。