CoolFace
Apppublic

NguyNhu/ScaleImage

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py67 linesDownload Raw Back to root
1import insightface2from insightface.app import FaceAnalysis3import cv24import os5import numpy as np6import gradio as gr7import urllib.request8 9# URL đến mô hình hoán đổi khuôn mặt10model_url = "https://huggingface.co/ezioruan/inswapper_128.onnx/resolve/main/inswapper_128.onnx"11model_path = os.path.expanduser('~/.insightface/models/inswapper_128.onnx')12 13# Tải mô hình nếu chưa tồn tại14os.makedirs(os.path.dirname(model_path), exist_ok=True)15if not os.path.exists(model_path):16    print("Đang tải mô hình từ URL...")17    urllib.request.urlretrieve(model_url, model_path)18    print("Hoàn tất tải mô hình!")19 20# Khởi tạo đối tượng INSwapper21swapper = insightface.model_zoo.get_model(model_path)22 23# Khởi tạo mô hình nhận diện khuôn mặt24app = FaceAnalysis(name='buffalo_l')25app.prepare(ctx_id=0, det_size=(640, 640))26 27def swap_faces(source_img, target_img):28    # Đọc ảnh từ đầu vào Gradio29    source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)30    target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)31 32    # Phát hiện khuôn mặt33    source_faces = app.get(source_img)34    target_faces = app.get(target_img)35 36    # Kiểm tra xem có phát hiện được khuôn mặt hay không37    if len(source_faces) == 0:38        raise gr.Error("❌ Không tìm thấy khuôn mặt trong ảnh nguồn.")39    if len(target_faces) == 0:40        raise gr.Error("❌ Không tìm thấy khuôn mặt trong ảnh đích.")41 42    # Chọn khuôn mặt đầu tiên trong ảnh nguồn43    source_face = source_faces[0]44 45    # Thực hiện hoán đổi khuôn mặt46    result_img = target_img.copy()47    for target_face in target_faces:48        result_img = swapper.get(result_img, target_face, source_face, paste_back=True)49 50    # Chuyển kết quả sang định dạng RGB để hiển thị trong Gradio51    result_img = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB)52    return result_img53 54# Tạo giao diện Gradio55iface = gr.Interface(56    fn=swap_faces,57    inputs=[58        gr.Image(type="pil", label="Ảnh Nguồn"),59        gr.Image(type="pil", label="Ảnh Đích"),60    ],61    outputs=gr.Image(type="numpy", label="Kết Quả Hoán Đổi Khuôn Mặt"),62    title="Hoán Đổi Khuôn Mặt",63    description="Tải lên ảnh nguồn và ảnh đích để hoán đổi khuôn mặt.",64)65 66# Chạy giao diện67iface.launch()