object_detection.py 8.0 KB

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