forked from nazmiasri95/Face-Recognition
-
Notifications
You must be signed in to change notification settings - Fork 18
/
training.py
69 lines (48 loc) · 1.94 KB
/
training.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
####################################################
# Modified by Sacha Arbonel #
# Original code: http://thecodacus.com/ #
# All right reserved to the respective owner #
####################################################
# Import OpenCV2 for image processing
# Import os for file path
import cv2, os
# Import numpy for matrix calculation
import numpy as np
# Import Python Image Library (PIL)
from PIL import Image
# Create Local Binary Patterns Histograms for face recognization
recognizer = cv2.cv2.face.LBPHFaceRecognizer_create()
# Using prebuilt frontal face training model, for face detection
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
# Create method to get the images and label data
def getImagesAndLabels(path):
# Get all file path
imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
# Initialize empty face sample
faceSamples=[]
# Initialize empty id
ids = []
# Loop all the file path
for imagePath in imagePaths:
# Get the image and convert it to grayscale
PIL_img = Image.open(imagePath).convert('L')
# PIL image to numpy array
img_numpy = np.array(PIL_img,'uint8')
# Get the image id
id = int(os.path.split(imagePath)[-1].split(".")[1])
# Get the face from the training images
faces = detector.detectMultiScale(img_numpy)
# Loop for each face, append to their respective ID
for (x,y,w,h) in faces:
# Add the image to face samples
faceSamples.append(img_numpy[y:y+h,x:x+w])
# Add the ID to IDs
ids.append(id)
# Pass the face array and IDs array
return faceSamples,ids
# Get the faces and IDs
faces,ids = getImagesAndLabels('dataset')
# Train the model using the faces and IDs
recognizer.train(faces, np.array(ids))
# Save the model into trainer.yml
recognizer.write('trainer/trainer.yml')