pipeline.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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
  15. import pickle
  16. from pathlib import Path
  17. import numpy as np
  18. from ...utils.pp_option import PaddlePredictorOption
  19. from ...common.reader import ReadImage
  20. from ...common.batch_sampler import ImageBatchSampler
  21. from ..components import CropByBoxes
  22. from ..base import BasePipeline
  23. from .result import AttributeRecResult
  24. class AttributeRecPipeline(BasePipeline):
  25. """Attribute Rec Pipeline"""
  26. def __init__(
  27. self,
  28. config: Dict,
  29. device: str = None,
  30. pp_option: PaddlePredictorOption = None,
  31. use_hpip: bool = False,
  32. hpi_params: Optional[Dict[str, Any]] = None,
  33. ):
  34. super().__init__(
  35. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  36. )
  37. self.det_model = self.create_model(config["SubModules"]["Detection"])
  38. self.cls_model = self.create_model(config["SubModules"]["Classification"])
  39. self._crop_by_boxes = CropByBoxes()
  40. self._img_reader = ReadImage(format="BGR")
  41. self.det_threshold = config["SubModules"]["Detection"].get("threshold", 0.7)
  42. self.cls_threshold = config["SubModules"]["Classification"].get(
  43. "threshold", 0.7
  44. )
  45. self.batch_sampler = ImageBatchSampler(
  46. batch_size=config["SubModules"]["Detection"]["batch_size"]
  47. )
  48. self.img_reader = ReadImage(format="BGR")
  49. def predict(self, input, **kwargs):
  50. det_threshold = kwargs.pop("det_threshold", self.det_threshold)
  51. cls_threshold = kwargs.pop("cls_threshold", self.cls_threshold)
  52. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  53. raw_imgs = self.img_reader(batch_data)
  54. all_det_res = list(self.det_model(raw_imgs, threshold=det_threshold))
  55. for input_data, raw_img, det_res in zip(batch_data, raw_imgs, all_det_res):
  56. cls_res = self.get_cls_result(raw_img, det_res, cls_threshold)
  57. yield self.get_final_result(input_data, raw_img, det_res, cls_res)
  58. def get_cls_result(self, raw_img, det_res, cls_threshold):
  59. subs_of_img = list(self._crop_by_boxes(raw_img, det_res["boxes"]))
  60. img_list = [img["img"] for img in subs_of_img]
  61. all_cls_res = list(self.cls_model(img_list, threshold=cls_threshold))
  62. output = {"label": [], "score": []}
  63. for res in all_cls_res:
  64. output["label"].append(res["label_names"])
  65. output["score"].append(res["scores"])
  66. return output
  67. def get_final_result(self, input_data, raw_img, det_res, rec_res):
  68. single_img_res = {"input_path": input_data, "input_img": raw_img, "boxes": []}
  69. for i, obj in enumerate(det_res["boxes"]):
  70. rec_scores = rec_res["score"][i]
  71. labels = rec_res["label"][i]
  72. single_img_res["boxes"].append(
  73. {
  74. "labels": labels,
  75. "rec_scores": rec_scores,
  76. "det_score": obj["score"],
  77. "coordinate": obj["coordinate"],
  78. }
  79. )
  80. return AttributeRecResult(single_img_res)
  81. class PedestrianAttributeRecPipeline(AttributeRecPipeline):
  82. entities = "pedestrian_attribute_recognition"
  83. class VehicleAttributeRecPipeline(AttributeRecPipeline):
  84. entities = "vehicle_attribute_recognition"