Keras目標檢測mtcnn?facenet搭建人臉識別平臺
什么是mtcnn和facenet
1、mtcnn
MTCNN,英文全稱是Multi-task convolutional neural network,中文全稱是多任務卷積神經網絡,該神經網絡將人臉區(qū)域檢測與人臉關鍵點檢測放在了一起。
總體可分為P-Net、R-Net、和O-Net三層網絡結構。
2、facenet
谷歌人臉檢測算法,發(fā)表于 CVPR 2015,利用相同人臉在不同角度等姿態(tài)的照片下有高內聚性,不同人臉有低耦合性,提出使用 cnn + triplet mining 方法,在 LFW 數(shù)據集上準確度達到 99.63%。
通過 CNN 將人臉映射到歐式空間的特征向量上,實質上:不同圖片人臉特征的距離較大;通過相同個體的人臉的距離,總是小于不同個體的人臉這一先驗知識訓練網絡。
測試時只需要計算人臉特征EMBEDDING,然后計算距離使用閾值即可判定兩張人臉照片是否屬于相同的個體。
簡單來講,在使用階段,facenet即是:
1、輸入一張人臉圖片
2、通過深度學習網絡提取特征
3、L2標準化
4、得到128維特征向量。
mtcnn原理和facenet原理可以參考我的另外兩篇博客。
神經網絡學習——facenet詳解及其keras實現(xiàn)
實現(xiàn)流程
整體的代碼擺放如下:
一、數(shù)據庫的初始化
face_dataset里面裝的是想要識別的人臉,比如說obama.jpg指的就是奧巴馬。
數(shù)據庫中每一張圖片對應一個人的人臉,圖片名字就是這個人的名字。
數(shù)據庫初始化指的是人臉數(shù)據庫的初始化。
想要實現(xiàn)人臉識別,首先要知道自己需要識別哪些人臉。
這就是數(shù)據庫的一個功能,將想要檢測到的人臉放入數(shù)據庫中,并進行編碼。
數(shù)據庫的初始化具體執(zhí)行的過程就是:
1、遍歷數(shù)據庫中所有的圖片。
2、檢測每個圖片中的人臉位置。
3、利用mtcnn將人臉截取下載。
4、將獲取到的人臉進行對齊。
5、利用facenet將人臉進行編碼。
6、將所有人臉編碼的結果放在一個列表中。
第6步得到的列表就是已知的所有人臉的特征列表,在之后獲得的實時圖片中的人臉都需要與已知人臉進行比對,這樣我們才能知道誰是誰。實現(xiàn)代碼如下:
class face_rec(): def __init__(self): # 創(chuàng)建mtcnn對象 # 檢測圖片中的人臉 self.mtcnn_model = mtcnn() # 門限函數(shù) self.threshold = [0.5,0.8,0.9] # 載入facenet # 將檢測到的人臉轉化為128維的向量 self.facenet_model = InceptionResNetV1() # model.summary() model_path = './model_data/facenet_keras.h5' self.facenet_model.load_weights(model_path) #-----------------------------------------------# # 對數(shù)據庫中的人臉進行編碼 # known_face_encodings中存儲的是編碼后的人臉 # known_face_names為人臉的名字 #-----------------------------------------------# face_list = os.listdir("face_dataset") self.known_face_encodings=[] self.known_face_names=[] for face in face_list: name = face.split(".")[0] img = cv2.imread("./face_dataset/"+face) img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) # 檢測人臉 rectangles = self.mtcnn_model.detectFace(img, self.threshold) # 轉化成正方形 rectangles = utils.rect2square(np.array(rectangles)) # facenet要傳入一個160x160的圖片 rectangle = rectangles[0] # 記下他們的landmark landmark = (np.reshape(rectangle[5:15],(5,2)) - np.array([int(rectangle[0]),int(rectangle[1])]))/(rectangle[3]-rectangle[1])*160 crop_img = img[int(rectangle[1]):int(rectangle[3]), int(rectangle[0]):int(rectangle[2])] crop_img = cv2.resize(crop_img,(160,160)) new_img,_ = utils.Alignment_1(crop_img,landmark) new_img = np.expand_dims(new_img,0) # 將檢測到的人臉傳入到facenet的模型中,實現(xiàn)128維特征向量的提取 face_encoding = utils.calc_128_vec(self.facenet_model,new_img) self.known_face_encodings.append(face_encoding) self.known_face_names.append(name)
二、實時圖片的處理
1、人臉的截取與對齊
利用mtcnn我們可以獲得一張圖片中人臉的位置,但是我們截取下來的人臉是這樣的:
我們可以很明顯的看出來人臉是歪著的,我們如果人臉可以正過來,那么將對人臉的特征提取非常有好處。
下面這張圖看著就正多了。
常見的對齊方法有
1、通過雙眼坐標進行旋正
2、通過矩陣運算求解仿射矩陣進行旋正
這里簡單講講通過雙眼坐標進行旋正。
利用雙眼坐標進行旋正需要用到兩個參數(shù),如圖所示分別是:
1、眼睛連線相對于水平線的傾斜角。
2、圖片的中心。
利用這兩個參數(shù)我們可以知道需要圖片需要旋轉的角度是多少,圖片旋轉的中心是什么。
代碼實現(xiàn)如下,其中l(wèi)andmark是五個人臉特征點的位置:
#-------------------------------------# # 人臉對齊 #-------------------------------------# def Alignment_1(img,landmark): if landmark.shape[0]==68: x = landmark[36,0] - landmark[45,0] y = landmark[36,1] - landmark[45,1] elif landmark.shape[0]==5: x = landmark[0,0] - landmark[1,0] y = landmark[0,1] - landmark[1,1] # 眼睛連線相對于水平線的傾斜角 if x==0: angle = 0 else: # 計算它的弧度制 angle = math.atan(y/x)*180/math.pi center = (img.shape[1]//2, img.shape[0]//2) RotationMatrix = cv2.getRotationMatrix2D(center, angle, 1) # 仿射函數(shù) new_img = cv2.warpAffine(img,RotationMatrix,(img.shape[1],img.shape[0])) RotationMatrix = np.array(RotationMatrix) new_landmark = [] for i in range(landmark.shape[0]): pts = [] pts.append(RotationMatrix[0,0]*landmark[i,0]+RotationMatrix[0,1]*landmark[i,1]+RotationMatrix[0,2]) pts.append(RotationMatrix[1,0]*landmark[i,0]+RotationMatrix[1,1]*landmark[i,1]+RotationMatrix[1,2]) new_landmark.append(pts) new_landmark = np.array(new_landmark) return new_img, new_landmark
2、利用facenet對矯正后的人臉進行編碼
facenet是一個人臉特征獲取的模型,將第1步獲得的對齊人臉傳入facenet模型就可以得到每個人臉的特征向量。
將所有特征向量保存在一個列表中,在第3步進行比對。
height,width,_ = np.shape(draw) draw_rgb = cv2.cvtColor(draw,cv2.COLOR_BGR2RGB) # 檢測人臉 rectangles = self.mtcnn_model.detectFace(draw_rgb, self.threshold) print(np.shape(rectangles)) if len(rectangles)==0: return # 轉化成正方形 rectangles = utils.rect2square(np.array(rectangles,dtype=np.int32)) rectangles[:,0] = np.clip(rectangles[:,0],0,width) rectangles[:,1] = np.clip(rectangles[:,1],0,height) rectangles[:,2] = np.clip(rectangles[:,2],0,width) rectangles[:,3] = np.clip(rectangles[:,3],0,height) #-----------------------------------------------# # 對檢測到的人臉進行編碼 #-----------------------------------------------# face_encodings = [] for rectangle in rectangles: # 獲取landmark在小圖中的坐標 landmark = (np.reshape(rectangle[5:15],(5,2)) - np.array([int(rectangle[0]),int(rectangle[1])]))/(rectangle[3]-rectangle[1])*160 # 截取圖像 crop_img = draw_rgb[int(rectangle[1]):int(rectangle[3]), int(rectangle[0]):int(rectangle[2])] crop_img = cv2.resize(crop_img,(160,160)) # 對齊 new_img,_ = utils.Alignment_1(crop_img,landmark) new_img = np.expand_dims(new_img,0) # 利用facenet_model計算128維特征向量 face_encoding = utils.calc_128_vec(self.facenet_model,new_img) face_encodings.append(face_encoding)
3、將實時圖片中的人臉特征與數(shù)據庫中的進行比對
這個比對過程是這樣的:
1、獲取實時圖片中的每一張人臉特征。
2、將每一張人臉特征和數(shù)據庫中所有的人臉進行比較,計算距離。如果距離小于門限值,則認為其具有一定的相似度。
3、獲得每一張人臉在數(shù)據庫中最相似的人臉的序號。
4、判斷這個序號對應的人臉距離是否小于門限,是則認為人臉識別成功,他就是這個人。
實現(xiàn)代碼如下:
face_names = [] for face_encoding in face_encodings: # 取出一張臉并與數(shù)據庫中所有的人臉進行對比,計算得分 matches = utils.compare_faces(self.known_face_encodings, face_encoding, tolerance = 0.9) name = "Unknown" # 找出距離最近的人臉 face_distances = utils.face_distance(self.known_face_encodings, face_encoding) # 取出這個最近人臉的評分 best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = self.known_face_names[best_match_index] face_names.append(name)
4、實時處理圖片整體代碼
class face_rec(): def recognize(self,draw): #-----------------------------------------------# # 人臉識別 # 先定位,再進行數(shù)據庫匹配 #-----------------------------------------------# height,width,_ = np.shape(draw) draw_rgb = cv2.cvtColor(draw,cv2.COLOR_BGR2RGB) # 檢測人臉 rectangles = self.mtcnn_model.detectFace(draw_rgb, self.threshold) print(np.shape(rectangles)) if len(rectangles)==0: return # 轉化成正方形 rectangles = utils.rect2square(np.array(rectangles,dtype=np.int32)) rectangles[:,0] = np.clip(rectangles[:,0],0,width) rectangles[:,1] = np.clip(rectangles[:,1],0,height) rectangles[:,2] = np.clip(rectangles[:,2],0,width) rectangles[:,3] = np.clip(rectangles[:,3],0,height) #-----------------------------------------------# # 對檢測到的人臉進行編碼 #-----------------------------------------------# face_encodings = [] for rectangle in rectangles: # 獲取landmark在小圖中的坐標 landmark = (np.reshape(rectangle[5:15],(5,2)) - np.array([int(rectangle[0]),int(rectangle[1])]))/(rectangle[3]-rectangle[1])*160 # 截取圖像 crop_img = draw_rgb[int(rectangle[1]):int(rectangle[3]), int(rectangle[0]):int(rectangle[2])] crop_img = cv2.resize(crop_img,(160,160)) # 對齊 new_img,_ = utils.Alignment_1(crop_img,landmark) new_img = np.expand_dims(new_img,0) # 利用facenet_model計算128維特征向量 face_encoding = utils.calc_128_vec(self.facenet_model,new_img) face_encodings.append(face_encoding) face_names = [] for face_encoding in face_encodings: # 取出一張臉并與數(shù)據庫中所有的人臉進行對比,計算得分 matches = utils.compare_faces(self.known_face_encodings, face_encoding, tolerance = 0.9) name = "Unknown" # 找出距離最近的人臉 face_distances = utils.face_distance(self.known_face_encodings, face_encoding) # 取出這個最近人臉的評分 best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = self.known_face_names[best_match_index] face_names.append(name) rectangles = rectangles[:,0:4] #-----------------------------------------------# # 畫框~!~ #-----------------------------------------------# for (left, top, right, bottom), name in zip(rectangles, face_names): cv2.rectangle(draw, (left, top), (right, bottom), (0, 0, 255), 2) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(draw, name, (left , bottom - 15), font, 0.75, (255, 255, 255), 2) return draw
全部代碼:
這里只放出主文件的全部代碼,需要的可以去github下載:
import cv2 import os import numpy as np from net.mtcnn import mtcnn import utils.utils as utils from net.inception import InceptionResNetV1 class face_rec(): def __init__(self): # 創(chuàng)建mtcnn對象 # 檢測圖片中的人臉 self.mtcnn_model = mtcnn() # 門限函數(shù) self.threshold = [0.5,0.8,0.9] # 載入facenet # 將檢測到的人臉轉化為128維的向量 self.facenet_model = InceptionResNetV1() # model.summary() model_path = './model_data/facenet_keras.h5' self.facenet_model.load_weights(model_path) #-----------------------------------------------# # 對數(shù)據庫中的人臉進行編碼 # known_face_encodings中存儲的是編碼后的人臉 # known_face_names為人臉的名字 #-----------------------------------------------# face_list = os.listdir("face_dataset") self.known_face_encodings=[] self.known_face_names=[] for face in face_list: name = face.split(".")[0] img = cv2.imread("./face_dataset/"+face) img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) # 檢測人臉 rectangles = self.mtcnn_model.detectFace(img, self.threshold) # 轉化成正方形 rectangles = utils.rect2square(np.array(rectangles)) # facenet要傳入一個160x160的圖片 rectangle = rectangles[0] # 記下他們的landmark landmark = (np.reshape(rectangle[5:15],(5,2)) - np.array([int(rectangle[0]),int(rectangle[1])]))/(rectangle[3]-rectangle[1])*160 crop_img = img[int(rectangle[1]):int(rectangle[3]), int(rectangle[0]):int(rectangle[2])] crop_img = cv2.resize(crop_img,(160,160)) new_img,_ = utils.Alignment_1(crop_img,landmark) new_img = np.expand_dims(new_img,0) # 將檢測到的人臉傳入到facenet的模型中,實現(xiàn)128維特征向量的提取 face_encoding = utils.calc_128_vec(self.facenet_model,new_img) self.known_face_encodings.append(face_encoding) self.known_face_names.append(name) def recognize(self,draw): #-----------------------------------------------# # 人臉識別 # 先定位,再進行數(shù)據庫匹配 #-----------------------------------------------# height,width,_ = np.shape(draw) draw_rgb = cv2.cvtColor(draw,cv2.COLOR_BGR2RGB) # 檢測人臉 rectangles = self.mtcnn_model.detectFace(draw_rgb, self.threshold) print(np.shape(rectangles)) if len(rectangles)==0: return # 轉化成正方形 rectangles = utils.rect2square(np.array(rectangles,dtype=np.int32)) rectangles[:,0] = np.clip(rectangles[:,0],0,width) rectangles[:,1] = np.clip(rectangles[:,1],0,height) rectangles[:,2] = np.clip(rectangles[:,2],0,width) rectangles[:,3] = np.clip(rectangles[:,3],0,height) #-----------------------------------------------# # 對檢測到的人臉進行編碼 #-----------------------------------------------# face_encodings = [] for rectangle in rectangles: # 獲取landmark在小圖中的坐標 landmark = (np.reshape(rectangle[5:15],(5,2)) - np.array([int(rectangle[0]),int(rectangle[1])]))/(rectangle[3]-rectangle[1])*160 # 截取圖像 crop_img = draw_rgb[int(rectangle[1]):int(rectangle[3]), int(rectangle[0]):int(rectangle[2])] crop_img = cv2.resize(crop_img,(160,160)) # 對齊 new_img,_ = utils.Alignment_1(crop_img,landmark) new_img = np.expand_dims(new_img,0) # 利用facenet_model計算128維特征向量 face_encoding = utils.calc_128_vec(self.facenet_model,new_img) face_encodings.append(face_encoding) face_names = [] for face_encoding in face_encodings: # 取出一張臉并與數(shù)據庫中所有的人臉進行對比,計算得分 matches = utils.compare_faces(self.known_face_encodings, face_encoding, tolerance = 0.9) name = "Unknown" # 找出距離最近的人臉 face_distances = utils.face_distance(self.known_face_encodings, face_encoding) # 取出這個最近人臉的評分 best_match_index = np.argmin(face_distances) if matches[best_match_index]: name = self.known_face_names[best_match_index] face_names.append(name) rectangles = rectangles[:,0:4] #-----------------------------------------------# # 畫框~!~ #-----------------------------------------------# for (left, top, right, bottom), name in zip(rectangles, face_names): cv2.rectangle(draw, (left, top), (right, bottom), (0, 0, 255), 2) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(draw, name, (left , bottom - 15), font, 0.75, (255, 255, 255), 2) return draw if __name__ == "__main__": dududu = face_rec() video_capture = cv2.VideoCapture(1) while True: ret, draw = video_capture.read() dududu.recognize(draw) cv2.imshow('Video', draw) if cv2.waitKey(20) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows()
以上就是Keras目標檢測mtcnn facenet搭建人臉識別平臺的詳細內容,更多關于Keras目標檢測mtcnn facenet人臉識別的資料請關注腳本之家其它相關文章!
相關文章
Python PyWebIO實現(xiàn)網頁版數(shù)據查詢器
PyWebIO提供了一系列命令式的交互函數(shù)來在瀏覽器上獲取用戶輸入和進行輸出,將瀏覽器變成了一個“富文本終端”,可以用于構建簡單的Web應用或基于瀏覽器的GUI應用。本文將利用PyWebIO制作一個網頁版的數(shù)據查詢器,感興趣的可以學習一下2021-12-12使用Python開發(fā)游戲運行腳本實現(xiàn)模擬點擊
這篇文章主要介紹了使用Python開發(fā)游戲運行腳本實現(xiàn)模擬點擊,這樣我們要想實現(xiàn)手游腳本開發(fā)的第一步,就是下載Android模擬器,然后在對安卓模擬器進行鼠標和鍵盤的模擬,以此來實現(xiàn)自動化游戲腳本,需要的朋友可以參考下2021-11-11詳解Django關于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法
這篇文章主要介紹了詳解Django關于StreamingHttpResponse與FileResponse文件下載的最優(yōu)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01Python實現(xiàn)ElGamal加密算法的示例代碼
ElGamal加密算法是一個基于迪菲-赫爾曼密鑰交換的非對稱加密算法。這篇文章通過示例代碼給大家介紹Python實現(xiàn)ElGamal加密算法的相關知識,感興趣的朋友一起看看吧2020-06-06django中上傳圖片分頁三級聯(lián)動效果的實現(xiàn)代碼
這篇文章主要介紹了django中上傳圖片分頁三級聯(lián)動效果的實現(xiàn)代碼,非常不錯,具有一定的參考借鑒價值,需要的朋友參考下吧2019-08-08torchxrayvision包安裝過程(附pytorch1.6cpu版安裝)
這篇文章主要介紹了torchxrayvision包安裝過程(附pytorch1.6cpu版安裝),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-08-08Python實現(xiàn)微信自動好友驗證,自動回復,發(fā)送群聊鏈接方法
今天小編就為大家分享一篇Python實現(xiàn)微信自動好友驗證,自動回復,發(fā)送群聊鏈接方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02django虛擬環(huán)境(virtualenv)的創(chuàng)建
在使用django開發(fā)項目的時候,一個環(huán)境只能對應一個項目,若不安裝虛擬環(huán)境、都裝在系統(tǒng)里面,每次項目加載都需要加載所有的安裝包,本文就介紹django虛擬環(huán)境的安裝,感興趣的可以了解一下2021-08-08