predict.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. import torch
  3. from ultralytics.engine.results import Results
  4. from ultralytics.models.fastsam.utils import bbox_iou
  5. from ultralytics.models.yolo.detect.predict import DetectionPredictor
  6. from ultralytics.utils import DEFAULT_CFG, ops
  7. class FastSAMPredictor(DetectionPredictor):
  8. def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
  9. super().__init__(cfg, overrides, _callbacks)
  10. self.args.task = 'segment'
  11. def postprocess(self, preds, img, orig_imgs):
  12. p = ops.non_max_suppression(preds[0],
  13. self.args.conf,
  14. self.args.iou,
  15. agnostic=self.args.agnostic_nms,
  16. max_det=self.args.max_det,
  17. nc=len(self.model.names),
  18. classes=self.args.classes)
  19. full_box = torch.zeros_like(p[0][0])
  20. full_box[2], full_box[3], full_box[4], full_box[6:] = img.shape[3], img.shape[2], 1.0, 1.0
  21. full_box = full_box.view(1, -1)
  22. critical_iou_index = bbox_iou(full_box[0][:4], p[0][:, :4], iou_thres=0.9, image_shape=img.shape[2:])
  23. if critical_iou_index.numel() != 0:
  24. full_box[0][4] = p[0][critical_iou_index][:, 4]
  25. full_box[0][6:] = p[0][critical_iou_index][:, 6:]
  26. p[0][critical_iou_index] = full_box
  27. results = []
  28. is_list = isinstance(orig_imgs, list) # input images are a list, not a torch.Tensor
  29. proto = preds[1][-1] if len(preds[1]) == 3 else preds[1] # second output is len 3 if pt, but only 1 if exported
  30. for i, pred in enumerate(p):
  31. orig_img = orig_imgs[i] if is_list else orig_imgs
  32. img_path = self.batch[0][i]
  33. if not len(pred): # save empty boxes
  34. masks = None
  35. elif self.args.retina_masks:
  36. if is_list:
  37. pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)
  38. masks = ops.process_mask_native(proto[i], pred[:, 6:], pred[:, :4], orig_img.shape[:2]) # HWC
  39. else:
  40. masks = ops.process_mask(proto[i], pred[:, 6:], pred[:, :4], img.shape[2:], upsample=True) # HWC
  41. if is_list:
  42. pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)
  43. results.append(Results(orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6], masks=masks))
  44. return results