欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

face_recognition 简单识别人脸案例

程序员文章站 2022-07-12 21:03:07
...

案例1

import face_recognition

lxt_image = face_recognition.load_image_file("./1.jpg")
zxc_image = face_recognition.load_image_file("./3.jpg")

# 从已知图像中获取脸部编码特征
lxt_face_encoding = face_recognition.face_encodings(lxt_image)[0]
zxc_face_encoding = face_recognition.face_encodings(zxc_image)[0]

known_encodings = [
    lxt_face_encoding,
    zxc_face_encoding
]
label=['小可爱','美少女']

# 装载图片并获取其编码特征
image_to_test = face_recognition.load_image_file("./2.jpg")
image_to_test_encoding = face_recognition.face_encodings(image_to_test)[0]

# See how far apart the test image is from the known faces
face_distances = face_recognition.face_distance(known_encodings, image_to_test_encoding)

for i, face_distance in enumerate(face_distances):
    print("测试图片与已知图片间的距离是 {:.2} 已知图片#{}".format(face_distance, label[i]))
    print("普通界限0.6, 测试图片是否匹配已知图片? {}".format(face_distance < 0.6))
    print("严格界限0.5, 测试图片是否匹配已知图片? {}".format(face_distance < 0.5))
    print()

案例:封装成类

前提:创建一个文件夹用于存放脸库,并以图片名作为标签
face_recognition 简单识别人脸案例

import glob  # 用于遍历文件夹
import face_recognition

class face_recognizer:
    # faces_lib_path 为脸库文件夹路径  extension 为脸库图片的后缀
    def __init__(self, faces_lib_path='./FaceLibs/', extension='*.jpg'):
        # 遍历人脸库的图片
        self.face_file_names = glob.glob(os.path.join(faces_lib_path, extension))  # 获取图片名的列表
        self.face_targets = [name.split('\\')[-1].split('.')[0] for name in self.face_file_names]  # 以图片名作为标签

        self.tips = ''  # 显示预测结果
        
        self.known_encodings = []  # 存放编码集
        
        for i, image_name in enumerate(self.face_file_names):
            image_arr = face_recognition.load_image_file(image_name)  # 加载图片为numpy数组
            try:  
                encodings = face_recognition.face_encodings(image_arr)  # 获得图片中每张脸的编码
                assert len(encodings) == 1  # 保证一张图只存在一张脸
                image_name_encoding = encodings[0]  # 获取脸的编码
                self.known_encodings.append(image_name_encoding)
            except:  # 如果编码为空或者过多(多张人脸)则剔除
                self.face_file_names.pop(i)  
                self.face_targets.pop(i)
        
    
    def predict(self, file_path):
        image_arr = face_recognition.load_image_file(file_path)  # 加载图片
        image_encodings = face_recognition.face_encodings(image_arr)  # 获得图片中每张脸的编码
        if len(image_encodings) == 1:  # 保证测试图片只有一张脸
            image_encoding = image_encodings[0]  # 获取脸的编码 
            self.face_distances = face_recognition.face_distance(self.known_encodings, image_encoding) # 计算距离
            # 如果最小的距离小于0.5,则不识别,否则将标签传给tips
            self.tips = self.face_targets[self.face_distances.argmin()] if min(self.face_distances) < 0.5 else '不认识'  
        else:
            self.tips = '图片中的没有脸或者脸数超过1'

测试
face_recognition 简单识别人脸案例

r = face_recognizer()
r.predict(file_path='./3.jpg')
print(r.tips)