Upload swap.py
Browse files- scripts/swap.py +48 -0
scripts/swap.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
from insightface.app import FaceAnalysis
|
| 4 |
+
from insightface.model_zoo import get_model
|
| 5 |
+
import cv2
|
| 6 |
+
|
| 7 |
+
app = None
|
| 8 |
+
swapper = None
|
| 9 |
+
|
| 10 |
+
def setup_models(execution_provider="cpu"):
|
| 11 |
+
global app, swapper
|
| 12 |
+
if app is None:
|
| 13 |
+
app = FaceAnalysis(name="buffalo_l", providers=[execution_provider])
|
| 14 |
+
app.prepare(ctx_id=0, det_size=(640, 640))
|
| 15 |
+
if swapper is None:
|
| 16 |
+
model_path = "models/inswapper_128.onnx"
|
| 17 |
+
swapper = get_model(model_path, providers=[execution_provider])
|
| 18 |
+
|
| 19 |
+
def run_swap(target_path, source_path, output_path, execution_provider="cpu", frame_processors=["face_swapper"]):
|
| 20 |
+
setup_models(execution_provider)
|
| 21 |
+
|
| 22 |
+
# Leer imágenes
|
| 23 |
+
target_img = cv2.imread(target_path)
|
| 24 |
+
source_img = cv2.imread(source_path)
|
| 25 |
+
|
| 26 |
+
# Verificar carga
|
| 27 |
+
if target_img is None or source_img is None:
|
| 28 |
+
print("❌ Error al leer las imágenes.")
|
| 29 |
+
return False
|
| 30 |
+
|
| 31 |
+
# Detectar rostros
|
| 32 |
+
target_faces = app.get(target_img)
|
| 33 |
+
source_faces = app.get(source_img)
|
| 34 |
+
|
| 35 |
+
if len(target_faces) == 0 or len(source_faces) == 0:
|
| 36 |
+
print("⚠️ No se detectaron rostros.")
|
| 37 |
+
return False
|
| 38 |
+
|
| 39 |
+
# Tomar el primer rostro detectado de la fuente
|
| 40 |
+
source_face = source_faces[0]
|
| 41 |
+
|
| 42 |
+
# Procesar cada rostro en la imagen objetivo
|
| 43 |
+
for face in target_faces:
|
| 44 |
+
target_img = swapper.get(target_img, face, source_face, paste_back=True)
|
| 45 |
+
|
| 46 |
+
# Guardar imagen final
|
| 47 |
+
cv2.imwrite(output_path, target_img)
|
| 48 |
+
return True
|