使用 Python、OpenCV 和人脸识别模块比较两张图像并获得这些图像之间的准确度水平。
使用Face Recognition python 模块来获取两张图像的128 个面部编码,并比较这些编码。比较结果返回 True 或 False。如果结果为True ,那么两个图像将是相同的。如果是False,则两个图像将不相同。
仅当比较结果返回 True 值时,才会打印准确度级别。
首先在conda中或终端安装需要的模块
- pip install opencv-python
- pip install face-recognition
安装后导入模块
创建一个名为 find_face_encodings(image_path) 的新函数,它获取图像位置(路径)并返回 128 个面部编码,这在比较图像时非常有用。
find_face_encodings(image_path) 函数将使用 OpenCV 模块,从我们作为参数传递的路径中读取图像,然后返回使用 face_recognition 模块中的 face_encodings() 函数获得的 128 个人脸编码。使用两个不同的图像路径调用 find_face_encodings(image_path) 函数,并将其存储在两个不同的变量中,image_1和image_2
- import cv2
- import face_recognition
- def find_face_encodings(image_path):
- # reading image
- image = cv2.imread(image_path)
-
- # get face encodings from the image
- face_enc = face_recognition.face_encodings(image)
-
- # return face encodings
- return face_enc[0]
- # getting face encodings for first image
- image_1 = find_face_encodings("image_1.jpg")
-
- # getting face encodings for second image
- image_2 = find_face_encodings("image_2.jpg")
现在,我们可以使用编码执行比较和查找这些图像的准确性等操作。
比较将通过使用 face_recognition 中的 compare_faces() 函数来完成。
通过找到 100 和 face_distance 之间的差异来确定准确性。
- # checking both images are same
- is_same = face_recognition.compare_faces([image_1], image_2)[0]
- print(f"Is Same: {is_same}")
- if is_same:
- # finding the distance level between images
- distance = face_recognition.face_distance([image_1], image_2)
- distance = round(distance[0] * 100)
-
- # calcuating accuracy level between images
- accuracy = 100 - round(distance)
-
- print("The images are same")
- print(f"Accuracy Level: {accuracy}%")
- else:
- print("The images are not same")
参考链接:https://blog.csdn.net/woshicver/article/details/12860789