python人脸对比 | Hlwdy's blog
python人脸对比
发表于 2020-03-28 共 748 字
分类于 python

python人脸对比

之前,我们利用opencv进行了人脸检测,而人脸对比我们需要用到另外一个库——dilb

请注意:直接安装dlib会出错(我之前遇到的),要先安装boost和cmake,依次执行如下命令:

(安装时间可能较长,请耐心等待)

pip install boost
pip install cmake
pip install dlib

然后,我们开始写代码,引用如下几个库(如果numpy报错要自行安装):

import os,cv2,dlib
import numpy as np

随后,我们需要下载dlib的数据包

链接: https://share.weiyun.com/5zRqA8q (密码:5i1K)

将两个dat文件放到目录下的'dlib'文件夹,加定义几个变量

predictor_path = 'dlib/shape_predictor_5_face_landmarks.dat'
face_model_path = 'dlib/dlib_face_recognition_resnet_model_v1.dat'

接着,我们定义一个函数,使用这个函数就可以获取128D脸部特征值

def faces_to_128D(imdata,count):
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor(predictor_path)
    face_model = dlib.face_recognition_model_v1(face_model_path)
    image_rgb = cv2.cvtColor(imdata, cv2.COLOR_BGR2RGB)
    has_face = detector(image_rgb, 1)
    shape = predictor(image_rgb, has_face[0])
    face_desc = face_model.compute_face_descriptor(image_rgb, shape)
    feature_array = np.array([])
    for _, desc in enumerate(face_desc):
        feature_array = np.append(feature_array, desc)
    return feature_array

上面是重要的部分,下面的代码可以自行按需求自定义,进行获取匹配度

在判断两个脸部的相似度的时候,我们用到一个公式来进行计算欧氏距离(欧几里得距离)

用来获取在n维空间中两个点之间的真实距离,也就是说,得到的距离值越小,两个人脸的相似度就越高

知道了这些,我们就可以直接使用numpy来计算欧氏距离

def faces_same(face1, face2):
    distance = np.linalg.norm(face1 - face2) #计算欧氏距离
    print(distance)
    if (distance < 0.38): #这里可以修改,也就是距离小于0.38时判断匹配成功
        return True
    else:
        return False


def faces_compare(feature1, feature2):
    same_v = faces_same(feature1, feature2)
    if same_v:
        print('yes')
    else:
        print('no')

于是,我们就可以用faces_compare来对比两个人脸了

(以下的代码不是关键代码,只是使用示例,用到了之前的人脸检测,读取两个图片中的人脸,进行对比

两个图片为c1.jpg和c2.jpg,保证图片中都只有一个人脸)

image=cv2.imread("c1.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascades\\haarcascade_frontalface_alt2.xml')
faces1 = face_cascade.detectMultiScale(
    gray,
    scaleFactor=1.15,
    minNeighbors=5,
    minSize=(5, 5),
)
img1=None
for (x, y, w, h) in faces1:
    img1 = image[y:y + w, x:x + w] #截取图片中人脸
image=cv2.imread("c2.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces2 = face_cascade.detectMultiScale(
    gray,
    scaleFactor=1.15,
    minNeighbors=5,
    minSize=(5, 5),
)
img2=None
for (x, y, w, h) in faces2:
    img2 = image[y:y + w, x:x + w]
face_compare(faces_to_128D(img1),faces_to_128D(img2)) #调用face_compare进行人脸对比

至此,python人脸处理就到这里了,可以充分利用这项技术来做一些有意思的程序。

筛选文章
类别选择 (分类/标签)
全屏 关闭