pp_shitu_v2.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. import pickle
  15. from pathlib import Path
  16. import numpy as np
  17. from ..utils.io import ImageReader
  18. from ..components import CropByBoxes, FaissIndexer
  19. from ..components.retrieval.faiss import FaissBuilder
  20. from ..results import ShiTuResult
  21. from .base import BasePipeline
  22. class ShiTuV2Pipeline(BasePipeline):
  23. """ShiTuV2 Pipeline"""
  24. entities = "PP-ShiTuV2"
  25. def __init__(
  26. self,
  27. det_model,
  28. rec_model,
  29. det_batch_size=1,
  30. rec_batch_size=1,
  31. index=None,
  32. score_thres=None,
  33. hamming_radius=None,
  34. return_k=5,
  35. device=None,
  36. predictor_kwargs=None,
  37. _build_models=True,
  38. ):
  39. super().__init__(device, predictor_kwargs)
  40. if _build_models:
  41. self._build_predictor(det_model, rec_model)
  42. self.set_predictor(det_batch_size, rec_batch_size, device)
  43. self._return_k, self._score_thres, self._hamming_radius = (
  44. return_k,
  45. score_thres,
  46. hamming_radius,
  47. )
  48. self._indexer = self._build_indexer(index=index) if index else None
  49. def _build_indexer(self, index):
  50. return FaissIndexer(
  51. index=index,
  52. return_k=self._return_k,
  53. score_thres=self._score_thres,
  54. hamming_radius=self._hamming_radius,
  55. )
  56. def _build_predictor(self, det_model, rec_model):
  57. self.det_model = self._create(model=det_model)
  58. self.rec_model = self._create(model=rec_model)
  59. self._crop_by_boxes = CropByBoxes()
  60. self._img_reader = ImageReader(backend="opencv")
  61. def set_predictor(self, det_batch_size=None, rec_batch_size=None, device=None):
  62. if det_batch_size:
  63. self.det_model.set_predictor(batch_size=det_batch_size)
  64. if rec_batch_size:
  65. self.rec_model.set_predictor(batch_size=rec_batch_size)
  66. if device:
  67. self.det_model.set_predictor(device=device)
  68. self.rec_model.set_predictor(device=device)
  69. def predict(self, input, index=None, **kwargs):
  70. indexer = self._build_indexer(index) if index is not None else self._indexer
  71. assert indexer
  72. self.set_predictor(**kwargs)
  73. for det_res in self.det_model(input):
  74. rec_res = self.get_rec_result(det_res, indexer)
  75. yield self.get_final_result(det_res, rec_res)
  76. def get_rec_result(self, det_res, indexer):
  77. if len(det_res["boxes"]) == 0:
  78. full_img = self._img_reader.read(det_res["input_path"])
  79. w, h = full_img.shape[:2]
  80. det_res["boxes"].append(
  81. {
  82. "cls_id": 0,
  83. "label": "full_img",
  84. "score": 0,
  85. "coordinate": [0, 0, h, w],
  86. }
  87. )
  88. subs_of_img = list(self._crop_by_boxes(det_res))
  89. img_list = [img["img"] for img in subs_of_img]
  90. all_rec_res = list(self.rec_model(img_list))
  91. all_rec_res = next(indexer(all_rec_res))
  92. output = {"label": [], "score": []}
  93. for res in all_rec_res:
  94. output["label"].append(res["label"])
  95. output["score"].append(res["score"])
  96. return output
  97. def get_final_result(self, det_res, rec_res):
  98. single_img_res = {"input_path": det_res["input_path"], "boxes": []}
  99. for i, obj in enumerate(det_res["boxes"]):
  100. rec_scores = rec_res["score"][i]
  101. labels = rec_res["label"][i]
  102. single_img_res["boxes"].append(
  103. {
  104. "labels": labels,
  105. "rec_scores": rec_scores,
  106. "det_score": obj["score"],
  107. "coordinate": obj["coordinate"],
  108. }
  109. )
  110. return ShiTuResult(single_img_res)
  111. def build_index(
  112. self,
  113. gallery_imgs,
  114. gallery_label,
  115. metric_type="IP",
  116. index_type="HNSW32",
  117. **kwargs
  118. ):
  119. return FaissBuilder.build(
  120. gallery_imgs,
  121. gallery_label,
  122. self.rec_model.predict,
  123. metric_type=metric_type,
  124. index_type=index_type,
  125. )
  126. def remove_index(self, remove_ids, index):
  127. return FaissBuilder.remove(remove_ids, index)
  128. def append_index(
  129. self,
  130. gallery_imgs,
  131. gallery_label,
  132. index,
  133. ):
  134. return FaissBuilder.append(
  135. gallery_imgs,
  136. gallery_label,
  137. self.rec_model.predict,
  138. index,
  139. )