pip install opencv-python然后,将使用到的模块cv2/face-recognition两个模块导入到代码块中即可。
# OpenCV is a library of programming functions mainly aimed at real-time computer vision.
import cv2
# It's loading a pre-trained model that can detect faces in images.
import face_recognition新建一个python函数get_face_encodings,用来获取人脸部分的编码,后面可以根据这个编码来进行人脸比对。
def get_face_encodings(image_path):
"""
It takes an image path, oads the image, finds the faces in the image, and returns the 128-d face encodings for each
face
:param image_path: The path to the image to be processed
"""
# It's loading a pre-trained model that can detect faces in images.
image = cv2.imread(image_path)
# It's converting the image from BGR to RGB.
image_RGB = image[:, :, ::-1]
# It's taking the image and the face locations and returning the face encodings.
face_env = face_recognition.face_encodings(image_RGB, image_face)
# It's returning the first face encoding in the list.
return face_env[0]上述函数中注释都是通过Pycharm插件自动生成的,接下来我们直接调用get_face_encodings函数分别获取两个人脸的编码。
# It's taking the image and the face locations and returning the face encodings.
ima1 = get_face_encodings('03.jpg')
# It's taking the image and the face locations and returning the face encodings.
ima2 = get_face_encodings('05.jpg')
# It's taking the image and the face locations and returning the face encodings.
ima1 = get_face_encodings('03.jpg')
# It's taking the image and the face locations and returning the face encodings.
ima2 = get_face_encodings('05.jpg')上面我们选择了两张附有人脸的图片,并且已经获取到了对应的人脸编码。接着使用compare_faces函数进行人脸比对。
# It's comparing the two face encodings and returning True if they match.
is_same = face_recognition.compare_faces([ima1], ima2, tolerance=0.3)[0]