Swap Faces Using OpenCV

Here I will be giving a very simple explanation about the OpenCV Library and how we can use it to make a program to swap faces.

So the main point to understand is that an image is basically just an array and the elements in the array contain the color codes of the color that needs to be filled in that particular block.

So where am I going with this?

All of the above introduction lets us know that we can easily initialize an array and then pass a BGR Value. In cv2 module we define a color code in BGR (Blue, Green, Red).

So before I start with the swapping face application, let us first code our own image. So let us make an image of a red cross.

Now in the above code I have first made a numpy array of zeros — a size of 400x400, which means that we will go with a 400x400 pixel image. I am then putting the BGR values for certain ranges of the array.

So we have now successfully generated an image.

Time to swap faces!

  • haarcascade_frontalface_default.xml is the pre-trained model that I have used which helps me find the coordinates of the face. You can find the same here
  • p1x1, p2x2 etc. are all the coordinates of the faces of photo 1 and 2.
  • cphoto1 and cphoto2 are the cropped photos. tcphoto2 is kind of a temporary image which accompanies us in the swap.
  • In the for loops then the cropped photos are swapped, so that the faces can be swapped.

We can also merge images with this simple concept by just stacking the arrays of both images.

So above we just perform a simple horizontal stack of the two arrays which as discussed before is basically just merging two images horizontally.

I hope you got to take away something from the article. Don’t forget to Clap 👏 for the article if you liked it and also Don’t forget to Follow!

Thank you.