object_detection.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. from typing import TYPE_CHECKING, Any, Union, overload
  2. from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
  3. from .base import Pipeline, build_pipeline_init_args
  4. if is_vision_available():
  5. from ..image_utils import load_image
  6. if is_torch_available():
  7. import torch
  8. from ..models.auto.modeling_auto import (
  9. MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
  10. MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
  11. )
  12. if TYPE_CHECKING:
  13. from PIL import Image
  14. logger = logging.get_logger(__name__)
  15. @add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
  16. class ObjectDetectionPipeline(Pipeline):
  17. """
  18. Object detection pipeline using any `AutoModelForObjectDetection`. This pipeline predicts bounding boxes of objects
  19. and their classes.
  20. Example:
  21. ```python
  22. >>> from transformers import pipeline
  23. >>> detector = pipeline(model="facebook/detr-resnet-50")
  24. >>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
  25. [{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}]
  26. >>> # x, y are expressed relative to the top left hand corner.
  27. ```
  28. Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
  29. This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier:
  30. `"object-detection"`.
  31. See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=object-detection).
  32. """
  33. _load_processor = False
  34. _load_image_processor = True
  35. _load_feature_extractor = False
  36. _load_tokenizer = None
  37. def __init__(self, *args, **kwargs):
  38. super().__init__(*args, **kwargs)
  39. requires_backends(self, "vision")
  40. mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES.copy()
  41. mapping.update(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES)
  42. self.check_model_type(mapping)
  43. def _sanitize_parameters(self, **kwargs):
  44. preprocess_params = {}
  45. if "timeout" in kwargs:
  46. preprocess_params["timeout"] = kwargs["timeout"]
  47. postprocess_kwargs = {}
  48. if "threshold" in kwargs:
  49. postprocess_kwargs["threshold"] = kwargs["threshold"]
  50. return preprocess_params, {}, postprocess_kwargs
  51. @overload
  52. def __call__(self, image: Union[str, "Image.Image"], *args: Any, **kwargs: Any) -> list[dict[str, Any]]: ...
  53. @overload
  54. def __call__(
  55. self, image: list[str] | list["Image.Image"], *args: Any, **kwargs: Any
  56. ) -> list[list[dict[str, Any]]]: ...
  57. def __call__(self, *args, **kwargs) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
  58. """
  59. Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
  60. Args:
  61. inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
  62. The pipeline handles three types of images:
  63. - A string containing an HTTP(S) link pointing to an image
  64. - A string containing a local path to an image
  65. - An image loaded in PIL directly
  66. The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the
  67. same format: all as HTTP(S) links, all as local paths, or all as PIL images.
  68. threshold (`float`, *optional*, defaults to 0.5):
  69. The probability necessary to make a prediction.
  70. timeout (`float`, *optional*, defaults to None):
  71. The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
  72. the call may block forever.
  73. Return:
  74. A list of dictionaries or a list of list of dictionaries containing the result. If the input is a single
  75. image, will return a list of dictionaries, if the input is a list of several images, will return a list of
  76. list of dictionaries corresponding to each image.
  77. The dictionaries contain the following keys:
  78. - **label** (`str`) -- The class label identified by the model.
  79. - **score** (`float`) -- The score attributed by the model for that label.
  80. - **box** (`list[dict[str, int]]`) -- The bounding box of detected object in image's original size.
  81. """
  82. # After deprecation of this is completed, remove the default `None` value for `images`
  83. if "images" in kwargs and "inputs" not in kwargs:
  84. kwargs["inputs"] = kwargs.pop("images")
  85. return super().__call__(*args, **kwargs)
  86. def preprocess(self, image, timeout=None):
  87. image = load_image(image, timeout=timeout)
  88. target_size = torch.IntTensor([[image.height, image.width]])
  89. inputs = self.image_processor(images=[image], return_tensors="pt")
  90. inputs = inputs.to(self.dtype)
  91. if self.tokenizer is not None:
  92. inputs = self.tokenizer(text=inputs["words"], boxes=inputs["boxes"], return_tensors="pt")
  93. inputs["target_size"] = target_size
  94. return inputs
  95. def _forward(self, model_inputs):
  96. target_size = model_inputs.pop("target_size")
  97. outputs = self.model(**model_inputs)
  98. model_outputs = outputs.__class__({"target_size": target_size, **outputs})
  99. if self.tokenizer is not None:
  100. model_outputs["bbox"] = model_inputs["bbox"]
  101. return model_outputs
  102. def postprocess(self, model_outputs, threshold=0.5):
  103. target_size = model_outputs["target_size"]
  104. if self.tokenizer is not None:
  105. # This is a LayoutLMForTokenClassification variant.
  106. # The OCR got the boxes and the model classified the words.
  107. height, width = target_size[0].tolist()
  108. def unnormalize(bbox):
  109. return self._get_bounding_box(
  110. torch.Tensor(
  111. [
  112. (width * bbox[0] / 1000),
  113. (height * bbox[1] / 1000),
  114. (width * bbox[2] / 1000),
  115. (height * bbox[3] / 1000),
  116. ]
  117. )
  118. )
  119. scores, classes = model_outputs["logits"].squeeze(0).softmax(dim=-1).max(dim=-1)
  120. labels = [self.model.config.id2label[prediction] for prediction in classes.tolist()]
  121. boxes = [unnormalize(bbox) for bbox in model_outputs["bbox"].squeeze(0)]
  122. keys = ["score", "label", "box"]
  123. annotation = [dict(zip(keys, vals)) for vals in zip(scores.tolist(), labels, boxes) if vals[0] > threshold]
  124. else:
  125. # This is a regular ForObjectDetectionModel
  126. raw_annotations = self.image_processor.post_process_object_detection(model_outputs, threshold, target_size)
  127. raw_annotation = raw_annotations[0]
  128. scores = raw_annotation["scores"]
  129. labels = raw_annotation["labels"]
  130. boxes = raw_annotation["boxes"]
  131. raw_annotation["scores"] = scores.tolist()
  132. raw_annotation["labels"] = [self.model.config.id2label[label.item()] for label in labels]
  133. raw_annotation["boxes"] = [self._get_bounding_box(box) for box in boxes]
  134. # {"scores": [...], ...} --> [{"score":x, ...}, ...]
  135. keys = ["score", "label", "box"]
  136. annotation = [
  137. dict(zip(keys, vals))
  138. for vals in zip(raw_annotation["scores"], raw_annotation["labels"], raw_annotation["boxes"])
  139. ]
  140. return annotation
  141. def _get_bounding_box(self, box: "torch.Tensor") -> dict[str, int]:
  142. """
  143. Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }
  144. Args:
  145. box (`torch.Tensor`): Tensor containing the coordinates in corners format.
  146. Returns:
  147. bbox (`dict[str, int]`): Dict containing the coordinates in corners format.
  148. """
  149. xmin, ymin, xmax, ymax = box.int().tolist()
  150. bbox = {
  151. "xmin": xmin,
  152. "ymin": ymin,
  153. "xmax": xmax,
  154. "ymax": ymax,
  155. }
  156. return bbox