Celebrity Look Alike Finder With Python DeepFace Module
Published: 2023-03-10 13:15:21

The _Python Deepface_ module has recently become popular for its ease in creating machine learning projects. So I thought of giving it a try. Forgive me if I mistake somewhere, I am still learning

So I went to [kaggle.com](https://kaggle.com) and got a [Celebrity Face Image Dataset](https://www.kaggle.com/datasets/vishesh1412/celebrity-face-image-dataset) which contains 100 images of different styles of each of the following actors and actresses:

-   Angelina Jolie
-   Brad Pitt
-   Denzel Washington
-   Hugh Jackman
-   Jennifer Lawrence
-   Johnny Depp
-   Kate Winslet
-   Leonardo DiCaprio
-   Megan Fox
-   Natalie Portman
-   Nicole Kidman
-   Robert Downey Jr.
-   Sandra Bullock
-   Scarlett Johansson
-   Tom Cruise
-   Tom Hanks
-   Will Smith

## The Code

We use Jupyter notebook for this project.
The first snippet goes as

```python
import os
import shutil

data_dir = 'Celebrity Faces Dataset'

for directory in os.listdir(data_dir):
    first_file = os.listdir(os.path.join(data_dir, directory))[1]
    shutil.copyfile(os.path.join(data_dir, directory, first_file), os.path.join("Samples", f"{directory}.jpg"))
```
What it does is it extracts the first image from the folders of every celebrity and copies it and pastes it in a separate folder called `Samples` by the name of the actor/actress. This will later be used the the ML model to detect matches.

The second and the final snippet is:

```python
from deepface import DeepFace

smallest_distance = None

for file in os.listdir("Samples"):
    if file.endswith('.jpg'):
        result = DeepFace.verify('me1.jpg', f'Samples/{file}')
        if result['verified']:
            print("This person looks exactly like", file.split('.')[0])
            break
        if smallest_distance is None:
            smallest_distance = (file.split('.')[0], result['distance'])
        else:
            smallest_distance = (file.split('.')[0], result['distance']) if result['distance'] < smallest_distance[1] else smallest_distance
else:
    print(f"No exact match found. Closest match is {smallest_distance[0]}")
```
Here we import the **Deepface** module. The Deepface module has a function called `DeepFace.verify()` which verifies an image pair is same person or different persons. In the background, verification function represents facial images as vectors and then calculates the similarity between those vectors. Vectors of same person images should have more similarity (or less distance) than vectors of different persons.

The output is stored in a variable called `result`.
If the supplied image exactly matches with one of the images of the Dataset, i.e, the `result['verified']` parameter gets equivalent to **True** the program responds with a message showing the celebrity the supplied subject resembles.

The `smallest_distance` variable is assigned **None** initially. It later is assigned the value of the `result['distance']` which is a numeric value showing the closest match of the subject to the data and described by the module author as _distance_metric (string): cosine, euclidean, euclidean_l2_. The program verifies if the `smallest_distance` variable is **None** in every iteration through the samples. For not being None, if the `smallest_distance` value is lesser than the value of `result['distance']` from the latest iteration, the new result['distance'] is assigned to the `smallest_distance` variable. To note that the `smallest_distance` variable contains the name of the celebrity too since it is stored as a string separated with a `.` where the 0th index holds the celebrity name in the current iteration while the 1st index holds the value of `result['distance']` of that iteration. At the end when the loop ends and no exact match is found, the last most closest match iterated is retrieved and printed in the console to the user.

## Some notes from my experience
I personally saw that the model is not totally accurate, in fact it matched one of my pics to Angelina Jolie once (I am male). This greatly depends on the image passed. If no face is in the given image, the program will raise error.

You can view the code here: (https://github.com/Sannidhya127/Celebrity-Look-Alike-Finder)

I would really appreciate a star on the GitHub repo. Thank you and have a great day!