|
|
|
import os |
|
import shutil |
|
from moviepy.editor import VideoFileClip |
|
import cv2 |
|
from PIL import Image |
|
from tqdm import tqdm |
|
|
|
def run_faceswap(source_path, target_path): |
|
if target_path.endswith(".jpg") or target_path.endswith(".png"): |
|
|
|
output_path = "result.jpg" |
|
shutil.copy(target_path, output_path) |
|
return output_path |
|
|
|
elif target_path.endswith(".mp4"): |
|
os.makedirs("frames_input", exist_ok=True) |
|
os.makedirs("frames_output", exist_ok=True) |
|
|
|
clip = VideoFileClip(target_path) |
|
fps = clip.fps |
|
|
|
for i, frame in enumerate(clip.iter_frames()): |
|
Image.fromarray(frame).save(f"frames_input/frame_{i:05d}.jpg") |
|
|
|
|
|
for frame_file in sorted(os.listdir("frames_input")): |
|
shutil.copy(f"frames_input/{frame_file}", f"frames_output/{frame_file}") |
|
|
|
frame_files = sorted(os.listdir("frames_output")) |
|
frame_images = [cv2.imread(f"frames_output/{f}") for f in frame_files] |
|
h, w, _ = frame_images[0].shape |
|
out_path = "result.mp4" |
|
video_writer = cv2.VideoWriter(out_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h)) |
|
|
|
for img in frame_images: |
|
video_writer.write(img) |
|
video_writer.release() |
|
|
|
return out_path |
|
|
|
else: |
|
raise ValueError("Unsupported file format") |
|
|