| import cv2 | |
| import dlib | |
| def swap_faces(image_path1, image_path2, output_path): | |
| # Load the images | |
| img1 = cv2.imread(image_path1) | |
| img2 = cv2.imread(image_path2) | |
| # Initialize the face detector | |
| detector = dlib.get_frontal_face_detector() | |
| # Detect faces in both images | |
| faces1 = detector(img1) | |
| faces2 = detector(img2) | |
| # Swap the faces | |
| for face1, face2 in zip(faces1, faces2): | |
| x1, y1, w1, h1 = face1.left(), face1.top(), face1.width(), face1.height() | |
| x2, y2, w2, h2 = face2.left(), face2.top(), face2.width(), face2.height() | |
| # Extract the face regions | |
| face1_region = img1[y1:y1 + h1, x1:x1 + w1] | |
| face2_region = img2[y2:y2 + h2, x2:x2 + w2] | |
| # Swap the faces | |
| img1[y1:y1 + h1, x1:x1 + w1] = face2_region | |
| img2[y2:y2 + h2, x2:x2 + w2] = face1_region | |
| # Save the output images | |
| cv2.imwrite(output_path + "_1.jpg", img1) | |
| cv2.imwrite(output_path + "_2.jpg", img2) | |
| if __name__ == "__main__": | |
| image1_path = "path/to/your/image1.jpg" | |
| image2_path = "path/to/your/image2.jpg" | |
| output_path = "path/to/output/directory/output" | |
| swap_faces(image1_path, image2_path, output_path) | |