-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrainer.py
62 lines (39 loc) · 1.63 KB
/
trainer.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
#!/usr/bin/python
import cv2, os, sys
import numpy as np
from PIL import Image
classifier_file = 'haarcascade_frontalface_default.xml'
images_ext = ['.png', '.jpg', '.jpeg']
def getFacesForTrainer(imagesPath, detector):
faces = []
identifiers = []
images = [os.path.join(imagesPath, img) for img in os.listdir(imagesPath) if os.path.splitext(img)[1] in images_ext]
count=1
for image in images:
pilImage = Image.open(image).convert('L')
imageNp = np.array(pilImage, 'uint8')
_faces = detector.detectMultiScale(imageNp)
for (x, y, w, h) in _faces:
faces.append(imageNp[y: y+h, x: x+w])
identifiers.append(count)
count=count+1
return faces, identifiers
def setTrainer(imagesPath, outputDirectory, fileName='trainer'):
detector, recognizer = getDectectorAndReconigzer()
outputFile = os.path.join(outputDirectory, '{0}.yml'.format(fileName))
faces, identifiers = getFacesForTrainer(imagesPath, detector)
recognizer.train(faces, np.array(identifiers))
recognizer.save(outputFile)
print('{0} faces detected! Info stored in {1}'.format(len(faces), outputFile))
def getDectectorAndReconigzer():
if not os.path.isfile(classifier_file):
print("%s does not exits in the current directory!" % classifier_file)
return
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier(classifier_file)
return detector, recognizer
if __name__ == '__main__':
if len(sys.argv) <= 1:
print('You must provide the full path of the image!')
sys.exit(-1)
setTrainer(sys.argv[1], '.')