1+ import dlib
2+ from skimage import io , transform
3+ import cv2
4+ import matplotlib .pyplot as plt
5+ import numpy as np
6+ import pandas as pd
7+ import glob
8+ import openface
9+ import pickle
10+ import os
11+ import sys
12+
13+ from sklearn .svm import SVC
14+ from sklearn .preprocessing import LabelEncoder
15+
16+ import face_recognition_models
17+
18+ face_detector = dlib .get_frontal_face_detector ()
19+ face_recognition_model = face_recognition_models .face_recognition_model_location ()
20+ face_encoder = dlib .face_recognition_model_v1 (face_recognition_model )
21+ face_pose_predictor = dlib .shape_predictor ('./model/shape_predictor_68_face_landmarks.dat' )
22+
23+ def get_detected_faces (filename ):
24+ image = cv2 .imread (filename )
25+ image = cv2 .cvtColor (image , cv2 .COLOR_BGR2RGB )
26+ return image , face_detector (image , 1 )
27+
28+ def get_face_encoding (image , detected_face ):
29+ pose_landmarks = face_pose_predictor (image , detected_face )
30+ face_encoding = face_encoder .compute_face_descriptor (image , pose_landmarks , 1 )
31+ return np .array (face_encoding )
32+
33+ def training (people ):
34+ """
35+ We need to have only one person/face per picture
36+ """
37+ # parsing labels and reprensations
38+ df = pd .DataFrame ()
39+ for p in people :
40+ l = []
41+ for filename in glob .glob ('./data/%s/*' % p ):
42+ image , face_detect = get_detected_faces (filename )
43+ face_encoding = get_face_encoding (image , face_detect [0 ])
44+ l .append (np .append (face_encoding , [p ]))
45+ temp = pd .DataFrame (np .array (l ))
46+ df = pd .concat ([df , temp ])
47+ df .reset_index (drop = True , inplace = True )
48+
49+ # converting labels into int
50+ le = LabelEncoder ()
51+ y = le .fit_transform (df [128 ])
52+ print ("Training for {} classes." .format (len (le .classes_ )))
53+ X = df .drop (128 , axis = 1 )
54+
55+ # training
56+ clf = SVC (C = 1 , kernel = 'linear' , probability = True )
57+ clf .fit (X , y )
58+
59+ # dumping model
60+ fName = "./classifier.pkl"
61+ print ("Saving classifier to '{}'" .format (fName ))
62+ with open (fName , 'wb' ) as f :
63+ pickle .dump ((le , clf ), f )
64+
65+ def predict (filename ):
66+ with open ("./classifier.pkl" , 'rb' ) as f :
67+ (le , clf ) = pickle .load (f )
68+ image , detected_faces = get_detected_faces (filename )
69+ img = np .copy (image )
70+ font = cv2 .FONT_HERSHEY_SIMPLEX
71+ for face_detect in detected_faces :
72+ # draw bounding boxes
73+ cv2 .rectangle (img , (face_detect .left (), face_detect .top ()),
74+ (face_detect .right (), face_detect .bottom ()), (255 , 0 , 0 ), 2 )
75+ p = clf .predict_proba (get_face_encoding (image , face_detect ).reshape (1 , 128 ))
76+ if np .max (p ) > 0.8 :
77+ y_pred = le .inverse_transform (np .argmax (p ))
78+ cv2 .putText (img , y_pred , (face_detect .left (), face_detect .top ()- 5 ), font , 0.3 , (255 , 0 , 0 ))
79+ return img
80+
81+ if __name__ == '__main__' :
82+ people = os .listdir ('./data/' )
0 commit comments