|
import gradio as gr |
|
import cv2 |
|
import numpy as np |
|
import insightface |
|
from insightface.app import FaceAnalysis |
|
import datetime |
|
import os |
|
from PIL import Image |
|
|
|
|
|
def faceswapper(user_image, result_image, username="test"): |
|
output_folder = 'outputs' |
|
|
|
|
|
guest_img = np.array(user_image) |
|
result_img = np.array(result_image) |
|
|
|
|
|
guest_img = guest_img[:, :, ::-1] |
|
result_img = result_img[:, :, ::-1] |
|
|
|
|
|
|
|
app = FaceAnalysis(name='buffalo_l') |
|
app.prepare(ctx_id=0, det_size=(640, 640)) |
|
|
|
|
|
swapper = insightface.model_zoo.get_model('inswapper_128.onnx', download=False, download_zip=False) |
|
|
|
|
|
guest_faces = app.get(guest_img) |
|
guest_face = guest_faces[0] |
|
|
|
|
|
faces = app.get(result_img) |
|
|
|
|
|
for face in faces: |
|
result_img = swapper.get(result_img, face, guest_face, paste_back=True) |
|
|
|
|
|
if not os.path.exists(output_folder): |
|
os.makedirs(output_folder) |
|
current_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") |
|
output_path = os.path.join(output_folder, f'{username}_swapped_face_{current_time}.jpg') |
|
cv2.imwrite(output_path, result_img) |
|
|
|
|
|
result_img = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB) |
|
|
|
|
|
|
|
result_img_pil = Image.fromarray(result_img) |
|
original_size = result_image.size |
|
result_img_pil = result_img_pil.resize(original_size, Image.Resampling.LANCZOS) |
|
|
|
return result_img_pil |
|
|
|
with gr.Blocks() as demo: |
|
with gr.Row(): |
|
with gr.Column(): |
|
name = gr.Textbox(label="์ด๋ฆ(ํ์ผ์ ์ฅ์ฉ)") |
|
with gr.Row(): |
|
user_image_input = gr.Image(type="pil", label="์ ์ ์ฌ์ง(์ผ๊ตด์ถ์ถ)", width=512, height=512) |
|
result_image_input = gr.Image(type="pil", label="๊ฒฐ๊ณผ๋ฌผ ์ฌ์ง", width=512, height=512) |
|
swap_btn = gr.Button("Swap Faces") |
|
output_image = gr.Image(label="ํฉ์ฑ ํ ์ฌ์ง", width=512, height=512) |
|
swap_btn.click(fn=faceswapper, inputs=[user_image_input, result_image_input, name], outputs=output_image) |
|
|
|
demo.launch(debug=True) |