processing_sam.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. # Copyright 2023 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Processor class for SAM.
  16. """
  17. from copy import deepcopy
  18. from typing import Union
  19. import numpy as np
  20. from ...image_utils import ImageInput
  21. from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin
  22. from ...tokenization_utils_base import BatchEncoding, PreTokenizedInput, TextInput
  23. from ...utils import auto_docstring, is_torch_available
  24. if is_torch_available():
  25. import torch
  26. NestedList = list[Union[float | int | None, "NestedList"]]
  27. class SamImagesKwargs(ImagesKwargs, total=False):
  28. """
  29. segmentation_maps (`ImageInput`, *optional*):
  30. Ground truth segmentation maps to process alongside the input images. These maps are used for training
  31. or evaluation purposes and are resized and normalized to match the processed image dimensions.
  32. input_points (`NestedList`, *optional*):
  33. Input points for prompt-based segmentation. Should be a nested list with structure
  34. `[image_level, object_level, point_level, [x, y]]` where each point is specified as `[x, y]` coordinates
  35. in the original image space. Points are normalized to the target image size before being passed to the model.
  36. input_labels (`NestedList`, *optional*):
  37. Labels for the input points, indicating whether each point is a foreground (1) or background (0) point.
  38. Should be a nested list with structure `[image_level, object_level, point_level]`. Must have the same
  39. structure as `input_points` (excluding the coordinate dimension).
  40. input_boxes (`NestedList`, *optional*):
  41. Bounding boxes for prompt-based segmentation. Should be a nested list with structure
  42. `[image_level, box_level, [x1, y1, x2, y2]]` where each box is specified as `[x1, y1, x2, y2]` coordinates
  43. in the original image space. Boxes are normalized to the target image size before being passed to the model.
  44. point_pad_value (`int`, *optional*, defaults to `-10`):
  45. The value used for padding input points when batching sequences of different lengths. This value marks
  46. padded positions and is preserved during coordinate normalization to distinguish real points from padding.
  47. mask_size (`dict[str, int]`, *optional*):
  48. Dictionary specifying the target mask size with keys `"height"` and `"width"`. This determines the
  49. resolution of the output segmentation masks generated by the model.
  50. mask_pad_size (`dict[str, int]`, *optional*):
  51. Dictionary specifying the padding size for masks with keys `"height"` and `"width"`. This is used when
  52. batching masks of different sizes to ensure consistent dimensions.
  53. """
  54. segmentation_maps: ImageInput | None
  55. input_points: "NestedList | torch.Tensor | None"
  56. input_labels: "NestedList | int | torch.Tensor | None"
  57. input_boxes: "NestedList | torch.Tensor | None"
  58. point_pad_value: int | None
  59. mask_size: dict[str, int]
  60. mask_pad_size: dict[str, int]
  61. class SamProcessorKwargs(ProcessingKwargs, total=False):
  62. images_kwargs: SamImagesKwargs
  63. _defaults = {
  64. "images_kwargs": {
  65. "point_pad_value": -10,
  66. }
  67. }
  68. @auto_docstring
  69. class SamProcessor(ProcessorMixin):
  70. def __init__(self, image_processor):
  71. super().__init__(image_processor)
  72. self.target_size = self.image_processor.size["longest_edge"]
  73. @auto_docstring
  74. def __call__(
  75. self,
  76. images: ImageInput | None = None,
  77. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
  78. **kwargs,
  79. ) -> BatchEncoding:
  80. output_kwargs = self._merge_kwargs(
  81. SamProcessorKwargs,
  82. tokenizer_init_kwargs={},
  83. **kwargs,
  84. )
  85. input_points = output_kwargs["images_kwargs"].pop("input_points", None)
  86. input_labels = output_kwargs["images_kwargs"].pop("input_labels", None)
  87. input_boxes = output_kwargs["images_kwargs"].pop("input_boxes", None)
  88. point_pad_value = output_kwargs["images_kwargs"].pop("point_pad_value", None)
  89. encoding_image_processor = self.image_processor(
  90. images,
  91. **output_kwargs["images_kwargs"],
  92. )
  93. # pop arguments that are not used in the forward but used nevertheless
  94. original_sizes = encoding_image_processor["original_sizes"]
  95. if hasattr(original_sizes, "numpy"):
  96. original_sizes = original_sizes.numpy()
  97. input_points, input_labels, input_boxes = self._check_and_preprocess_points(
  98. input_points=input_points,
  99. input_labels=input_labels,
  100. input_boxes=input_boxes,
  101. )
  102. encoding_image_processor = self._normalize_and_convert(
  103. encoding_image_processor,
  104. original_sizes,
  105. input_points=input_points,
  106. input_labels=input_labels,
  107. input_boxes=input_boxes,
  108. return_tensors=output_kwargs["images_kwargs"].get("return_tensors"),
  109. point_pad_value=point_pad_value,
  110. )
  111. return encoding_image_processor
  112. def _normalize_and_convert(
  113. self,
  114. encoding_image_processor,
  115. original_sizes,
  116. input_points=None,
  117. input_labels=None,
  118. input_boxes=None,
  119. return_tensors="pt",
  120. point_pad_value=-10,
  121. ):
  122. if input_points is not None:
  123. if len(original_sizes) != len(input_points):
  124. input_points = [
  125. self._normalize_coordinates(self.target_size, point, original_sizes[0]) for point in input_points
  126. ]
  127. else:
  128. input_points = [
  129. self._normalize_coordinates(self.target_size, point, original_size)
  130. for point, original_size in zip(input_points, original_sizes)
  131. ]
  132. # check that all arrays have the same shape
  133. if not all(point.shape == input_points[0].shape for point in input_points):
  134. if input_labels is not None:
  135. input_points, input_labels = self._pad_points_and_labels(
  136. input_points, input_labels, point_pad_value
  137. )
  138. input_points = np.array(input_points)
  139. if input_labels is not None:
  140. input_labels = np.array(input_labels)
  141. if input_boxes is not None:
  142. if len(original_sizes) != len(input_boxes):
  143. input_boxes = [
  144. self._normalize_coordinates(self.target_size, box, original_sizes[0], is_bounding_box=True)
  145. for box in input_boxes
  146. ]
  147. else:
  148. input_boxes = [
  149. self._normalize_coordinates(self.target_size, box, original_size, is_bounding_box=True)
  150. for box, original_size in zip(input_boxes, original_sizes)
  151. ]
  152. input_boxes = np.array(input_boxes)
  153. if input_boxes is not None:
  154. if return_tensors == "pt":
  155. input_boxes = torch.from_numpy(input_boxes)
  156. # boxes batch size of 1 by default
  157. input_boxes = input_boxes.unsqueeze(1) if len(input_boxes.shape) != 3 else input_boxes
  158. encoding_image_processor.update({"input_boxes": input_boxes})
  159. if input_points is not None:
  160. if return_tensors == "pt":
  161. input_points = torch.from_numpy(input_points)
  162. # point batch size of 1 by default
  163. input_points = input_points.unsqueeze(1) if len(input_points.shape) != 4 else input_points
  164. encoding_image_processor.update({"input_points": input_points})
  165. if input_labels is not None:
  166. if return_tensors == "pt":
  167. input_labels = torch.from_numpy(input_labels)
  168. # point batch size of 1 by default
  169. input_labels = input_labels.unsqueeze(1) if len(input_labels.shape) != 3 else input_labels
  170. encoding_image_processor.update({"input_labels": input_labels})
  171. return encoding_image_processor
  172. def _pad_points_and_labels(self, input_points, input_labels, point_pad_value):
  173. r"""
  174. The method pads the 2D points and labels to the maximum number of points in the batch.
  175. """
  176. expected_nb_points = max(point.shape[0] for point in input_points)
  177. processed_input_points = []
  178. for i, point in enumerate(input_points):
  179. if point.shape[0] != expected_nb_points:
  180. point = np.concatenate(
  181. [point, np.zeros((expected_nb_points - point.shape[0], 2)) + point_pad_value], axis=0
  182. )
  183. input_labels[i] = np.append(input_labels[i], [point_pad_value])
  184. processed_input_points.append(point)
  185. input_points = processed_input_points
  186. return input_points, input_labels
  187. def _normalize_coordinates(
  188. self, target_size: int, coords: np.ndarray, original_size, is_bounding_box=False
  189. ) -> np.ndarray:
  190. """
  191. Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H, W) format.
  192. """
  193. old_h, old_w = original_size
  194. new_h, new_w = self.image_processor._get_preprocess_shape(original_size, longest_edge=target_size)
  195. coords = deepcopy(coords).astype(float)
  196. if is_bounding_box:
  197. coords = coords.reshape(-1, 2, 2)
  198. coords[..., 0] = coords[..., 0] * (new_w / old_w)
  199. coords[..., 1] = coords[..., 1] * (new_h / old_h)
  200. if is_bounding_box:
  201. coords = coords.reshape(-1, 4)
  202. return coords
  203. def _check_and_preprocess_points(
  204. self,
  205. input_points=None,
  206. input_labels=None,
  207. input_boxes=None,
  208. ):
  209. r"""
  210. Check and preprocesses the 2D points, labels and bounding boxes. It checks if the input is valid and if they
  211. are, it converts the coordinates of the points and bounding boxes. If a user passes directly a `torch.Tensor`,
  212. it is converted to a `numpy.ndarray` and then to a `list`.
  213. """
  214. if input_points is not None:
  215. if hasattr(input_points, "numpy"):
  216. input_points = input_points.numpy().tolist()
  217. if not isinstance(input_points, list) or not isinstance(input_points[0], list):
  218. raise ValueError("Input points must be a list of list of floating points.")
  219. input_points = [np.array(input_point) for input_point in input_points]
  220. else:
  221. input_points = None
  222. if input_labels is not None:
  223. if hasattr(input_labels, "numpy"):
  224. input_labels = input_labels.numpy().tolist()
  225. if not isinstance(input_labels, list) or not isinstance(input_labels[0], list):
  226. raise ValueError("Input labels must be a list of list integers.")
  227. input_labels = [np.array(label) for label in input_labels]
  228. else:
  229. input_labels = None
  230. if input_boxes is not None:
  231. if hasattr(input_boxes, "numpy"):
  232. input_boxes = input_boxes.numpy().tolist()
  233. if (
  234. not isinstance(input_boxes, list)
  235. or not isinstance(input_boxes[0], list)
  236. or not isinstance(input_boxes[0][0], list)
  237. ):
  238. raise ValueError("Input boxes must be a list of list of list of floating points.")
  239. input_boxes = [np.array(box).astype(np.float32) for box in input_boxes]
  240. else:
  241. input_boxes = None
  242. return input_points, input_labels, input_boxes
  243. @property
  244. def model_input_names(self):
  245. image_processor_input_names = self.image_processor.model_input_names
  246. return list(image_processor_input_names + ["original_sizes", "reshaped_input_sizes"])
  247. def post_process_masks(self, *args, **kwargs):
  248. return self.image_processor.post_process_masks(*args, **kwargs)
  249. __all__ = ["SamProcessor"]