gaur3009 commited on
Commit
9cebca9
·
verified ·
1 Parent(s): bb4e136

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -64
app.py CHANGED
@@ -7,103 +7,74 @@ from torchvision import transforms
7
  from cloth_segmentation.networks.u2net import U2NET # Import U²-Net
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()} # Remove 'module.' prefix
14
  model.load_state_dict(state_dict)
15
  model.eval()
16
 
17
  def segment_dress(image_np):
18
- """Segment the dress using U²-Net & refine with Lab color space."""
19
-
20
- # Convert to Lab space
21
- img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
22
- L, A, B = cv2.split(img_lab)
23
-
24
- # Use K-means clustering to detect dominant dress region
25
- pixel_values = img_lab.reshape((-1, 3)).astype(np.float32)
26
- k = 3 # Three clusters: background, skin, dress
27
- _, 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)
28
- labels = labels.reshape(image_np.shape[:2])
29
-
30
- # Assume dress is the largest non-background cluster
31
- unique_labels, counts = np.unique(labels, return_counts=True)
32
- dress_label = unique_labels[np.argmax(counts[1:]) + 1] # Avoid background
33
-
34
- # Create dress mask
35
- mask = (labels == dress_label).astype(np.uint8) * 255
36
-
37
- # Use U²-Net prediction to refine segmentation
38
  transform_pipeline = transforms.Compose([
39
  transforms.ToTensor(),
40
  transforms.Resize((320, 320))
41
  ])
42
-
43
  image = Image.fromarray(image_np).convert("RGB")
44
  input_tensor = transform_pipeline(image).unsqueeze(0)
45
-
46
  with torch.no_grad():
47
  output = model(input_tensor)[0][0].squeeze().cpu().numpy()
48
-
49
- u2net_mask = (output > 0.5).astype(np.uint8) * 255
50
- u2net_mask = cv2.resize(u2net_mask, (image_np.shape[1], image_np.shape[0]), interpolation=cv2.INTER_NEAREST)
51
 
52
- # Combine K-means and U²-Net masks
53
- refined_mask = cv2.bitwise_and(mask, u2net_mask)
54
-
55
- # Morphological operations for smoothness
56
- kernel = np.ones((5, 5), np.uint8)
57
- refined_mask = cv2.morphologyEx(refined_mask, cv2.MORPH_CLOSE, kernel)
58
- refined_mask = cv2.GaussianBlur(refined_mask, (15, 15), 5)
59
 
60
- return refined_mask
61
-
62
- def detect_design(image_np):
63
- """Detects design patterns on the dress using edge detection."""
64
- gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
65
- edges = cv2.Canny(gray, 50, 150)
66
- kernel = np.ones((3, 3), np.uint8)
67
- design_mask = cv2.dilate(edges, kernel, iterations=2)
68
- return design_mask
69
-
70
- def recolor_dress(image_np, mask, design_mask, target_color):
71
- """Change dress color while preserving texture and design."""
72
 
73
- img_lab = cv2.cvtColor(image_np, cv2.COLOR_RGB2LAB)
74
- target_color_lab = cv2.cvtColor(np.uint8([[target_color]]), cv2.COLOR_BGR2LAB)[0][0]
 
 
75
 
76
- # Preserve lightness (L) and change only chromatic channels (A & B)
77
- blend_factor = 0.7
78
- img_lab[..., 1] = np.where((mask > 128) & (design_mask == 0), img_lab[..., 1] * (1 - blend_factor) + target_color_lab[1] * blend_factor, img_lab[..., 1])
79
- img_lab[..., 2] = np.where((mask > 128) & (design_mask == 0), img_lab[..., 2] * (1 - blend_factor) + target_color_lab[2] * blend_factor, img_lab[..., 2])
80
-
81
- img_recolored = cv2.cvtColor(img_lab, cv2.COLOR_LAB2RGB)
82
- return img_recolored
83
 
84
  def change_dress_color(image_path, color):
85
- """Change the dress color naturally while keeping textures and design."""
86
  if image_path is None:
87
  return None
88
 
89
  img = Image.open(image_path).convert("RGB")
90
  img_np = np.array(img)
91
  mask = segment_dress(img_np)
92
- design_mask = detect_design(img_np)
93
-
94
  if mask is None:
95
  return img # No dress detected
96
 
97
  # Convert the selected color to BGR
98
  color_map = {
99
- "Red": (0, 0, 255), "Blue": (255, 0, 0), "Green": (0, 255, 0), "Yellow": (0, 255, 255),
100
- "Purple": (128, 0, 128), "Orange": (0, 165, 255), "Cyan": (255, 255, 0), "Magenta": (255, 0, 255),
101
- "White": (255, 255, 255), "Black": (0, 0, 0)
 
 
102
  }
103
  new_color_bgr = np.array(color_map.get(color, (0, 0, 255)), dtype=np.uint8) # Default to Red
104
 
105
- # Recolor the dress naturally while preserving design
106
- img_recolored = recolor_dress(img_np, mask, design_mask, new_color_bgr)
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  return Image.fromarray(img_recolored)
109
 
@@ -112,11 +83,11 @@ demo = gr.Interface(
112
  fn=change_dress_color,
113
  inputs=[
114
  gr.Image(type="filepath", label="Upload Dress Image"),
115
- gr.Radio(["Red", "Blue", "Green", "Yellow", "Purple", "Orange", "Cyan", "Magenta", "White", "Black"], label="Choose New Dress Color")
116
  ],
117
  outputs=gr.Image(type="pil", label="Color Changed Dress"),
118
  title="Dress Color Changer",
119
- description="Upload an image of a dress and select a new color to change its appearance naturally while preserving any design patterns."
120
  )
121
 
122
  if __name__ == "__main__":
 
7
  from cloth_segmentation.networks.u2net import U2NET # Import U²-Net
8
 
9
  # Load U²-Net model
10
+ model_path = "cloth_segmentation/networks/u2net.pth" # Ensure this path is correct
11
  model = U2NET(3, 1)
12
+
13
+ # Load the state dictionary
14
  state_dict = torch.load(model_path, map_location=torch.device('cpu'))
15
  state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()} # Remove 'module.' prefix
16
  model.load_state_dict(state_dict)
17
  model.eval()
18
 
19
  def segment_dress(image_np):
20
+ """Segment the dress from the image using U²-Net and refine the mask."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  transform_pipeline = transforms.Compose([
22
  transforms.ToTensor(),
23
  transforms.Resize((320, 320))
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 # Binary mask
 
 
 
 
 
 
32
 
33
+ # Resize mask to original image size
34
+ mask = cv2.resize(mask, (image_np.shape[1], image_np.shape[0]), interpolation=cv2.INTER_NEAREST)
 
 
 
 
 
 
 
 
 
 
35
 
36
+ # Apply morphological operations for better segmentation
37
+ kernel = np.ones((7, 7), np.uint8)
38
+ mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # Close small gaps
39
+ mask = cv2.dilate(mask, kernel, iterations=2) # Expand the detected dress area
40
 
41
+ return mask
 
 
 
 
 
 
42
 
43
  def change_dress_color(image_path, color):
44
+ """Change the dress color naturally while keeping textures."""
45
  if image_path is None:
46
  return None
47
 
48
  img = Image.open(image_path).convert("RGB")
49
  img_np = np.array(img)
50
  mask = segment_dress(img_np)
51
+
 
52
  if mask is None:
53
  return img # No dress detected
54
 
55
  # Convert the selected color to BGR
56
  color_map = {
57
+ "Red": (0, 0, 255),
58
+ "Blue": (255, 0, 0),
59
+ "Green": (0, 255, 0),
60
+ "Yellow": (0, 255, 255),
61
+ "Purple": (128, 0, 128)
62
  }
63
  new_color_bgr = np.array(color_map.get(color, (0, 0, 255)), dtype=np.uint8) # Default to Red
64
 
65
+ # Convert image to LAB color space for better blending
66
+ img_lab = cv2.cvtColor(img_np, cv2.COLOR_RGB2LAB)
67
+ new_color_lab = cv2.cvtColor(np.uint8([[new_color_bgr]]), cv2.COLOR_BGR2LAB)[0][0]
68
+
69
+ # Preserve texture by only modifying the A & B channels
70
+ img_lab[..., 1] = np.where(mask == 255, new_color_lab[1], img_lab[..., 1]) # Modify A-channel
71
+ img_lab[..., 2] = np.where(mask == 255, new_color_lab[2], img_lab[..., 2]) # Modify B-channel
72
+
73
+ # Convert back to RGB
74
+ img_recolored = cv2.cvtColor(img_lab, cv2.COLOR_LAB2RGB)
75
+
76
+ # Apply Poisson blending for realistic color application
77
+ img_recolored = cv2.seamlessClone(img_recolored, img_np, mask, (img_np.shape[1]//2, img_np.shape[0]//2), cv2.NORMAL_CLONE)
78
 
79
  return Image.fromarray(img_recolored)
80
 
 
83
  fn=change_dress_color,
84
  inputs=[
85
  gr.Image(type="filepath", label="Upload Dress Image"),
86
+ gr.Radio(["Red", "Blue", "Green", "Yellow", "Purple"], label="Choose New Dress Color")
87
  ],
88
  outputs=gr.Image(type="pil", label="Color Changed Dress"),
89
  title="Dress Color Changer",
90
+ description="Upload an image of a dress and select a new color to change its appearance naturally."
91
  )
92
 
93
  if __name__ == "__main__":