import os import cv2 from insightface.app import FaceAnalysis import torch # prompt: compare face embediggs class FaceRec: def __init__(self): self.foldername = '/home/emmanuel/Pictures/Webcam' self.files = [] self.embeds = [] self.diff = [] self.ground_mathches = [] self.sampling = None def folder(self, attempt=True, folder='/home/emmanuel/Pictures/Webcam'): if attempt: for file in os.listdir(folder): self.files.append(file) self.image_pair = list(zip(self.files[0:len(self.files)//2], self.files[len(self.files)//2:])) print(self.image_pair) else: self.foldername = '/home/emmanuel/Pictures/webcam' self.files = [] self.folder(attempt=True, folder=self.foldername) def embeddings(self, image): app = FaceAnalysis(name="buffalo_l", providers=['CUDAExecutionProvider', 'CPUExecutionProvider']) app.prepare(ctx_id=0, det_size=(640, 640)) image1 = cv2.imread(image) faces = app.get(image1) faceid_embeds = torch.from_numpy(faces[0].normed_embedding).unsqueeze(0) return(torch.Tensor(faceid_embeds)) def face_embed(self, face, face1): # Load the two images and get their face embeddings. face_encodings = self.embeddings(face) face_encodings1 = self.embeddings(face1) return(torch.nn.functional.cosine_similarity(face_encodings, face_encodings1)) def closeness(self): self.embeds = [] for faces in self.image_pair: self.embeds.append(self.face_embed(self.foldername+'/'+faces[0], self.foldername+'/'+faces[1])) return(0) def compare(self, attempt=True): self.diff = [] for diffs in list(zip(self.embeds[0:len(self.embeds)//2], self.embeds[len(self.embeds)//2:])): self.diff.append(torch.nn.functional.pairwise_distance(diffs[0], diffs[1])) def expectation(self): mean, std = torch.mean(torch.Tensor(self.diff[0:])), torch.std(torch.Tensor(self.diff[0:])) distribute = torch.distributions.Normal(mean, std) self.sampling = distribute.sample(sample_shape=(10,)) def model(self): self.closeness() return(self.compare()) def verify(self): self.folder() self.model() self.expectation() self.folder(attempt=False) self.model() fails = 0 success = 0 max_itter = 10 while max_itter >= 0: for samples in self.sampling: if self.diff[0] <= samples: success = success+1 else: fails = fails+1 max_itter = max_itter-1 if fails > success: return(False) else: return(True) Recognition = FaceRec() print(Recognition.verify())