formula_rec.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 random
  15. import numpy as np
  16. from PIL import Image, ImageDraw
  17. from .base import CVResult
  18. class FormulaRecResult(CVResult):
  19. _HARD_FLAG = False
  20. def _to_str(self, *args, **kwargs):
  21. return super()._to_str(*args, **kwargs).replace("\\\\", "\\")
  22. def _to_img(
  23. self,
  24. ):
  25. """draw formula result"""
  26. boxes = self["dt_polys"]
  27. formula = self["rec_formula"]
  28. image = self._img_reader.read(self["input_path"])
  29. if self._HARD_FLAG:
  30. image_np = np.array(image)
  31. image = Image.fromarray(image_np[:, :, ::-1])
  32. img = image.copy()
  33. random.seed(0)
  34. draw_img = ImageDraw.Draw(img)
  35. if formula is None or len(formula) != len(boxes):
  36. formula = [None] * len(boxes)
  37. for idx, (box, txt) in enumerate(zip(boxes, formula)):
  38. try:
  39. color = (
  40. random.randint(0, 255),
  41. random.randint(0, 255),
  42. random.randint(0, 255),
  43. )
  44. box = np.array(box)
  45. pts = [(x, y) for x, y in box.tolist()]
  46. draw_img.polygon(pts, outline=color, width=8)
  47. draw_img.polygon(box, fill=color)
  48. except:
  49. continue
  50. img = Image.blend(image, img, 0.5)
  51. return img