Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. import cv2
  2. import os
  3. import pickle
  4. from PIL import Image
  5. import numpy as np
  6.  
  7. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  8. image_dir = os.path.join(BASE_DIR, "images")
  9.  
  10. face_cascade = cv2.CascadeClassifier('cascades/data/haarcascade_frontalface_alt.xml')
  11. recognizer = cv2.face.LBPHFaceRecognizer_create()
  12.  
  13. current_id = 0
  14. label_ids = {}
  15. y_labels = []
  16. x_train = []
  17.  
  18. for root, dirs, files in os.walk(image_dir):
  19.     for file in files:
  20.         if file.endswith("png") or file.endswith("jpg"):
  21.             path = os.path.join(root, file)
  22.             label = os.path.basename(root).replace(" ", "-").lower()
  23.             # print(label, path)
  24.            
  25.             if not label in label_ids:
  26.                 label_ids[label] = current_id
  27.                 current_id += 1
  28.             id_ = label_ids[label]
  29.             print(label_ids)
  30.            
  31.             # y_labels.append(label) # some number
  32.             # x_train.append(path) # verify this image, turn into NUMPY array, GRAY
  33.             pil_image = Image.open(path).convert("L") # grayscale
  34.             size = (550, 550)
  35.             final_image = pil_image.resize(size, Image.ANTIALIAS)
  36.             image_array = np.array(final_image, "uint8")
  37.             # print(image_array)
  38.             faces = face_cascade.detectMultiScale(image_array, scaleFactor=1.5, minNeighbors=5)
  39.  
  40.             for(x, y, w, h) in faces:
  41.                 roi = image_array[y:y+h, x:x+h]
  42.                 x_train.append(roi)
  43.                 y_labels.append(id_)
  44.  
  45. # print(y_labels)
  46. # print(x_train)
  47.  
  48. with open("labels.pickle", 'wb') as f:
  49.     pickle.dump(label_ids, f)
  50.  
  51. recognizer.train(x_train, np.array(y_labels))
  52. recognizer.save("trainner.xml")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement