det.py 2.3 KB

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