# Switching Eds: Face swapping with Python, dlib, and OpenCV

## Introduction

In this post I’ll describe how I wrote a short (200 line) Python script to automatically replace facial features on an image of a face, with the facial features from a second image of a face.

The process breaks down into four steps:

• Detecting facial landmarks.
• Rotating, scaling, and translating the second image to fit over the first.
• Adjusting the colour balance in the second image to match that of the first.
• Blending features from the second image on top of the first.

The full source-code for the script can be found here.

## 1. Using dlib to extract facial landmarks

The script uses dlib’s Python bindings to extract facial landmarks:

Dlib implements the algorithm described in the paper One Millisecond Face Alignment with an Ensemble of Regression Trees, by Vahid Kazemi and Josephine Sullivan. The algorithm itself is very complex, but dlib’s interface for using it is incredibly simple:

The function get_landmarks() takes an image in the form of a numpy array, and returns a 68x2 element matrix, each row of which corresponding with the x, y coordinates of a particular feature point in the input image.

The feature extractor (predictor) requires a rough bounding box as input to the algorithm. This is provided by a traditional face detector (detector) which returns a list of rectangles, each of which corresponding with a face in the image.

To make the predictor a pre-trained model is required. Such a model can be downloaded from the dlib sourceforge repository.

##2. Aligning faces with a procrustes analysis

So at this point we have our two landmark matrices, each row having coordinates to a particular facial feature (eg. the 30th row gives the coordinates of the tip of the nose). We’re now going to work out how to rotate, translate, and scale the points of the first vector such that they fit as closely as possible to the points in the second vector, the idea being that the same transformation can be used to overlay the second image over the first.

To put it more mathematically, we seek $$T$$, $$s$$, and $$R$$ such that:

$\sum_{i=1}^{68}||s R p_i^T + T - q_i^T||^{2}$

is minimized, where $$R$$ is an orthogonal 2x2 matrix, $$s$$ is a scalar, $$T$$ is a 2-vector, and $$p_i$$ and $$q_i$$ are the rows of the landmark matrices calculated above.

It turns out that this sort of problem can be solved with an Ordinary Procrustes Analysis:

Stepping through the code:

1. Convert the input matrices into floats. This is required for the operations that are to follow.
2. Subtract the centroid form each of the point sets. Once an optimal scaling and rotation has been found for the resulting point sets, the centroids c1 and c2 can be used to find the full solution.
3. Similarly, divide each point set by its standard deviation. This removes the scaling component of the problem.
4. Calculate the rotation portion using the Singular Value Decomposition. See the wikipedia article on the Orthogonal Procrustes Problem for details of how this works.
5. Return the complete transformaton as an affine transformation matrix.

The result can then be plugged into OpenCV’s cv2.warpAffine function to map the second image onto the first:

Which produces the following alignment:

## 3. Colour correcting the second image

If we tried to overlay facial features at this point, we’d soon see we have a problem:

The issue is that differences in skin-tone and lighting between the two images is causing a discontinuity around the edges of the overlaid region. Let’s try to correct that:

And the result:

This function attempts to change the colouring of im2 to match that of im1. It does this by dividing im2 by a gaussian blur of im2, and then multiplying by a gaussian blur of im1. The idea here is that of a RGB scaling colour-correction, but instead of a constant scale factor across all of the image, each pixel has its own localised scale factor.

With this approach differences in lighting between the two images can be accounted for, to some degree. For example, if image 1 is lit from one side but image 2 has uniform lighting then the colour corrected image 2 will appear darker on the unlit side aswell.

That said, this is a fairly crude solution to the problem and an appropriate size gaussian kernel is key. Too small and facial features from the first image will show up in the second. Too large and kernel strays outside of the face area for pixels being overlaid, and discolouration occurs. Here a kernel of 0.6 * the pupillary distance is used.

## 4. Blending features from the second image onto the first

A mask is used to select which parts of image 2 and which parts of image 1 should be shown in the final image: Regions with value 1 (shown white here) correspond with areas where image 2 should show, and regions with colour 0 (shown black here) correspond with areas where image 1 should show. Value in between 0 and 1 correspond with a mixture of image 1 and image2.

Here’s the code to generate the above:

Let’s break this down:

• A routine get_face_mask() is defined to generate a mask for an image and a landmark matrix. It draws two convex polygons in white: One surrounding the eye area, and one surrounding the nose and mouth area. It then feathers the edge of the mask outwards by 11 pixels. The feathering helps hide any remaning discontinuities.
• Such a face mask is generated for both images. The mask for the second is transformed into image 1’s coordinate space, using the same transformation as in step 2.
• The masks are then combined into one by taking an element-wise maximum. Combining both masks ensures that the features from image 1 are covered up, and that the features from image 2 show through.

Finally, the mask is applied to give the final image: