hasnanmr commited on
Commit
82191d9
1 Parent(s): fd50f72

change the similarity algorithm

Browse files
Files changed (1) hide show
  1. app.py +8 -8
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import torch
2
  from torch import nn
3
  import torchvision.transforms as transforms
4
- import cv2
5
  import numpy as np
6
  import gradio as gr
7
  from PIL import Image
@@ -36,13 +35,14 @@ model.to(device)
36
  # Initialize MTCNN for face detection
37
  mtcnn = MTCNN(keep_all=True, device=device)
38
 
39
- # Define the transformation
40
- transform = transforms.Compose([
41
  transforms.Resize((224, 224)),
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
 
@@ -76,8 +76,8 @@ def process_images(image1, image2):
76
  if face1 is None or face2 is None:
77
  return None, "Face not detected in one or both images."
78
 
79
- face1 = transform(face1).unsqueeze(0).to(device)
80
- face2 = transform(face2).unsqueeze(0).to(device)
81
 
82
  with torch.no_grad():
83
  embedding1 = model(face1)
@@ -86,7 +86,7 @@ def process_images(image1, image2):
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
 
1
  import torch
2
  from torch import nn
3
  import torchvision.transforms as transforms
 
4
  import numpy as np
5
  import gradio as gr
6
  from PIL import Image
 
35
  # Initialize MTCNN for face detection
36
  mtcnn = MTCNN(keep_all=True, device=device)
37
 
38
+ # Define the transformation with normalization
39
+ val_test_transform_vit = transforms.Compose([
40
  transforms.Resize((224, 224)),
41
+ transforms.ToTensor(),
42
+ transforms.Normalize(mean=processor.image_mean, std=processor.image_std)
43
  ])
44
 
45
+ def compare_faces(embedding1, embedding2, threshold=0.6): # Adjusted threshold
46
  dist = np.linalg.norm(embedding1.cpu().numpy() - embedding2.cpu().numpy())
47
  return dist, dist < threshold
48
 
 
76
  if face1 is None or face2 is None:
77
  return None, "Face not detected in one or both images."
78
 
79
+ face1 = val_test_transform_vit(face1).unsqueeze(0).to(device)
80
+ face2 = val_test_transform_vit(face2).unsqueeze(0).to(device)
81
 
82
  with torch.no_grad():
83
  embedding1 = model(face1)
 
86
  embedding1 = l2_normalize(embedding1)
87
  embedding2 = l2_normalize(embedding2)
88
 
89
+ distance, is_match = compare_faces(embedding1, embedding2, threshold=0.88)
90
 
91
  end_time = time.time()
92
  inference_time = end_time - start_time