How to Build a One‑Click Face Swap System with OpenCV, dlib, and Flask
This guide walks through installing required libraries, preparing source and target images, detecting and aligning facial landmarks with dlib, swapping faces using OpenCV, displaying and saving the result, and adding a Flask‑based image‑upload interface to automate the one‑click face swap workflow.
This article provides a step‑by‑step tutorial for creating a one‑click face swap system using Python, OpenCV, and dlib, and then extending it with a Flask web interface for image upload.
1. Install required libraries
Use pip to install OpenCV, dlib, NumPy, and imutils:
pip install opencv-python
pip install dlib
pip install numpy
pip install imutils2. Prepare source and target images
Obtain two photos: a source face image and a target face image with similar size and orientation.
3. Load images and detect facial landmarks
Load the images with cv2.imread and use dlib’s frontal face detector and shape predictor to locate faces and extract 68 facial landmarks.
4. Align faces
Align both faces using dlib’s get_face_chip() so they share the same pose and scale.
5. Swap faces
Replace the target face region with the aligned source face using NumPy slicing and OpenCV image operations.
6. Display and save the result
Show the final image with cv2.imshow and optionally save it using cv2.imwrite .
Example implementation
import cv2
import dlib
import numpy as np
import imutils
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
source_image = cv2.imread('source_image.jpg')
target_image = cv2.imread('target_image.jpg')
source_faces = detector(source_image)
target_faces = detector(target_image)
if len(source_faces) > 0 and len(target_faces) > 0:
source_face = source_faces[0]
target_face = target_faces[0]
source_landmarks = predictor(source_image, source_face)
target_landmarks = predictor(target_image, target_face)
aligned_source_face = dlib.get_face_chip(source_image, source_landmarks)
aligned_target_face = dlib.get_face_chip(target_image, target_landmarks)
output_image = target_image.copy()
output_image[target_face.top():target_face.bottom(), target_face.left():target_face.right()] = aligned_source_face
cv2.imshow('Result', output_image)
cv2.waitKey(0)
cv2.imwrite('result.jpg', output_image)
cv2.destroyAllWindows()Adding an image‑upload feature with Flask
Install Flask:
pip install flaskCreate app.py :
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
if 'file' not in request.files:
return 'No file uploaded'
file = request.files['file']
if file.filename == '':
return 'No file selected'
file.save(file.filename)
return 'File uploaded successfully'
if __name__ == '__main__':
app.run(debug=True)Create templates/index.html with a simple upload form:
<!DOCTYPE html>
<html>
<head><title>Image Upload</title></head>
<body>
<h1>Image Upload</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
</body>
</html>Run the Flask app ( python app.py ), open http://localhost:5000 , upload an image, and then you can call the face‑swap functions on the uploaded file.
Note that this is a basic example; production code should include validation, security checks, and more sophisticated face‑swap algorithms for better visual quality.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.