Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -14,29 +14,36 @@ state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()} # Rem
|
|
14 |
model.load_state_dict(state_dict)
|
15 |
model.eval()
|
16 |
|
17 |
-
def
|
18 |
-
"""
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
25 |
|
26 |
-
#
|
27 |
-
|
28 |
|
29 |
-
return
|
30 |
|
31 |
def segment_dress(image_np):
|
32 |
-
"""
|
33 |
|
34 |
-
# Convert to Lab space
|
35 |
img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
|
36 |
-
L, A, B = cv2.split(img_lab)
|
37 |
-
|
38 |
-
# Use K-means clustering to detect dominant dress region
|
39 |
pixel_values = img_lab.reshape((-1, 3)).astype(np.float32)
|
|
|
|
|
40 |
k = 3 # Three clusters: background, skin, dress
|
41 |
_, labels, centers = cv2.kmeans(pixel_values, k, None, (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0), 10, cv2.KMEANS_RANDOM_CENTERS)
|
42 |
labels = labels.reshape(image_np.shape[:2])
|
@@ -48,7 +55,7 @@ def segment_dress(image_np):
|
|
48 |
# Create dress mask
|
49 |
mask = (labels == dress_label).astype(np.uint8) * 255
|
50 |
|
51 |
-
#
|
52 |
transform_pipeline = transforms.Compose([
|
53 |
transforms.ToTensor(),
|
54 |
transforms.Resize((320, 320))
|
@@ -63,7 +70,7 @@ def segment_dress(image_np):
|
|
63 |
u2net_mask = (output > 0.5).astype(np.uint8) * 255
|
64 |
u2net_mask = cv2.resize(u2net_mask, (image_np.shape[1], image_np.shape[0]), interpolation=cv2.INTER_NEAREST)
|
65 |
|
66 |
-
# Combine
|
67 |
refined_mask = cv2.bitwise_and(mask, u2net_mask)
|
68 |
|
69 |
# Morphological operations for smoothness
|
@@ -73,15 +80,11 @@ def segment_dress(image_np):
|
|
73 |
|
74 |
return refined_mask
|
75 |
|
76 |
-
def recolor_dress(image_np, mask, target_color
|
77 |
-
"""Change dress color while
|
78 |
|
79 |
img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
|
80 |
target_color_lab = cv2.cvtColor(np.uint8([[target_color]]), cv2.COLOR_BGR2LAB)[0][0]
|
81 |
-
|
82 |
-
# Exclude design from recoloring
|
83 |
-
design_mask = (edges > 0).astype(np.uint8) * 255
|
84 |
-
mask = cv2.bitwise_and(mask, cv2.bitwise_not(design_mask))
|
85 |
|
86 |
# Preserve lightness (L) and change only chromatic channels (A & B)
|
87 |
blend_factor = 0.7
|
@@ -89,26 +92,27 @@ def recolor_dress(image_np, mask, target_color, edges):
|
|
89 |
img_lab[..., 2] = np.where(mask > 128, img_lab[..., 2] * (1 - blend_factor) + target_color_lab[2] * blend_factor, img_lab[..., 2])
|
90 |
|
91 |
img_recolored = cv2.cvtColor(img_lab, cv2.COLOR_LAB2RGB)
|
|
|
92 |
return img_recolored
|
93 |
|
94 |
-
def
|
95 |
-
"""
|
96 |
if image_path is None:
|
97 |
return None
|
98 |
|
99 |
img = Image.open(image_path).convert("RGB")
|
100 |
img_np = np.array(img)
|
101 |
|
102 |
-
#
|
103 |
-
|
104 |
|
105 |
# Get dress segmentation mask
|
106 |
mask = segment_dress(img_np)
|
107 |
|
108 |
if mask is None:
|
109 |
-
return
|
110 |
-
|
111 |
-
# Convert
|
112 |
color_map = {
|
113 |
"Red": (0, 0, 255), "Blue": (255, 0, 0), "Green": (0, 255, 0), "Yellow": (0, 255, 255),
|
114 |
"Purple": (128, 0, 128), "Orange": (0, 165, 255), "Cyan": (255, 255, 0), "Magenta": (255, 0, 255),
|
@@ -116,26 +120,21 @@ def change_dress_color(image_path, color):
|
|
116 |
}
|
117 |
new_color_bgr = np.array(color_map.get(color, (0, 0, 255)), dtype=np.uint8) # Default to Red
|
118 |
|
119 |
-
# Apply recoloring
|
120 |
-
|
121 |
-
print("Design detected! Coloring only non-design areas.")
|
122 |
-
img_recolored = recolor_dress(img_np, mask, new_color_bgr, edges)
|
123 |
-
else:
|
124 |
-
print("No design detected. Coloring entire dress.")
|
125 |
-
img_recolored = recolor_dress(img_np, mask, new_color_bgr, np.zeros_like(mask)) # No design mask
|
126 |
|
127 |
return Image.fromarray(img_recolored)
|
128 |
|
129 |
# Gradio Interface
|
130 |
demo = gr.Interface(
|
131 |
-
fn=
|
132 |
inputs=[
|
133 |
gr.Image(type="filepath", label="Upload Dress Image"),
|
134 |
gr.Radio(["Red", "Blue", "Green", "Yellow", "Purple", "Orange", "Cyan", "Magenta", "White", "Black"], label="Choose New Dress Color")
|
135 |
],
|
136 |
-
outputs=gr.Image(type="pil", label="
|
137 |
-
title="Dress Color Changer",
|
138 |
-
description="Upload an image of a dress
|
139 |
)
|
140 |
|
141 |
if __name__ == "__main__":
|
|
|
14 |
model.load_state_dict(state_dict)
|
15 |
model.eval()
|
16 |
|
17 |
+
def remove_background(image_np):
|
18 |
+
"""Removes background using U²-Net and replaces it with white."""
|
19 |
+
|
20 |
+
transform_pipeline = transforms.Compose([
|
21 |
+
transforms.ToTensor(),
|
22 |
+
transforms.Resize((320, 320))
|
23 |
+
])
|
24 |
+
|
25 |
+
image = Image.fromarray(image_np).convert("RGB")
|
26 |
+
input_tensor = transform_pipeline(image).unsqueeze(0)
|
27 |
|
28 |
+
with torch.no_grad():
|
29 |
+
output = model(input_tensor)[0][0].squeeze().cpu().numpy()
|
30 |
+
|
31 |
+
mask = (output > 0.5).astype(np.uint8) * 255
|
32 |
+
mask = cv2.resize(mask, (image_np.shape[1], image_np.shape[0]), interpolation=cv2.INTER_NEAREST)
|
33 |
|
34 |
+
white_bg = np.ones_like(image_np) * 255 # White background
|
35 |
+
segmented_image = np.where(mask[..., None] > 128, image_np, white_bg)
|
36 |
|
37 |
+
return segmented_image, mask
|
38 |
|
39 |
def segment_dress(image_np):
|
40 |
+
"""Segments the dress using K-means and refines with U²-Net."""
|
41 |
|
42 |
+
# Convert to Lab color space
|
43 |
img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
|
|
|
|
|
|
|
44 |
pixel_values = img_lab.reshape((-1, 3)).astype(np.float32)
|
45 |
+
|
46 |
+
# K-means clustering to detect dress region
|
47 |
k = 3 # Three clusters: background, skin, dress
|
48 |
_, labels, centers = cv2.kmeans(pixel_values, k, None, (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0), 10, cv2.KMEANS_RANDOM_CENTERS)
|
49 |
labels = labels.reshape(image_np.shape[:2])
|
|
|
55 |
# Create dress mask
|
56 |
mask = (labels == dress_label).astype(np.uint8) * 255
|
57 |
|
58 |
+
# Refine with U²-Net prediction
|
59 |
transform_pipeline = transforms.Compose([
|
60 |
transforms.ToTensor(),
|
61 |
transforms.Resize((320, 320))
|
|
|
70 |
u2net_mask = (output > 0.5).astype(np.uint8) * 255
|
71 |
u2net_mask = cv2.resize(u2net_mask, (image_np.shape[1], image_np.shape[0]), interpolation=cv2.INTER_NEAREST)
|
72 |
|
73 |
+
# Combine masks
|
74 |
refined_mask = cv2.bitwise_and(mask, u2net_mask)
|
75 |
|
76 |
# Morphological operations for smoothness
|
|
|
80 |
|
81 |
return refined_mask
|
82 |
|
83 |
+
def recolor_dress(image_np, mask, target_color):
|
84 |
+
"""Change dress color while keeping the white background intact."""
|
85 |
|
86 |
img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
|
87 |
target_color_lab = cv2.cvtColor(np.uint8([[target_color]]), cv2.COLOR_BGR2LAB)[0][0]
|
|
|
|
|
|
|
|
|
88 |
|
89 |
# Preserve lightness (L) and change only chromatic channels (A & B)
|
90 |
blend_factor = 0.7
|
|
|
92 |
img_lab[..., 2] = np.where(mask > 128, img_lab[..., 2] * (1 - blend_factor) + target_color_lab[2] * blend_factor, img_lab[..., 2])
|
93 |
|
94 |
img_recolored = cv2.cvtColor(img_lab, cv2.COLOR_LAB2RGB)
|
95 |
+
|
96 |
return img_recolored
|
97 |
|
98 |
+
def process_image(image_path, color):
|
99 |
+
"""Remove background, segment dress, and recolor while keeping background white."""
|
100 |
if image_path is None:
|
101 |
return None
|
102 |
|
103 |
img = Image.open(image_path).convert("RGB")
|
104 |
img_np = np.array(img)
|
105 |
|
106 |
+
# Remove background
|
107 |
+
img_segmented, _ = remove_background(img_np)
|
108 |
|
109 |
# Get dress segmentation mask
|
110 |
mask = segment_dress(img_np)
|
111 |
|
112 |
if mask is None:
|
113 |
+
return Image.fromarray(img_segmented) # No dress detected, return only background removal
|
114 |
+
|
115 |
+
# Convert selected color to BGR
|
116 |
color_map = {
|
117 |
"Red": (0, 0, 255), "Blue": (255, 0, 0), "Green": (0, 255, 0), "Yellow": (0, 255, 255),
|
118 |
"Purple": (128, 0, 128), "Orange": (0, 165, 255), "Cyan": (255, 255, 0), "Magenta": (255, 0, 255),
|
|
|
120 |
}
|
121 |
new_color_bgr = np.array(color_map.get(color, (0, 0, 255)), dtype=np.uint8) # Default to Red
|
122 |
|
123 |
+
# Apply recoloring
|
124 |
+
img_recolored = recolor_dress(img_segmented, mask, new_color_bgr)
|
|
|
|
|
|
|
|
|
|
|
125 |
|
126 |
return Image.fromarray(img_recolored)
|
127 |
|
128 |
# Gradio Interface
|
129 |
demo = gr.Interface(
|
130 |
+
fn=process_image,
|
131 |
inputs=[
|
132 |
gr.Image(type="filepath", label="Upload Dress Image"),
|
133 |
gr.Radio(["Red", "Blue", "Green", "Yellow", "Purple", "Orange", "Cyan", "Magenta", "White", "Black"], label="Choose New Dress Color")
|
134 |
],
|
135 |
+
outputs=gr.Image(type="pil", label="Final Dress Image"),
|
136 |
+
title="Dress Color Changer with Background Removal",
|
137 |
+
description="Upload an image of a dress, remove its background, and recolor it naturally while keeping the background white."
|
138 |
)
|
139 |
|
140 |
if __name__ == "__main__":
|