Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- app.py +49 -0
- inswapper_128.onnx +3 -0
- requirements.txt +5 -0
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import cv2
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import insightface
|
| 6 |
+
from insightface.app import FaceAnalysis
|
| 7 |
+
|
| 8 |
+
# Load face detector and swapper
|
| 9 |
+
app = FaceAnalysis(name='buffalo_l')
|
| 10 |
+
app.prepare(ctx_id=0, det_size=(640, 640))
|
| 11 |
+
swapper = insightface.model_zoo.get_model('inswapper_128.onnx')
|
| 12 |
+
|
| 13 |
+
def to_numpy(img):
|
| 14 |
+
if isinstance(img, Image.Image):
|
| 15 |
+
return np.array(img.convert("RGB"))
|
| 16 |
+
return img
|
| 17 |
+
|
| 18 |
+
def swap_faces(source_img, dest_img, source_index=1, dest_index=1):
|
| 19 |
+
source_np = to_numpy(source_img)
|
| 20 |
+
dest_np = to_numpy(dest_img)
|
| 21 |
+
|
| 22 |
+
# Detect faces
|
| 23 |
+
source_faces = sorted(app.get(source_np), key=lambda x: x.bbox[0])
|
| 24 |
+
dest_faces = sorted(app.get(dest_np), key=lambda x: x.bbox[0])
|
| 25 |
+
|
| 26 |
+
if len(source_faces) < source_index or len(dest_faces) < dest_index:
|
| 27 |
+
raise gr.Error("Face index out of range!")
|
| 28 |
+
|
| 29 |
+
source_face = source_faces[source_index - 1]
|
| 30 |
+
dest_face = dest_faces[dest_index - 1]
|
| 31 |
+
|
| 32 |
+
# Swap
|
| 33 |
+
result = swapper.get(dest_np, dest_face, source_face, paste_back=True)
|
| 34 |
+
result_rgb = cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
|
| 35 |
+
return Image.fromarray(result_rgb)
|
| 36 |
+
|
| 37 |
+
# Gradio app
|
| 38 |
+
gr.Interface(
|
| 39 |
+
fn=swap_faces,
|
| 40 |
+
inputs=[
|
| 41 |
+
gr.Image(label="Source Image"),
|
| 42 |
+
gr.Image(label="Target Image"),
|
| 43 |
+
gr.Number(value=1, label="Source Face Index"),
|
| 44 |
+
gr.Number(value=1, label="Target Face Index"),
|
| 45 |
+
],
|
| 46 |
+
outputs=gr.Image(label="Swapped Output"),
|
| 47 |
+
title="Face Swap with InsightFace",
|
| 48 |
+
description="Swap faces using InsightFace and ONNX model (inswapper_128.onnx)."
|
| 49 |
+
).launch()
|
inswapper_128.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e4a3f08c753cb72d04e10aa0f7dbe3deebbf39567d4ead6dce08e98aa49e16af
|
| 3 |
+
size 554253681
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
insightface>=0.7
|
| 3 |
+
onnxruntime
|
| 4 |
+
opencv-python
|
| 5 |
+
Pillow
|