pipeline.py 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. ):
  33. super().__init__(device=device, pp_option=pp_option, use_hpip=use_hpip)
  34. self.det_model = self.create_model(config["SubModules"]["Detection"])
  35. self.cls_model = self.create_model(config["SubModules"]["Classification"])
  36. self._crop_by_boxes = CropByBoxes()
  37. self._img_reader = ReadImage(format="BGR")
  38. self.det_threshold = config["SubModules"]["Detection"].get("threshold", 0.5)
  39. self.cls_threshold = config["SubModules"]["Classification"].get(
  40. "threshold", 0.7
  41. )
  42. self.batch_sampler = ImageBatchSampler(
  43. batch_size=config["SubModules"]["Detection"]["batch_size"]
  44. )
  45. self.img_reader = ReadImage(format="BGR")
  46. def predict(self, input, **kwargs):
  47. det_threshold = kwargs.pop("det_threshold", self.det_threshold)
  48. cls_threshold = kwargs.pop("cls_threshold", self.cls_threshold)
  49. for img_id, batch_data in enumerate(self.batch_sampler(input)):
  50. raw_imgs = self.img_reader(batch_data)
  51. all_det_res = list(self.det_model(raw_imgs, threshold=det_threshold))
  52. for input_data, raw_img, det_res in zip(batch_data, raw_imgs, all_det_res):
  53. cls_res = self.get_cls_result(raw_img, det_res, cls_threshold)
  54. yield self.get_final_result(input_data, raw_img, det_res, cls_res)
  55. def get_cls_result(self, raw_img, det_res, cls_threshold):
  56. subs_of_img = list(self._crop_by_boxes(raw_img, det_res["boxes"]))
  57. img_list = [img["img"] for img in subs_of_img]
  58. all_cls_res = list(self.cls_model(img_list, threshold=cls_threshold))
  59. output = {"label": [], "score": []}
  60. for res in all_cls_res:
  61. output["label"].append(res["label_names"])
  62. output["score"].append(res["scores"])
  63. return output
  64. def get_final_result(self, input_data, raw_img, det_res, rec_res):
  65. single_img_res = {"input_path": input_data, "input_img": raw_img, "boxes": []}
  66. for i, obj in enumerate(det_res["boxes"]):
  67. cls_scores = rec_res["score"][i]
  68. labels = rec_res["label"][i]
  69. single_img_res["boxes"].append(
  70. {
  71. "labels": labels,
  72. "cls_scores": cls_scores,
  73. "det_score": obj["score"],
  74. "coordinate": obj["coordinate"],
  75. }
  76. )
  77. return AttributeRecResult(single_img_res)
  78. class PedestrianAttributeRecPipeline(AttributeRecPipeline):
  79. entities = "pedestrian_attribute_recognition"
  80. class VehicleAttributeRecPipeline(AttributeRecPipeline):
  81. entities = "vehicle_attribute_recognition"