-
Notifications
You must be signed in to change notification settings - Fork 0
/
yolo_segmentation.py
32 lines (26 loc) · 1.1 KB
/
yolo_segmentation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#https://pysource.com/2023/02/21/yolo-v8-segmentation
from ultralytics import YOLO
import numpy as np
class YOLOSegmentation:
def __init__(self, model_path):
self.model = YOLO(model_path)
def detect(self, img):
# Get img shape
height, width, channels = img.shape
results = self.model.predict(source=img.copy(), save=False, save_txt=False)
result = results[0]
segmentation_contours_idx = []
for seg in result.masks.segments:
# contours
seg[:, 0] *= width
seg[:, 1] *= height
segment = np.array(seg, dtype=np.int32)
segmentation_contours_idx.append(segment)
bboxes = np.array(result.boxes.xyxy.cpu(), dtype="int")
# Get class ids
class_ids = np.array(result.boxes.cls.cpu(), dtype="int")
# Get scores
scores = np.array(result.boxes.conf.cpu(), dtype="float").round(2)
#get masks
masks = np.array(result.masks.data.cpu(), dtype="float")
return bboxes, class_ids, segmentation_contours_idx, scores, masks