processing_owlvit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. # coding=utf-8
  2. # Copyright 2022 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. Image/Text processor class for OWL-ViT
  17. """
  18. import warnings
  19. from typing import TYPE_CHECKING, Optional, Union
  20. import numpy as np
  21. from ...image_processing_utils import BatchFeature
  22. from ...image_utils import ImageInput
  23. from ...processing_utils import (
  24. ImagesKwargs,
  25. ProcessingKwargs,
  26. ProcessorMixin,
  27. Unpack,
  28. )
  29. from ...tokenization_utils_base import PreTokenizedInput, TextInput
  30. from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available
  31. if TYPE_CHECKING:
  32. from .modeling_owlvit import OwlViTImageGuidedObjectDetectionOutput, OwlViTObjectDetectionOutput
  33. class OwlViTImagesKwargs(ImagesKwargs, total=False):
  34. query_images: Optional[ImageInput]
  35. class OwlViTProcessorKwargs(ProcessingKwargs, total=False):
  36. images_kwargs: OwlViTImagesKwargs
  37. _defaults = {
  38. "text_kwargs": {
  39. "padding": "max_length",
  40. },
  41. "images_kwargs": {},
  42. "common_kwargs": {
  43. "return_tensors": "np",
  44. },
  45. }
  46. class OwlViTProcessor(ProcessorMixin):
  47. r"""
  48. Constructs an OWL-ViT processor which wraps [`OwlViTImageProcessor`] and [`CLIPTokenizer`]/[`CLIPTokenizerFast`]
  49. into a single processor that inherits both the image processor and tokenizer functionalities. See the
  50. [`~OwlViTProcessor.__call__`] and [`~OwlViTProcessor.decode`] for more information.
  51. Args:
  52. image_processor ([`OwlViTImageProcessor`], *optional*):
  53. The image processor is a required input.
  54. tokenizer ([`CLIPTokenizer`, `CLIPTokenizerFast`], *optional*):
  55. The tokenizer is a required input.
  56. """
  57. attributes = ["image_processor", "tokenizer"]
  58. image_processor_class = "OwlViTImageProcessor"
  59. tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast")
  60. def __init__(self, image_processor=None, tokenizer=None, **kwargs):
  61. feature_extractor = None
  62. if "feature_extractor" in kwargs:
  63. warnings.warn(
  64. "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
  65. " instead.",
  66. FutureWarning,
  67. )
  68. feature_extractor = kwargs.pop("feature_extractor")
  69. image_processor = image_processor if image_processor is not None else feature_extractor
  70. super().__init__(image_processor, tokenizer)
  71. def __call__(
  72. self,
  73. images: Optional[ImageInput] = None,
  74. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  75. audio=None,
  76. videos=None,
  77. **kwargs: Unpack[OwlViTProcessorKwargs],
  78. ) -> BatchFeature:
  79. """
  80. Main method to prepare for the model one or several text(s) and image(s). This method forwards the `text` and
  81. `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to encode:
  82. the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
  83. CLIPImageProcessor's [`~CLIPImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
  84. of the above two methods for more information.
  85. Args:
  86. images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`,
  87. `list[torch.Tensor]`):
  88. The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
  89. tensor. Both channels-first and channels-last formats are supported.
  90. text (`str`, `list[str]`, `list[list[str]]`):
  91. The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
  92. (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
  93. `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
  94. query_images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
  95. The query image to be prepared, one query image is expected per target image to be queried. Each image
  96. can be a PIL image, NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image
  97. should be of shape (C, H, W), where C is a number of channels, H and W are image height and width.
  98. return_tensors (`str` or [`~utils.TensorType`], *optional*):
  99. If set, will return tensors of a particular framework. Acceptable values are:
  100. - `'tf'`: Return TensorFlow `tf.constant` objects.
  101. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  102. - `'np'`: Return NumPy `np.ndarray` objects.
  103. - `'jax'`: Return JAX `jnp.ndarray` objects.
  104. Returns:
  105. [`BatchFeature`]: A [`BatchFeature`] with the following fields:
  106. - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
  107. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  108. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
  109. `None`).
  110. - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
  111. - **query_pixel_values** -- Pixel values of the query images to be fed to a model. Returned when `query_images` is not `None`.
  112. """
  113. output_kwargs = self._merge_kwargs(
  114. OwlViTProcessorKwargs,
  115. tokenizer_init_kwargs=self.tokenizer.init_kwargs,
  116. **kwargs,
  117. )
  118. query_images = output_kwargs["images_kwargs"].pop("query_images", None)
  119. return_tensors = output_kwargs["common_kwargs"]["return_tensors"]
  120. if text is None and query_images is None and images is None:
  121. raise ValueError(
  122. "You have to specify at least one text or query image or image. All three cannot be none."
  123. )
  124. data = {}
  125. if text is not None:
  126. if isinstance(text, str) or (isinstance(text, list) and not isinstance(text[0], list)):
  127. encodings = [self.tokenizer(text, **output_kwargs["text_kwargs"])]
  128. elif isinstance(text, list) and isinstance(text[0], list):
  129. encodings = []
  130. # Maximum number of queries across batch
  131. max_num_queries = max(len(text_single) for text_single in text)
  132. # Pad all batch samples to max number of text queries
  133. for text_single in text:
  134. if len(text_single) != max_num_queries:
  135. text_single = text_single + [" "] * (max_num_queries - len(text_single))
  136. encoding = self.tokenizer(text_single, **output_kwargs["text_kwargs"])
  137. encodings.append(encoding)
  138. else:
  139. raise TypeError("Input text should be a string, a list of strings or a nested list of strings")
  140. if return_tensors == "np":
  141. input_ids = np.concatenate([encoding["input_ids"] for encoding in encodings], axis=0)
  142. attention_mask = np.concatenate([encoding["attention_mask"] for encoding in encodings], axis=0)
  143. elif return_tensors == "jax" and is_flax_available():
  144. import jax.numpy as jnp
  145. input_ids = jnp.concatenate([encoding["input_ids"] for encoding in encodings], axis=0)
  146. attention_mask = jnp.concatenate([encoding["attention_mask"] for encoding in encodings], axis=0)
  147. elif return_tensors == "pt" and is_torch_available():
  148. import torch
  149. input_ids = torch.cat([encoding["input_ids"] for encoding in encodings], dim=0)
  150. attention_mask = torch.cat([encoding["attention_mask"] for encoding in encodings], dim=0)
  151. elif return_tensors == "tf" and is_tf_available():
  152. import tensorflow as tf
  153. input_ids = tf.stack([encoding["input_ids"] for encoding in encodings], axis=0)
  154. attention_mask = tf.stack([encoding["attention_mask"] for encoding in encodings], axis=0)
  155. else:
  156. raise ValueError("Target return tensor type could not be returned")
  157. data["input_ids"] = input_ids
  158. data["attention_mask"] = attention_mask
  159. if query_images is not None:
  160. query_pixel_values = self.image_processor(query_images, **output_kwargs["images_kwargs"]).pixel_values
  161. # Query images always override the text prompt
  162. data = {"query_pixel_values": query_pixel_values}
  163. if images is not None:
  164. image_features = self.image_processor(images, **output_kwargs["images_kwargs"])
  165. data["pixel_values"] = image_features.pixel_values
  166. return BatchFeature(data=data, tensor_type=return_tensors)
  167. def post_process(self, *args, **kwargs):
  168. """
  169. This method forwards all its arguments to [`OwlViTImageProcessor.post_process`]. Please refer to the docstring
  170. of this method for more information.
  171. """
  172. return self.image_processor.post_process(*args, **kwargs)
  173. def post_process_object_detection(self, *args, **kwargs):
  174. """
  175. This method forwards all its arguments to [`OwlViTImageProcessor.post_process_object_detection`]. Please refer
  176. to the docstring of this method for more information.
  177. """
  178. warnings.warn(
  179. "`post_process_object_detection` method is deprecated for OwlVitProcessor and will be removed in v5. "
  180. "Use `post_process_grounded_object_detection` instead.",
  181. FutureWarning,
  182. )
  183. return self.image_processor.post_process_object_detection(*args, **kwargs)
  184. def post_process_grounded_object_detection(
  185. self,
  186. outputs: "OwlViTObjectDetectionOutput",
  187. threshold: float = 0.1,
  188. target_sizes: Optional[Union[TensorType, list[tuple]]] = None,
  189. text_labels: Optional[list[list[str]]] = None,
  190. ):
  191. """
  192. Converts the raw output of [`OwlViTForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
  193. bottom_right_x, bottom_right_y) format.
  194. Args:
  195. outputs ([`OwlViTObjectDetectionOutput`]):
  196. Raw outputs of the model.
  197. threshold (`float`, *optional*, defaults to 0.1):
  198. Score threshold to keep object detection predictions.
  199. target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
  200. Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
  201. `(height, width)` of each image in the batch. If unset, predictions will not be resized.
  202. text_labels (`list[list[str]]`, *optional*):
  203. List of lists of text labels for each image in the batch. If unset, "text_labels" in output will be
  204. set to `None`.
  205. Returns:
  206. `list[Dict]`: A list of dictionaries, each dictionary containing the following keys:
  207. - "scores": The confidence scores for each predicted box on the image.
  208. - "labels": Indexes of the classes predicted by the model on the image.
  209. - "boxes": Image bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format.
  210. - "text_labels": The text labels for each predicted bounding box on the image.
  211. """
  212. output = self.image_processor.post_process_object_detection(
  213. outputs=outputs, threshold=threshold, target_sizes=target_sizes
  214. )
  215. if text_labels is not None and len(text_labels) != len(output):
  216. raise ValueError("Make sure that you pass in as many lists of text labels as images")
  217. # adding text labels to the output
  218. if text_labels is not None:
  219. for image_output, image_text_labels in zip(output, text_labels):
  220. object_text_labels = [image_text_labels[i] for i in image_output["labels"]]
  221. image_output["text_labels"] = object_text_labels
  222. else:
  223. for image_output in output:
  224. image_output["text_labels"] = None
  225. return output
  226. def post_process_image_guided_detection(
  227. self,
  228. outputs: "OwlViTImageGuidedObjectDetectionOutput",
  229. threshold: float = 0.0,
  230. nms_threshold: float = 0.3,
  231. target_sizes: Optional[Union[TensorType, list[tuple]]] = None,
  232. ):
  233. """
  234. Converts the output of [`OwlViTForObjectDetection.image_guided_detection`] into the format expected by the COCO
  235. api.
  236. Args:
  237. outputs ([`OwlViTImageGuidedObjectDetectionOutput`]):
  238. Raw outputs of the model.
  239. threshold (`float`, *optional*, defaults to 0.0):
  240. Minimum confidence threshold to use to filter out predicted boxes.
  241. nms_threshold (`float`, *optional*, defaults to 0.3):
  242. IoU threshold for non-maximum suppression of overlapping boxes.
  243. target_sizes (`torch.Tensor`, *optional*):
  244. Tensor of shape (batch_size, 2) where each entry is the (height, width) of the corresponding image in
  245. the batch. If set, predicted normalized bounding boxes are rescaled to the target sizes. If left to
  246. None, predictions will not be unnormalized.
  247. Returns:
  248. `list[Dict]`: A list of dictionaries, each dictionary containing the following keys:
  249. - "scores": The confidence scores for each predicted box on the image.
  250. - "boxes": Image bounding boxes in (top_left_x, top_left_y, bottom_right_x, bottom_right_y) format.
  251. - "labels": Set to `None`.
  252. """
  253. return self.image_processor.post_process_image_guided_detection(
  254. outputs=outputs, threshold=threshold, nms_threshold=nms_threshold, target_sizes=target_sizes
  255. )
  256. @property
  257. def feature_extractor_class(self):
  258. warnings.warn(
  259. "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
  260. FutureWarning,
  261. )
  262. return self.image_processor_class
  263. @property
  264. def feature_extractor(self):
  265. warnings.warn(
  266. "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
  267. FutureWarning,
  268. )
  269. return self.image_processor
  270. __all__ = ["OwlViTProcessor"]