processing_sam.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. # coding=utf-8
  2. # Copyright 2023 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """
  16. Processor class for SAM.
  17. """
  18. from copy import deepcopy
  19. from typing import Optional, Union
  20. import numpy as np
  21. from ...image_utils import ImageInput
  22. from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin
  23. from ...tokenization_utils_base import AudioInput, BatchEncoding, PreTokenizedInput, TextInput
  24. from ...utils import is_tf_available, is_torch_available
  25. from ...video_utils import VideoInput
  26. if is_torch_available():
  27. import torch
  28. if is_tf_available():
  29. import tensorflow as tf
  30. class SamImagesKwargs(ImagesKwargs):
  31. segmentation_maps: Optional[ImageInput]
  32. input_points: Optional[list[list[float]]]
  33. input_labels: Optional[list[list[int]]]
  34. input_boxes: Optional[list[list[list[float]]]]
  35. point_pad_value: Optional[int]
  36. class SamProcessorKwargs(ProcessingKwargs, total=False):
  37. images_kwargs: SamImagesKwargs
  38. _defaults = {
  39. "images_kwargs": {
  40. "point_pad_value": -10,
  41. }
  42. }
  43. class SamProcessor(ProcessorMixin):
  44. r"""
  45. Constructs a SAM processor which wraps a SAM image processor and an 2D points & Bounding boxes processor into a
  46. single processor.
  47. [`SamProcessor`] offers all the functionalities of [`SamImageProcessor`]. See the docstring of
  48. [`~SamImageProcessor.__call__`] for more information.
  49. Args:
  50. image_processor (`SamImageProcessor`):
  51. An instance of [`SamImageProcessor`]. The image processor is a required input.
  52. """
  53. attributes = ["image_processor"]
  54. image_processor_class = "SamImageProcessor"
  55. def __init__(self, image_processor):
  56. super().__init__(image_processor)
  57. self.target_size = self.image_processor.size["longest_edge"]
  58. def __call__(
  59. self,
  60. images: Optional[ImageInput] = None,
  61. text: Optional[Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]] = None,
  62. audio: Optional[AudioInput] = None,
  63. video: Optional[VideoInput] = None,
  64. **kwargs,
  65. ) -> BatchEncoding:
  66. """
  67. This method uses [`SamImageProcessor.__call__`] method to prepare image(s) for the model. It also prepares 2D
  68. points and bounding boxes for the model if they are provided.
  69. """
  70. output_kwargs = self._merge_kwargs(
  71. SamProcessorKwargs,
  72. tokenizer_init_kwargs={},
  73. **kwargs,
  74. )
  75. input_points = output_kwargs["images_kwargs"].pop("input_points", None)
  76. input_labels = output_kwargs["images_kwargs"].pop("input_labels", None)
  77. input_boxes = output_kwargs["images_kwargs"].pop("input_boxes", None)
  78. point_pad_value = output_kwargs["images_kwargs"].pop("point_pad_value", None)
  79. encoding_image_processor = self.image_processor(
  80. images,
  81. **output_kwargs["images_kwargs"],
  82. )
  83. # pop arguments that are not used in the forward but used nevertheless
  84. original_sizes = encoding_image_processor["original_sizes"]
  85. if hasattr(original_sizes, "numpy"): # Checks if Torch or TF tensor
  86. original_sizes = original_sizes.numpy()
  87. input_points, input_labels, input_boxes = self._check_and_preprocess_points(
  88. input_points=input_points,
  89. input_labels=input_labels,
  90. input_boxes=input_boxes,
  91. )
  92. encoding_image_processor = self._normalize_and_convert(
  93. encoding_image_processor,
  94. original_sizes,
  95. input_points=input_points,
  96. input_labels=input_labels,
  97. input_boxes=input_boxes,
  98. return_tensors=output_kwargs["common_kwargs"].get("return_tensors"),
  99. point_pad_value=point_pad_value,
  100. )
  101. return encoding_image_processor
  102. def _normalize_and_convert(
  103. self,
  104. encoding_image_processor,
  105. original_sizes,
  106. input_points=None,
  107. input_labels=None,
  108. input_boxes=None,
  109. return_tensors="pt",
  110. point_pad_value=-10,
  111. ):
  112. if input_points is not None:
  113. if len(original_sizes) != len(input_points):
  114. input_points = [
  115. self._normalize_coordinates(self.target_size, point, original_sizes[0]) for point in input_points
  116. ]
  117. else:
  118. input_points = [
  119. self._normalize_coordinates(self.target_size, point, original_size)
  120. for point, original_size in zip(input_points, original_sizes)
  121. ]
  122. # check that all arrays have the same shape
  123. if not all(point.shape == input_points[0].shape for point in input_points):
  124. if input_labels is not None:
  125. input_points, input_labels = self._pad_points_and_labels(
  126. input_points, input_labels, point_pad_value
  127. )
  128. input_points = np.array(input_points)
  129. if input_labels is not None:
  130. input_labels = np.array(input_labels)
  131. if input_boxes is not None:
  132. if len(original_sizes) != len(input_boxes):
  133. input_boxes = [
  134. self._normalize_coordinates(self.target_size, box, original_sizes[0], is_bounding_box=True)
  135. for box in input_boxes
  136. ]
  137. else:
  138. input_boxes = [
  139. self._normalize_coordinates(self.target_size, box, original_size, is_bounding_box=True)
  140. for box, original_size in zip(input_boxes, original_sizes)
  141. ]
  142. input_boxes = np.array(input_boxes)
  143. if input_boxes is not None:
  144. if return_tensors == "pt":
  145. input_boxes = torch.from_numpy(input_boxes)
  146. # boxes batch size of 1 by default
  147. input_boxes = input_boxes.unsqueeze(1) if len(input_boxes.shape) != 3 else input_boxes
  148. elif return_tensors == "tf":
  149. input_boxes = tf.convert_to_tensor(input_boxes)
  150. # boxes batch size of 1 by default
  151. input_boxes = tf.expand_dims(input_boxes, 1) if len(input_boxes.shape) != 3 else input_boxes
  152. encoding_image_processor.update({"input_boxes": input_boxes})
  153. if input_points is not None:
  154. if return_tensors == "pt":
  155. input_points = torch.from_numpy(input_points)
  156. # point batch size of 1 by default
  157. input_points = input_points.unsqueeze(1) if len(input_points.shape) != 4 else input_points
  158. elif return_tensors == "tf":
  159. input_points = tf.convert_to_tensor(input_points)
  160. # point batch size of 1 by default
  161. input_points = tf.expand_dims(input_points, 1) if len(input_points.shape) != 4 else input_points
  162. encoding_image_processor.update({"input_points": input_points})
  163. if input_labels is not None:
  164. if return_tensors == "pt":
  165. input_labels = torch.from_numpy(input_labels)
  166. # point batch size of 1 by default
  167. input_labels = input_labels.unsqueeze(1) if len(input_labels.shape) != 3 else input_labels
  168. elif return_tensors == "tf":
  169. input_labels = tf.convert_to_tensor(input_labels)
  170. # point batch size of 1 by default
  171. input_labels = tf.expand_dims(input_labels, 1) if len(input_labels.shape) != 3 else input_labels
  172. encoding_image_processor.update({"input_labels": input_labels})
  173. return encoding_image_processor
  174. def _pad_points_and_labels(self, input_points, input_labels, point_pad_value):
  175. r"""
  176. The method pads the 2D points and labels to the maximum number of points in the batch.
  177. """
  178. expected_nb_points = max(point.shape[0] for point in input_points)
  179. processed_input_points = []
  180. for i, point in enumerate(input_points):
  181. if point.shape[0] != expected_nb_points:
  182. point = np.concatenate(
  183. [point, np.zeros((expected_nb_points - point.shape[0], 2)) + point_pad_value], axis=0
  184. )
  185. input_labels[i] = np.append(input_labels[i], [point_pad_value])
  186. processed_input_points.append(point)
  187. input_points = processed_input_points
  188. return input_points, input_labels
  189. def _normalize_coordinates(
  190. self, target_size: int, coords: np.ndarray, original_size, is_bounding_box=False
  191. ) -> np.ndarray:
  192. """
  193. Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H, W) format.
  194. """
  195. old_h, old_w = original_size
  196. new_h, new_w = self.image_processor._get_preprocess_shape(original_size, longest_edge=target_size)
  197. coords = deepcopy(coords).astype(float)
  198. if is_bounding_box:
  199. coords = coords.reshape(-1, 2, 2)
  200. coords[..., 0] = coords[..., 0] * (new_w / old_w)
  201. coords[..., 1] = coords[..., 1] * (new_h / old_h)
  202. if is_bounding_box:
  203. coords = coords.reshape(-1, 4)
  204. return coords
  205. def _check_and_preprocess_points(
  206. self,
  207. input_points=None,
  208. input_labels=None,
  209. input_boxes=None,
  210. ):
  211. r"""
  212. Check and preprocesses the 2D points, labels and bounding boxes. It checks if the input is valid and if they
  213. are, it converts the coordinates of the points and bounding boxes. If a user passes directly a `torch.Tensor`,
  214. it is converted to a `numpy.ndarray` and then to a `list`.
  215. """
  216. if input_points is not None:
  217. if hasattr(input_points, "numpy"): # Checks for TF or Torch tensor
  218. input_points = input_points.numpy().tolist()
  219. if not isinstance(input_points, list) or not isinstance(input_points[0], list):
  220. raise ValueError("Input points must be a list of list of floating points.")
  221. input_points = [np.array(input_point) for input_point in input_points]
  222. else:
  223. input_points = None
  224. if input_labels is not None:
  225. if hasattr(input_labels, "numpy"):
  226. input_labels = input_labels.numpy().tolist()
  227. if not isinstance(input_labels, list) or not isinstance(input_labels[0], list):
  228. raise ValueError("Input labels must be a list of list integers.")
  229. input_labels = [np.array(label) for label in input_labels]
  230. else:
  231. input_labels = None
  232. if input_boxes is not None:
  233. if hasattr(input_boxes, "numpy"):
  234. input_boxes = input_boxes.numpy().tolist()
  235. if (
  236. not isinstance(input_boxes, list)
  237. or not isinstance(input_boxes[0], list)
  238. or not isinstance(input_boxes[0][0], list)
  239. ):
  240. raise ValueError("Input boxes must be a list of list of list of floating points.")
  241. input_boxes = [np.array(box).astype(np.float32) for box in input_boxes]
  242. else:
  243. input_boxes = None
  244. return input_points, input_labels, input_boxes
  245. @property
  246. def model_input_names(self):
  247. image_processor_input_names = self.image_processor.model_input_names
  248. return list(image_processor_input_names + ["original_sizes", "reshaped_input_sizes"])
  249. def post_process_masks(self, *args, **kwargs):
  250. return self.image_processor.post_process_masks(*args, **kwargs)
  251. __all__ = ["SamProcessor"]