python dlib人臉識別代碼實例
更新時間:2019年04月04日 14:22:52 作者:一粒馬豆
這篇文章主要介紹了python dlib人臉識別,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
本文實例為大家分享了python dlib人臉識別的具體代碼,供大家參考,具體內(nèi)容如下
import matplotlib.pyplot as plt
import dlib
import numpy as np
import glob
import re
#正臉檢測器
detector=dlib.get_frontal_face_detector()
#臉部關鍵形態(tài)檢測器
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人臉識別詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
Python中使用matplotlib模塊errorbar函數(shù)繪制誤差棒圖實例代碼
在matplotlib中,errorbar方法用于繪制帶誤差線的折線圖,下面這篇文章主要給大家介紹了關于Python中使用matplotlib模塊errorbar函數(shù)繪制誤差棒圖的相關資料,需要的朋友可以參考下2022-08-08
Python3利用Dlib19.7實現(xiàn)攝像頭人臉識別的方法
這篇文章主要介紹了Python 3 利用 Dlib 19.7 實現(xiàn)攝像頭人臉識別 ,利用python開發(fā),借助Dlib庫捕獲攝像頭中的人臉,提取人臉特征,通過計算歐氏距離來和預存的人臉特征進行對比,達到人臉識別的目的,感興趣的小伙伴們可以參考一下2018-05-05

