face_recognition是号称世界上最简单的人脸识别工具和Python库。虽然,是国外开源的项目(良心的MIT开源协议),居然有官方的中文文档支持,从未见过如此亲近天朝人民的开源项目了。python
手里有一张目标人物图,须要从一堆图片文件中,找出这我的是谁?这一堆的图片文件时,按人的姓名分类的。原本想直接使用face_recognition命令行解决,以下:git
face_recognition ./pictures_of_people_i_know/ ./unknown_pictures/
然而,个人unknown_pictures文件下面是按人姓名作为文件夹划分的,face_recognition不支持递归文件夹来找文件,因此,就只能编写python程序来解决了。github
from __future__ import division from tqdm import tqdm import os import face_recognition import imghdr import sys def get_all_files(path_dir): all_file = [] for dir_path, dir_names, filenames in os.walk(path_dir): for dir_ in dir_names: all_file.append(os.path.join(dir_path, dir_)) for name in filenames: all_file.append(os.path.join(dir_path, name)) return all_file def get_image_file(file_check): if os.path.isfile(file_check): if imghdr.what(file_check) == 'jpeg': unknown_picture = face_recognition.load_image_file(file_check) unknown_face_encoding_list = face_recognition.face_encodings(unknown_picture) if len(unknown_face_encoding_list) > 0: unknown_face_encoding = unknown_face_encoding_list[0] results = face_recognition.compare_faces([my_face_encoding], unknown_face_encoding, tolerance=0.2) if results[0]: return file_check if __name__ == '__main__': picture_of_me = face_recognition.load_image_file( "/Users/zhangyalin/Downloads/images/pictures_of_people_i_know/zyl.jpg") my_face_encoding = face_recognition.face_encodings(picture_of_me)[0] resultList = [] path = "/Users/zhangyalin/Downloads/images/unknown_pictures/" files = get_all_files(path) num_tasks = len(files) for file in tqdm(files): fileTarget = get_image_file(file) if fileTarget is not None: resultList.append(file) break print("定位:") print(resultList) sys.exit()
这里就是递归unknown_pictures
文件夹,而后不断将得到的图像中人脸与pictures_of_people_i_know/zyl.jpg
图像中人脸进行对比,而zyl.jpg
中人叫zyl
。具体能够去看Face Recognition 人脸识别,说的很清楚的。bash
Note:tolerance=0.2
,容错率须要设置为0.2,这样人脸识别更加准确。熟悉Python线程池的朋友,能够补充完善一下上面的代码。app