File size: 2,052 Bytes
5cd2ff7
 
87214ba
5cd2ff7
 
87214ba
5cd2ff7
 
 
87214ba
5cd2ff7
 
87214ba
 
5cd2ff7
 
 
87214ba
5cd2ff7
 
 
 
87214ba
 
fff6b44
87214ba
 
 
 
 
 
 
5cd2ff7
 
 
 
 
 
 
87214ba
5cd2ff7
 
 
 
 
 
 
 
 
 
 
 
 
 
87214ba
fff6b44
 
 
 
 
 
 
 
87214ba
5cd2ff7
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

import os
import cv2
from insightface.app import FaceAnalysis
from insightface.model_zoo import get_model
from gfpgan import GFPGANer

app = None
swapper = None
enhancer = None

def setup_models(execution_provider="cpu"):
    global app, swapper, enhancer

    if app is None:
        app = FaceAnalysis(name="buffalo_l", providers=[execution_provider])
        app.prepare(ctx_id=0, det_size=(640, 640))

    if swapper is None:
        model_path = "models/inswapper_128.onnx"
        swapper = get_model(model_path, providers=[execution_provider])

    if enhancer is None:
        enhancer = GFPGANer(
            model_path="gfpgan/weights/GFPGANv1.4.pth",  # Modelo local
            upscale=1,
            arch="clean",
            channel_multiplier=2,
            bg_upsampler=None,
            device="cuda" if execution_provider == "cuda" else "cpu"
        )

def run_swap(target_path, source_path, output_path, execution_provider="cpu", frame_processors=["face_swapper"]):
    setup_models(execution_provider)

    target_img = cv2.imread(target_path)
    source_img = cv2.imread(source_path)

    if target_img is None or source_img is None:
        print("❌ No se pudieron cargar las imágenes.")
        return False

    target_faces = app.get(target_img)
    source_faces = app.get(source_img)

    if len(target_faces) == 0 or len(source_faces) == 0:
        print("⚠️ No se detectaron rostros.")
        return False

    source_face = source_faces[0]

    for face in target_faces:
        target_img = swapper.get(target_img, face, source_face, paste_back=True)

    if "face_enhancer" in frame_processors:
        h, w = target_img.shape[:2]  # Guardar dimensiones originales
        _, _, enhanced_img = enhancer.enhance(
            target_img,
            has_aligned=False,
            only_center_face=False
        )
        # Devolver imagen restaurada a tamaño original
        target_img = cv2.resize(enhanced_img, (w, h), interpolation=cv2.INTER_CUBIC)

    cv2.imwrite(output_path, target_img)
    return True