Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,15 +1,43 @@
|
|
1 |
-
import
|
2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
def calculate_similarity(image1, image2):
|
5 |
-
#
|
6 |
try:
|
7 |
-
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
except Exception as e:
|
11 |
return str(e)
|
12 |
|
|
|
13 |
# Create a Gradio interface
|
14 |
iface = gr.Interface(
|
15 |
fn=calculate_similarity,
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
def crop_face(image_path):
|
5 |
+
# Load the Haarcascade classifier for face detection
|
6 |
+
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
7 |
+
|
8 |
+
# Read the image
|
9 |
+
img = cv2.imread(image_path)
|
10 |
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
11 |
+
|
12 |
+
# Detect faces in the image
|
13 |
+
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
|
14 |
+
|
15 |
+
# If a face is detected, crop it
|
16 |
+
if len(faces) > 0:
|
17 |
+
(x, y, w, h) = faces[0] # Take the first detected face
|
18 |
+
cropped_face = img[y:y+h, x:x+w]
|
19 |
+
return cropped_face
|
20 |
+
else:
|
21 |
+
raise ValueError("No face detected in the image.")
|
22 |
|
23 |
def calculate_similarity(image1, image2):
|
24 |
+
# Crop faces from both images
|
25 |
try:
|
26 |
+
face1 = crop_face(image1)
|
27 |
+
face2 = crop_face(image2)
|
28 |
+
|
29 |
+
# Convert cropped images to RGB format for DeepFace
|
30 |
+
face1 = cv2.cvtColor(face1, cv2.COLOR_BGR2RGB)
|
31 |
+
face2 = cv2.cvtColor(face2, cv2.COLOR_BGR2RGB)
|
32 |
+
|
33 |
+
# Analyze the two cropped images for facial similarity
|
34 |
+
result = DeepFace.verify(face1, face2, model_name='VGG-Face', enforce_detection=False)
|
35 |
+
similarity_percentage = (1 - result['distance']) * 100 # Convert distance to similarity percentage
|
36 |
+
return similarity_percentage
|
37 |
except Exception as e:
|
38 |
return str(e)
|
39 |
|
40 |
+
|
41 |
# Create a Gradio interface
|
42 |
iface = gr.Interface(
|
43 |
fn=calculate_similarity,
|