Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
import cv2
|
5 |
+
from PIL import Image
|
6 |
+
from torchvision import transforms
|
7 |
+
from cloth_segmentation.networks.u2net import U2NET
|
8 |
+
import matplotlib.colors as mcolors
|
9 |
+
|
10 |
+
# Load U²-Net
|
11 |
+
model_path = "cloth_segmentation/networks/u2net.pth"
|
12 |
+
model = U2NET(3, 1)
|
13 |
+
state_dict = torch.load(model_path, map_location=torch.device("cpu"))
|
14 |
+
state_dict = {k.replace("module.", ""): v for k, v in state_dict.items()}
|
15 |
+
model.load_state_dict(state_dict)
|
16 |
+
model.eval()
|
17 |
+
|
18 |
+
# Util to get BGR color from name
|
19 |
+
def get_bgr_from_color_name(color_name):
|
20 |
+
try:
|
21 |
+
rgb = mcolors.to_rgb(color_name.lower())
|
22 |
+
return tuple(int(255 * c) for c in rgb[::-1]) # Convert to BGR
|
23 |
+
except:
|
24 |
+
return (0, 0, 255) # Default to red
|
25 |
+
|
26 |
+
# Mask refinement
|
27 |
+
def refine_mask(mask):
|
28 |
+
close_kernel = np.ones((5, 5), np.uint8)
|
29 |
+
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, close_kernel)
|
30 |
+
erode_kernel = np.ones((3, 3), np.uint8)
|
31 |
+
mask = cv2.erode(mask, erode_kernel, iterations=1)
|
32 |
+
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, close_kernel)
|
33 |
+
return cv2.GaussianBlur(mask, (5, 5), 1.5)
|
34 |
+
|
35 |
+
# U²-Net segmentation
|
36 |
+
def segment_dress(image_np):
|
37 |
+
transform_pipeline = transforms.Compose([
|
38 |
+
transforms.ToTensor(),
|
39 |
+
transforms.Resize((320, 320))
|
40 |
+
])
|
41 |
+
image = Image.fromarray(image_np).convert("RGB")
|
42 |
+
input_tensor = transform_pipeline(image).unsqueeze(0)
|
43 |
+
|
44 |
+
with torch.no_grad():
|
45 |
+
output = model(input_tensor)[0][0].squeeze().cpu().numpy()
|
46 |
+
|
47 |
+
output = (output - output.min()) / (output.max() - output.min() + 1e-8)
|
48 |
+
adaptive_thresh = np.mean(output) + 0.2
|
49 |
+
dress_mask = (output > adaptive_thresh).astype(np.uint8) * 255
|
50 |
+
return refine_mask(cv2.resize(dress_mask, (image_np.shape[1], image_np.shape[0]), interpolation=cv2.INTER_NEAREST))
|
51 |
+
|
52 |
+
# Optional GrabCut refinement
|
53 |
+
def apply_grabcut(image_np, dress_mask):
|
54 |
+
bgd_model = np.zeros((1, 65), np.float64)
|
55 |
+
fgd_model = np.zeros((1, 65), np.float64)
|
56 |
+
mask = np.where(dress_mask > 0, cv2.GC_PR_FGD, cv2.GC_BGD).astype('uint8')
|
57 |
+
coords = cv2.findNonZero(dress_mask)
|
58 |
+
if coords is not None:
|
59 |
+
x, y, w, h = cv2.boundingRect(coords)
|
60 |
+
rect = (x, y, w, h)
|
61 |
+
cv2.grabCut(image_np, mask, rect, bgd_model, fgd_model, 3, cv2.GC_INIT_WITH_MASK)
|
62 |
+
refined = np.where((mask == cv2.GC_FGD) | (mask == cv2.GC_PR_FGD), 255, 0).astype("uint8")
|
63 |
+
return refine_mask(refined)
|
64 |
+
|
65 |
+
# LAB color recoloring
|
66 |
+
def recolor_dress(image_np, dress_mask, target_color):
|
67 |
+
target_color_lab = cv2.cvtColor(np.uint8([[target_color]]), cv2.COLOR_BGR2LAB)[0][0]
|
68 |
+
img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
|
69 |
+
|
70 |
+
dress_pixels = img_lab[dress_mask > 0]
|
71 |
+
if len(dress_pixels) == 0:
|
72 |
+
return image_np
|
73 |
+
|
74 |
+
mean_L, mean_A, mean_B = np.mean(dress_pixels, axis=0)
|
75 |
+
a_shift = target_color_lab[1] - mean_A
|
76 |
+
b_shift = target_color_lab[2] - mean_B
|
77 |
+
|
78 |
+
img_lab[..., 1] = np.clip(img_lab[..., 1] + (dress_mask / 255.0) * a_shift, 0, 255)
|
79 |
+
img_lab[..., 2] = np.clip(img_lab[..., 2] + (dress_mask / 255.0) * b_shift, 0, 255)
|
80 |
+
|
81 |
+
img_recolored = cv2.cvtColor(img_lab.astype(np.uint8), cv2.COLOR_LAB2RGB)
|
82 |
+
feathered_mask = cv2.GaussianBlur(dress_mask, (21, 21), 7)
|
83 |
+
lightness_mask = (img_lab[..., 0] / 255.0) ** 0.7
|
84 |
+
adaptive_feather = (feathered_mask * lightness_mask).astype(np.uint8)
|
85 |
+
|
86 |
+
return (image_np * (1 - adaptive_feather[..., None] / 255) + img_recolored * (adaptive_feather[..., None] / 255)).astype(np.uint8)
|
87 |
+
|
88 |
+
# Main function
|
89 |
+
def change_dress_color(img, color_prompt):
|
90 |
+
if img is None or not color_prompt:
|
91 |
+
return img
|
92 |
+
|
93 |
+
img_np = np.array(img)
|
94 |
+
target_bgr = get_bgr_from_color_name(color_prompt)
|
95 |
+
|
96 |
+
try:
|
97 |
+
dress_mask = segment_dress(img_np)
|
98 |
+
if np.sum(dress_mask) < 1000:
|
99 |
+
return img
|
100 |
+
dress_mask = apply_grabcut(img_np, dress_mask)
|
101 |
+
img_recolored = recolor_dress(img_np, dress_mask, target_bgr)
|
102 |
+
return Image.fromarray(img_recolored)
|
103 |
+
except Exception as e:
|
104 |
+
print(f"Error: {e}")
|
105 |
+
return img
|
106 |
+
|
107 |
+
# Gradio UI
|
108 |
+
with gr.Blocks() as demo:
|
109 |
+
gr.Markdown("## 🎨 AI Dress Recolorer - Prompt Based")
|
110 |
+
gr.Markdown("Upload an image and type a color (e.g., 'lavender', 'light green', 'royal blue').")
|
111 |
+
|
112 |
+
with gr.Row():
|
113 |
+
with gr.Column():
|
114 |
+
input_image = gr.Image(type="pil", label="Upload Image")
|
115 |
+
color_input = gr.Textbox(label="Enter Dress Color", placeholder="e.g. crimson, lavender, sky blue")
|
116 |
+
recolor_btn = gr.Button("Apply New Color")
|
117 |
+
|
118 |
+
with gr.Column():
|
119 |
+
output_image = gr.Image(type="pil", label="Recolored Result")
|
120 |
+
|
121 |
+
recolor_btn.click(fn=change_dress_color, inputs=[input_image, color_input], outputs=output_image)
|
122 |
+
|
123 |
+
if __name__ == "__main__":
|
124 |
+
demo.launch()
|