File size: 2,423 Bytes
3ba3e17
 
 
 
f330d7c
 
3ba3e17
f330d7c
3ba3e17
 
 
f330d7c
3ba3e17
 
 
 
 
 
f330d7c
3ba3e17
 
f330d7c
3ba3e17
 
 
f330d7c
3ba3e17
 
 
 
f330d7c
3ba3e17
 
 
f330d7c
3ba3e17
 
 
 
 
f330d7c
3ba3e17
 
f330d7c
3ba3e17
 
 
 
f330d7c
3ba3e17
 
 
f330d7c
3ba3e17
 
 
f330d7c
3ba3e17
 
 
 
 
 
f330d7c
3ba3e17
 
 
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 insightface
from insightface.app import FaceAnalysis
import cv2
import os
import numpy as np
import gradio as gr
import urllib.request

# URL đến mô hình hoán đổi khuôn mặt
model_url = "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx"
model_path = os.path.expanduser('~/.insightface/models/inswapper_128.onnx')

# Tải mô hình nếu chưa tồn tại
os.makedirs(os.path.dirname(model_path), exist_ok=True)
if not os.path.exists(model_path):
    print("Đang tải mô hình từ URL...")
    urllib.request.urlretrieve(model_url, model_path)
    print("Hoàn tất tải mô hình!")

# Khởi tạo đối tượng INSwapper
swapper = insightface.model_zoo.get_model(model_path)

# Khởi tạo mô hình nhận diện khuôn mặt
app = FaceAnalysis(name='buffalo_l')
app.prepare(ctx_id=0, det_size=(640, 640))

def swap_faces(source_img, target_img):
    # Đọc ảnh từ đầu vào Gradio
    source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
    target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)

    # Phát hiện khuôn mặt
    source_faces = app.get(source_img)
    target_faces = app.get(target_img)

    # Kiểm tra xem có phát hiện được khuôn mặt hay không
    if len(source_faces) == 0:
        raise gr.Error("❌ Không tìm thấy khuôn mặt trong ảnh nguồn.")
    if len(target_faces) == 0:
        raise gr.Error("❌ Không tìm thấy khuôn mặt trong ảnh đích.")

    # Chọn khuôn mặt đầu tiên trong ảnh nguồn
    source_face = source_faces[0]

    # Thực hiện hoán đổi khuôn mặt
    result_img = target_img.copy()
    for target_face in target_faces:
        result_img = swapper.get(result_img, target_face, source_face, paste_back=True)

    # Chuyển kết quả sang định dạng RGB để hiển thị trong Gradio
    result_img = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB)
    return result_img

# Tạo giao diện Gradio
iface = gr.Interface(
    fn=swap_faces,
    inputs=[
        gr.Image(type="pil", label="Ảnh Nguồn"),
        gr.Image(type="pil", label="Ảnh Đích"),
    ],
    outputs=gr.Image(type="numpy", label="Kết Quả Hoán Đổi Khuôn Mặt"),
    title="Hoán Đổi Khuôn Mặt",
    description="Tải lên ảnh nguồn và ảnh đích để hoán đổi khuôn mặt.",
)

# Chạy giao diện
iface.launch()