Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2, os
- import numpy as np
- from PIL import Image
- # Create data analizer for facerecognition
- recognizer = cv2.face.LBPHFaceRecognizer_create()
- # Assign the facerecognition classifier to use
- detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
- # Assign the path where dataset are stored
- path = 'C:/Users/PC/PycharmProjects/pythonProject1/DataSet'
- # Create an data structure
- def getImagesID(path):
- # get the path of all the files in the folder
- imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
- # create empty face list
- faceSamples = []
- # create empty ID list
- Ids = []
- # now looping through all the image paths and loading the Ids and the images
- for imagePath in imagePaths:
- # ignore if the file does not have jpg extension :
- print(imagePath)
- if os.path.split(imagePath)[-1].split(".")[-1] != 'jpg':
- continue
- # loading the image and converting it to gray scale
- faceImage = Image.open(imagePath).convert('L')
- # Now we are converting the PIL image into numpy array
- faceNp = np.array(faceImage, 'uint8')
- print(faceNp)
- # getting the Id from the image
- Id = os.path.split(imagePath)[-1].split(".")[1]
- print(Id)
- # extract the face from the training image sample
- faces = detector.detectMultiScale(faceNp)
- # Add face i,age in the array to faceSamples
- faceSamples.append(faceNp)
- print(faceSamples)
- # Add label Id to Ids array
- Ids.append(Id)
- # print the Id for checking
- # display the extracted face image on the screen
- cv2.imshow("Training", faceNp)
- # wait for user key press
- cv2.waitKey(10)
- # exit the loop and return array Ids and faceSamples
- return Ids, faceSamples
- # Assign the content of getImagesID data structure to Ids and
- Ids, faceSamples = getImagesID(path)
- for i in range(0, len(Ids)):
- Ids[i] = int(Ids[i])
- # Analize and record the data from facesample and Ids
- print(Ids)
- recognizer.train(faceSamples, np.array(Ids))
- # Save the process data in the training data file
- recognizer.save('C:/Users/PC/PycharmProjects/pythonProject1/trainner.yml')
- # Close all opened windows cv2.destroyAllWindows
Add Comment
Please, Sign In to add comment