File size: 1,936 Bytes
5da5004
 
82b1bd2
 
5b0e9de
82b1bd2
5b0e9de
82b1bd2
 
 
 
 
5b0e9de
 
82b1bd2
5b0e9de
 
 
 
 
82b1bd2
 
 
5b0e9de
 
 
 
 
 
 
82b1bd2
9692264
82b1bd2
5da5004
f988474
82b1bd2
 
 
 
5b0e9de
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import os
from moviepy.editor import VideoFileClip
import insightface
import cv2
import numpy as np

# Load the InsightFace model
model = insightface.app.FaceAnalysis(name="buffalo_l", providers=["CPUExecutionProvider"])
model.prepare(ctx_id=0)

def swap_face(source_path, target_path, output_path):
    source_img = cv2.imread(source_path)
    source_faces = model.get(source_img)
    if len(source_faces) == 0:
        raise Exception("No face found in source.")
    source_face = source_faces[0]
    source_crop = source_img[
        int(source_face.bbox[1]):int(source_face.bbox[3]),
        int(source_face.bbox[0]):int(source_face.bbox[2])
    ]

    if target_path.endswith(".jpg"):
        target_img = cv2.imread(target_path)
        target_faces = model.get(target_img)
        if len(target_faces) == 0:
            raise Exception("No face found in target image.")
        target_face = target_faces[0]
        x1, y1, x2, y2 = map(int, target_face.bbox)
        resized_crop = cv2.resize(source_crop, (x2 - x1, y2 - y1))
        target_img[y1:y2, x1:x2] = resized_crop
        cv2.imwrite(output_path, target_img)

    else:
        clip = VideoFileClip(target_path)

        def process_frame(frame):
            frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
            faces = model.get(frame_bgr)
            if len(faces) > 0:
                face = faces[0]
                x1, y1, x2, y2 = map(int, face.bbox)
                resized_crop = cv2.resize(source_crop, (x2 - x1, y2 - y1))
                frame_bgr[y1:y2, x1:x2] = resized_crop
            return cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)

        new_clip = clip.fl_image(process_frame)
        new_clip.write_videofile(output_path, audio=True)

def run_faceswap(source_path, target_path):
    output_path = "result.jpg" if target_path.endswith(".jpg") else "result.mp4"
    swap_face(source_path, target_path, output_path)
    return output_path