infer_e2e.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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 __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import numpy as np
  18. import os
  19. import sys
  20. __dir__ = os.path.dirname(os.path.abspath(__file__))
  21. sys.path.append(__dir__)
  22. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, "..")))
  23. os.environ["FLAGS_allocator_strategy"] = "auto_growth"
  24. import cv2
  25. import json
  26. import paddle
  27. from ppocr.data import create_operators, transform
  28. from ppocr.modeling.architectures import build_model
  29. from ppocr.postprocess import build_post_process
  30. from ppocr.utils.save_load import load_model
  31. from ppocr.utils.utility import get_image_file_list
  32. import tools.program as program
  33. from PIL import Image, ImageDraw, ImageFont
  34. import math
  35. def draw_e2e_res_for_chinese(
  36. image, boxes, txts, config, img_name, font_path="./doc/simfang.ttf"
  37. ):
  38. h, w = image.height, image.width
  39. img_left = image.copy()
  40. img_right = Image.new("RGB", (w, h), (255, 255, 255))
  41. import random
  42. random.seed(0)
  43. draw_left = ImageDraw.Draw(img_left)
  44. draw_right = ImageDraw.Draw(img_right)
  45. for idx, (box, txt) in enumerate(zip(boxes, txts)):
  46. box = np.array(box)
  47. box = [tuple(x) for x in box]
  48. color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
  49. draw_left.polygon(box, fill=color)
  50. draw_right.polygon(box, outline=color)
  51. font = ImageFont.truetype(font_path, 15, encoding="utf-8")
  52. draw_right.text([box[0][0], box[0][1]], txt, fill=(0, 0, 0), font=font)
  53. img_left = Image.blend(image, img_left, 0.5)
  54. img_show = Image.new("RGB", (w * 2, h), (255, 255, 255))
  55. img_show.paste(img_left, (0, 0, w, h))
  56. img_show.paste(img_right, (w, 0, w * 2, h))
  57. save_e2e_path = os.path.dirname(config["Global"]["save_res_path"]) + "/e2e_results/"
  58. if not os.path.exists(save_e2e_path):
  59. os.makedirs(save_e2e_path)
  60. save_path = os.path.join(save_e2e_path, os.path.basename(img_name))
  61. cv2.imwrite(save_path, np.array(img_show)[:, :, ::-1])
  62. logger.info("The e2e Image saved in {}".format(save_path))
  63. def draw_e2e_res(dt_boxes, strs, config, img, img_name):
  64. if len(dt_boxes) > 0:
  65. src_im = img
  66. for box, str in zip(dt_boxes, strs):
  67. box = box.astype(np.int32).reshape((-1, 1, 2))
  68. cv2.polylines(src_im, [box], True, color=(255, 255, 0), thickness=2)
  69. cv2.putText(
  70. src_im,
  71. str,
  72. org=(int(box[0, 0, 0]), int(box[0, 0, 1])),
  73. fontFace=cv2.FONT_HERSHEY_COMPLEX,
  74. fontScale=0.7,
  75. color=(0, 255, 0),
  76. thickness=1,
  77. )
  78. save_det_path = (
  79. os.path.dirname(config["Global"]["save_res_path"]) + "/e2e_results/"
  80. )
  81. if not os.path.exists(save_det_path):
  82. os.makedirs(save_det_path)
  83. save_path = os.path.join(save_det_path, os.path.basename(img_name))
  84. cv2.imwrite(save_path, src_im)
  85. logger.info("The e2e Image saved in {}".format(save_path))
  86. def main():
  87. global_config = config["Global"]
  88. # build model
  89. model = build_model(config["Architecture"])
  90. load_model(config, model)
  91. # build post process
  92. post_process_class = build_post_process(config["PostProcess"], global_config)
  93. # create data ops
  94. transforms = []
  95. for op in config["Eval"]["dataset"]["transforms"]:
  96. op_name = list(op)[0]
  97. if "Label" in op_name:
  98. continue
  99. elif op_name == "KeepKeys":
  100. op[op_name]["keep_keys"] = ["image", "shape"]
  101. transforms.append(op)
  102. ops = create_operators(transforms, global_config)
  103. save_res_path = config["Global"]["save_res_path"]
  104. if not os.path.exists(os.path.dirname(save_res_path)):
  105. os.makedirs(os.path.dirname(save_res_path))
  106. model.eval()
  107. with open(save_res_path, "wb") as fout:
  108. for file in get_image_file_list(config["Global"]["infer_img"]):
  109. logger.info("infer_img: {}".format(file))
  110. with open(file, "rb") as f:
  111. img = f.read()
  112. data = {"image": img}
  113. batch = transform(data, ops)
  114. images = np.expand_dims(batch[0], axis=0)
  115. shape_list = np.expand_dims(batch[1], axis=0)
  116. images = paddle.to_tensor(images)
  117. preds = model(images)
  118. post_result = post_process_class(preds, shape_list)
  119. points, strs = post_result["points"], post_result["texts"]
  120. # write result
  121. dt_boxes_json = []
  122. for poly, str in zip(points, strs):
  123. tmp_json = {"transcription": str}
  124. tmp_json["points"] = poly.tolist()
  125. dt_boxes_json.append(tmp_json)
  126. otstr = file + "\t" + json.dumps(dt_boxes_json) + "\n"
  127. fout.write(otstr.encode())
  128. src_img = cv2.imread(file)
  129. if global_config["infer_visual_type"] == "EN":
  130. draw_e2e_res(points, strs, config, src_img, file)
  131. elif global_config["infer_visual_type"] == "CN":
  132. src_img = Image.fromarray(cv2.cvtColor(src_img, cv2.COLOR_BGR2RGB))
  133. draw_e2e_res_for_chinese(
  134. src_img,
  135. points,
  136. strs,
  137. config,
  138. file,
  139. font_path="./doc/fonts/simfang.ttf",
  140. )
  141. logger.info("success!")
  142. if __name__ == "__main__":
  143. config, device, logger, vdl_writer = program.preprocess()
  144. main()