processing_sam.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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 ...processing_utils import ProcessorMixin
  22. from ...tokenization_utils_base import BatchEncoding
  23. from ...utils import TensorType, is_tf_available, is_torch_available
  24. if is_torch_available():
  25. import torch
  26. if is_tf_available():
  27. import tensorflow as tf
  28. class SamProcessor(ProcessorMixin):
  29. r"""
  30. Constructs a SAM processor which wraps a SAM image processor and an 2D points & Bounding boxes processor into a
  31. single processor.
  32. [`SamProcessor`] offers all the functionalities of [`SamImageProcessor`]. See the docstring of
  33. [`~SamImageProcessor.__call__`] for more information.
  34. Args:
  35. image_processor (`SamImageProcessor`):
  36. An instance of [`SamImageProcessor`]. The image processor is a required input.
  37. """
  38. attributes = ["image_processor"]
  39. image_processor_class = "SamImageProcessor"
  40. def __init__(self, image_processor):
  41. super().__init__(image_processor)
  42. self.current_processor = self.image_processor
  43. self.point_pad_value = -10
  44. self.target_size = self.image_processor.size["longest_edge"]
  45. def __call__(
  46. self,
  47. images=None,
  48. segmentation_maps=None,
  49. input_points=None,
  50. input_labels=None,
  51. input_boxes=None,
  52. return_tensors: Optional[Union[str, TensorType]] = None,
  53. **kwargs,
  54. ) -> BatchEncoding:
  55. """
  56. This method uses [`SamImageProcessor.__call__`] method to prepare image(s) for the model. It also prepares 2D
  57. points and bounding boxes for the model if they are provided.
  58. """
  59. encoding_image_processor = self.image_processor(
  60. images,
  61. segmentation_maps=segmentation_maps,
  62. return_tensors=return_tensors,
  63. **kwargs,
  64. )
  65. # pop arguments that are not used in the foward but used nevertheless
  66. original_sizes = encoding_image_processor["original_sizes"]
  67. if hasattr(original_sizes, "numpy"): # Checks if Torch or TF tensor
  68. original_sizes = original_sizes.numpy()
  69. input_points, input_labels, input_boxes = self._check_and_preprocess_points(
  70. input_points=input_points,
  71. input_labels=input_labels,
  72. input_boxes=input_boxes,
  73. )
  74. encoding_image_processor = self._normalize_and_convert(
  75. encoding_image_processor,
  76. original_sizes,
  77. input_points=input_points,
  78. input_labels=input_labels,
  79. input_boxes=input_boxes,
  80. return_tensors=return_tensors,
  81. )
  82. return encoding_image_processor
  83. def _normalize_and_convert(
  84. self,
  85. encoding_image_processor,
  86. original_sizes,
  87. input_points=None,
  88. input_labels=None,
  89. input_boxes=None,
  90. return_tensors="pt",
  91. ):
  92. if input_points is not None:
  93. if len(original_sizes) != len(input_points):
  94. input_points = [
  95. self._normalize_coordinates(self.target_size, point, original_sizes[0]) for point in input_points
  96. ]
  97. else:
  98. input_points = [
  99. self._normalize_coordinates(self.target_size, point, original_size)
  100. for point, original_size in zip(input_points, original_sizes)
  101. ]
  102. # check that all arrays have the same shape
  103. if not all(point.shape == input_points[0].shape for point in input_points):
  104. if input_labels is not None:
  105. input_points, input_labels = self._pad_points_and_labels(input_points, input_labels)
  106. input_points = np.array(input_points)
  107. if input_labels is not None:
  108. input_labels = np.array(input_labels)
  109. if input_boxes is not None:
  110. if len(original_sizes) != len(input_boxes):
  111. input_boxes = [
  112. self._normalize_coordinates(self.target_size, box, original_sizes[0], is_bounding_box=True)
  113. for box in input_boxes
  114. ]
  115. else:
  116. input_boxes = [
  117. self._normalize_coordinates(self.target_size, box, original_size, is_bounding_box=True)
  118. for box, original_size in zip(input_boxes, original_sizes)
  119. ]
  120. input_boxes = np.array(input_boxes)
  121. if input_boxes is not None:
  122. if return_tensors == "pt":
  123. input_boxes = torch.from_numpy(input_boxes)
  124. # boxes batch size of 1 by default
  125. input_boxes = input_boxes.unsqueeze(1) if len(input_boxes.shape) != 3 else input_boxes
  126. elif return_tensors == "tf":
  127. input_boxes = tf.convert_to_tensor(input_boxes)
  128. # boxes batch size of 1 by default
  129. input_boxes = tf.expand_dims(input_boxes, 1) if len(input_boxes.shape) != 3 else input_boxes
  130. encoding_image_processor.update({"input_boxes": input_boxes})
  131. if input_points is not None:
  132. if return_tensors == "pt":
  133. input_points = torch.from_numpy(input_points)
  134. # point batch size of 1 by default
  135. input_points = input_points.unsqueeze(1) if len(input_points.shape) != 4 else input_points
  136. elif return_tensors == "tf":
  137. input_points = tf.convert_to_tensor(input_points)
  138. # point batch size of 1 by default
  139. input_points = tf.expand_dims(input_points, 1) if len(input_points.shape) != 4 else input_points
  140. encoding_image_processor.update({"input_points": input_points})
  141. if input_labels is not None:
  142. if return_tensors == "pt":
  143. input_labels = torch.from_numpy(input_labels)
  144. # point batch size of 1 by default
  145. input_labels = input_labels.unsqueeze(1) if len(input_labels.shape) != 3 else input_labels
  146. elif return_tensors == "tf":
  147. input_labels = tf.convert_to_tensor(input_labels)
  148. # point batch size of 1 by default
  149. input_labels = tf.expand_dims(input_labels, 1) if len(input_labels.shape) != 3 else input_labels
  150. encoding_image_processor.update({"input_labels": input_labels})
  151. return encoding_image_processor
  152. def _pad_points_and_labels(self, input_points, input_labels):
  153. r"""
  154. The method pads the 2D points and labels to the maximum number of points in the batch.
  155. """
  156. expected_nb_points = max([point.shape[0] for point in input_points])
  157. processed_input_points = []
  158. for i, point in enumerate(input_points):
  159. if point.shape[0] != expected_nb_points:
  160. point = np.concatenate(
  161. [point, np.zeros((expected_nb_points - point.shape[0], 2)) + self.point_pad_value], axis=0
  162. )
  163. input_labels[i] = np.append(input_labels[i], [self.point_pad_value])
  164. processed_input_points.append(point)
  165. input_points = processed_input_points
  166. return input_points, input_labels
  167. def _normalize_coordinates(
  168. self, target_size: int, coords: np.ndarray, original_size, is_bounding_box=False
  169. ) -> np.ndarray:
  170. """
  171. Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H, W) format.
  172. """
  173. old_h, old_w = original_size
  174. new_h, new_w = self.image_processor._get_preprocess_shape(original_size, longest_edge=target_size)
  175. coords = deepcopy(coords).astype(float)
  176. if is_bounding_box:
  177. coords = coords.reshape(-1, 2, 2)
  178. coords[..., 0] = coords[..., 0] * (new_w / old_w)
  179. coords[..., 1] = coords[..., 1] * (new_h / old_h)
  180. if is_bounding_box:
  181. coords = coords.reshape(-1, 4)
  182. return coords
  183. def _check_and_preprocess_points(
  184. self,
  185. input_points=None,
  186. input_labels=None,
  187. input_boxes=None,
  188. ):
  189. r"""
  190. Check and preprocesses the 2D points, labels and bounding boxes. It checks if the input is valid and if they
  191. are, it converts the coordinates of the points and bounding boxes. If a user passes directly a `torch.Tensor`,
  192. it is converted to a `numpy.ndarray` and then to a `list`.
  193. """
  194. if input_points is not None:
  195. if hasattr(input_points, "numpy"): # Checks for TF or Torch tensor
  196. input_points = input_points.numpy().tolist()
  197. if not isinstance(input_points, list) or not isinstance(input_points[0], list):
  198. raise ValueError("Input points must be a list of list of floating points.")
  199. input_points = [np.array(input_point) for input_point in input_points]
  200. else:
  201. input_points = None
  202. if input_labels is not None:
  203. if hasattr(input_labels, "numpy"):
  204. input_labels = input_labels.numpy().tolist()
  205. if not isinstance(input_labels, list) or not isinstance(input_labels[0], list):
  206. raise ValueError("Input labels must be a list of list integers.")
  207. input_labels = [np.array(label) for label in input_labels]
  208. else:
  209. input_labels = None
  210. if input_boxes is not None:
  211. if hasattr(input_boxes, "numpy"):
  212. input_boxes = input_boxes.numpy().tolist()
  213. if (
  214. not isinstance(input_boxes, list)
  215. or not isinstance(input_boxes[0], list)
  216. or not isinstance(input_boxes[0][0], list)
  217. ):
  218. raise ValueError("Input boxes must be a list of list of list of floating points.")
  219. input_boxes = [np.array(box).astype(np.float32) for box in input_boxes]
  220. else:
  221. input_boxes = None
  222. return input_points, input_labels, input_boxes
  223. @property
  224. def model_input_names(self):
  225. image_processor_input_names = self.image_processor.model_input_names
  226. return list(dict.fromkeys(image_processor_input_names))
  227. def post_process_masks(self, *args, **kwargs):
  228. return self.image_processor.post_process_masks(*args, **kwargs)