det.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 os
  15. from ...utils.io import ImageReader
  16. from ..base import BaseComponent
  17. class DetPostProcess(BaseComponent):
  18. """Save Result Transform"""
  19. INPUT_KEYS = ["img_path", "boxes"]
  20. OUTPUT_KEYS = ["boxes", "labels"]
  21. DEAULT_INPUTS = {"boxes": "boxes"}
  22. DEAULT_OUTPUTS = {
  23. "boxes": "boxes",
  24. "labels": "labels",
  25. }
  26. def __init__(self, threshold=0.5, labels=None):
  27. super().__init__()
  28. self.threshold = threshold
  29. self.labels = labels
  30. def apply(self, boxes):
  31. """apply"""
  32. expect_boxes = (boxes[:, 1] > self.threshold) & (boxes[:, 0] > -1)
  33. boxes = boxes[expect_boxes, :]
  34. result = {"boxes": boxes, "labels": self.labels}
  35. return result
  36. class CropByBoxes(BaseComponent):
  37. """Crop Image by Box"""
  38. INPUT_KEYS = ["img_path", "boxes", "labels"]
  39. OUTPUT_KEYS = ["img", "box", "label"]
  40. DEAULT_INPUTS = {"img_path": "img_path", "boxes": "boxes", "labels": "labels"}
  41. DEAULT_OUTPUTS = {"img": "img", "box": "box", "label": "label"}
  42. def __init__(self):
  43. super().__init__()
  44. self._reader = ImageReader(backend="opencv")
  45. def apply(self, img_path, boxes, labels=None):
  46. output_list = []
  47. img = self._reader.read(img_path)
  48. for bbox in boxes:
  49. label_id = int(bbox[0])
  50. box = bbox[2:]
  51. if labels is not None:
  52. label = labels[label_id]
  53. else:
  54. label = label_id
  55. xmin, ymin, xmax, ymax = [int(i) for i in box]
  56. img_crop = img[ymin:ymax, xmin:xmax]
  57. output_list.append({"img": img_crop, "box": box, "label": label})
  58. return output_list