人脸辨识在 Computer Vision 中一直是很火热的话题,也是目前广为人知的一项技术。本质上分为 Face Verification、Face Recognition:前者为验证两张人脸是否为同一个人,属于一对一的过程;后者则是从数据库里辨识出相同的人脸,属于一对多的过程。
本文将要使用 Python 来进行人脸辨识的实作,过程分为几个阶段:
- Face Detection
- Face Align
- Feature extraction
- Create Database
- Face Recognition
首先安装相关 library
$ pip install scikit-learn
$ pip install onnxruntime
Face Detection
这部分要进行人脸侦测,可以使用 Python API MTCNN、RetinaFace,这边示范使用 RetinaFace 来进行侦测。
- 安裝 RetinaFace
$ pip install retinaface
- 侦测
接着就可以来侦测人脸啦~输出会有预测框左上角跟右下角、两个眼睛、鼻子、嘴巴两边的座标值
import cv2
from retinaface import RetinaFace
detector = RetinaFace(quality="normal")
img_path = '001.jpg'
img_bgr = cv2.imread(img_path, cv2.IMREAD_COLOR)
img_rgb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)
detections = detector.predict(img_rgb)
print(detections)
img_result = detector.draw(img_rgb, detections)
img = cv2.cvtColor(img_result, cv2.COLOR_RGB2BGR)
cv2.imshow("windows", img)
key = cv2.waitKey()
if key == ord("q"):
print("exit")
cv2.destroyWindow("windows")
# output[{‘x1’: 243, ‘y1’: 142, ‘x2’: 557, ‘y2’: 586, ‘left_eye’: (303, 305), ‘right_eye’: (431, 346), ‘nose’: (305, 403), ‘left_lip’: (272, 468), ‘right_lip’: (364, 505)}]
❗ 若在使用 RetinaFace 的时候,出现以下错误
有可能是因为无法导入 shapely.geometry 模块的关系,因此要先去下载 Shapely package,下载网址 → 🔗
下载完后再执行以下指令
$ pip install <your Shapely package path>
测试是否安装成功
$ python
>>> from shapely.geometry
import Polygon
Face Align
这部分要来将人脸特征点进行对齐,需要先定义对齐的座标,在 onnx arcface_inference.ipynb 里的 Preprocess images 中可以看到。
接着就用 skimage 套件 transform.SimilarityTransform() 得到要变换的矩阵,然后进行对齐。
import cv2
from retinaface import RetinaFace
import numpy as np
from skimage import transform as trans
src = np.array([
[30.2946, 51.6963],
[65.5318, 51.5014],
[48.0252, 71.7366],
[33.5493, 92.3655],
[62.7299, 92.2041]]