pipeline.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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.hpi import HPIConfig
  19. from ...utils.pp_option import PaddlePredictorOption
  20. from ..base import BasePipeline
  21. Number = Union[int, float]
  22. @pipeline_requires_extra("cv")
  23. class KeypointDetectionPipeline(BasePipeline):
  24. """Keypoint Detection pipeline"""
  25. entities = "human_keypoint_detection"
  26. def __init__(
  27. self,
  28. config: Dict,
  29. device: str = None,
  30. pp_option: PaddlePredictorOption = None,
  31. use_hpip: bool = False,
  32. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  33. ) -> None:
  34. """
  35. Initializes the class with given configurations and options.
  36. Args:
  37. config (Dict): Configuration dictionary containing model and other parameters.
  38. device (str): The device to run the prediction on. Default is None.
  39. pp_option (PaddlePredictorOption): Options for PaddlePaddle predictor. Default is None.
  40. use_hpip (bool, optional): Whether to use the high-performance
  41. inference plugin (HPIP) by default. Defaults to False.
  42. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  43. The default high-performance inference configuration dictionary.
  44. Defaults to None.
  45. """
  46. super().__init__(
  47. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_config=hpi_config
  48. )
  49. # create object detection model
  50. model_cfg = config["SubModules"]["ObjectDetection"]
  51. model_kwargs = {}
  52. self.det_threshold = None
  53. if "threshold" in model_cfg:
  54. model_kwargs["threshold"] = model_cfg["threshold"]
  55. self.det_threshold = model_cfg["threshold"]
  56. if "imgsz" in model_cfg:
  57. model_kwargs["imgsz"] = model_cfg["imgsz"]
  58. self.det_model = self.create_model(model_cfg, **model_kwargs)
  59. # create keypoint detection model
  60. model_cfg = config["SubModules"]["KeypointDetection"]
  61. model_kwargs = {}
  62. if "flip" in model_cfg:
  63. model_kwargs["flip"] = model_cfg["flip"]
  64. if "use_udp" in model_cfg:
  65. model_kwargs["use_udp"] = model_cfg["use_udp"]
  66. self.kpt_model = self.create_model(model_cfg, **model_kwargs)
  67. self.kpt_input_size = self.kpt_model.input_size
  68. def _box_xyxy2cs(
  69. self, bbox: Union[Number, np.ndarray], padding: float = 1.25
  70. ) -> Tuple[np.ndarray, np.ndarray]:
  71. """
  72. Convert bounding box from (x1, y1, x2, y2) to center and scale.
  73. Args:
  74. bbox (Union[Number, np.ndarray]): The bounding box coordinates (x1, y1, x2, y2).
  75. padding (float): The padding factor to adjust the scale of the bounding box.
  76. Returns:
  77. Tuple[np.ndarray, np.ndarray]: The center and scale of the bounding box.
  78. """
  79. x1, y1, x2, y2 = bbox[:4]
  80. center = np.array([x1 + x2, y1 + y2]) * 0.5
  81. # reshape bbox to fixed aspect ratio
  82. aspect_ratio = self.kpt_input_size[0] / self.kpt_input_size[1]
  83. w, h = x2 - x1, y2 - y1
  84. if w > aspect_ratio * h:
  85. h = w / aspect_ratio
  86. elif w < aspect_ratio * h:
  87. w = h * aspect_ratio
  88. scale = np.array([w, h]) * padding
  89. return center, scale
  90. def predict(
  91. self,
  92. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  93. det_threshold: Optional[float] = None,
  94. **kwargs,
  95. ) -> KptResult:
  96. """Predicts image classification results for the given input.
  97. Args:
  98. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) or path(s) to the images.
  99. det_threshold (float): The detection threshold. Defaults to None.
  100. **kwargs: Additional keyword arguments that can be passed to the function.
  101. Returns:
  102. KptResult: The predicted KeyPoint Detection results.
  103. """
  104. det_threshold = self.det_threshold if det_threshold is None else det_threshold
  105. for det_res in self.det_model(input, threshold=det_threshold):
  106. ori_img, img_path = det_res["input_img"], det_res["input_path"]
  107. single_img_res = {"input_path": img_path, "input_img": ori_img, "boxes": []}
  108. for box in det_res["boxes"]:
  109. center, scale = self._box_xyxy2cs(box["coordinate"])
  110. kpt_res = next(
  111. self.kpt_model(
  112. {
  113. "img": ori_img,
  114. "center": center,
  115. "scale": scale,
  116. }
  117. )
  118. )
  119. single_img_res["boxes"].append(
  120. {
  121. "coordinate": box["coordinate"],
  122. "det_score": box["score"],
  123. "keypoints": kpt_res["kpts"][0]["keypoints"],
  124. "kpt_score": kpt_res["kpts"][0]["kpt_score"],
  125. }
  126. )
  127. yield KptResult(single_img_res)