Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.46 KB | None | 0 0
  1. import face_recognition
  2. import time
  3. import pickle
  4. import configparser
  5.  
  6. config_file = 'settings.ini'
  7.  
  8. def recognition_image_from_ndarray(X_img):
  9.     try:
  10.         config = configparser.ConfigParser()
  11.         config.read(config_file)
  12.         trained_NN_path = config.get("Settings", 'trained_NN_path')
  13.     except:
  14.         trained_NN_path = '20TI8T_trained_knn_model.clf'
  15.  
  16.     # time_before_prediction = time.time()
  17.     predictions = predict(X_img, model_path=trained_NN_path)
  18.     # print(predictions)
  19.     #print('Prediction time:', time.time() - time_before_prediction)
  20.     #print('###Predicitons:', predictions)
  21.     output = {
  22.         'status': 'Ok',
  23.         'faces': []
  24.     }
  25.     for name, (top, right, bottom, left), accurate in predictions:
  26.         output['faces'].append({
  27.             'id': name,
  28.             'accurate': 1 - accurate[0],
  29.             'position': {
  30.                 'top': top,
  31.                 'right': right,
  32.                 'bottom': bottom,
  33.                 'left': left,
  34.             }
  35.         })
  36.  
  37.     return output
  38.  
  39.  
  40. def predict(X_img, knn_clf=None, model_path=None, distance_threshold=0.6):
  41.     """
  42.    Recognizes faces in given image using a trained KNN classifier
  43.  
  44.    :param X_img_path: path to image to be recognized
  45.    :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.
  46.    :param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.
  47.    :param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance
  48.           of mis-classifying an unknown person as a known one.
  49.    :return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].
  50.        For faces of unrecognized persons, the name 'unknown' will be returned.
  51.    """
  52.     # if not os.path.isfile(X_img_path) or os.path.splitext(X_img_path)[1][1:] not in ALLOWED_EXTENSIONS:
  53.     #     raise Exception("Invalid image path: {}".format(X_img_path))
  54.  
  55.     if knn_clf is None and model_path is None:
  56.         raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")
  57.  
  58.     # Load a trained KNN model (if one was passed in)
  59.     if knn_clf is None:
  60.         with open(model_path, 'rb') as f:
  61.             knn_clf = pickle.load(f)
  62.  
  63.     # Load image file and find face locations
  64.     #X_img = face_recognition.load_image_file(X_img_path)
  65.     X_face_locations = face_recognition.face_locations(X_img)
  66.  
  67.     # If no faces are found in the image, return an empty result.
  68.     if len(X_face_locations) == 0:
  69.         return []
  70.  
  71.     # Find encodings for faces in the test iamge
  72.     faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_face_locations)
  73.  
  74.     # Use the KNN model to find the best matches for the test face
  75.     closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)
  76.     # print(closest_distances)
  77.     are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]
  78.     # print(are_matches)
  79.  
  80.     # Predict classes and remove classifications that aren't within the threshold
  81.     # print(knn_clf.predict(faces_encodings))
  82.     # print(X_face_locations)
  83.     # print('----------')
  84.     return [(pred, loc, accurate) if rec else ("unknown", loc, accurate) for pred, loc, rec, accurate in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches, closest_distances[0])]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement