test_hubserving.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. import os
  15. import sys
  16. __dir__ = os.path.dirname(os.path.abspath(__file__))
  17. sys.path.append(__dir__)
  18. sys.path.append(os.path.abspath(os.path.join(__dir__, '..')))
  19. from ppocr.utils.logging import get_logger
  20. logger = get_logger()
  21. import cv2
  22. import numpy as np
  23. import time
  24. from PIL import Image
  25. from ppocr.utils.utility import get_image_file_list
  26. from tools.infer.utility import draw_ocr, draw_boxes, str2bool
  27. from ppstructure.utility import draw_structure_result
  28. from ppstructure.predict_system import to_excel
  29. import requests
  30. import json
  31. import base64
  32. def cv2_to_base64(image):
  33. return base64.b64encode(image).decode('utf8')
  34. def draw_server_result(image_file, res):
  35. img = cv2.imread(image_file)
  36. image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  37. if len(res) == 0:
  38. return np.array(image)
  39. keys = res[0].keys()
  40. if 'text_region' not in keys: # for ocr_rec, draw function is invalid
  41. logger.info("draw function is invalid for ocr_rec!")
  42. return None
  43. elif 'text' not in keys: # for ocr_det
  44. logger.info("draw text boxes only!")
  45. boxes = []
  46. for dno in range(len(res)):
  47. boxes.append(res[dno]['text_region'])
  48. boxes = np.array(boxes)
  49. draw_img = draw_boxes(image, boxes)
  50. return draw_img
  51. else: # for ocr_system
  52. logger.info("draw boxes and texts!")
  53. boxes = []
  54. texts = []
  55. scores = []
  56. for dno in range(len(res)):
  57. boxes.append(res[dno]['text_region'])
  58. texts.append(res[dno]['text'])
  59. scores.append(res[dno]['confidence'])
  60. boxes = np.array(boxes)
  61. scores = np.array(scores)
  62. draw_img = draw_ocr(
  63. image, boxes, texts, scores, draw_txt=True, drop_score=0.5)
  64. return draw_img
  65. def save_structure_res(res, save_folder, image_file):
  66. img = cv2.imread(image_file)
  67. excel_save_folder = os.path.join(save_folder, os.path.basename(image_file))
  68. os.makedirs(excel_save_folder, exist_ok=True)
  69. # save res
  70. with open(
  71. os.path.join(excel_save_folder, 'res.txt'), 'w',
  72. encoding='utf8') as f:
  73. for region in res:
  74. if region['type'] == 'Table':
  75. excel_path = os.path.join(excel_save_folder,
  76. '{}.xlsx'.format(region['bbox']))
  77. to_excel(region['res'], excel_path)
  78. elif region['type'] == 'Figure':
  79. x1, y1, x2, y2 = region['bbox']
  80. print(region['bbox'])
  81. roi_img = img[y1:y2, x1:x2, :]
  82. img_path = os.path.join(excel_save_folder,
  83. '{}.jpg'.format(region['bbox']))
  84. cv2.imwrite(img_path, roi_img)
  85. else:
  86. for text_result in region['res']:
  87. f.write('{}\n'.format(json.dumps(text_result)))
  88. def main(args):
  89. image_file_list = get_image_file_list(args.image_dir)
  90. is_visualize = False
  91. headers = {"Content-type": "application/json"}
  92. cnt = 0
  93. total_time = 0
  94. for image_file in image_file_list:
  95. img = open(image_file, 'rb').read()
  96. if img is None:
  97. logger.info("error in loading image:{}".format(image_file))
  98. continue
  99. img_name = os.path.basename(image_file)
  100. # seed http request
  101. starttime = time.time()
  102. data = {'images': [cv2_to_base64(img)]}
  103. r = requests.post(
  104. url=args.server_url, headers=headers, data=json.dumps(data))
  105. elapse = time.time() - starttime
  106. total_time += elapse
  107. logger.info("Predict time of %s: %.3fs" % (image_file, elapse))
  108. res = r.json()["results"][0]
  109. logger.info(res)
  110. if args.visualize:
  111. draw_img = None
  112. if 'structure_table' in args.server_url:
  113. to_excel(res['html'], './{}.xlsx'.format(img_name))
  114. elif 'structure_system' in args.server_url:
  115. save_structure_res(res['regions'], args.output, image_file)
  116. else:
  117. draw_img = draw_server_result(image_file, res)
  118. if draw_img is not None:
  119. if not os.path.exists(args.output):
  120. os.makedirs(args.output)
  121. cv2.imwrite(
  122. os.path.join(args.output, os.path.basename(image_file)),
  123. draw_img[:, :, ::-1])
  124. logger.info("The visualized image saved in {}".format(
  125. os.path.join(args.output, os.path.basename(image_file))))
  126. cnt += 1
  127. if cnt % 100 == 0:
  128. logger.info("{} processed".format(cnt))
  129. logger.info("avg time cost: {}".format(float(total_time) / cnt))
  130. def parse_args():
  131. import argparse
  132. parser = argparse.ArgumentParser(description="args for hub serving")
  133. parser.add_argument("--server_url", type=str, required=True)
  134. parser.add_argument("--image_dir", type=str, required=True)
  135. parser.add_argument("--visualize", type=str2bool, default=False)
  136. parser.add_argument("--output", type=str, default='./hubserving_result')
  137. args = parser.parse_args()
  138. return args
  139. if __name__ == '__main__':
  140. args = parse_args()
  141. main(args)