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

2023-01-28 14:34 445 阅读 ID:736
磐创AI
磐创AI

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

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

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_1和image_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

Is Same: True
The images are same
Accuracy Level: 64%

输出——案例 2

Is Same: False
The images are not same
免责声明:作者保留权利,不代表本站立场。如想了解更多和作者有关的信息可以查看页面右侧作者信息卡片。
反馈
to-top--btn