背景
face_recognition是號稱世界上最簡單的人臉識別工具和Python庫。雖然,是國外開源的項目(良心的MIT開源協議),竟然有官方的中文文檔支持,從未見過如此親近天朝人民的開源項目了。
問題
手裏有一張目標人物圖,需要從一堆圖片文件中,找出這個人是誰?這一堆的圖片文件時,按人的姓名分類的。本來想直接使用face_recognition命令行解決,如下:
face_recognition ./pictures_of_people_i_know/ ./unknown_pictures/
然而,我的unknown_pictures文件下面是按人姓名做爲文件夾劃分的,face_recognition不支持遞歸文件夾來找文件,所以,就只能編寫python程序來解決了。
Python3
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 人臉識別,說的很清楚的。
Note:tolerance=0.2
,容錯率需要設置爲0.2,這樣人臉識別更加準確。熟悉Python線程池的朋友,可以補充完善一下上面的代碼。