Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import cv2
|
| 4 |
+
from insightface.app import FaceAnalysis
|
| 5 |
+
|
| 6 |
+
# Initialize InsightFace
|
| 7 |
+
app = FaceAnalysis(name='buffalo_s')
|
| 8 |
+
app.prepare(ctx_id=0, det_size=(640, 640)) # Use GPU if available and onnxruntime-gpu is installed, otherwise CPU
|
| 9 |
+
|
| 10 |
+
def compute_similarity(img1, img2):
|
| 11 |
+
# Convert RGB to BGR (InsightFace expects BGR format)
|
| 12 |
+
img1_bgr = cv2.cvtColor(img1, cv2.COLOR_RGB2BGR)
|
| 13 |
+
img2_bgr = cv2.cvtColor(img2, cv2.COLOR_RGB2BGR)
|
| 14 |
+
|
| 15 |
+
# Get faces and embeddings
|
| 16 |
+
faces1 = app.get(img1_bgr)
|
| 17 |
+
faces2 = app.get(img2_bgr)
|
| 18 |
+
|
| 19 |
+
# Check for no faces detected
|
| 20 |
+
if len(faces1) == 0 or len(faces2) == 0:
|
| 21 |
+
return "No faces detected in one or both images."
|
| 22 |
+
|
| 23 |
+
# Check for multiple faces
|
| 24 |
+
if len(faces1) > 1 or len(faces2) > 1:
|
| 25 |
+
return "Multiple faces detected in one or both images. Please upload images with single faces."
|
| 26 |
+
|
| 27 |
+
# Extract embeddings
|
| 28 |
+
embedding1 = faces1[0].embedding
|
| 29 |
+
embedding2 = faces2[0].embedding
|
| 30 |
+
|
| 31 |
+
# Compute cosine similarity
|
| 32 |
+
similarity = np.dot(embedding1, embedding2) / (np.linalg.norm(embedding1) * np.linalg.norm(embedding2))
|
| 33 |
+
|
| 34 |
+
# Interpret result
|
| 35 |
+
threshold = 0.5
|
| 36 |
+
if similarity > threshold:
|
| 37 |
+
result = "Same person"
|
| 38 |
+
else:
|
| 39 |
+
result = "Person mismatch"
|
| 40 |
+
|
| 41 |
+
return f"Similarity Score: {similarity:.4f}\nResult: {result}"
|
| 42 |
+
|
| 43 |
+
# Create Gradio interface
|
| 44 |
+
iface = gr.Interface(
|
| 45 |
+
fn=compute_similarity,
|
| 46 |
+
inputs=[gr.Image(type="numpy", label="Image 1"), gr.Image(type="numpy", label="Image 2")],
|
| 47 |
+
outputs="text",
|
| 48 |
+
title="Face Similarity Checker",
|
| 49 |
+
description="Upload two images to check if they are of the same person."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# Launch the interface
|
| 53 |
+
iface.launch()
|