pipeline.py 5.1 KB

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