File size: 2,013 Bytes
06cd1c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from moviepy.editor import VideoFileClip
import cv2
import numpy as np
import insightface

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)
    faces = model.get(source_img)
    if len(faces) == 0:
        raise Exception("No face found in source.")
    source_face = faces[0]

    if target_path.endswith(".jpg"):
        target_img = cv2.imread(target_path)
        faces = model.get(target_img)
        if len(faces) == 0:
            raise Exception("No face found in target.")
        target_img[faces[0].bbox.astype(int)[1]:faces[0].bbox.astype(int)[3],
                   faces[0].bbox.astype(int)[0]:faces[0].bbox.astype(int)[2]] =                    source_img[source_face.bbox.astype(int)[1]:source_face.bbox.astype(int)[3],
                              source_face.bbox.astype(int)[0]:source_face.bbox.astype(int)[2]]
        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:
                frame_bgr[faces[0].bbox.astype(int)[1]:faces[0].bbox.astype(int)[3],
                          faces[0].bbox.astype(int)[0]:faces[0].bbox.astype(int)[2]] =                           source_img[source_face.bbox.astype(int)[1]:source_face.bbox.astype(int)[3],
                                     source_face.bbox.astype(int)[0]:source_face.bbox.astype(int)[2]]
            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