NLinker

Faces comparison

Mar 20th, 2019
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. import cv2, dlib, os
  2. from scipy.spatial import distance
  3. import pickle
  4.  
  5. def save(name, list):
  6.     with open(str(name) + '.pkl', 'wb') as filehandle:
  7.         pickle.dump(list, filehandle)
  8.  
  9.  
  10. def load(name):
  11.     with open(str(name) + '.pkl', 'rb') as filehandle:
  12.         list = pickle.load(filehandle)
  13.     return list
  14.  
  15. predictor_path = 'datasets/shape_predictor_5_face_landmarks.dat'
  16. face_rec_model_path = 'datasets/dlib_face_recognition_resnet_model_v1.dat'
  17. weights = 'datasets/mmod_human_face_detector.dat'
  18. path = 'photo_pairs/'
  19. files = os.listdir(path)
  20.  
  21. detector = dlib.get_frontal_face_detector()
  22. sp = dlib.shape_predictor(predictor_path)
  23. facerec = dlib.face_recognition_model_v1(face_rec_model_path)
  24.  
  25. pics = {}
  26. fail_pics = []
  27.  
  28. for img in files:
  29.     image = cv2.imread(path + img)
  30.     cnn_face_detector = dlib.cnn_face_detection_model_v1(weights)
  31.     faces_cnn = cnn_face_detector(image, 1)
  32.  
  33.     if len(faces_cnn) > 0:
  34.         for ind, face in enumerate(faces_cnn):
  35.             destRGB = dlib.load_rgb_image(path + img)
  36.             faceBox = dlib.rectangle(left=face.rect.left(), top=face.rect.top(), right=face.rect.right(),
  37.                                      bottom=face.rect.bottom())
  38.             shape = sp(destRGB, faceBox)
  39.             face_descriptor = facerec.compute_face_descriptor(destRGB, shape)
  40.             newname = '123/rez/' + str(ind) + '_' + img.split('.')[0]
  41.             if len(face_descriptor) > 0:
  42.                 print('got vectors', img)
  43.                 save(newname, face_descriptor)
  44.                 if img in pics:
  45.                     pics[img].append(face_descriptor)
  46.                 else:
  47.                     pics[img] = []
  48.                     pics[img].append(face_descriptor)
  49.             else:
  50.                 print('no vectors', img)
  51.                 fail_pics.append(img)
  52.     else:
  53.         print('no face', img)
  54.         fail_pics.append(img)
  55.  
  56. save('photo_pairs', pics)
  57. save('fail_photo_pairs', fail_pics)
Add Comment
Please, Sign In to add comment