Skip to content

Commit f5d8516

Browse files
authored
initial build
1 parent 4bef0d1 commit f5d8516

8 files changed

+266
-0
lines changed

README.md

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
Take a video and replace the face in it with a face of your choice. You only need one image of the desired face. No dataset, no training.
2+
3+
That's it, that's the software.
4+
5+
![demo-gif](demo.gif)
6+
7+
## Installation
8+
> Do not create any issues regarding installation problems. I am only responsible for issues in this program, use google for help.
9+
10+
1. install `python`, `pip` and `git`
11+
2. install `ffmpeg`
12+
3. run the following commands in terminal:
13+
```
14+
git clone https://github.com/s0md3v/roop
15+
cd roop
16+
pip3 install -r requirements.txt
17+
```
18+
19+
### Do you have a decent GPU?
20+
If you have a good enough GPU, you can use it to speed up the face-swapping process by running `run.py` with `--gpu` flag.
21+
If you plan on doing, you will need to install the appropriate `onnxruntime-*` package as follows:
22+
23+
#### NVIDIA
24+
```
25+
pip3 install onnxruntime-gpu
26+
```
27+
#### AMD
28+
```
29+
git clone https://github.com/microsoft/onnxruntime
30+
cd onnxruntime
31+
./build.sh --config Release --build_wheel --update --build --parallel --cmake_extra_defines CMAKE_PREFIX_PATH=/opt/rocm/lib/cmake ONNXRUNTIME_VERSION=$ONNXRUNTIME_VERSION onnxruntime_BUILD_UNIT_TESTS=off --use_rocm --rocm_home=/opt/rocm
32+
pip install build/Linux/Release/dist/*.whl
33+
```
34+
35+
## Usage
36+
> Note: When you run this program for the first time, it will download some models ~300MB in size.
37+
38+
Executing `python run.py` command will launch this window:
39+
40+
Choose a face (image with desired face) and the target image/video (image/video in which you want to replace the face) and click on `Start`. The output will be saved in `output.mp4` file.
41+
42+
Don't touch the FPS checkbox unless you know what you are doing.
43+
44+
Additional command line arguments are given below:
45+
```
46+
-h, --help show this help message and exit
47+
-f SOURCE_IMG, --face SOURCE_IMG
48+
use this face
49+
-t TARGET_PATH, --target TARGET_PATH
50+
replace this face
51+
--keep-fps keep original fps
52+
--gpu use gpu
53+
--keep-frames don't delete frames directory
54+
```
55+
56+
Looking for a CLI mode? Using the -f/--face argument will make the program in cli mode.
57+
58+
## Future plans
59+
- [ ] Replace a selective face throughout the video
60+
- [ ] Support for replacing multiple faces
61+
62+
## Credits
63+
- [ffmpeg](https://ffmpeg.org/): for making video related operations easy
64+
- [deepinsight](https://github.com/deepinsight): for their [insightface](https://github.com/deepinsight/insightface) project which provided a well-made library and models.
65+
- and all developers behind libraries used in this project.

core/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+

core/config.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import insightface
2+
3+
face_analyser = insightface.app.FaceAnalysis(name='buffalo_l', providers=['CUDAExecutionProvider', 'ROCMExecutionProvider', 'CPUExecutionProvider'])
4+
face_analyser.prepare(ctx_id=0, det_size=(640, 640))
5+
6+
7+
def get_face(img_data):
8+
analysed = face_analyser.get(img_data)
9+
return sorted(analysed, key=lambda x: x.bbox[0])[0]

core/processor.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import cv2
2+
import insightface
3+
from core.config import get_face
4+
from core.utils import rreplace
5+
6+
face_swapper = insightface.model_zoo.get_model('inswapper_128.onnx', providers=['CUDAExecutionProvider', 'ROCMExecutionProvider', 'CPUExecutionProvider'])
7+
8+
9+
def process_video(source_img, frame_paths):
10+
source_face = get_face(cv2.imread(source_img))
11+
for frame_path in frame_paths:
12+
frame = cv2.imread(frame_path)
13+
try:
14+
face = get_face(frame)
15+
result = face_swapper.get(frame, face, source_face, paste_back=True)
16+
cv2.imwrite(frame_path, result)
17+
except Exception as e:
18+
pass
19+
20+
21+
def process_img(source_img, target_path):
22+
frame = cv2.imread(target_path)
23+
face = get_face(frame)
24+
source_face = get_face(cv2.imread(source_img))
25+
result = face_swapper.get(frame, face, source_face, paste_back=True)
26+
target_path = rreplace(target_path, "/", "/swapped-", 1) if "/" in target_path else "swapped-"+target_path
27+
print(target_path)
28+
cv2.imwrite(target_path, result)

core/utils.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import os
2+
import shutil
3+
4+
def run_command(command, mode="silent"):
5+
if mode == "debug":
6+
return os.system(command)
7+
return os.popen(command).read()
8+
9+
def detect_fps(input_path):
10+
output = os.popen(f"ffprobe -v error -select_streams v -of default=noprint_wrappers=1:nokey=1 -show_entries stream=r_frame_rate {input_path}").read()
11+
if "/" in output:
12+
try:
13+
return int(output.split("/")[0]) // int(output.split("/")[1])
14+
except:
15+
pass
16+
return 60
17+
18+
19+
def set_fps(input_path, output_path, fps):
20+
os.system(f"ffmpeg -i {input_path} -filter:v fps=fps={fps} {output_path}")
21+
22+
23+
def create_video(video_name, fps, output_dir):
24+
os.system(f"ffmpeg -framerate {fps} -pattern_type glob -i '{output_dir}/*.png' -c:v libx264 -pix_fmt yuv420p -y {output_dir}/output.mp4")
25+
26+
27+
def extract_frames(input_path, output_dir):
28+
os.system(f"ffmpeg -i {input_path} '{output_dir}/%04d.png'")
29+
30+
31+
def add_audio(current_dir, output_dir, target_path, keep_frames):
32+
video = target_path.split("/")[-1]
33+
video_name = video.split(".")[0]
34+
os.system(f"ffmpeg -i {output_dir}/output.mp4 -i {output_dir}/{video} -c:v copy -map 0:v:0 -map 1:a:0 -y {current_dir}/swapped-{video_name}.mp4")
35+
if not os.path.isfile(current_dir + "/swapped-" + video_name + ".mp4"):
36+
shutil.move(output_dir + "/output.mp4", current_dir + "/swapped-" + video_name + ".mp4")
37+
if not keep_frames:
38+
shutil.rmtree(output_dir)
39+
40+
41+
def is_img(path):
42+
return path.lower().endswith(("png", "jpg", "jpeg", "bmp"))
43+
44+
def rreplace(s, old, new, occurrence):
45+
li = s.rsplit(old, occurrence)
46+
return new.join(li)

demo.gif

3.59 MB
Loading

requirements.txt

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
numpy
2+
opencv-python
3+
onnx
4+
insightface

run.py

+113
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import glob
2+
import argparse
3+
import multiprocessing as mp
4+
import os
5+
from pathlib import Path
6+
import tkinter as tk
7+
from tkinter import filedialog
8+
from core.processor import process_video, process_img
9+
from core.utils import is_img, detect_fps, set_fps, create_video, add_audio, extract_frames
10+
import webbrowser
11+
import psutil
12+
import shutil
13+
14+
pool = None
15+
args = {}
16+
17+
parser = argparse.ArgumentParser()
18+
parser.add_argument('-f', '--face', help='use this face', dest='source_img')
19+
parser.add_argument('-t', '--target', help='replace this face', dest='target_path')
20+
parser.add_argument('--keep-fps', help='maintain original fps', dest='keep_fps', action='store_true', default=False)
21+
parser.add_argument('--gpu', help='use gpu', dest='gpu', action='store_true', default=False)
22+
parser.add_argument('--keep-frames', help='keep frames directory', dest='keep_frames', action='store_true', default=False)
23+
24+
for name, value in vars(parser.parse_args()).items():
25+
args[name] = value
26+
27+
def start_processing():
28+
if args['gpu']:
29+
process_video(args['source_img'], args["frame_paths"])
30+
return
31+
frame_paths = args["frame_paths"]
32+
n = len(frame_paths)//(psutil.cpu_count()-1)
33+
processes = []
34+
for i in range(0, len(frame_paths), n):
35+
p = pool.apply_async(process_video, args=(args['source_img'], frame_paths[i:i+n],))
36+
processes.append(p)
37+
for p in processes:
38+
p.get()
39+
pool.close()
40+
pool.join()
41+
42+
43+
def select_face():
44+
args['source_img'] = filedialog.askopenfilename(title="Select a face")
45+
46+
47+
def select_target():
48+
args['target_path'] = filedialog.askopenfilename(title="Select a target")
49+
50+
51+
def toggle_fps_limit():
52+
args['keep_fps'] = limit_fps.get() != True
53+
54+
55+
def start():
56+
global pool
57+
pool = mp.Pool(psutil.cpu_count()-1)
58+
current_dir = os.getcwd()
59+
target_path = args['target_path']
60+
if is_img(target_path):
61+
process_img(args['source_img'], target_path)
62+
return
63+
video_name = target_path.split("/")[-1].split(".")[0]
64+
output_dir = current_dir + "/" + video_name
65+
Path(output_dir).mkdir(exist_ok=True)
66+
fps = detect_fps(target_path)
67+
if not args['keep_fps'] and fps > 30:
68+
this_path = output_dir + "/" + video_name + ".mp4"
69+
set_fps(target_path, this_path, 30)
70+
target_path, fps = this_path, 30
71+
else:
72+
shutil.copy(target_path, output_dir)
73+
extract_frames(target_path, output_dir)
74+
args['frame_paths'] = tuple(sorted(
75+
glob.glob(output_dir + "/*.png"),
76+
key=lambda x: int(x.split("/")[-1].replace(".png", ""))
77+
))
78+
start_processing()
79+
create_video(video_name, fps, output_dir)
80+
add_audio(current_dir, output_dir, target_path, args['keep_frames'])
81+
82+
83+
if __name__ == "__main__":
84+
if args['source_img']:
85+
start()
86+
quit()
87+
window = tk.Tk()
88+
window.geometry("600x200")
89+
window.title("roop")
90+
91+
# Contact information
92+
support_link = tk.Label(window, text="Support the project ^_^", fg="red", cursor="hand2")
93+
support_link.pack(padx=10, pady=10)
94+
support_link.bind("<Button-1>", lambda e: webbrowser.open("https://github.com/sponsors/s0md3v"))
95+
96+
# Select a face button
97+
face_button = tk.Button(window, text="Select a face", command=select_face)
98+
face_button.pack(side=tk.LEFT, padx=10, pady=10)
99+
100+
# Select a target button
101+
target_button = tk.Button(window, text="Select a target", command=select_target)
102+
target_button.pack(side=tk.RIGHT, padx=10, pady=10)
103+
104+
# FPS limit checkbox
105+
limit_fps = tk.IntVar()
106+
fps_checkbox = tk.Checkbutton(window, text="Limit FPS to 30", variable=limit_fps, command=toggle_fps_limit, font=("Arial", 8))
107+
fps_checkbox.pack(side=tk.BOTTOM)
108+
fps_checkbox.select()
109+
110+
# Start button
111+
start_button = tk.Button(window, text="Start", bg="green", command=start)
112+
start_button.pack(side=tk.BOTTOM, padx=10, pady=10)
113+
window.mainloop()

0 commit comments

Comments
 (0)