-
人臉檢測
-
人臉特征點提取
-
人臉對比,等於兩張人臉對比,識別
封裝的所有識別函數,直接看下面調用就好了。
# coding:utf-8 ''' 本本次封裝,我主要是做兩張人臉對比。 就只人臉識別部分,簡單應用。 # 調用注意事項,因為模型底層是外國人寫的。所以路徑圖片名字千萬別使用中文,這樣它直接找不到 好像是OpenCV的問題吧,一直沒有解決。中文他會亂碼。真的坑。 ''' import dlib import cv2 import glob import numpy as np class face_recognition: ''' 模型路徑 predictor_path = "./face_model/shape_predictor_68_face_landmarks.dat" face_rec_model_path = "./face_model/dlib_face_recognition_resnet_model_v1.dat" # 調用注意事項,因為模型底層是外國人寫的。所以路徑圖片名字千萬別使用中文,這樣它直接找不到 好像是OpenCV的問題吧,一直沒有解決。中文他會亂碼。真的坑。 ''' def __init__(self,predictor_path,face_rec_model_path): self.predictor_path = predictor_path self.face_rec_model_path = face_rec_model_path self.detector = dlib.get_frontal_face_detector() self.shape_predictor = dlib.shape_predictor(self.predictor_path) self.face_rec_model = dlib.face_recognition_model_v1(self.face_rec_model_path) def face_detection(self,url_img_1,url_img_2): img_path_list = [url_img_1,url_img_2] dist = [] for img_path in img_path_list: img = cv2.imread(img_path) # 轉換rgb順序的顏色。 b, g, r = cv2.split(img) img2 = cv2.merge([r, g, b]) # 檢測人臉 faces = self.detector(img, 1) if len(faces): for index, face in enumerate(faces): # # 提取68個特征點 shape = self.shape_predictor(img2, face) # 計算人臉的128維的向量 face_descriptor = self.face_rec_model.compute_face_descriptor(img2, shape) dist.append(list(face_descriptor)) else: pass return dist # 歐式距離 def dist_o(self,dist_1,dist_2): dis = np.sqrt(sum((np.array(dist_1)-np.array(dist_2))**2)) return dis def score(self,url_img_1,url_img_2): url_img_1 = glob.glob(url_img_1)[0] url_img_2 = glob.glob(url_img_2)[0] data = self.face_detection(url_img_1,url_img_2) goal = self.dist_o(data[0],data[1]) # 判斷結果,如果goal小於0.6的話是同一個人,否則不是。我所用的是歐式距離判別 return 1-goal
調用封裝識別函數進行,判別
# 調用 模型下載地址:http://dlib.net/files/ predictor_path = "./face_model/shape_predictor_68_face_landmarks.dat" face_rec_model_path = "./face_model/dlib_face_recognition_resnet_model_v1.dat" face_ = face_recognition(predictor_path,face_rec_model_path) # img_1 = './faces/User.1.4.jpg' # img_2 = './faces/User.1.46.jpg' img_1 = './faces/fan.jpg' img_2 = './faces/fan_2.jpg' goal = face_.score(img_1,img_2) print(goal)
這兩張圖片的距離為0.32左右,但是只要距離小於0.6就屬於同一個人,所以對比結果還是比較好的。