File size: 2,018 Bytes
6c28e78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import numpy as np
import tensorflow as tf
from PIL import Image
import cv2

IMG_SIZE = (105, 105)  # same size you trained on

# Load the trained Siamese model
def load_model(model_path):
    model = tf.keras.models.load_model(model_path, custom_objects={'L1Dist': L1Dist})
    return model

# Custom L1 distance layer (used in Siamese networks)
class L1Dist(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super().__init__()

    def call(self, input_embedding, validation_embedding):
        return tf.math.abs(input_embedding - validation_embedding)

# Preprocess image for model input
def preprocess(image):
    # Convert to numpy array if it's PIL
    if isinstance(image, Image.Image):
        image = np.array(image)

    image = cv2.resize(image, IMG_SIZE)
    image = image / 255.0
    image = np.expand_dims(image, axis=0)  # (1, 105, 105, 3)
    return image

# Verify identity by comparing input image to stored validation images
def verify_identity(model, input_img, users_folder, detection_threshold=0.5):
    input_processed = preprocess(input_img)

    highest_score = 0
    identity = "Unknown"

    for user in os.listdir(users_folder):
        user_path = os.path.join(users_folder, user)
        if not os.path.isdir(user_path):
            continue

        for img_file in os.listdir(user_path):
            img_path = os.path.join(user_path, img_file)

            try:
                val_img = Image.open(img_path).convert('RGB')
            except:
                continue

            val_processed = preprocess(val_img)

            # Predict
            result = model.predict([input_processed, val_processed])[0][0]

            if result > highest_score:
                highest_score = result
                identity = user

    if highest_score < detection_threshold:
        return "User not recognized."
    else:
        return f"Verified: {identity} (Confidence: {highest_score:.2f})"