Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,43 +1,47 @@
|
|
1 |
-
from
|
2 |
from PIL import Image
|
3 |
-
import
|
4 |
from io import BytesIO
|
5 |
-
import
|
6 |
-
from SegCloth import segment_clothing
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
# Créer une instance FastAPI
|
11 |
-
app = Flask(__name__)
|
12 |
-
|
13 |
-
def segment_image(img, clothes):
|
14 |
-
img = decode_image_from_base64(img)
|
15 |
-
return segment_clothing(img, clothes)
|
16 |
|
17 |
-
#
|
18 |
-
|
19 |
-
image_data = base64.b64decode(image_data)
|
20 |
-
image = Image.open(io.BytesIO(image_data))
|
21 |
-
return image
|
22 |
|
23 |
def encode_image_to_base64(image):
|
24 |
buffered = BytesIO()
|
25 |
image.save(buffered, format="PNG")
|
26 |
return base64.b64encode(buffered.getvalue()).decode('utf-8')
|
27 |
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
#
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import pipeline
|
2 |
from PIL import Image
|
3 |
+
import numpy as np
|
4 |
from io import BytesIO
|
5 |
+
import base64
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
# Initialize segmentation pipeline
|
8 |
+
segmenter = pipeline(model="mattmdjaga/segformer_b2_clothes")
|
|
|
|
|
|
|
9 |
|
10 |
def encode_image_to_base64(image):
|
11 |
buffered = BytesIO()
|
12 |
image.save(buffered, format="PNG")
|
13 |
return base64.b64encode(buffered.getvalue()).decode('utf-8')
|
14 |
|
15 |
+
def segment_clothing(img, clothes=["Hat", "Upper-clothes", "Skirt", "Pants", "Dress", "Belt", "Left-shoe", "Right-shoe", "Scarf"]):
|
16 |
+
# Segment image
|
17 |
+
segments = segmenter(img)
|
18 |
+
|
19 |
+
# Convert image to RGBA
|
20 |
+
img = img.convert("RGBA")
|
21 |
+
|
22 |
+
# Create list of masks
|
23 |
+
result_images = []
|
24 |
+
for s in segments:
|
25 |
+
if s['label'] in clothes:
|
26 |
+
# Extract mask and resize image to mask size
|
27 |
+
current_mask = np.array(s['mask'])
|
28 |
+
mask_size = current_mask.shape[::-1] # Mask size is (width, height)
|
29 |
+
|
30 |
+
# Resize the original image to match the mask size
|
31 |
+
resized_img = img.resize(mask_size)
|
32 |
+
|
33 |
+
# Apply mask to resized image
|
34 |
+
final_mask = Image.fromarray(current_mask)
|
35 |
+
resized_img.putalpha(final_mask)
|
36 |
+
|
37 |
+
# Convert the final image to base64
|
38 |
+
imageBase64 = encode_image_to_base64(resized_img)
|
39 |
+
result_images.append((s['label'], imageBase64))
|
40 |
+
|
41 |
+
return result_images
|
42 |
+
|
43 |
+
# Example usage
|
44 |
+
# img = Image.open('your_image_path_here.png')
|
45 |
+
# result_images = segment_clothing(img)
|
46 |
+
# for clothing_type, image_base64 in result_images:
|
47 |
+
# print(clothing_type, image_base64)
|