result.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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 List
  15. import PIL
  16. from PIL import Image, ImageDraw, ImageFont
  17. from ....utils.fonts import PINGFANG_FONT_FILE_PATH
  18. from ...utils.color_map import get_colormap, font_colormap
  19. from ...common.result import BaseCVResult
  20. def draw_box(img: Image.Image, boxes: List[dict]) -> Image.Image:
  21. """
  22. Args:
  23. img (PIL.Image.Image): PIL image
  24. boxes (list): a list of dictionaries representing detection box information.
  25. Returns:
  26. img (PIL.Image.Image): visualized image
  27. """
  28. font_size = int(0.018 * int(img.width)) + 2
  29. font = ImageFont.truetype(PINGFANG_FONT_FILE_PATH, font_size, encoding="utf-8")
  30. draw_thickness = int(max(img.size) * 0.002)
  31. draw = ImageDraw.Draw(img)
  32. label2color = {}
  33. catid2fontcolor = {}
  34. color_list = get_colormap(rgb=True)
  35. for i, dt in enumerate(boxes):
  36. # clsid = dt["cls_id"]
  37. label, bbox, score = dt["label"], dt["coordinate"], dt["score"]
  38. if label not in label2color:
  39. color_index = i % len(color_list)
  40. label2color[label] = color_list[color_index]
  41. catid2fontcolor[label] = font_colormap(color_index)
  42. color = tuple(label2color[label])
  43. font_color = tuple(catid2fontcolor[label])
  44. if len(bbox) == 4:
  45. # draw bbox of normal object detection
  46. xmin, ymin, xmax, ymax = bbox
  47. rectangle = [
  48. (xmin, ymin),
  49. (xmin, ymax),
  50. (xmax, ymax),
  51. (xmax, ymin),
  52. (xmin, ymin),
  53. ]
  54. elif len(bbox) == 8:
  55. # draw bbox of rotated object detection
  56. x1, y1, x2, y2, x3, y3, x4, y4 = bbox
  57. rectangle = [(x1, y1), (x2, y2), (x3, y3), (x4, y4), (x1, y1)]
  58. xmin = min(x1, x2, x3, x4)
  59. ymin = min(y1, y2, y3, y4)
  60. else:
  61. raise ValueError(
  62. f"Only support bbox format of [xmin,ymin,xmax,ymax] or [x1,y1,x2,y2,x3,y3,x4,y4], got bbox of shape {len(bbox)}."
  63. )
  64. # draw bbox
  65. draw.line(
  66. rectangle,
  67. width=draw_thickness,
  68. fill=color,
  69. )
  70. # draw label
  71. text = "{} {:.2f}".format(dt["label"], score)
  72. if tuple(map(int, PIL.__version__.split("."))) <= (10, 0, 0):
  73. tw, th = draw.textsize(text, font=font)
  74. else:
  75. left, top, right, bottom = draw.textbbox((0, 0), text, font)
  76. tw, th = right - left, bottom - top + 4
  77. if ymin < th:
  78. draw.rectangle([(xmin, ymin), (xmin + tw + 4, ymin + th + 1)], fill=color)
  79. draw.text((xmin + 2, ymin - 2), text, fill=font_color, font=font)
  80. else:
  81. draw.rectangle([(xmin, ymin - th), (xmin + tw + 4, ymin + 1)], fill=color)
  82. draw.text((xmin + 2, ymin - th - 2), text, fill=font_color, font=font)
  83. return img
  84. class DetResult(BaseCVResult):
  85. def _to_img(self) -> Image.Image:
  86. """apply"""
  87. boxes = self["boxes"]
  88. image = Image.fromarray(self._input_img)
  89. return draw_box(image, boxes)