hasnanmr commited on
Commit
fd50f72
1 Parent(s): ea79e5c

change the similarity algorithm

Browse files
Files changed (1) hide show
  1. app.py +13 -9
app.py CHANGED
@@ -42,9 +42,9 @@ transform = transforms.Compose([
42
  transforms.ToTensor()
43
  ])
44
 
45
- def cosine_similarity(embedding1, embedding2):
46
- similarity = torch.nn.functional.cosine_similarity(embedding1.unsqueeze(0), embedding2.unsqueeze(0))
47
- return similarity.item()
48
 
49
  def align_face(frame):
50
  # Convert the frame to a PIL image if it's a numpy array
@@ -60,6 +60,10 @@ def align_face(frame):
60
  return face
61
  return None
62
 
 
 
 
 
63
  def process_images(image1, image2):
64
  start_time = time.time()
65
 
@@ -79,17 +83,17 @@ def process_images(image1, image2):
79
  embedding1 = model(face1)
80
  embedding2 = model(face2)
81
 
82
- similarity = cosine_similarity(embedding1, embedding2)
83
- print(embedding1)
84
- print(embedding2)
85
- print(similarity)
86
 
87
  end_time = time.time()
88
  inference_time = end_time - start_time
89
 
90
- result = f"Similarity: {similarity:.2f}\nInference time: {inference_time:.2f} seconds"
91
 
92
- return (frame1, frame2), result
93
 
94
  # Create the Gradio interface
95
  iface = gr.Interface(
 
42
  transforms.ToTensor()
43
  ])
44
 
45
+ def compare_faces(embedding1, embedding2, threshold=1.0):
46
+ dist = np.linalg.norm(embedding1.cpu().numpy() - embedding2.cpu().numpy())
47
+ return dist, dist < threshold
48
 
49
  def align_face(frame):
50
  # Convert the frame to a PIL image if it's a numpy array
 
60
  return face
61
  return None
62
 
63
+ def l2_normalize(tensor):
64
+ norm = torch.norm(tensor, p=2, dim=1, keepdim=True)
65
+ return tensor / norm
66
+
67
  def process_images(image1, image2):
68
  start_time = time.time()
69
 
 
83
  embedding1 = model(face1)
84
  embedding2 = model(face2)
85
 
86
+ embedding1 = l2_normalize(embedding1)
87
+ embedding2 = l2_normalize(embedding2)
88
+
89
+ distance, is_match = compare_faces(embedding1, embedding2)
90
 
91
  end_time = time.time()
92
  inference_time = end_time - start_time
93
 
94
+ result = f"Distance: {distance:.2f}\nMatch: {is_match}\nInference time: {inference_time:.2f} seconds"
95
 
96
+ return (image1, image2), result
97
 
98
  # Create the Gradio interface
99
  iface = gr.Interface(