Create utils/preprocessing.py
Browse files- utils/preprocessing.py +34 -0
utils/preprocessing.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
from rembg import remove
|
4 |
+
from ultralytics import YOLO
|
5 |
+
|
6 |
+
class ImageProcessor:
|
7 |
+
def __init__(self, model_path):
|
8 |
+
self.model = YOLO(model_path)
|
9 |
+
self.class_names = {0: "upper_clothes", 1: "lower_clothes"}
|
10 |
+
|
11 |
+
def remove_background(self, image_bytes):
|
12 |
+
return remove(image_bytes)
|
13 |
+
|
14 |
+
def process_image(self, image_bytes):
|
15 |
+
# Background removal
|
16 |
+
bg_removed = self.remove_background(image_bytes)
|
17 |
+
|
18 |
+
# Convert to OpenCV format
|
19 |
+
nparr = np.frombuffer(bg_removed, np.uint8)
|
20 |
+
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
21 |
+
|
22 |
+
# Segmentation
|
23 |
+
results = self.model.predict(img)
|
24 |
+
return self._process_masks(results, img)
|
25 |
+
|
26 |
+
def _process_masks(self, results, img):
|
27 |
+
segmented = {}
|
28 |
+
if results[0].masks is not None:
|
29 |
+
for mask, class_id in zip(results[0].masks.data, results[0].boxes.cls):
|
30 |
+
class_id = int(class_id.item())
|
31 |
+
mask_np = mask.cpu().numpy()
|
32 |
+
# ... [your mask processing logic here] ...
|
33 |
+
segmented[self.class_names[class_id]] = processed_mask
|
34 |
+
return segmented
|