
Python OpenCV Build a Fun Face Swap Tool
Face swapping is a fascinating computer vision trick that allows you to swap faces between two people in real-time. Using OpenCV and dlib, we can build a simple face swap tool that works efficiently.
Step 1: Install Required Libraries
Make sure OpenCV and dlib are installed:
pip install opencv-python dlib numpy
Step 2: Import Libraries and Load Models
import cv2
import dlib
import numpy as np
# Load facial landmark predictor
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(“shape_predictor_68_face_landmarks.dat”)
Step 3: Define Helper Functions
Extract Facial Landmarks:
def get_landmarks(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
if len(faces) == 0:
return None
return predictor(gray, faces[0])
Warp Face to Target:
def warp_face(source_img, target_img, landmarks_src, landmarks_tgt):
hull_index = cv2.convexHull(np.array(landmarks_tgt), returnPoints=False)
hull_src = [landmarks_src[i[0]] for i in hull_index]
hull_tgt = [landmarks_tgt[i[0]] for i in hull_index]
warp_matrix = cv2.estimateAffinePartial2D(np.array(hull_src), np.array(hull_tgt))[0]
warped_face = cv2.warpAffine(source_img, warp_matrix, (target_img.shape[1], target_img.shape[0]))
return warped_face
Step 4: Implement Face Swapping
def face_swap(source_img, target_img):
landmarks_src = get_landmarks(source_img)
landmarks_tgt = get_landmarks(target_img)
if landmarks_src is None or landmarks_tgt is None:
print(“No face detected!”)
return target_img
points_src = [(p.x, p.y) for p in landmarks_src.parts()]
points_tgt = [(p.x, p.y) for p in landmarks_tgt.parts()]
swapped_face = warp_face(source_img, target_img, points_src, points_tgt)
mask = np.zeros_like(target_img[:, :, 0])
cv2.fillConvexPoly(mask, np.array(points_tgt, dtype=np.int32), 255)
result = cv2.seamlessClone(swapped_face, target_img, mask, (target_img.shape[1]//2, target_img.shape[0]//2), cv2.NORMAL_CLONE)
return result
Step 5: Run Real-Time Face Swap
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
target_face = frame.copy() # Use a static image or another face
swapped = face_swap(target_face, frame)
cv2.imshow(“Face Swap Tool”, swapped)
if cv2.waitKey(1) & 0xFF == ord(‘q’):
break
cap.release()
cv2.destroyAllWindows()
Conclusion
This face swap tool demonstrates how OpenCV and dlib can be used for real-time facial transformations. You can enhance it further by swapping faces in videos or adding deep learning models for more realistic results!