test_hubserving.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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
  27. import requests
  28. import json
  29. import base64
  30. def cv2_to_base64(image):
  31. return base64.b64encode(image).decode('utf8')
  32. def draw_server_result(image_file, res):
  33. img = cv2.imread(image_file)
  34. image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  35. if len(res) == 0:
  36. return np.array(image)
  37. keys = res[0].keys()
  38. if 'text_region' not in keys: # for ocr_rec, draw function is invalid
  39. logger.info("draw function is invalid for ocr_rec!")
  40. return None
  41. elif 'text' not in keys: # for ocr_det
  42. logger.info("draw text boxes only!")
  43. boxes = []
  44. for dno in range(len(res)):
  45. boxes.append(res[dno]['text_region'])
  46. boxes = np.array(boxes)
  47. draw_img = draw_boxes(image, boxes)
  48. return draw_img
  49. else: # for ocr_system
  50. logger.info("draw boxes and texts!")
  51. boxes = []
  52. texts = []
  53. scores = []
  54. for dno in range(len(res)):
  55. boxes.append(res[dno]['text_region'])
  56. texts.append(res[dno]['text'])
  57. scores.append(res[dno]['confidence'])
  58. boxes = np.array(boxes)
  59. scores = np.array(scores)
  60. draw_img = draw_ocr(image, boxes, texts, scores, drop_score=0.5)
  61. return draw_img
  62. def main(url, image_path):
  63. image_file_list = get_image_file_list(image_path)
  64. is_visualize = False
  65. headers = {"Content-type": "application/json"}
  66. cnt = 0
  67. total_time = 0
  68. for image_file in image_file_list:
  69. img = open(image_file, 'rb').read()
  70. if img is None:
  71. logger.info("error in loading image:{}".format(image_file))
  72. continue
  73. # 发送HTTP请求
  74. starttime = time.time()
  75. data = {'images': [cv2_to_base64(img)]}
  76. r = requests.post(url=url, headers=headers, data=json.dumps(data))
  77. elapse = time.time() - starttime
  78. total_time += elapse
  79. logger.info("Predict time of %s: %.3fs" % (image_file, elapse))
  80. res = r.json()["results"][0]
  81. logger.info(res)
  82. if is_visualize:
  83. draw_img = draw_server_result(image_file, res)
  84. if draw_img is not None:
  85. draw_img_save = "./server_results/"
  86. if not os.path.exists(draw_img_save):
  87. os.makedirs(draw_img_save)
  88. cv2.imwrite(
  89. os.path.join(draw_img_save, os.path.basename(image_file)),
  90. draw_img[:, :, ::-1])
  91. logger.info("The visualized image saved in {}".format(
  92. os.path.join(draw_img_save, os.path.basename(image_file))))
  93. cnt += 1
  94. if cnt % 100 == 0:
  95. logger.info("{} processed".format(cnt))
  96. logger.info("avg time cost: {}".format(float(total_time) / cnt))
  97. if __name__ == '__main__':
  98. if len(sys.argv) != 3:
  99. logger.info("Usage: %s server_url image_path" % sys.argv[0])
  100. else:
  101. server_url = sys.argv[1]
  102. image_path = sys.argv[2]
  103. main(server_url, image_path)