Face Swap
Face Swap Website
from flask import Flask, request, jsonify
import cv2
import dlib
import numpy as np
import base64
app = Flask(__name__)
# Load the shape predictor
predictor_path = "shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
def get_landmarks(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = detector(gray)
if len(faces) == 0:
return None
return np.array([[p.x, p.y] for p in predictor(gray, faces[0]).parts()])
def apply_mask(image, landmarks):
mask = np.zeros_like(image)
points = cv2.convexHull(landmarks)
cv2.fillConvexPoly(mask, points, (255, 255, 255))
return cv2.bitwise_and(image, mask)
def face_swap(img1, img2):
landmarks1 = get_landmarks(img1)
landmarks2 = get_landmarks(img2)
if landmarks1 is None or landmarks2 is None:
return None
mask1 = apply_mask(img1, landmarks1)
mask2 = apply_mask(img2, landmarks2)
swapped = cv2.seamlessClone(mask1, img2, mask2, tuple(landmarks2.mean(axis=0).astype(int)), cv2.NORMAL_CLONE)
return swapped
@app.route('/upload', methods=['POST'])
def upload_image():
try:
img1 = cv2.imdecode(np.frombuffer(request.files['image1'].read(), np.uint8), cv2.IMREAD_COLOR)
img2 = cv2.imdecode(np.frombuffer(request.files['image2'].read(), np.uint8), cv2.IMREAD_COLOR)
result = face_swap(img1, img2)
if result is None:
return jsonify({'status': 'failure', 'message': 'Face swap failed'})
_, img_encoded = cv2.imencode('.jpg', result)
img_base64 = base64.b64encode(img_encoded).decode('utf-8')
return jsonify({'status': 'success', 'image': img_base64})
except Exception as e:
return jsonify({'status': 'failure', 'message': str(e)})
if __name__ == '__main__':
app.run(debug=True)
No comments: