python dlib人臉識別代碼實例

這篇文章主要介紹了python dlib人臉識別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨着小編來一起學習學習吧

本文實例爲大家分享了python dlib人臉識別的具體代碼,供大家參考,具體內容如下

import matplotlib.pyplot as plt
import dlib
import numpy as np
import glob
import re
 
#正臉檢測器
detector=dlib.get_frontal_face_detector()
#臉部關鍵形態檢測器
sp=dlib.shape_predictor(r"D:\LB\JAVASCRIPT\shape_predictor_68_face_landmarks.dat")
#人臉識別模型
facerec = dlib.face_recognition_model_v1(r"D:\LB\JAVASCRIPT\dlib_face_recognition_resnet_model_v1.dat")
 
#候選人臉部描述向量集
descriptors=[]
 
photo_locations=[]
 
for photo in glob.glob(r'D:\LB\JAVASCRIPT\faces\*.jpg'):
  photo_locations.append(photo)
  img=plt.imread(photo)
  img=np.array(img)
  
  #開始檢測人臉
  dets=detector(img,1)
  
  for k,d in enumerate(dets):
    #檢測每張照片中人臉的特徵
    shape=sp(img,d)
    face_descriptor=facerec.compute_face_descriptor(img,shape)
    v=np.array(face_descriptor)
    descriptors.append(v)
		
#輸入的待識別的人臉處理方法相同
img=plt.imread(r'D:\test_photo10.jpg')
img=np.array(img)
dets=detector(img,1)
#計算輸入人臉和已有人臉之間的差異程度(比如用歐式距離來衡量)
differences=[]
for k,d in enumerate(dets):
  shape=sp(img,d)
  face_descriptor=facerec.compute_face_descriptor(img,shape)
  d_test=np.array(face_descriptor)
  
  #計算輸入人臉和所有已有人臉描述向量的歐氏距離
  for i in descriptors:
    distance=np.linalg.norm(i-d_test)
    differences.append(distance)
 
#按歐式距離排序 歐式距離最小的就是匹配的人臉
candidate_count=len(photo_locations)
candidates_dict=dict(zip(photo_locations,differences))
candidates_dict_sorted=sorted(candidates_dict.items(),key=lambda x:x[1])
 
#matplotlib要正確顯示中文需要設置
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
 
plt.rcParams['figure.figsize'] = (20.0, 70.0) 
 
ax=plt.subplot(candidate_count+1,4,1)
ax.set_title("輸入的人臉")
ax.imshow(img)
 
for i,(photo,distance) in enumerate(candidates_dict_sorted):
  img=plt.imread(photo)
  
  face_name=""
  photo_name=re.search(r'([^\\]*)\.jpg$',photo)
  if photo_name:
    face_name=photo_name[1]
    
  ax=plt.subplot(candidate_count+1,4,i+2)
  ax.set_xticks([])
  ax.set_yticks([])
  ax.spines['top'].set_visible(False)
  ax.spines['right'].set_visible(False)
  ax.spines['bottom'].set_visible(False)
  ax.spines['left'].set_visible(False)
  
  if i==0:
    ax.set_title("最匹配的人臉\n\n"+face_name+"\n\n差異度:"+str(distance))
  else:
    ax.set_title(face_name+"\n\n差異度:"+str(distance))
  ax.imshow(img)
 
plt.show()

以上所述是小編給大家介紹的python dlib人臉識別詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對神馬文庫網站的支持!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章