File size: 2,075 Bytes
cd7d726
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccce0ef
cd7d726
 
 
ccce0ef
 
cd7d726
ccce0ef
cd7d726
ccce0ef
 
 
cd7d726
ccce0ef
 
 
 
 
cd7d726
ccce0ef
 
 
cd7d726
a347ff8
ccce0ef
 
cd7d726
 
ccce0ef
cd7d726
ccce0ef
 
 
cd7d726
 
 
 
 
 
ccce0ef
cd7d726
 
 
 
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
import gradio as gr
from PIL import Image
import os

def load_hairstyles():
    folder = "hairstyles"
    if not os.path.exists(folder):
        return []
    return [
        Image.open(os.path.join(folder, f)).convert("RGBA")
        for f in sorted(os.listdir(folder)) if f.endswith(".png")
    ]

hairstyles = load_hairstyles()

def apply_hairstyle(user_img, style_index, x_offset, y_offset, scale):
    if user_img is None or not hairstyles:
        return None

    user_img = user_img.convert("RGBA")
    base_w, base_h = user_img.size

    hairstyle = hairstyles[style_index]

    # Resize the hairstyle based on scale
    new_size = (int(base_w * scale), int(hairstyle.height * (base_w * scale / hairstyle.width)))
    hairstyle = hairstyle.resize(new_size)

    # Create a blank transparent image to position the hairstyle
    composite = Image.new("RGBA", user_img.size)
    paste_x = int((base_w - new_size[0]) / 2 + x_offset)
    paste_y = int(y_offset)
    composite.paste(hairstyle, (paste_x, paste_y), hairstyle)

    # Overlay it
    result = Image.alpha_composite(user_img, composite)
    return result.convert("RGB")

with gr.Blocks() as demo:
    gr.Markdown("## 💇 Salon Virtual Hairstyle Try-On (Adjustable)")

    with gr.Row():
        with gr.Column():
            image_input = gr.Image(type="pil", label="📷 Upload an Image")
            style_slider = gr.Slider(0, max(len(hairstyles)-1, 0), step=1, label="🎨 Select Hairstyle")
            x_offset = gr.Slider(-200, 200, value=0, step=1, label="⬅️➡️ Move Left / Right")
            y_offset = gr.Slider(-200, 200, value=0, step=1, label="⬆️⬇️ Move Up / Down")
            scale = gr.Slider(0.3, 2.0, value=1.0, step=0.05, label="📏 Scale Hairstyle")
            apply_btn = gr.Button("✨ Apply Hairstyle")
        with gr.Column():
            result_output = gr.Image(label="🔍 Result Preview")

    apply_btn.click(
        fn=apply_hairstyle,
        inputs=[image_input, style_slider, x_offset, y_offset, scale],
        outputs=result_output
    )

demo.launch()