人脸识别库face_recognition

/

图片来自https://www.deviantart.com/telpo/art/Face-OFF-125686802

软硬件环境

  • ubuntu 18.04 64bit
  • GTX 1070Ti
  • anaconda with python 3.6
  • face_recognition 1.2.3
  • dlib
  • opencv

face_recognition简介

face_recognition号称是世界上最简单的基于python的人脸识别库,是在大名鼎鼎的深度学习框架dlib上做的整合,dlib模型在LFW(Labeled Faces in the Wild)能有99.38的准确率。另外face_recognition提供了相应的命令行工具,可以通过命令行来对图片文件夹进行人脸识别,非常的酷。

安装face_recognition

可以利用pip来安装

  1. pip install face_recognition

或者从源码开始安装

  1. git clone https://github.com/ageitgey/face_recognition.git
  2. cd face_recognition
  3. python setup.py install

face_recognition工作流

找出人脸

第一步就是要找出给定图片中包含的全部的脸的位置

  1. import face_recognition
  2. image = face_recognition.load_image_file("your_file.jpg")
  3. face_locations = face_recognition.face_locations(image)
操作特征点

找出每个人的眼睛、鼻子、嘴巴和下巴

  1. import face_recognition
  2. image = face_recognition.load_image_file("your_file.jpg")
  3. face_landmarks_list = face_recognition.face_landmarks(image)

进行识别

最后一步,也是最关键的一步,识别出这张脸是属于谁的。face_recognition使用了欧几里得距离(可以参考我的另一篇文章https://www.xugaoxiang.com/147)来确定是不是同一张脸。

  1. import face_recognition
  2. known_image = face_recognition.load_image_file("biden.jpg")
  3. unknown_image = face_recognition.load_image_file("unknown.jpg")
  4. biden_encoding = face_recognition.face_encodings(known_image)[0]
  5. unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
  6. results = face_recognition.compare_faces([biden_encoding], unknown_encoding)

命令行工具

face_recognition提供了2个命令行工具

  • face_detection - 找出给定图片或图片文件夹中的人脸
  • face_recognition - 进行人脸识别

具体如何使用,可以通过--help来查看参数。face_detection比较简单,这里就不讲了。

命令行工具face_recognition使用

要进行人脸识别,首先必须准备已知人员的信息,这里用一个独立的文件夹来存放,比如known,然后每一个人的图片都以他的名字来命令,如Joe Biden.jpgKobe.jpg

然后将需要识别的图片放置在另一个文件夹中,如unknown,执行以下命令进行识别

  1. face_recognition known unknown

默认情况下,不设置阈值的话,正确识别率是非常非常低的。在实际情况下,需要根据自己的情况,来适当调整阈值。在同样的测试环境下,将相似度阈设成了0.38,识别结果就正确了。

  1. face_recognition known unknown --tolerance 0.38

打印中的unknown_person表明是陌生人

另一个有用的参数是--cpus,如果你使用的是多核CPU,可以利用这个参数来提升识别速度。--cpus=-1表示使用所有的CPU核。

KNN分类器

KNN(K-Nearest Neighbor)通过测量不同特征值之间的距离进行分类。它的思路是:如果一个样本在特征空间中的k个最相似(即特征空间中最邻近)的样本中的大多数属于某一个类别,则该样本也属于这个类别,其中K通常是不大于20的整数。KNN算法中,所选择的邻居都是已经正确分类的对象。该方法在定类决策上只依据最邻近的一个或者几个样本的类别来决定待分样本所属的类别。

在实际的项目中,一般都会用一个分类器(classifier)来存储已知人脸的数据,方便管理。face_recognition使用了基于KNN算法的分类器。

制作分类器

代码来自examples/face_recognition_knn.py,注释很详细了,就不一一解释了。经测试,同一人的图片越多,识别的准确率就越高。

  1. def train(train_dir, model_save_path=None, n_neighbors=None, knn_algo='ball_tree', verbose=False):
  2. """
  3. Trains a k-nearest neighbors classifier for face recognition.
  4. :param train_dir: directory that contains a sub-directory for each known person, with its name.
  5. (View in source code to see train_dir example tree structure)
  6. Structure:
  7. <train_dir>/
  8. ├── <person1>/
  9. │ ├── <somename1>.jpeg
  10. │ ├── <somename2>.jpeg
  11. │ ├── ...
  12. ├── <person2>/
  13. │ ├── <somename1>.jpeg
  14. │ └── <somename2>.jpeg
  15. └── ...
  16. :param model_save_path: (optional) path to save model on disk
  17. :param n_neighbors: (optional) number of neighbors to weigh in classification. Chosen automatically if not specified
  18. :param knn_algo: (optional) underlying data structure to support knn.default is ball_tree
  19. :param verbose: verbosity of training
  20. :return: returns knn classifier that was trained on the given data.
  21. """
  22. X = []
  23. y = []
  24. # Loop through each person in the training set
  25. for class_dir in os.listdir(train_dir):
  26. if not os.path.isdir(os.path.join(train_dir, class_dir)):
  27. continue
  28. # Loop through each training image for the current person
  29. for img_path in image_files_in_folder(os.path.join(train_dir, class_dir)):
  30. image = face_recognition.load_image_file(img_path)
  31. face_bounding_boxes = face_recognition.face_locations(image)
  32. if len(face_bounding_boxes) != 1:
  33. # If there are no people (or too many people) in a training image, skip the image.
  34. if verbose:
  35. print("Image {} not suitable for training: {}".format(img_path, "Didn't find a face" if len(face_bounding_boxes) < 1 else "Found more than one face"))
  36. else:
  37. # Add face encoding for current image to the training set
  38. X.append(face_recognition.face_encodings(image, known_face_locations=face_bounding_boxes)[0])
  39. y.append(class_dir)
  40. # Determine how many neighbors to use for weighting in the KNN classifier
  41. if n_neighbors is None:
  42. n_neighbors = int(round(math.sqrt(len(X))))
  43. if verbose:
  44. print("Chose n_neighbors automatically:", n_neighbors)
  45. # Create and train the KNN classifier
  46. knn_clf = neighbors.KNeighborsClassifier(n_neighbors=n_neighbors, algorithm=knn_algo, weights='distance')
  47. knn_clf.fit(X, y)
  48. # Save the trained KNN classifier
  49. if model_save_path is not None:
  50. with open(model_save_path, 'wb') as f:
  51. pickle.dump(knn_clf, f)
  52. return knn_clf
使用分类器
  1. def predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6):
  2. """
  3. Recognizes faces in given image using a trained KNN classifier
  4. :param X_img_path: path to image to be recognized
  5. :param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.
  6. :param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.
  7. :param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance
  8. of mis-classifying an unknown person as a known one.
  9. :return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].
  10. For faces of unrecognized persons, the name 'unknown' will be returned.
  11. """
  12. if not os.path.isfile(X_img_path) or os.path.splitext(X_img_path)[1][1:] not in ALLOWED_EXTENSIONS:
  13. raise Exception("Invalid image path: {}".format(X_img_path))
  14. if knn_clf is None and model_path is None:
  15. raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")
  16. # Load a trained KNN model (if one was passed in)
  17. if knn_clf is None:
  18. with open(model_path, 'rb') as f:
  19. knn_clf = pickle.load(f)
  20. # Load image file and find face locations
  21. X_img = face_recognition.load_image_file(X_img_path)
  22. X_face_locations = face_recognition.face_locations(X_img)
  23. # If no faces are found in the image, return an empty result.
  24. if len(X_face_locations) == 0:
  25. return []
  26. # Find encodings for faces in the test iamge
  27. faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_face_locations)
  28. # Use the KNN model to find the best matches for the test face
  29. closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)
  30. are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]
  31. # Predict classes and remove classifications that aren't within the threshold
  32. return [(pred, loc) if rec else ("unknown", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]

CUDA加速

如果还想提升性能,那就必须上显卡了,由于face_recognition依赖与dlib,因此需要先安装支持CUDAdlib,可以参考另一篇文章https://www.xugaoxiang.com/138

  1. import face_recognition
  2. image = face_recognition.load_image_file("my_picture.jpg")
  3. face_locations = face_recognition.face_locations(image, model="cnn")
  4. # face_locations is now an array listing the co-ordinates of each face!

与摄像头联动

这里使用opencv来实现,opencv读取摄像头每一帧的数据,然后进行resize、颜色空间的转换(由opecv使用的BGR转换成face_recognition使用的RGB),最后进行人脸的检测及识别。

  1. import face_recognition
  2. import cv2
  3. video_capture = cv2.VideoCapture(0)
  4. # Load a sample picture and learn how to recognize it.
  5. obama_image = face_recognition.load_image_file("obama.jpg")
  6. obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
  7. # Load a second sample picture and learn how to recognize it.
  8. biden_image = face_recognition.load_image_file("biden.jpg")
  9. biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
  10. # Create arrays of known face encodings and their names
  11. known_face_encodings = [
  12. obama_face_encoding,
  13. biden_face_encoding
  14. ]
  15. known_face_names = [
  16. "Barack Obama",
  17. "Joe Biden"
  18. ]
  19. # Initialize some variables
  20. face_locations = []
  21. face_encodings = []
  22. face_names = []
  23. process_this_frame = True
  24. while True:
  25. # Grab a single frame of video
  26. ret, frame = video_capture.read()
  27. # Resize frame of video to 1/4 size for faster face recognition processing
  28. small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
  29. # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
  30. rgb_small_frame = small_frame[:, :, ::-1]
  31. # Only process every other frame of video to save time
  32. if process_this_frame:
  33. # Find all the faces and face encodings in the current frame of video
  34. face_locations = face_recognition.face_locations(rgb_small_frame)
  35. face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
  36. face_names = []
  37. for face_encoding in face_encodings:
  38. # See if the face is a match for the known face(s)
  39. matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
  40. name = "Unknown"
  41. # If a match was found in known_face_encodings, just use the first one.
  42. if True in matches:
  43. first_match_index = matches.index(True)
  44. name = known_face_names[first_match_index]
  45. face_names.append(name)
  46. process_this_frame = not process_this_frame
  47. # Display the results
  48. for (top, right, bottom, left), name in zip(face_locations, face_names):
  49. # Scale back up face locations since the frame we detected in was scaled to 1/4 size
  50. top *= 4
  51. right *= 4
  52. bottom *= 4
  53. left *= 4
  54. # Draw a box around the face
  55. cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
  56. # Draw a label with a name below the face
  57. cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
  58. font = cv2.FONT_HERSHEY_DUPLEX
  59. cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
  60. # Display the resulting image
  61. cv2.imshow('Video', frame)
  62. # Hit 'q' on the keyboard to quit!
  63. if cv2.waitKey(1) & 0xFF == ord('q'):
  64. break
  65. # Release handle to the webcam
  66. video_capture.release()
  67. cv2.destroyAllWindows()

另外本地视频文件、网络摄像头(基于rtsp视频流)的识别场景跟本地摄像头的处理非常相似,这里以就不再继续贴代码了。

参考资料

转载请注明作者和出处,并添加本页链接。
原文链接: blog.xugaoxiang.com/150