Saad0KH commited on
Commit
8f2a481
Β·
verified Β·
1 Parent(s): 8b5ea58

Create SegCloth.py

Browse files
Files changed (1) hide show
  1. SegCloth.py +63 -0
SegCloth.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+ from PIL import Image
3
+ import numpy as np
4
+ import io
5
+ import base64
6
+
7
+ # Initialize segmentation pipeline
8
+ segmenter = pipeline(model="mattmdjaga/segformer_b2_clothes")
9
+
10
+ def image_to_base64(img):
11
+ buffered = io.BytesIO()
12
+ img.save(buffered, format="PNG")
13
+ img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
14
+ return img_str
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
+ # List to hold the results
21
+ results = []
22
+
23
+ # Process each segment
24
+ for s in segments:
25
+ if s['label'] in clothes:
26
+ # Convert mask to array
27
+ mask = np.array(s['mask'])
28
+
29
+ # Find bounding box of the mask
30
+ y_nonzero, x_nonzero = np.nonzero(mask)
31
+ if len(x_nonzero) == 0 or len(y_nonzero) == 0:
32
+ continue
33
+ min_x, max_x = np.min(x_nonzero), np.max(x_nonzero)
34
+ min_y, max_y = np.min(y_nonzero), np.max(y_nonzero)
35
+
36
+ # Crop mask and original image to the bounding box
37
+ cropped_mask = mask[min_y:max_y+1, min_x:max_x+1]
38
+ cropped_image = img.crop((min_x, min_y, max_x+1, max_y+1))
39
+
40
+ # Create an image with the same size as the bounding box
41
+ clothing_image = Image.new("RGBA", (max_x - min_x + 1, max_y - min_y + 1), (0, 0, 0, 0))
42
+
43
+ # Apply the mask to the new image
44
+ mask_image = Image.fromarray(cropped_mask * 255) # Convert mask to 255 range for alpha channel
45
+
46
+ # Paste cropped image onto the blank image using the mask
47
+ clothing_image.paste(cropped_image, mask=mask_image)
48
+
49
+ # Convert image to base64
50
+ image_base64 = image_to_base64(clothing_image)
51
+
52
+ # Add to results list
53
+ results.append({
54
+ "type": s['label'],
55
+ "image_base64": image_base64
56
+ })
57
+
58
+ return results
59
+
60
+ # Example usage
61
+ # img = Image.open("path_to_your_image.jpg")
62
+ # results = segment_clothing(img)
63
+ # print(results)