Creating Face Swaps with Python and OpenCV

mdshamsfiroz
3 min readAug 13, 2023

--

Introduction: Image manipulation is a fascinating field that allows us to explore creative ways to transform and combine images. One interesting technique is face swapping, where you take a person’s face from one image and paste it onto another person’s body in a different image. In this tutorial, we’ll guide you through the process of face-swapping using Python and the OpenCV library.

Prerequisites:

  • Basic understanding of Python programming.
  • Familiarity with image processing concepts.
  • OpenCV library installed (pip install opencv-python).

Step 1: Face Detection The first step is to detect faces in the input images. OpenCV provides a pre-trained Haar cascade classifier for face detection.

import cv2

def detect_face(image_path):
# Load the face detection classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Read and convert the image to grayscale
image = cv2.imread(image_path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)

# Assuming there's only one face in the image, return its coordinates
if len(faces) == 1:
return faces[0]
else:
return None

Step 2: Swapping Faces Next, we’ll swap the faces between the two input images. The process involves resizing the source face to match the size of the target face and then blending them together.

NOTE:- Both image files must be in one folder where you python code file is available.

def main():
# Paths to the input images
image_path_1 = 'path_to_image1.jpg'
image_path_2 = 'path_to_image2.jpg'

# Detect the face in the second image
face_coords_2 = detect_face(image_path_2)
if face_coords_2 is None:
print("No face found in the second image.")
return

# Load and resize the source face
image_1 = cv2.imread(image_path_1)
face_width, face_height = face_coords_2[2], face_coords_2[3]
image_1_resized = cv2.resize(image_1, (face_width, face_height))

# Extract the target face region from the second image
image_2 = cv2.imread(image_path_2)
roi = image_2[face_coords_2[1]:face_coords_2[1] + face_height, face_coords_2[0]:face_coords_2[0] + face_width]

# Flip the target face horizontally
reflected_roi = cv2.flip(roi, 1)

# Blend the two faces together
alpha = 0.7
blended_image = cv2.addWeighted(image_1_resized, alpha, reflected_roi, 1 - alpha, 0)

# Replace the target face region with the blended image
image_2[face_coords_2[1]:face_coords_2[1] + face_height, face_coords_2[0]:face_coords_2[0] + face_width] = blended_image

# Display the result
cv2.imshow('Blended Image', image_2)
cv2.waitKey(0)
cv2.destroyAllWindows()

if __name__ == "__main__":
main()
Result

Conclusion: In this tutorial, we’ve explored the process of face swapping using Python and OpenCV. We started by detecting faces in the input images, then resized and blended them to create the final swapped image. This technique can result in amusing and interesting visual outcomes, showcasing the power of image manipulation. Remember to experiment with different images and adjust parameters to achieve the desired results!

Thank you @Vimal Daga for teaching me fundamentals so that I can able to research and perform this project.

--

--

mdshamsfiroz
mdshamsfiroz

Written by mdshamsfiroz

Trying to learn tool by putting heart inside to make something

Responses (3)