pipeline.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Any, Dict, List, Optional, Tuple, Union
  15. import numpy as np
  16. from ....utils.deps import pipeline_requires_extra
  17. from ...models.keypoint_detection.result import KptResult
  18. from ...utils.benchmark import benchmark
  19. from ...utils.hpi import HPIConfig
  20. from ...utils.pp_option import PaddlePredictorOption
  21. from .._parallel import AutoParallelImageSimpleInferencePipeline
  22. from ..base import BasePipeline
  23. Number = Union[int, float]
  24. @benchmark.time_methods
  25. class _KeypointDetectionPipeline(BasePipeline):
  26. """Keypoint Detection pipeline"""
  27. def __init__(
  28. self,
  29. config: Dict,
  30. device: str = None,
  31. pp_option: PaddlePredictorOption = None,
  32. use_hpip: bool = False,
  33. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  34. ) -> None:
  35. """
  36. Initializes the class with given configurations and options.
  37. Args:
  38. config (Dict): Configuration dictionary containing model and other parameters.
  39. device (str): The device to run the prediction on. Default is None.
  40. pp_option (PaddlePredictorOption): Options for PaddlePaddle predictor. Default is None.
  41. use_hpip (bool, optional): Whether to use the high-performance
  42. inference plugin (HPIP) by default. Defaults to False.
  43. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  44. The default high-performance inference configuration dictionary.
  45. Defaults to None.
  46. """
  47. super().__init__(
  48. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_config=hpi_config
  49. )
  50. # create object detection model
  51. model_cfg = config["SubModules"]["ObjectDetection"]
  52. model_kwargs = {}
  53. self.det_threshold = None
  54. if "threshold" in model_cfg:
  55. model_kwargs["threshold"] = model_cfg["threshold"]
  56. self.det_threshold = model_cfg["threshold"]
  57. if "imgsz" in model_cfg:
  58. model_kwargs["imgsz"] = model_cfg["imgsz"]
  59. self.det_model = self.create_model(model_cfg, **model_kwargs)
  60. # create keypoint detection model
  61. model_cfg = config["SubModules"]["KeypointDetection"]
  62. model_kwargs = {}
  63. if "flip" in model_cfg:
  64. model_kwargs["flip"] = model_cfg["flip"]
  65. if "use_udp" in model_cfg:
  66. model_kwargs["use_udp"] = model_cfg["use_udp"]
  67. self.kpt_model = self.create_model(model_cfg, **model_kwargs)
  68. self.kpt_input_size = self.kpt_model.input_size
  69. def _box_xyxy2cs(
  70. self, bbox: Union[Number, np.ndarray], padding: float = 1.25
  71. ) -> Tuple[np.ndarray, np.ndarray]:
  72. """
  73. Convert bounding box from (x1, y1, x2, y2) to center and scale.
  74. Args:
  75. bbox (Union[Number, np.ndarray]): The bounding box coordinates (x1, y1, x2, y2).
  76. padding (float): The padding factor to adjust the scale of the bounding box.
  77. Returns:
  78. Tuple[np.ndarray, np.ndarray]: The center and scale of the bounding box.
  79. """
  80. x1, y1, x2, y2 = bbox[:4]
  81. center = np.array([x1 + x2, y1 + y2]) * 0.5
  82. # reshape bbox to fixed aspect ratio
  83. aspect_ratio = self.kpt_input_size[0] / self.kpt_input_size[1]
  84. w, h = x2 - x1, y2 - y1
  85. if w > aspect_ratio * h:
  86. h = w / aspect_ratio
  87. elif w < aspect_ratio * h:
  88. w = h * aspect_ratio
  89. scale = np.array([w, h]) * padding
  90. return center, scale
  91. def predict(
  92. self,
  93. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  94. det_threshold: Optional[float] = None,
  95. **kwargs,
  96. ) -> KptResult:
  97. """Predicts image classification results for the given input.
  98. Args:
  99. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) or path(s) to the images.
  100. det_threshold (float): The detection threshold. Defaults to None.
  101. **kwargs: Additional keyword arguments that can be passed to the function.
  102. Returns:
  103. KptResult: The predicted KeyPoint Detection results.
  104. """
  105. det_threshold = self.det_threshold if det_threshold is None else det_threshold
  106. for det_res in self.det_model(input, threshold=det_threshold):
  107. ori_img, img_path = det_res["input_img"], det_res["input_path"]
  108. single_img_res = {"input_path": img_path, "input_img": ori_img, "boxes": []}
  109. for box in det_res["boxes"]:
  110. center, scale = self._box_xyxy2cs(box["coordinate"])
  111. kpt_res = list(
  112. self.kpt_model(
  113. {
  114. "img": ori_img,
  115. "center": center,
  116. "scale": scale,
  117. }
  118. )
  119. )[0]
  120. single_img_res["boxes"].append(
  121. {
  122. "coordinate": box["coordinate"],
  123. "det_score": box["score"],
  124. "keypoints": kpt_res["kpts"][0]["keypoints"],
  125. "kpt_score": kpt_res["kpts"][0]["kpt_score"],
  126. }
  127. )
  128. yield KptResult(single_img_res)
  129. @pipeline_requires_extra("cv")
  130. class KeypointDetectionPipeline(AutoParallelImageSimpleInferencePipeline):
  131. entities = "human_keypoint_detection"
  132. @property
  133. def _pipeline_cls(self):
  134. return _KeypointDetectionPipeline
  135. def _get_batch_size(self, config):
  136. return config["SubModules"]["ObjectDetection"].get("batch_size", 1)