Alessio Grancini commited on
Commit
6490caa
·
verified ·
1 Parent(s): 864e7db

Update image_segmenter.py

Browse files
Files changed (1) hide show
  1. image_segmenter.py +3 -16
image_segmenter.py CHANGED
@@ -2,12 +2,11 @@ import cv2
2
  import numpy as np
3
  from ultralytics import YOLO
4
  import random
5
- import torch
6
  import spaces
7
 
8
  class ImageSegmenter:
9
  def __init__(self, model_type="yolov8s-seg") -> None:
10
- # Store parameters but don't initialize CUDA
11
  self.model_type = model_type
12
  self.is_show_bounding_boxes = True
13
  self.is_show_segmentation_boundary = False
@@ -17,13 +16,11 @@ class ImageSegmenter:
17
  self.bb_thickness = 2
18
  self.bb_clr = (255, 0, 0)
19
  self.masks = {}
20
- self.model = None # Model will be loaded in predict
21
 
22
  def get_cls_clr(self, cls_id):
23
  if cls_id in self.cls_clr:
24
  return self.cls_clr[cls_id]
25
-
26
- # gen rand color
27
  r = random.randint(50, 200)
28
  g = random.randint(50, 200)
29
  b = random.randint(50, 200)
@@ -32,11 +29,10 @@ class ImageSegmenter:
32
 
33
  @spaces.GPU
34
  def predict(self, image):
35
- # Load model if not loaded
36
  if self.model is None:
37
  print("Loading YOLO model...")
38
  self.model = YOLO('models/' + self.model_type + '.pt')
39
- self.model.to('cuda')
40
  print("Model loaded successfully")
41
 
42
  # params
@@ -48,7 +44,6 @@ class ImageSegmenter:
48
  bounding_boxes = predictions[0].boxes.xyxy.int().cpu().numpy()
49
  cls_conf = predictions[0].boxes.conf.cpu().numpy()
50
 
51
- # segmentation
52
  if predictions[0].masks:
53
  seg_mask_boundary = predictions[0].masks.xy
54
  seg_mask = predictions[0].masks.data.cpu().numpy()
@@ -58,27 +53,21 @@ class ImageSegmenter:
58
  for id, cls in enumerate(cls_ids):
59
  cls_clr = self.get_cls_clr(cls)
60
 
61
- # draw filled segmentation region
62
  if seg_mask.any() and cls_conf[id] > self.confidence_threshold:
63
  self.masks[id] = seg_mask[id]
64
 
65
  if self.is_show_segmentation:
66
  alpha = 0.8
67
-
68
- # converting the mask from 1 channel to 3 channels
69
  colored_mask = np.expand_dims(seg_mask[id], 0).repeat(3, axis=0)
70
  colored_mask = np.moveaxis(colored_mask, 0, -1)
71
 
72
- # Resize the mask to match the image size, if necessary
73
  if image.shape[:2] != seg_mask[id].shape[:2]:
74
  colored_mask = cv2.resize(colored_mask, (image.shape[1], image.shape[0]))
75
 
76
- # filling the mased area with class color
77
  masked = np.ma.MaskedArray(image, mask=colored_mask, fill_value=cls_clr)
78
  image_overlay = masked.filled()
79
  image = cv2.addWeighted(image, 1 - alpha, image_overlay, alpha, 0)
80
 
81
- # draw bounding box with class name and score
82
  if self.is_show_bounding_boxes and cls_conf[id] > self.confidence_threshold:
83
  (x1, y1, x2, y2) = bounding_boxes[id]
84
  cls_name = self.model.names[cls]
@@ -88,11 +77,9 @@ class ImageSegmenter:
88
  cv2.rectangle(image, (x1, y1), (x1+(len(disp_str)*9), y1+15), cls_clr, -1)
89
  cv2.putText(image, disp_str, (x1+5, y1+10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
90
 
91
- # draw segmentation boundary
92
  if len(seg_mask_boundary) and self.is_show_segmentation_boundary and cls_conf[id] > self.confidence_threshold:
93
  cv2.polylines(image, [np.array(seg_mask_boundary[id], dtype=np.int32)], isClosed=True, color=cls_clr, thickness=2)
94
 
95
- # object variables
96
  (x1, y1, x2, y2) = bounding_boxes[id]
97
  center = x1+(x2-x1)//2, y1+(y2-y1)//2
98
  objects_data.append([cls, self.model.names[cls], center, self.masks[id], cls_clr])
 
2
  import numpy as np
3
  from ultralytics import YOLO
4
  import random
 
5
  import spaces
6
 
7
  class ImageSegmenter:
8
  def __init__(self, model_type="yolov8s-seg") -> None:
9
+ # Don't initialize any CUDA/GPU stuff here
10
  self.model_type = model_type
11
  self.is_show_bounding_boxes = True
12
  self.is_show_segmentation_boundary = False
 
16
  self.bb_thickness = 2
17
  self.bb_clr = (255, 0, 0)
18
  self.masks = {}
19
+ self.model = None
20
 
21
  def get_cls_clr(self, cls_id):
22
  if cls_id in self.cls_clr:
23
  return self.cls_clr[cls_id]
 
 
24
  r = random.randint(50, 200)
25
  g = random.randint(50, 200)
26
  b = random.randint(50, 200)
 
29
 
30
  @spaces.GPU
31
  def predict(self, image):
32
+ # Initialize model if needed
33
  if self.model is None:
34
  print("Loading YOLO model...")
35
  self.model = YOLO('models/' + self.model_type + '.pt')
 
36
  print("Model loaded successfully")
37
 
38
  # params
 
44
  bounding_boxes = predictions[0].boxes.xyxy.int().cpu().numpy()
45
  cls_conf = predictions[0].boxes.conf.cpu().numpy()
46
 
 
47
  if predictions[0].masks:
48
  seg_mask_boundary = predictions[0].masks.xy
49
  seg_mask = predictions[0].masks.data.cpu().numpy()
 
53
  for id, cls in enumerate(cls_ids):
54
  cls_clr = self.get_cls_clr(cls)
55
 
 
56
  if seg_mask.any() and cls_conf[id] > self.confidence_threshold:
57
  self.masks[id] = seg_mask[id]
58
 
59
  if self.is_show_segmentation:
60
  alpha = 0.8
 
 
61
  colored_mask = np.expand_dims(seg_mask[id], 0).repeat(3, axis=0)
62
  colored_mask = np.moveaxis(colored_mask, 0, -1)
63
 
 
64
  if image.shape[:2] != seg_mask[id].shape[:2]:
65
  colored_mask = cv2.resize(colored_mask, (image.shape[1], image.shape[0]))
66
 
 
67
  masked = np.ma.MaskedArray(image, mask=colored_mask, fill_value=cls_clr)
68
  image_overlay = masked.filled()
69
  image = cv2.addWeighted(image, 1 - alpha, image_overlay, alpha, 0)
70
 
 
71
  if self.is_show_bounding_boxes and cls_conf[id] > self.confidence_threshold:
72
  (x1, y1, x2, y2) = bounding_boxes[id]
73
  cls_name = self.model.names[cls]
 
77
  cv2.rectangle(image, (x1, y1), (x1+(len(disp_str)*9), y1+15), cls_clr, -1)
78
  cv2.putText(image, disp_str, (x1+5, y1+10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1)
79
 
 
80
  if len(seg_mask_boundary) and self.is_show_segmentation_boundary and cls_conf[id] > self.confidence_threshold:
81
  cv2.polylines(image, [np.array(seg_mask_boundary[id], dtype=np.int32)], isClosed=True, color=cls_clr, thickness=2)
82
 
 
83
  (x1, y1, x2, y2) = bounding_boxes[id]
84
  center = x1+(x2-x1)//2, y1+(y2-y1)//2
85
  objects_data.append([cls, self.model.names[cls], center, self.masks[id], cls_clr])