Spaces:
Runtime error
Runtime error
File size: 2,413 Bytes
81319f5 7aa2615 81319f5 7aa2615 81319f5 |
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 68 69 70 |
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) |