-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTrain_Image.py
55 lines (46 loc) · 1.83 KB
/
Train_Image.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
import os
import time
import cv2
import numpy as np
from PIL import Image
from threading import Thread
# -------------- image labesl ------------------------
def getImagesAndLabels(path):
# get the path of all the files in the folder
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
# print(imagePaths)
# create empth face list
faces = []
# create empty ID list
Ids = []
# now looping through all the image paths and loading the Ids and the images
for imagePath in imagePaths:
# loading the image and converting it to gray scale
pilImage = Image.open(imagePath).convert('L')
# Now we are converting the PIL image into numpy array
imageNp = np.array(pilImage, 'uint8')
# getting the Id from the image
Id = int(os.path.split(imagePath)[-1].split(".")[1])
# extract the face from the training image sample
faces.append(imageNp)
Ids.append(Id)
return faces, Ids
# ----------- train images function ---------------
def TrainImages():
recognizer = cv2.face_LBPHFaceRecognizer.create()
harcascadePath = "haarcascade_frontalface_default.xml"
detector = cv2.CascadeClassifier(harcascadePath)
faces, Id = getImagesAndLabels("TrainingImage")
Thread(target = recognizer.train(faces, np.array(Id))).start()
# Below line is optional for a visual counter effect
Thread(target = counter_img("TrainingImage")).start()
recognizer.save("TrainingImageLabel"+os.sep+"Trainner.yml")
print("All Images")
# Optional, adds a counter for images trained (You can remove it)
def counter_img(path):
imgcounter = 1
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
for imagePath in imagePaths:
print(str(imgcounter) + " Images Trained", end="\r")
time.sleep(0.008)
imgcounter += 1