如何使用 Python比较两张图像并获得准确度?

e6b166d1b34d758719be1e9858334c0b.jpeg

本文,将带你了解如何使用 Python、OpenCV 和人脸识别模块比较两张图像并获得这些图像之间的准确度水平。

首先,你需要了解我们是如何比较两个图像的。我们正在使用Face Recognition python 模块来获取两张图像的128 个面部编码,我们将比较这些编码。比较结果返回 True 或 False。如果结果为True ,那么两个图像将是相同的。如果是False,则两个图像将不相同。

128 种面部编码将如下所示👇🏻

ca929008ea030c963464f51e85ec9f10.jpeg

128 个人脸编码(人脸标志)

仅当比较结果返回 True 值时,才会打印准确度级别。

现在,让我们进入本主题的编码部分,

为了实现这一点,我们需要安装几个 python 模块。为此,只需打开命令提示符或终端,键入以下内容。

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 个人脸编码。

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]

现在,使用两个不同的图像路径调用 find_face_encodings(image_path) 函数,并将其存储在两个不同的变量中,image_1image_2

# 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")

输出——案例 1

fc707b74a231fcd264b7e044aa3ac3f8.jpegb54fea2b9c0b8f38394ac505fc360cc8.jpeg
Is Same: True
The images are same
Accuracy Level: 64%

输出——案例 2

109e69ce6220a60e1281ab2ac910c9a6.jpeg654a1af1ffa220f5715a313f5341e397.jpeg

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
乘风的头像乘风管理团队
上一篇 2023年2月26日
下一篇 2023年2月26日

相关推荐