File size: 2,511 Bytes
af7c159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e06122b
af7c159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e06122b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import cv2
import numpy as np
import torch
from PIL import Image
from facenet_pytorch import MTCNN, InceptionResnetV1
import gradio as gr
import os

# Load pre-trained model for face detection and face recognition
mtcnn = MTCNN(image_size=160, margin=0, min_face_size=20)
resnet = InceptionResnetV1(pretrained='vggface2').eval()

reference_image_embedding = None

# Function to preprocess image and extract face embeddings
def preprocess_image(image):
    image = Image.fromarray(image)
    image_cropped = mtcnn(image)
    if image_cropped is not None:
        image_embedding = resnet(image_cropped.unsqueeze(0))
        return image_embedding
    return None

def set_reference_image(image):
    global reference_image_embedding
    if image is not None:
        reference_image_embedding = preprocess_image(image)
        if reference_image_embedding is not None:
            return "Reference image set successfully."
        else:
            return "No face detected in the reference image."
    else:
        return "Failed to set reference image."

def capture_and_compare(captured_image):
    if reference_image_embedding is None:
        return "Please set the reference image first."

    captured_image_embedding = preprocess_image(captured_image)
    if captured_image_embedding is None:
        return "No face detected in the captured image."

    similarity = torch.nn.functional.cosine_similarity(captured_image_embedding, reference_image_embedding)
    if similarity.item() > 0.6:  # Adjust the threshold as necessary
        return "Faces match! Access granted."
    else:
        return "Faces do not match. Access denied."

# Gradio interface
with gr.Blocks() as demo:
    gr.Markdown("# Face Recognition Lock")

    with gr.Row():
        with gr.Column():
            reference_image_input = gr.Image(label="Upload Reference Image")
            reference_image_button = gr.Button("Set Reference Image")
            reference_image_status = gr.Textbox(label="Status")

        with gr.Column():
            captured_image_input = gr.Image(label="Capture or Upload Image to Compare")
            compare_faces_button = gr.Button("Compare Faces")
            compare_faces_status = gr.Textbox(label="Result")

    reference_image_button.click(set_reference_image, inputs=[reference_image_input], outputs=[reference_image_status])
    compare_faces_button.click(capture_and_compare, inputs=[captured_image_input], outputs=[compare_faces_status])

# Launch the Gradio interface
demo.launch()