Spaces:
Runtime error
Runtime error
Update SegCloth.py
Browse files- 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 |
-
#
|
23 |
-
|
24 |
|
25 |
-
#
|
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 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
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
|
|