Shekarss's picture
Upload 4 files
6c28e78 verified
raw
history blame
2.02 kB
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})"