You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
2.6 KiB
58 lines
2.6 KiB
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
|
|
import torch
|
|
|
|
from ultralytics.engine.results import Results
|
|
from ultralytics.models.yolo.detect.predict import DetectionPredictor
|
|
from ultralytics.utils import DEFAULT_CFG, ops
|
|
|
|
|
|
class SegmentationPredictor(DetectionPredictor):
|
|
"""
|
|
A class extending the DetectionPredictor class for prediction based on a segmentation model.
|
|
|
|
Example:
|
|
```python
|
|
from ultralytics.utils import ASSETS
|
|
from ultralytics.models.yolo.segment import SegmentationPredictor
|
|
|
|
args = dict(model='yolov8n-seg.pt', source=ASSETS)
|
|
predictor = SegmentationPredictor(overrides=args)
|
|
predictor.predict_cli()
|
|
```
|
|
"""
|
|
|
|
def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
|
|
super().__init__(cfg, overrides, _callbacks)
|
|
self.args.task = 'segment'
|
|
|
|
def postprocess(self, preds, img, orig_imgs):
|
|
"""TODO: filter by classes."""
|
|
p = ops.non_max_suppression(preds[0],
|
|
self.args.conf,
|
|
self.args.iou,
|
|
agnostic=self.args.agnostic_nms,
|
|
max_det=self.args.max_det,
|
|
nc=len(self.model.names),
|
|
classes=self.args.classes)
|
|
results = []
|
|
proto = preds[1][-1] if len(preds[1]) == 3 else preds[1] # second output is len 3 if pt, but only 1 if exported
|
|
for i, pred in enumerate(p):
|
|
orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs
|
|
path = self.batch[0]
|
|
img_path = path[i] if isinstance(path, list) else path
|
|
if not len(pred): # save empty boxes
|
|
results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6]))
|
|
continue
|
|
if self.args.retina_masks:
|
|
if not isinstance(orig_imgs, torch.Tensor):
|
|
pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)
|
|
masks = ops.process_mask_native(proto[i], pred[:, 6:], pred[:, :4], orig_img.shape[:2]) # HWC
|
|
else:
|
|
masks = ops.process_mask(proto[i], pred[:, 6:], pred[:, :4], img.shape[2:], upsample=True) # HWC
|
|
if not isinstance(orig_imgs, torch.Tensor):
|
|
pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)
|
|
results.append(
|
|
Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6], masks=masks))
|
|
return results
|