predict.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. """
  3. Generate predictions using the Segment Anything Model (SAM).
  4. SAM is an advanced image segmentation model offering features like promptable segmentation and zero-shot performance.
  5. This module contains the implementation of the prediction logic and auxiliary utilities required to perform segmentation
  6. using SAM. It forms an integral part of the Ultralytics framework and is designed for high-performance, real-time image
  7. segmentation tasks.
  8. """
  9. import numpy as np
  10. import torch
  11. import torch.nn.functional as F
  12. from ultralytics.data.augment import LetterBox
  13. from ultralytics.engine.predictor import BasePredictor
  14. from ultralytics.engine.results import Results
  15. from ultralytics.utils import DEFAULT_CFG, ops
  16. from ultralytics.utils.torch_utils import select_device
  17. from .amg import (
  18. batch_iterator,
  19. batched_mask_to_box,
  20. build_all_layer_point_grids,
  21. calculate_stability_score,
  22. generate_crop_boxes,
  23. is_box_near_crop_edge,
  24. remove_small_regions,
  25. uncrop_boxes_xyxy,
  26. uncrop_masks,
  27. )
  28. from .build import build_sam
  29. class Predictor(BasePredictor):
  30. """
  31. Predictor class for the Segment Anything Model (SAM), extending BasePredictor.
  32. The class provides an interface for model inference tailored to image segmentation tasks.
  33. With advanced architecture and promptable segmentation capabilities, it facilitates flexible and real-time
  34. mask generation. The class is capable of working with various types of prompts such as bounding boxes,
  35. points, and low-resolution masks.
  36. Attributes:
  37. cfg (dict): Configuration dictionary specifying model and task-related parameters.
  38. overrides (dict): Dictionary containing values that override the default configuration.
  39. _callbacks (dict): Dictionary of user-defined callback functions to augment behavior.
  40. args (namespace): Namespace to hold command-line arguments or other operational variables.
  41. im (torch.Tensor): Preprocessed input image tensor.
  42. features (torch.Tensor): Extracted image features used for inference.
  43. prompts (dict): Collection of various prompt types, such as bounding boxes and points.
  44. segment_all (bool): Flag to control whether to segment all objects in the image or only specified ones.
  45. """
  46. def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
  47. """
  48. Initialize the Predictor with configuration, overrides, and callbacks.
  49. The method sets up the Predictor object and applies any configuration overrides or callbacks provided. It
  50. initializes task-specific settings for SAM, such as retina_masks being set to True for optimal results.
  51. Args:
  52. cfg (dict): Configuration dictionary.
  53. overrides (dict, optional): Dictionary of values to override default configuration.
  54. _callbacks (dict, optional): Dictionary of callback functions to customize behavior.
  55. """
  56. if overrides is None:
  57. overrides = {}
  58. overrides.update(dict(task="segment", mode="predict", imgsz=1024))
  59. super().__init__(cfg, overrides, _callbacks)
  60. self.args.retina_masks = True
  61. self.im = None
  62. self.features = None
  63. self.prompts = {}
  64. self.segment_all = False
  65. def preprocess(self, im):
  66. """
  67. Preprocess the input image for model inference.
  68. The method prepares the input image by applying transformations and normalization.
  69. It supports both torch.Tensor and list of np.ndarray as input formats.
  70. Args:
  71. im (torch.Tensor | List[np.ndarray]): BCHW tensor format or list of HWC numpy arrays.
  72. Returns:
  73. (torch.Tensor): The preprocessed image tensor.
  74. """
  75. if self.im is not None:
  76. return self.im
  77. not_tensor = not isinstance(im, torch.Tensor)
  78. if not_tensor:
  79. im = np.stack(self.pre_transform(im))
  80. im = im[..., ::-1].transpose((0, 3, 1, 2))
  81. im = np.ascontiguousarray(im)
  82. im = torch.from_numpy(im)
  83. im = im.to(self.device)
  84. im = im.half() if self.model.fp16 else im.float()
  85. if not_tensor:
  86. im = (im - self.mean) / self.std
  87. return im
  88. def pre_transform(self, im):
  89. """
  90. Perform initial transformations on the input image for preprocessing.
  91. The method applies transformations such as resizing to prepare the image for further preprocessing.
  92. Currently, batched inference is not supported; hence the list length should be 1.
  93. Args:
  94. im (List[np.ndarray]): List containing images in HWC numpy array format.
  95. Returns:
  96. (List[np.ndarray]): List of transformed images.
  97. """
  98. assert len(im) == 1, "SAM model does not currently support batched inference"
  99. letterbox = LetterBox(self.args.imgsz, auto=False, center=False)
  100. return [letterbox(image=x) for x in im]
  101. def inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False, *args, **kwargs):
  102. """
  103. Perform image segmentation inference based on the given input cues, using the currently loaded image. This
  104. method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder, and
  105. mask decoder for real-time and promptable segmentation tasks.
  106. Args:
  107. im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
  108. bboxes (np.ndarray | List, optional): Bounding boxes with shape (N, 4), in XYXY format.
  109. points (np.ndarray | List, optional): Points indicating object locations with shape (N, 2), in pixels.
  110. labels (np.ndarray | List, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background.
  111. masks (np.ndarray, optional): Low-resolution masks from previous predictions shape (N,H,W). For SAM H=W=256.
  112. multimask_output (bool, optional): Flag to return multiple masks. Helpful for ambiguous prompts.
  113. Returns:
  114. (tuple): Contains the following three elements.
  115. - np.ndarray: The output masks in shape CxHxW, where C is the number of generated masks.
  116. - np.ndarray: An array of length C containing quality scores predicted by the model for each mask.
  117. - np.ndarray: Low-resolution logits of shape CxHxW for subsequent inference, where H=W=256.
  118. """
  119. # Override prompts if any stored in self.prompts
  120. bboxes = self.prompts.pop("bboxes", bboxes)
  121. points = self.prompts.pop("points", points)
  122. masks = self.prompts.pop("masks", masks)
  123. if all(i is None for i in [bboxes, points, masks]):
  124. return self.generate(im, *args, **kwargs)
  125. return self.prompt_inference(im, bboxes, points, labels, masks, multimask_output)
  126. def prompt_inference(self, im, bboxes=None, points=None, labels=None, masks=None, multimask_output=False):
  127. """
  128. Internal function for image segmentation inference based on cues like bounding boxes, points, and masks.
  129. Leverages SAM's specialized architecture for prompt-based, real-time segmentation.
  130. Args:
  131. im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
  132. bboxes (np.ndarray | List, optional): Bounding boxes with shape (N, 4), in XYXY format.
  133. points (np.ndarray | List, optional): Points indicating object locations with shape (N, 2), in pixels.
  134. labels (np.ndarray | List, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background.
  135. masks (np.ndarray, optional): Low-resolution masks from previous predictions shape (N,H,W). For SAM H=W=256.
  136. multimask_output (bool, optional): Flag to return multiple masks. Helpful for ambiguous prompts.
  137. Returns:
  138. (tuple): Contains the following three elements.
  139. - np.ndarray: The output masks in shape CxHxW, where C is the number of generated masks.
  140. - np.ndarray: An array of length C containing quality scores predicted by the model for each mask.
  141. - np.ndarray: Low-resolution logits of shape CxHxW for subsequent inference, where H=W=256.
  142. """
  143. features = self.model.image_encoder(im) if self.features is None else self.features
  144. src_shape, dst_shape = self.batch[1][0].shape[:2], im.shape[2:]
  145. r = 1.0 if self.segment_all else min(dst_shape[0] / src_shape[0], dst_shape[1] / src_shape[1])
  146. # Transform input prompts
  147. if points is not None:
  148. points = torch.as_tensor(points, dtype=torch.float32, device=self.device)
  149. points = points[None] if points.ndim == 1 else points
  150. # Assuming labels are all positive if users don't pass labels.
  151. if labels is None:
  152. labels = np.ones(points.shape[0])
  153. labels = torch.as_tensor(labels, dtype=torch.int32, device=self.device)
  154. points *= r
  155. # (N, 2) --> (N, 1, 2), (N, ) --> (N, 1)
  156. points, labels = points[:, None, :], labels[:, None]
  157. if bboxes is not None:
  158. bboxes = torch.as_tensor(bboxes, dtype=torch.float32, device=self.device)
  159. bboxes = bboxes[None] if bboxes.ndim == 1 else bboxes
  160. bboxes *= r
  161. if masks is not None:
  162. masks = torch.as_tensor(masks, dtype=torch.float32, device=self.device).unsqueeze(1)
  163. points = (points, labels) if points is not None else None
  164. # Embed prompts
  165. sparse_embeddings, dense_embeddings = self.model.prompt_encoder(points=points, boxes=bboxes, masks=masks)
  166. # Predict masks
  167. pred_masks, pred_scores = self.model.mask_decoder(
  168. image_embeddings=features,
  169. image_pe=self.model.prompt_encoder.get_dense_pe(),
  170. sparse_prompt_embeddings=sparse_embeddings,
  171. dense_prompt_embeddings=dense_embeddings,
  172. multimask_output=multimask_output,
  173. )
  174. # (N, d, H, W) --> (N*d, H, W), (N, d) --> (N*d, )
  175. # `d` could be 1 or 3 depends on `multimask_output`.
  176. return pred_masks.flatten(0, 1), pred_scores.flatten(0, 1)
  177. def generate(
  178. self,
  179. im,
  180. crop_n_layers=0,
  181. crop_overlap_ratio=512 / 1500,
  182. crop_downscale_factor=1,
  183. point_grids=None,
  184. points_stride=32,
  185. points_batch_size=64,
  186. conf_thres=0.88,
  187. stability_score_thresh=0.95,
  188. stability_score_offset=0.95,
  189. crop_nms_thresh=0.7,
  190. ):
  191. """
  192. Perform image segmentation using the Segment Anything Model (SAM).
  193. This function segments an entire image into constituent parts by leveraging SAM's advanced architecture
  194. and real-time performance capabilities. It can optionally work on image crops for finer segmentation.
  195. Args:
  196. im (torch.Tensor): Input tensor representing the preprocessed image with dimensions (N, C, H, W).
  197. crop_n_layers (int): Specifies the number of layers for additional mask predictions on image crops.
  198. Each layer produces 2**i_layer number of image crops.
  199. crop_overlap_ratio (float): Determines the overlap between crops. Scaled down in subsequent layers.
  200. crop_downscale_factor (int): Scaling factor for the number of sampled points-per-side in each layer.
  201. point_grids (list[np.ndarray], optional): Custom grids for point sampling normalized to [0,1].
  202. Used in the nth crop layer.
  203. points_stride (int, optional): Number of points to sample along each side of the image.
  204. Exclusive with 'point_grids'.
  205. points_batch_size (int): Batch size for the number of points processed simultaneously.
  206. conf_thres (float): Confidence threshold [0,1] for filtering based on the model's mask quality prediction.
  207. stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on mask stability.
  208. stability_score_offset (float): Offset value for calculating stability score.
  209. crop_nms_thresh (float): IoU cutoff for NMS to remove duplicate masks between crops.
  210. Returns:
  211. (tuple): A tuple containing segmented masks, confidence scores, and bounding boxes.
  212. """
  213. import torchvision # scope for faster 'import ultralytics'
  214. self.segment_all = True
  215. ih, iw = im.shape[2:]
  216. crop_regions, layer_idxs = generate_crop_boxes((ih, iw), crop_n_layers, crop_overlap_ratio)
  217. if point_grids is None:
  218. point_grids = build_all_layer_point_grids(points_stride, crop_n_layers, crop_downscale_factor)
  219. pred_masks, pred_scores, pred_bboxes, region_areas = [], [], [], []
  220. for crop_region, layer_idx in zip(crop_regions, layer_idxs):
  221. x1, y1, x2, y2 = crop_region
  222. w, h = x2 - x1, y2 - y1
  223. area = torch.tensor(w * h, device=im.device)
  224. points_scale = np.array([[w, h]]) # w, h
  225. # Crop image and interpolate to input size
  226. crop_im = F.interpolate(im[..., y1:y2, x1:x2], (ih, iw), mode="bilinear", align_corners=False)
  227. # (num_points, 2)
  228. points_for_image = point_grids[layer_idx] * points_scale
  229. crop_masks, crop_scores, crop_bboxes = [], [], []
  230. for (points,) in batch_iterator(points_batch_size, points_for_image):
  231. pred_mask, pred_score = self.prompt_inference(crop_im, points=points, multimask_output=True)
  232. # Interpolate predicted masks to input size
  233. pred_mask = F.interpolate(pred_mask[None], (h, w), mode="bilinear", align_corners=False)[0]
  234. idx = pred_score > conf_thres
  235. pred_mask, pred_score = pred_mask[idx], pred_score[idx]
  236. stability_score = calculate_stability_score(
  237. pred_mask, self.model.mask_threshold, stability_score_offset
  238. )
  239. idx = stability_score > stability_score_thresh
  240. pred_mask, pred_score = pred_mask[idx], pred_score[idx]
  241. # Bool type is much more memory-efficient.
  242. pred_mask = pred_mask > self.model.mask_threshold
  243. # (N, 4)
  244. pred_bbox = batched_mask_to_box(pred_mask).float()
  245. keep_mask = ~is_box_near_crop_edge(pred_bbox, crop_region, [0, 0, iw, ih])
  246. if not torch.all(keep_mask):
  247. pred_bbox, pred_mask, pred_score = pred_bbox[keep_mask], pred_mask[keep_mask], pred_score[keep_mask]
  248. crop_masks.append(pred_mask)
  249. crop_bboxes.append(pred_bbox)
  250. crop_scores.append(pred_score)
  251. # Do nms within this crop
  252. crop_masks = torch.cat(crop_masks)
  253. crop_bboxes = torch.cat(crop_bboxes)
  254. crop_scores = torch.cat(crop_scores)
  255. keep = torchvision.ops.nms(crop_bboxes, crop_scores, self.args.iou) # NMS
  256. crop_bboxes = uncrop_boxes_xyxy(crop_bboxes[keep], crop_region)
  257. crop_masks = uncrop_masks(crop_masks[keep], crop_region, ih, iw)
  258. crop_scores = crop_scores[keep]
  259. pred_masks.append(crop_masks)
  260. pred_bboxes.append(crop_bboxes)
  261. pred_scores.append(crop_scores)
  262. region_areas.append(area.expand(len(crop_masks)))
  263. pred_masks = torch.cat(pred_masks)
  264. pred_bboxes = torch.cat(pred_bboxes)
  265. pred_scores = torch.cat(pred_scores)
  266. region_areas = torch.cat(region_areas)
  267. # Remove duplicate masks between crops
  268. if len(crop_regions) > 1:
  269. scores = 1 / region_areas
  270. keep = torchvision.ops.nms(pred_bboxes, scores, crop_nms_thresh)
  271. pred_masks, pred_bboxes, pred_scores = pred_masks[keep], pred_bboxes[keep], pred_scores[keep]
  272. return pred_masks, pred_scores, pred_bboxes
  273. def setup_model(self, model, verbose=True):
  274. """
  275. Initializes the Segment Anything Model (SAM) for inference.
  276. This method sets up the SAM model by allocating it to the appropriate device and initializing the necessary
  277. parameters for image normalization and other Ultralytics compatibility settings.
  278. Args:
  279. model (torch.nn.Module): A pre-trained SAM model. If None, a model will be built based on configuration.
  280. verbose (bool): If True, prints selected device information.
  281. Attributes:
  282. model (torch.nn.Module): The SAM model allocated to the chosen device for inference.
  283. device (torch.device): The device to which the model and tensors are allocated.
  284. mean (torch.Tensor): The mean values for image normalization.
  285. std (torch.Tensor): The standard deviation values for image normalization.
  286. """
  287. device = select_device(self.args.device, verbose=verbose)
  288. if model is None:
  289. model = build_sam(self.args.model)
  290. model.eval()
  291. self.model = model.to(device)
  292. self.device = device
  293. self.mean = torch.tensor([123.675, 116.28, 103.53]).view(-1, 1, 1).to(device)
  294. self.std = torch.tensor([58.395, 57.12, 57.375]).view(-1, 1, 1).to(device)
  295. # Ultralytics compatibility settings
  296. self.model.pt = False
  297. self.model.triton = False
  298. self.model.stride = 32
  299. self.model.fp16 = False
  300. self.done_warmup = True
  301. def postprocess(self, preds, img, orig_imgs):
  302. """
  303. Post-processes SAM's inference outputs to generate object detection masks and bounding boxes.
  304. The method scales masks and boxes to the original image size and applies a threshold to the mask predictions.
  305. The SAM model uses advanced architecture and promptable segmentation tasks to achieve real-time performance.
  306. Args:
  307. preds (tuple): The output from SAM model inference, containing masks, scores, and optional bounding boxes.
  308. img (torch.Tensor): The processed input image tensor.
  309. orig_imgs (list | torch.Tensor): The original, unprocessed images.
  310. Returns:
  311. (list): List of Results objects containing detection masks, bounding boxes, and other metadata.
  312. """
  313. # (N, 1, H, W), (N, 1)
  314. pred_masks, pred_scores = preds[:2]
  315. pred_bboxes = preds[2] if self.segment_all else None
  316. names = dict(enumerate(str(i) for i in range(len(pred_masks))))
  317. if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
  318. orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
  319. results = []
  320. for i, masks in enumerate([pred_masks]):
  321. orig_img = orig_imgs[i]
  322. if pred_bboxes is not None:
  323. pred_bboxes = ops.scale_boxes(img.shape[2:], pred_bboxes.float(), orig_img.shape, padding=False)
  324. cls = torch.arange(len(pred_masks), dtype=torch.int32, device=pred_masks.device)
  325. pred_bboxes = torch.cat([pred_bboxes, pred_scores[:, None], cls[:, None]], dim=-1)
  326. masks = ops.scale_masks(masks[None].float(), orig_img.shape[:2], padding=False)[0]
  327. masks = masks > self.model.mask_threshold # to bool
  328. img_path = self.batch[0][i]
  329. results.append(Results(orig_img, path=img_path, names=names, masks=masks, boxes=pred_bboxes))
  330. # Reset segment-all mode.
  331. self.segment_all = False
  332. return results
  333. def setup_source(self, source):
  334. """
  335. Sets up the data source for inference.
  336. This method configures the data source from which images will be fetched for inference. The source could be a
  337. directory, a video file, or other types of image data sources.
  338. Args:
  339. source (str | Path): The path to the image data source for inference.
  340. """
  341. if source is not None:
  342. super().setup_source(source)
  343. def set_image(self, image):
  344. """
  345. Preprocesses and sets a single image for inference.
  346. This function sets up the model if not already initialized, configures the data source to the specified image,
  347. and preprocesses the image for feature extraction. Only one image can be set at a time.
  348. Args:
  349. image (str | np.ndarray): Image file path as a string, or a np.ndarray image read by cv2.
  350. Raises:
  351. AssertionError: If more than one image is set.
  352. """
  353. if self.model is None:
  354. model = build_sam(self.args.model)
  355. self.setup_model(model)
  356. self.setup_source(image)
  357. assert len(self.dataset) == 1, "`set_image` only supports setting one image!"
  358. for batch in self.dataset:
  359. im = self.preprocess(batch[1])
  360. self.features = self.model.image_encoder(im)
  361. self.im = im
  362. break
  363. def set_prompts(self, prompts):
  364. """Set prompts in advance."""
  365. self.prompts = prompts
  366. def reset_image(self):
  367. """Resets the image and its features to None."""
  368. self.im = None
  369. self.features = None
  370. @staticmethod
  371. def remove_small_regions(masks, min_area=0, nms_thresh=0.7):
  372. """
  373. Perform post-processing on segmentation masks generated by the Segment Anything Model (SAM). Specifically, this
  374. function removes small disconnected regions and holes from the input masks, and then performs Non-Maximum
  375. Suppression (NMS) to eliminate any newly created duplicate boxes.
  376. Args:
  377. masks (torch.Tensor): A tensor containing the masks to be processed. Shape should be (N, H, W), where N is
  378. the number of masks, H is height, and W is width.
  379. min_area (int): The minimum area below which disconnected regions and holes will be removed. Defaults to 0.
  380. nms_thresh (float): The IoU threshold for the NMS algorithm. Defaults to 0.7.
  381. Returns:
  382. (tuple([torch.Tensor, List[int]])):
  383. - new_masks (torch.Tensor): The processed masks with small regions removed. Shape is (N, H, W).
  384. - keep (List[int]): The indices of the remaining masks post-NMS, which can be used to filter the boxes.
  385. """
  386. import torchvision # scope for faster 'import ultralytics'
  387. if len(masks) == 0:
  388. return masks
  389. # Filter small disconnected regions and holes
  390. new_masks = []
  391. scores = []
  392. for mask in masks:
  393. mask = mask.cpu().numpy().astype(np.uint8)
  394. mask, changed = remove_small_regions(mask, min_area, mode="holes")
  395. unchanged = not changed
  396. mask, changed = remove_small_regions(mask, min_area, mode="islands")
  397. unchanged = unchanged and not changed
  398. new_masks.append(torch.as_tensor(mask).unsqueeze(0))
  399. # Give score=0 to changed masks and 1 to unchanged masks so NMS prefers masks not needing postprocessing
  400. scores.append(float(unchanged))
  401. # Recalculate boxes and remove any new duplicates
  402. new_masks = torch.cat(new_masks, dim=0)
  403. boxes = batched_mask_to_box(new_masks)
  404. keep = torchvision.ops.nms(boxes.float(), torch.as_tensor(scores), nms_thresh)
  405. return new_masks[keep].to(device=masks.device, dtype=masks.dtype), keep