diff --git a/DEEPFACE b/DEEPFACE new file mode 100644 index 0000000..4f54d0e --- /dev/null +++ b/DEEPFACE @@ -0,0 +1,74 @@ +# +# https://pypi.org/project/deepface/ +# + +from deepface import DeepFace +import os +import cv2 +import numpy as np + +# Function to compute embeddings for a given image path +def compute_embeddings(image_path, model_name='VGG-Face'): + try: + # This returns a list of embeddings for each face found in the image + embeddings = DeepFace.represent(img_path=image_path, model_name=model_name) + return [res['embedding'] for res in embeddings] + except Exception as e: + print(f"Error processing image {image_path}: {e}") + return [] + +# Function to find the best matches between reference and target images +def find_best_matches(reference_images, target_images, model_name='VGG-Face', metric='cosine'): + # Store embeddings for reference images + reference_embeddings = {} + + for ref_img in reference_images: + ref_embeddings = compute_embeddings(ref_img, model_name=model_name) + if ref_embeddings: + reference_embeddings[ref_img] = ref_embeddings + + # Store best matches + best_matches = [] + + # Loop through each target image + for target_img in target_images: + target_embeddings = compute_embeddings(target_img, model_name=model_name) + + for target_emb in target_embeddings: + for ref_img, ref_emb_list in reference_embeddings.items(): + # Compare each reference embedding with the target embedding + for ref_emb in ref_emb_list: + # Compute the distance between embeddings using DeepFace's distance functions + distance = DeepFace.find_distance(ref_emb, target_emb, distance_metric=metric) + + # Store match details (target image, reference image, and distance) + best_matches.append({ + 'target_image': target_img, + 'reference_image': ref_img, + 'distance': distance + }) + + # Sort matches by the distance (smallest distances indicate best matches) + best_matches = sorted(best_matches, key=lambda x: x['distance']) + + return best_matches + +# Example usage +reference_images = [ + "path_to_reference_image1.jpg", + "path_to_reference_image2.jpg" +] + +target_images = [ + "path_to_target_image1.jpg", + "path_to_target_image2.jpg", + # Add more target images here... +] + +# Find the best matches +matches = find_best_matches(reference_images, target_images, model_name='VGG-Face', metric='cosine') + +# Display the best match +for match in matches[:5]: # Display top 5 matches + print(f"Reference Image: {match['reference_image']}, Target Image: {match['target_image']}, Distance: {match['distance']}") +