Spaces:
Running
Running
| import gradio as gr | |
| import numpy as np | |
| import os | |
| import cv2 | |
| from PIL import Image, ImageDraw | |
| import insightface | |
| from insightface.app import FaceAnalysis | |
| # Insightface model | |
| app = FaceAnalysis(name='buffalo_l') | |
| app.prepare(ctx_id=0, det_size=(640, 640)) | |
| def generate_image(src_img, dest_img): | |
| # Convert to RGB | |
| src_img = src_img.convert(mode='RGB') | |
| dest_img = dest_img.convert(mode='RGB') | |
| # Convert to array | |
| src_img_arr = np.asarray(src_img) | |
| dest_img_arr = np.asarray(dest_img) | |
| # Face detection | |
| src_faces = app.get(src_img_arr) | |
| dest_faces = app.get(dest_img_arr) | |
| # Initialize swapper | |
| swapper = insightface.model_zoo.get_model('./inswapper_128.onnx', download=False, download_zip=False) | |
| #swapper = insightface.model_zoo.get_model('./inswapper_128.onnx') | |
| # Swap face | |
| res = dest_img_arr.copy() | |
| for face in dest_faces: | |
| res = swapper.get(res, face, src_faces[0], paste_back=True) | |
| # Convert to PIL image | |
| final_image = Image.fromarray(np.uint8(res)).convert('RGB') | |
| return final_image | |
| iface = gr.Interface(fn=generate_image, inputs=[ | |
| gr.Image(type="pil", label="Source Image"), | |
| gr.Image(type="pil", label="Destination Image")], | |
| outputs=gr.Image(type="pil", label="Final Image"), | |
| theme=gr.themes.Base(primary_hue=gr.themes.colors.teal, font=["helvetica"]), | |
| examples=[["Images/kim.jpg", "Images/marilyn.jpg"]], | |
| description= | |
| """ # Face Swap | |
| by <a href="https://www.tonyassi.com/" style="color: #97d8be;">Tony Assi</a> | |
| Try out [Video Face Swap](https://huggingface.co/spaces/tonyassi/video-face-swap). Please ❤️ this Space. | |
| """ | |
| ) | |
| iface.launch() |