使用 OpenCV 和 Python 进行人脸对齐
这篇博文的目的是演示如何使用 OpenCV、Python 和面部标志对齐人脸。
给定一组面部标志(输入坐标),我们的目标是将图像扭曲并转换为输出坐标空间。
在这个输出坐标空间中,整个数据集中的所有面都应该:
在图像中居中。
旋转,使眼睛位于水平线上(即,旋转面部,使眼睛位于相同的 y 坐标上)。
进行缩放,使面的大小大致相同。
为此,我们将首先调用一个实现的 Python 类FaceAligner ,以使用仿射变换对齐人脸。
注意:仿射变换用于旋转、缩放、平移等。我们可以将上述所有三个要求打包到一个
cv2.warpAffine 调用中; 诀窍是创建旋转矩阵 M 。
然后,我们将创建一个示例驱动程序 Python 脚本来接受输入图像、检测人脸并对齐它们。
最后,我们将回顾我们使用 OpenCV 过程进行人脸对齐的结果。
实现面部矫正器
面部对齐算法本身基于 Mastering OpenCV with Practical Computer Vision Projects (Baggio,
2012) 的第 8 章,如果您有 C++ 背景或兴趣,我强烈推荐它。 本书在 GitHub 上提供了开放访问的代码
示例。
新建facealigner.py实现FaceAligner类。
导入必要的包
定义的构造函数开始我们的 FaceAligner 类。
我们的构造函数有 4 个参数:
predictor :面部标志性预测器模型。
# import the necessary packages
from imutils.face_utils.helpers import FACIAL_LANDMARKS_68_IDXS
from imutils.face_utils.helpers import FACIAL_LANDMARKS_5_IDXS
from imutils.face_utils.helpers import shape_to_np
import numpy as np
import cv2
class FaceAligner:
def __init__(self, predictor, desiredLeftEye=(0.35, 0.35),
desiredFaceWidth=256, desiredFaceHeight=None):
# store the facial landmark predictor, desired output left
# eye position, and desired output face width + height
self.predictor = predictor
self.desiredLeftEye = desiredLeftEye
self.desiredFaceWidth = desiredFaceWidth
self.desiredFaceHeight = desiredFaceHeight
# if the desired face height is None, set it to be the
# desired face width (normal behavior)
if self.desiredFaceHeight is None:
self.desiredFaceHeight = self.desiredFaceWidth
- 1
- 2
- 3
- 4
- 5
- 6
前往页