fannyxmikasa

OpenCv Trainer

Nov 10th, 2020 (edited)
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.31 KB | None | 0 0
  1. import cv2, os
  2. import numpy as np
  3. from PIL import Image
  4.  
  5. # Create data analizer for facerecognition
  6. recognizer = cv2.face.LBPHFaceRecognizer_create()
  7. # Assign the facerecognition classifier to use
  8. detector = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
  9. # Assign the path where dataset are stored
  10. path = 'C:/Users/PC/PycharmProjects/pythonProject1/DataSet'
  11.  
  12.  
  13. # Create an data structure
  14. def getImagesID(path):
  15.     # get the path of all the files in the folder
  16.     imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
  17.     # create empty face list
  18.     faceSamples = []
  19.     # create empty ID list
  20.     Ids = []
  21.     # now looping through all the image paths and loading the Ids and the images
  22.     for imagePath in imagePaths:
  23.         # ignore if the file does not have jpg extension :
  24.         print(imagePath)
  25.         if os.path.split(imagePath)[-1].split(".")[-1] != 'jpg':
  26.             continue
  27.         # loading the image and converting it to gray scale
  28.         faceImage = Image.open(imagePath).convert('L')
  29.        
  30.         # Now we are converting the PIL image into numpy array
  31.         faceNp = np.array(faceImage, 'uint8')
  32.         print(faceNp)
  33.         # getting the Id from the image
  34.         Id = os.path.split(imagePath)[-1].split(".")[1]
  35.         print(Id)
  36.         # extract the face from the training image sample
  37.         faces = detector.detectMultiScale(faceNp)
  38.         # Add face i,age in the array to faceSamples
  39.         faceSamples.append(faceNp)
  40.         print(faceSamples)
  41.         # Add label Id to Ids array
  42.         Ids.append(Id)
  43.         # print the Id for checking
  44.         # display the extracted face image on the screen
  45.         cv2.imshow("Training", faceNp)
  46.         # wait for user key press
  47.         cv2.waitKey(10)
  48.     # exit the loop and return array Ids and faceSamples
  49.     return Ids, faceSamples
  50.  
  51.  
  52. # Assign the content of getImagesID data structure to Ids and
  53. Ids, faceSamples = getImagesID(path)
  54. for i in range(0, len(Ids)):
  55.     Ids[i] = int(Ids[i])
  56. # Analize and record the data from facesample and Ids
  57. print(Ids)
  58. recognizer.train(faceSamples, np.array(Ids))
  59. # Save the process data in the training data file
  60. recognizer.save('C:/Users/PC/PycharmProjects/pythonProject1/trainner.yml')
  61. # Close all opened windows cv2.destroyAllWindows
  62.  
Add Comment
Please, Sign In to add comment