首页 > 解决方案 > 集体照中的人脸对比

问题描述

我想比较两张照片。第一个有一个人的脸。第二张是多张面孔的合影。我想看看第一张照片中的人是否出现在第二张照片中。

我尝试使用 python 中的 deepface 和 face_recognition 库来做到这一点,方法是从集体照片中一张一张地拉出面孔并将它们与原始照片进行比较。

face_locations = face_recognition.face_locations(img2_loaded)

        for face in face_locations:
            top, right, bottom, left = face
            face_img = img2_loaded[top:bottom, left:right]
           
            face_recognition.compare_faces(img1_loaded, face_img)

这会导致操作数无法与形状 (3088,2316,3) (90,89,3) 一起广播的错误。当我从合影中取出人脸时,我也会遇到同样的错误,使用 PIL 保存它们,然后尝试将它们传递给 deepface。谁能推荐任何替代方法来实现此功能?或者修复我目前的尝试?太感谢了!

标签: pythonface-recognition

解决方案


deepface 旨在比较两个人脸,但您仍然可以比较一对多的人脸识别。

你有两张照片。一个人只有一张人脸照片。我称之为img1.jpg。第二有很多面孔。我称之为img2.jpg。

您可以首先使用 OpenCV 检测 img2.jpg 中的人脸。

import cv2
img2 = cv2.imread("img2.jpg")
face_detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
faces = face_detector.detectMultiScale(img2, 1.3, 5)

detected_faces = []
for face in faces:
    x,y,w,h = face
    detected_face = img2[int(y):int(y+h), int(x):int(x+w)]
    detected_faces.append(detected_face)

然后,您需要将 faces 变量的每一项与 img1.jpg 进行比较。

img1 = cv2.imread("img1.jpg")
targets = face_detector.detectMultiScale(img1, 1.3, 5)
x,y,w,h = targets[0] #this has just a single face
target = img1[int(y):int(y+h), int(x):int(x+w)]

for face in detected_faces:
    #compare face and target in each iteration
    compare(face, target)

我们应该设计比较功能

from deepface import DeepFace

def compare(img1, img2):
    resp = DeepFace.verify(img1, img2)
    print(resp["verified"])

因此,您可以像这样为您的案例调整 deepface。


推荐阅读