formula_rec.py 2.0 KB

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