gaur3009 commited on
Commit
0c481b6
·
verified ·
1 Parent(s): 737e59f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -77
app.py CHANGED
@@ -5,81 +5,68 @@ 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 refine_mask(mask):
18
- """Enhanced mask refinement with erosion and morphological operations"""
19
- # First closing to fill small holes
20
  close_kernel = np.ones((5, 5), np.uint8)
21
  mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, close_kernel)
22
-
23
- # Erosion to remove small protrusions and extra areas
24
  erode_kernel = np.ones((3, 3), np.uint8)
25
  mask = cv2.erode(mask, erode_kernel, iterations=1)
26
-
27
- # Second closing to refine edges after erosion
28
  mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, close_kernel)
29
-
30
- # Final blur to smooth edges while preserving shape
31
- mask = cv2.GaussianBlur(mask, (5, 5), 1.5)
32
-
33
- return mask
34
 
 
35
  def segment_dress(image_np):
36
- """Improved dress segmentation with adaptive thresholding"""
37
  transform_pipeline = transforms.Compose([
38
  transforms.ToTensor(),
39
  transforms.Resize((320, 320))
40
  ])
41
-
42
  image = Image.fromarray(image_np).convert("RGB")
43
  input_tensor = transform_pipeline(image).unsqueeze(0)
44
 
45
  with torch.no_grad():
46
  output = model(input_tensor)[0][0].squeeze().cpu().numpy()
47
 
48
- # Adaptive threshold calculation
49
  output = (output - output.min()) / (output.max() - output.min() + 1e-8)
50
- adaptive_thresh = np.mean(output) + 0.2 # Increased threshold for tighter mask
51
  dress_mask = (output > adaptive_thresh).astype(np.uint8) * 255
52
-
53
- # Preserve hard edges during resize
54
- dress_mask = cv2.resize(dress_mask, (image_np.shape[1], image_np.shape[0]),
55
- interpolation=cv2.INTER_NEAREST)
56
-
57
- return refine_mask(dress_mask)
58
 
 
59
  def apply_grabcut(image_np, dress_mask):
60
- """Mask refinement using GrabCut"""
61
  bgd_model = np.zeros((1, 65), np.float64)
62
  fgd_model = np.zeros((1, 65), np.float64)
63
-
64
  mask = np.where(dress_mask > 0, cv2.GC_PR_FGD, cv2.GC_BGD).astype('uint8')
65
-
66
- # Get bounding box coordinates
67
  coords = cv2.findNonZero(dress_mask)
68
  if coords is not None:
69
  x, y, w, h = cv2.boundingRect(coords)
70
  rect = (x, y, w, h)
71
  cv2.grabCut(image_np, mask, rect, bgd_model, fgd_model, 3, cv2.GC_INIT_WITH_MASK)
72
-
73
- refined_mask = np.where((mask == cv2.GC_FGD) | (mask == cv2.GC_PR_FGD), 255, 0).astype("uint8")
74
- return refine_mask(refined_mask)
75
 
 
76
  def recolor_dress(image_np, dress_mask, target_color):
77
- """Color transformation with improved blending"""
78
- # Convert colors to LAB space
79
  target_color_lab = cv2.cvtColor(np.uint8([[target_color]]), cv2.COLOR_BGR2LAB)[0][0]
80
  img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
81
 
82
- # Calculate color shifts
83
  dress_pixels = img_lab[dress_mask > 0]
84
  if len(dress_pixels) == 0:
85
  return image_np
@@ -88,71 +75,50 @@ def recolor_dress(image_np, dress_mask, target_color):
88
  a_shift = target_color_lab[1] - mean_A
89
  b_shift = target_color_lab[2] - mean_B
90
 
91
- # Apply color transformation
92
  img_lab[..., 1] = np.clip(img_lab[..., 1] + (dress_mask / 255.0) * a_shift, 0, 255)
93
  img_lab[..., 2] = np.clip(img_lab[..., 2] + (dress_mask / 255.0) * b_shift, 0, 255)
94
 
95
- # Create adaptive blending mask
96
  img_recolored = cv2.cvtColor(img_lab.astype(np.uint8), cv2.COLOR_LAB2RGB)
97
  feathered_mask = cv2.GaussianBlur(dress_mask, (21, 21), 7)
98
  lightness_mask = (img_lab[..., 0] / 255.0) ** 0.7
99
  adaptive_feather = (feathered_mask * lightness_mask).astype(np.uint8)
100
 
101
- # Smooth blending
102
- return (image_np * (1 - adaptive_feather[..., None]/255) + img_recolored * (adaptive_feather[..., None]/255)).astype(np.uint8)
103
-
104
- def change_dress_color(img, color):
105
- """Main processing function with error handling"""
106
- if img is None:
107
- return None
108
-
109
- color_map = {
110
- "Red": (0, 0, 255), "Blue": (255, 0, 0), "Green": (0, 255, 0),
111
- "Yellow": (0, 255, 255), "Purple": (128, 0, 128), "Orange": (0, 165, 255),
112
- "Cyan": (255, 255, 0), "Magenta": (255, 0, 255), "White": (255, 255, 255),
113
- "Black": (0, 0, 0)
114
- }
115
-
116
- new_color_bgr = color_map.get(color, (0, 0, 255))
117
  img_np = np.array(img)
118
-
 
119
  try:
120
  dress_mask = segment_dress(img_np)
121
- if np.sum(dress_mask) < 1000: # Minimum mask area threshold
122
  return img
123
-
124
  dress_mask = apply_grabcut(img_np, dress_mask)
125
- img_recolored = recolor_dress(img_np, dress_mask, new_color_bgr)
126
  return Image.fromarray(img_recolored)
127
-
128
  except Exception as e:
129
- print(f"Error processing image: {str(e)}")
130
  return img
131
 
132
- # Gradio Interface
133
  with gr.Blocks() as demo:
134
- gr.Markdown("# AI Dress Color Changer")
135
- gr.Markdown("Upload a dress image and select a new color for realistic recoloring")
136
-
137
  with gr.Row():
138
  with gr.Column():
139
- input_image = gr.Image(type="pil", label="Input Image", image_mode = "RGB")
140
- color_choice = gr.Dropdown(
141
- choices=["Red", "Blue", "Green", "Yellow", "Purple",
142
- "Orange", "Cyan", "Magenta", "White", "Black"],
143
- value="Red",
144
- label="Select New Color"
145
- )
146
- process_btn = gr.Button("Recolor Dress")
147
-
148
  with gr.Column():
149
- output_image = gr.Image(type="pil", label="Result", image_mode = "RGB")
150
 
151
- process_btn.click(
152
- fn=change_dress_color,
153
- inputs=[input_image, color_choice],
154
- outputs=output_image
155
- )
156
 
157
  if __name__ == "__main__":
158
  demo.launch()
 
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
 
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()