pipeline.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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, Union
  15. import numpy as np
  16. from ....utils.deps import pipeline_requires_extra
  17. from ...common.batch_sampler import ImageBatchSampler
  18. from ...common.reader import ReadImage
  19. from ...utils.benchmark import benchmark
  20. from ...utils.hpi import HPIConfig
  21. from ...utils.pp_option import PaddlePredictorOption
  22. from .._parallel import AutoParallelImageSimpleInferencePipeline
  23. from ..base import BasePipeline
  24. from ..components import CropByBoxes
  25. from .result import AttributeRecResult
  26. @benchmark.time_methods
  27. class _AttributeRecPipeline(BasePipeline):
  28. """Attribute Rec Pipeline"""
  29. def __init__(
  30. self,
  31. config: Dict,
  32. device: str = None,
  33. pp_option: PaddlePredictorOption = None,
  34. use_hpip: bool = False,
  35. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  36. ):
  37. super().__init__(
  38. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_config=hpi_config
  39. )
  40. self.det_model = self.create_model(config["SubModules"]["Detection"])
  41. self.cls_model = self.create_model(config["SubModules"]["Classification"])
  42. self._crop_by_boxes = CropByBoxes()
  43. self._img_reader = ReadImage(format="BGR")
  44. self.det_threshold = config["SubModules"]["Detection"].get("threshold", 0.5)
  45. self.cls_threshold = config["SubModules"]["Classification"].get(
  46. "threshold", 0.7
  47. )
  48. self.batch_sampler = ImageBatchSampler(
  49. batch_size=config["SubModules"]["Detection"]["batch_size"]
  50. )
  51. self.img_reader = ReadImage(format="BGR")
  52. def predict(
  53. self,
  54. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  55. det_threshold: float = None,
  56. cls_threshold: Union[float, dict, list, None] = None,
  57. **kwargs
  58. ):
  59. det_threshold = self.det_threshold if det_threshold is None else det_threshold
  60. cls_threshold = self.cls_threshold if cls_threshold is None else cls_threshold
  61. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  62. raw_imgs = self.img_reader(batch_data.instances)
  63. all_det_res = list(self.det_model(raw_imgs, threshold=det_threshold))
  64. for input_path, input_data, raw_img, det_res in zip(
  65. batch_data.input_paths, batch_data.instances, raw_imgs, all_det_res
  66. ):
  67. cls_res = self.get_cls_result(raw_img, det_res, cls_threshold)
  68. yield self.get_final_result(input_path, raw_img, det_res, cls_res)
  69. def get_cls_result(self, raw_img, det_res, cls_threshold):
  70. subs_of_img = list(self._crop_by_boxes(raw_img, det_res["boxes"]))
  71. img_list = [img["img"] for img in subs_of_img]
  72. all_cls_res = list(self.cls_model(img_list, threshold=cls_threshold))
  73. output = {"label": [], "score": []}
  74. for res in all_cls_res:
  75. output["label"].append(res["label_names"])
  76. output["score"].append(res["scores"])
  77. return output
  78. def get_final_result(self, input_path, raw_img, det_res, rec_res):
  79. single_img_res = {"input_path": input_path, "input_img": raw_img, "boxes": []}
  80. for i, obj in enumerate(det_res["boxes"]):
  81. cls_scores = rec_res["score"][i]
  82. labels = rec_res["label"][i]
  83. single_img_res["boxes"].append(
  84. {
  85. "labels": labels,
  86. "cls_scores": cls_scores,
  87. "det_score": obj["score"],
  88. "coordinate": obj["coordinate"],
  89. }
  90. )
  91. return AttributeRecResult(single_img_res)
  92. class AttributeRecPipeline(AutoParallelImageSimpleInferencePipeline):
  93. @property
  94. def _pipeline_cls(self):
  95. return _AttributeRecPipeline
  96. def _get_batch_size(self, config):
  97. return config["SubModules"]["Detection"]["batch_size"]
  98. @pipeline_requires_extra("cv")
  99. class PedestrianAttributeRecPipeline(AttributeRecPipeline):
  100. entities = "pedestrian_attribute_recognition"
  101. @pipeline_requires_extra("cv")
  102. class VehicleAttributeRecPipeline(AttributeRecPipeline):
  103. entities = "vehicle_attribute_recognition"