Saad0KH commited on
Commit
c11222a
Β·
verified Β·
1 Parent(s): 871269e

Update SegCloth.py

Browse files
Files changed (1) hide show
  1. SegCloth.py +20 -27
SegCloth.py CHANGED
@@ -4,7 +4,6 @@ import numpy as np
4
  from io import BytesIO
5
  import io
6
  import base64
7
-
8
  # Initialize segmentation pipeline
9
  segmenter = pipeline(model="mattmdjaga/segformer_b2_clothes")
10
 
@@ -14,36 +13,30 @@ def encode_image_to_base64(image):
14
  image.save(buffered, format="PNG")
15
  return base64.b64encode(buffered.getvalue()).decode('utf-8')
16
 
17
-
18
- def segment_clothing(img, clothes= ["Hat", "Upper-clothes", "Skirt", "Pants", "Dress", "Belt", "Left-shoe", "Right-shoe", "Scarf"]):
19
  # Segment image
20
  segments = segmenter(img)
21
 
22
- # List to hold the results
23
- results = []
24
 
25
- # Process each segment
26
  for s in segments:
27
  if s['label'] in clothes:
28
- # Create a blank image with the same size as the original
29
- clothing_image = Image.new("RGBA", img.size, (0, 0, 0, 0))
30
-
31
- # Apply the mask to the new image
32
  mask = np.array(s['mask'])
33
- mask_image = Image.fromarray(mask * 255) # Convert mask to 255 range for alpha channel
34
-
35
- # Paste mask onto the blank image
36
- clothing_image.paste(img, mask=mask_image)
37
-
38
- # Convert image to base64
39
- image_base64 = encode_image_to_base64(clothing_image)
40
-
41
- # Add to results list
42
- results.append({
43
- "type": s['label'],
44
- "image_base64": image_base64
45
- })
46
-
47
- return results
48
-
49
-
 
4
  from io import BytesIO
5
  import io
6
  import base64
 
7
  # Initialize segmentation pipeline
8
  segmenter = pipeline(model="mattmdjaga/segformer_b2_clothes")
9
 
 
13
  image.save(buffered, format="PNG")
14
  return base64.b64encode(buffered.getvalue()).decode('utf-8')
15
 
16
+ def segment_clothing(img, clothes=["Hat", "Upper-clothes", "Skirt", "Pants", "Dress", "Belt", "Left-shoe", "Right-shoe", "Scarf"]):
 
17
  # Segment image
18
  segments = segmenter(img)
19
 
20
+ # Dictionary to store masks for each clothing type
21
+ masks = {clothing_type: None for clothing_type in clothes}
22
 
23
+ # Create individual masks for each clothing type
24
  for s in segments:
25
  if s['label'] in clothes:
 
 
 
 
26
  mask = np.array(s['mask'])
27
+ if masks[s['label']] is None:
28
+ masks[s['label']] = mask
29
+ else:
30
+ masks[s['label']] += mask
31
+
32
+ # Create and save images for each clothing type
33
+ result_images = []
34
+ for clothing_type, mask in masks.items():
35
+ if mask is not None:
36
+ final_mask = Image.fromarray(np.uint8(mask * 255)) # Normalize mask to 0-255 range
37
+ result_image = img.copy()
38
+ result_image.putalpha(final_mask)
39
+ imageBase64 = encode_image_to_base64(result_image)
40
+ result_images.append((clothing_type, imageBase64))
41
+
42
+ return result_images