|
import cv2 |
|
import ffmpeg |
|
import numpy as np |
|
import os |
|
import onnxruntime as rt |
|
|
|
class Refacer: |
|
def __init__(self, force_cpu=False, colab_performance=False): |
|
self.force_cpu = force_cpu |
|
self.colab_performance = colab_performance |
|
self.sess_options = None |
|
self.providers = ['CPUExecutionProvider'] |
|
self.model_path = "./inswapper_128.onnx" |
|
self.__init_apps() |
|
|
|
def __init_apps(self): |
|
self.sess = rt.InferenceSession(self.model_path, self.sess_options, providers=self.providers) |
|
|
|
def __convert_video(self, video_path, output_video_path): |
|
""" |
|
Convert the video using ffmpeg and return the output file. |
|
""" |
|
try: |
|
|
|
out = ffmpeg.input(video_path) |
|
out = ffmpeg.output(out, output_video_path, vcodec='libx264', acodec='aac') |
|
out.run(overwrite_output=True, quiet=False) |
|
except ffmpeg.Error as e: |
|
print("FFmpeg Error:", e.stderr.decode()) |
|
raise |
|
return output_video_path |
|
|
|
def reface(self, video_path, faces): |
|
""" |
|
Refacing the video by swapping faces. |
|
""" |
|
output_video_path = "output_video.mp4" |
|
|
|
|
|
print("Refacing video...") |
|
return self.__convert_video(video_path, output_video_path) |
|
|
|
|
|
if __name__ == "__main__": |
|
refacer = Refacer(force_cpu=True) |
|
faces = [{'origin': 'origin_image.jpg', 'destination': 'destination_image.jpg', 'threshold': 0.8}] |
|
video_path = 'input_video.mp4' |
|
refaced_video_path = refacer.reface(video_path, faces) |
|
print(f"Refaced video can be found at: {refaced_video_path}") |
|
|