常见的人脸对齐方法 python

该博客介绍了如何使用Dlib库和MTCNN进行人脸识别的关键点检测与对齐。首先,通过Dlib实现68个面部特征点检测,然后根据左眼和右眼中心点计算旋转矩阵进行图像校正。此外,还提到了ArcFace的人脸对齐方法,以及VGGFace2的简单裁剪方式。这些技术在人脸识别和验证中起到关键作用。

人脸对齐

1. 通过Dlib库

1.1.环境需求:

opencv-python
dlib

下载dlib库的68关键点文件:
http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2
然后解压后得到shape_predictor_68_face_landmarks.dat

其次,下面可能需要有一定python基础才能快速调用。

注意:Dlib库有cuda加速版本,用这个更快,否则CPU计算。

1.2.程序:

import cv2
import dlib
import numpy as np

class Face_Align(object):
    def __init__(self,shape_predictor_path):
        self.detector = dlib.get_frontal_face_detector()
        self.predictor = dlib.shape_predictor(shape_predictor_path)
        self.LEFT_EYE_INDICES = [36, 37, 38, 39, 40, 41]
        self.RIGHT_EYE_INDICES = [42, 43, 44, 45, 46, 47]

    def rect_to_tuple(self, rect):
        left = rect.left()
        right = rect.right()
        top = rect.top()
        bottom = rect.bottom()
        return left, top, right, bottom

    def extract_eye(self, shape, eye_indices):
        points = map(lambda i: shape.part(i), eye_indices)
        return list(points)

    def extract_eye_center(self, shape, eye_indices):
        points = self.extract_eye(shape, eye_indices)
        xs = map(lambda p: p.x, points)
        ys = map(lambda p: p.y, points)
        return sum(xs) // 6, sum(ys) // 6

    def extract_left_eye_center(self, shape):
        return self.extract_eye_center(shape, self.LEFT_EYE_INDICES)

    def extract_right_eye_center(self, shape):
        return self.extract_eye_center(shape, self.RIGHT_EYE_INDICES)

    def angle_between_2_points(self, p1, p2):
        x1, y1 = p1
        x2, y2 = p2
        tan = (y2 - y1) / (x2 - x1)
        return np.degrees(np.arctan(tan))

    def get_rotation_matrix(self, p1, p2):
        angle = self.angle_between_2_points(p1, p2)
        x1, y1 = p1
        x2, y2 = p2
        xc = (x1 + x2) // 2
        yc = (y1 + y2) // 2
        M = cv2.getRotationMatrix2D((xc, yc), angle, 1)
        return M

    def crop_image(self, image, det):
        left, top, right, bottom = self.rect_to_tuple(det)
        return image[top:bottom, left:right]

    def __call__(self, image=None,image_path=None,save_path=None,only_one=True):
        '''
        Face alignment, can select input image variable or image path, when input
        image format that return alignment face image crop or image path as input
        will return None but save image to the save path.
        :image: Face image input
        :image_path: if image is None than can input image
        :save_path: path to save image
        :detector: detector = dlib.get_frontal_face_detector()
        :pred
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值