Fffc / app.py
ucancode's picture
output image ์ˆ˜์ •ํ•˜๊ธฐ
7aa2615
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'
# Convert PIL images to NumPy arrays for processing
guest_img = np.array(user_image)
result_img = np.array(result_image)
# Convert RGB (PIL) to BGR (OpenCV)
guest_img = guest_img[:, :, ::-1]
result_img = result_img[:, :, ::-1]
# Initialize the FaceAnalysis app
app = FaceAnalysis(name='buffalo_l')
app.prepare(ctx_id=0, det_size=(640, 640))
# Initialize the face swapper model
swapper = insightface.model_zoo.get_model('inswapper_128.onnx', download=False, download_zip=False)
# Detect face in the guest image
guest_faces = app.get(guest_img)
guest_face = guest_faces[0]
# Detect faces in the result image
faces = app.get(result_img)
# Perform face swapping
for face in faces:
result_img = swapper.get(result_img, face, guest_face, paste_back=True)
# Save the result in the specified output folder
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)
# Convert the final image from BGR to RGB before returning
result_img = cv2.cvtColor(result_img, cv2.COLOR_BGR2RGB)
# Convert back to PIL image
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)