Spaces:
Runtime error
Runtime error
import gradio as gr | |
import cv2 | |
import numpy as np | |
import dlib | |
from skimage import io, color | |
# Load the facial landmark predictor | |
predictor_path = "shape_predictor_68_face_landmarks.dat" | |
detector = dlib.get_frontal_face_detector() | |
predictor = dlib.shape_predictor(predictor_path) | |
# Helper function to convert hex color to BGR tuple | |
def hex_to_bgr(hex_color): | |
hex_color = hex_color.lstrip('#') | |
rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) | |
return (rgb[2], rgb[1], rgb[0]) | |
# Function to apply makeup | |
def apply_makeup(image, eye_color, lipstick_color): | |
eye_color_bgr = hex_to_bgr(eye_color) if eye_color else (0, 0, 255) | |
lipstick_color_bgr = hex_to_bgr(lipstick_color) if lipstick_color else (0, 0, 255) | |
image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) | |
image_original = image_bgr.copy() | |
dets = detector(image_bgr, 1) | |
if len(dets) == 0: | |
return cv2.cvtColor(image_original, cv2.COLOR_BGR2RGB) | |
for k, d in enumerate(dets): | |
shape = predictor(image_bgr, d) | |
landmarks = np.array([(shape.part(i).x, shape.part(i).y) for i in range(68)]) | |
left_eye = landmarks[36:42] | |
right_eye = landmarks[42:48] | |
eyeshadow_mask = np.zeros_like(image_bgr, dtype=np.uint8) | |
left_eye_hull = cv2.convexHull(left_eye) | |
right_eye_hull = cv2.convexHull(right_eye) | |
cv2.fillConvexPoly(eyeshadow_mask, left_eye_hull, eye_color_bgr) | |
cv2.fillConvexPoly(eyeshadow_mask, right_eye_hull, eye_color_bgr) | |
eyeshadow_mask = cv2.GaussianBlur(eyeshadow_mask, (15, 15), 0) | |
alpha = 0.4 | |
image_bgr = cv2.addWeighted(image_bgr, 1, eyeshadow_mask, alpha, 0) | |
lips = landmarks[48:60] | |
lipstick_mask = np.zeros_like(image_bgr, dtype=np.uint8) | |
cv2.fillConvexPoly(lipstick_mask, cv2.convexHull(lips), lipstick_color_bgr) | |
lipstick_mask = cv2.GaussianBlur(lipstick_mask, (15, 15), 0) | |
image_bgr = cv2.addWeighted(image_bgr, 1, lipstick_mask, alpha, 0) | |
return cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) | |
# Gradio interface | |
iface = gr.Interface( | |
fn=apply_makeup, | |
inputs=[ | |
gr.Image(type="numpy", label="Input Image"), | |
gr.ColorPicker(label="Eye Color"), | |
gr.ColorPicker(label="Lipstick Color") | |
], | |
outputs=gr.Image(type="numpy", label="Output Image") | |
) | |
iface.launch() | |