sajjjadayobi / FaceLib

Face Analysis: Detection, Age Gender Estimation & Recognition
MIT License
294 stars 52 forks source link

How to Compare two faces? #11

Closed Adeel-Intizar closed 3 years ago

Adeel-Intizar commented 3 years ago

Hello, Thank you for your great work Is there any way to compare two detected faces and return a percentage of similarity? In other words, is there any way to get face encodings ?

sajjjadayobi commented 3 years ago

yes there is, you can look at the following function and find out your two image distance with print

diff = embs.unsqueeze(-1) - target_embs.transpose(1, 0).unsqueeze(0)
dist = torch.sum(torch.pow(diff, 2), dim=1)
print(dist) # it returns the distance between new face with all faces in your bank

it's in facelib/InsightFace/models/Learner.py or you can write your own function in Learner Class like the following

def compare2faces(self, conf, faces, tta=False)
        """faces : list of PIL Image (your faces for comparing) """
        faces = faces_preprocessing(faces, conf.device)
        if tta:
            faces_emb = self.model(faces)
            hflip_emb = self.model(faces.flip(-1))  # image horizontal flip
            embs = l2_norm((faces_emb + hflip_emb)/2)  # take mean
        else:
            embs = self.model(faces)

        diff = embs[0] - embs[1]
        dist = torch.sum(torch.pow(diff, 2), dim=1)
        return dist

and run it like this:

from facelib import FaceRecognizer, get_config
recognizer = FaceRecognizer(get_config())
recognizer.model.eval()
img1 = PIL.Image.open('')
img2 = PIL.Image.open('')
recognizer.compare2faces(self.conf, faces=[img1, img2], tta=self.tta)
sajjjadayobi commented 3 years ago

and you can also see the embeddings at (embs in the infer function) if you add any new features to this project let me know

Adeel-Intizar commented 3 years ago

sure I will let you know, Thank you

bistcuite commented 2 years ago

I tried to run this code but i got this error : Capture