Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -4,51 +4,18 @@ import torch
|
|
4 |
import cv2
|
5 |
from PIL import Image
|
6 |
from torchvision import transforms
|
7 |
-
from cloth_segmentation.networks.u2net import U2NET
|
8 |
|
9 |
-
# Load U²-Net
|
10 |
model_path = "cloth_segmentation/networks/u2net.pth"
|
11 |
model = U2NET(3, 1)
|
12 |
state_dict = torch.load(model_path, map_location=torch.device('cpu'))
|
13 |
-
state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()}
|
14 |
model.load_state_dict(state_dict)
|
15 |
model.eval()
|
16 |
|
17 |
-
def detect_design(image_np):
|
18 |
-
"""Detects if a design exists on the dress using edge detection & clustering."""
|
19 |
-
gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
|
20 |
-
edges = cv2.Canny(gray, 50, 150)
|
21 |
-
|
22 |
-
# Dilation to highlight patterns
|
23 |
-
kernel = np.ones((3, 3), np.uint8)
|
24 |
-
edges = cv2.dilate(edges, kernel, iterations=1)
|
25 |
-
|
26 |
-
# Count edge density
|
27 |
-
design_ratio = np.sum(edges > 0) / (image_np.shape[0] * image_np.shape[1])
|
28 |
-
|
29 |
-
return design_ratio > 0.02, edges # If edge density is high, assume a design is present
|
30 |
-
|
31 |
def segment_dress(image_np):
|
32 |
-
"""Segment the dress using U²-Net
|
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])
|
43 |
-
|
44 |
-
# Assume dress is the largest non-background cluster
|
45 |
-
unique_labels, counts = np.unique(labels, return_counts=True)
|
46 |
-
dress_label = unique_labels[np.argmax(counts[1:]) + 1] # Avoid background
|
47 |
-
|
48 |
-
# Create dress mask
|
49 |
-
mask = (labels == dress_label).astype(np.uint8) * 255
|
50 |
-
|
51 |
-
# Use U²-Net prediction to refine segmentation
|
52 |
transform_pipeline = transforms.Compose([
|
53 |
transforms.ToTensor(),
|
54 |
transforms.Resize((320, 320))
|
@@ -59,49 +26,48 @@ def segment_dress(image_np):
|
|
59 |
|
60 |
with torch.no_grad():
|
61 |
output = model(input_tensor)[0][0].squeeze().cpu().numpy()
|
62 |
-
|
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 K-means and U²-Net masks
|
67 |
-
refined_mask = cv2.bitwise_and(mask, u2net_mask)
|
68 |
|
69 |
-
#
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
|
|
73 |
|
74 |
-
|
|
|
|
|
|
|
75 |
|
76 |
-
def recolor_dress(image_np, mask, target_color
|
77 |
-
"""
|
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.
|
88 |
img_lab[..., 1] = np.where(mask > 128, img_lab[..., 1] * (1 - blend_factor) + target_color_lab[1] * blend_factor, img_lab[..., 1])
|
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 change_dress_color(image_path, color):
|
95 |
-
"""Change the dress color
|
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 |
-
# Detect if a design is present
|
103 |
-
design_present, edges = detect_design(img_np)
|
104 |
-
|
105 |
# Get dress segmentation mask
|
106 |
mask = segment_dress(img_np)
|
107 |
|
@@ -117,12 +83,7 @@ def change_dress_color(image_path, color):
|
|
117 |
new_color_bgr = np.array(color_map.get(color, (0, 0, 255)), dtype=np.uint8) # Default to Red
|
118 |
|
119 |
# Apply recoloring logic
|
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 |
|
|
|
4 |
import cv2
|
5 |
from PIL import Image
|
6 |
from torchvision import transforms
|
7 |
+
from cloth_segmentation.networks.u2net import U2NET
|
8 |
|
9 |
+
# Load U²-Net Model
|
10 |
model_path = "cloth_segmentation/networks/u2net.pth"
|
11 |
model = U2NET(3, 1)
|
12 |
state_dict = torch.load(model_path, map_location=torch.device('cpu'))
|
13 |
+
state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()}
|
14 |
model.load_state_dict(state_dict)
|
15 |
model.eval()
|
16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
def segment_dress(image_np):
|
18 |
+
"""Segment the dress using U²-Net and GrabCut."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
transform_pipeline = transforms.Compose([
|
20 |
transforms.ToTensor(),
|
21 |
transforms.Resize((320, 320))
|
|
|
26 |
|
27 |
with torch.no_grad():
|
28 |
output = model(input_tensor)[0][0].squeeze().cpu().numpy()
|
29 |
+
|
30 |
u2net_mask = (output > 0.5).astype(np.uint8) * 255
|
31 |
u2net_mask = cv2.resize(u2net_mask, (image_np.shape[1], image_np.shape[0]), interpolation=cv2.INTER_NEAREST)
|
|
|
|
|
|
|
32 |
|
33 |
+
# Apply GrabCut to refine the mask
|
34 |
+
mask = np.zeros(image_np.shape[:2], np.uint8)
|
35 |
+
mask[u2net_mask > 128] = cv2.GC_FGD
|
36 |
+
mask[u2net_mask <= 128] = cv2.GC_BGD
|
37 |
+
bg_model = np.zeros((1, 65), np.float64)
|
38 |
+
fg_model = np.zeros((1, 65), np.float64)
|
39 |
|
40 |
+
cv2.grabCut(image_np, mask, None, bg_model, fg_model, 5, cv2.GC_INIT_WITH_MASK)
|
41 |
+
mask = np.where((mask == 2) | (mask == 0), 0, 255).astype(np.uint8)
|
42 |
+
|
43 |
+
return mask
|
44 |
|
45 |
+
def recolor_dress(image_np, mask, target_color):
|
46 |
+
"""Recolor the dress while keeping texture, shadows, and designs."""
|
47 |
|
48 |
+
# Convert to LAB color space
|
49 |
img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
|
50 |
+
|
51 |
+
# Target color in LAB
|
52 |
target_color_lab = cv2.cvtColor(np.uint8([[target_color]]), cv2.COLOR_BGR2LAB)[0][0]
|
53 |
|
|
|
|
|
|
|
|
|
54 |
# Preserve lightness (L) and change only chromatic channels (A & B)
|
55 |
+
blend_factor = 0.8
|
56 |
img_lab[..., 1] = np.where(mask > 128, img_lab[..., 1] * (1 - blend_factor) + target_color_lab[1] * blend_factor, img_lab[..., 1])
|
57 |
img_lab[..., 2] = np.where(mask > 128, img_lab[..., 2] * (1 - blend_factor) + target_color_lab[2] * blend_factor, img_lab[..., 2])
|
58 |
|
59 |
+
# Convert back to RGB
|
60 |
img_recolored = cv2.cvtColor(img_lab, cv2.COLOR_LAB2RGB)
|
61 |
return img_recolored
|
62 |
|
63 |
def change_dress_color(image_path, color):
|
64 |
+
"""Change the dress color while preserving texture and design details."""
|
65 |
if image_path is None:
|
66 |
return None
|
67 |
|
68 |
img = Image.open(image_path).convert("RGB")
|
69 |
img_np = np.array(img)
|
70 |
|
|
|
|
|
|
|
71 |
# Get dress segmentation mask
|
72 |
mask = segment_dress(img_np)
|
73 |
|
|
|
83 |
new_color_bgr = np.array(color_map.get(color, (0, 0, 255)), dtype=np.uint8) # Default to Red
|
84 |
|
85 |
# Apply recoloring logic
|
86 |
+
img_recolored = recolor_dress(img_np, mask, new_color_bgr)
|
|
|
|
|
|
|
|
|
|
|
87 |
|
88 |
return Image.fromarray(img_recolored)
|
89 |
|