module.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # Copyright (c) 2022 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 os
  18. import sys
  19. sys.path.insert(0, ".")
  20. import copy
  21. import paddlehub
  22. from paddlehub.common.logger import logger
  23. from paddlehub.module.module import moduleinfo, runnable, serving
  24. import cv2
  25. import numpy as np
  26. import paddlehub as hub
  27. from tools.infer.utility import base64_to_cv2
  28. from tools.infer.predict_det import TextDetector
  29. from tools.infer.utility import parse_args
  30. from deploy.hubserving.ocr_system.params import read_params
  31. @moduleinfo(
  32. name="ocr_det",
  33. version="1.0.0",
  34. summary="ocr detection service",
  35. author="paddle-dev",
  36. author_email="paddle-dev@baidu.com",
  37. type="cv/text_detection")
  38. class OCRDet(hub.Module):
  39. def _initialize(self, use_gpu=False, enable_mkldnn=False):
  40. """
  41. initialize with the necessary elements
  42. """
  43. cfg = self.merge_configs()
  44. cfg.use_gpu = use_gpu
  45. if use_gpu:
  46. try:
  47. _places = os.environ["CUDA_VISIBLE_DEVICES"]
  48. int(_places[0])
  49. print("use gpu: ", use_gpu)
  50. print("CUDA_VISIBLE_DEVICES: ", _places)
  51. cfg.gpu_mem = 8000
  52. except:
  53. raise RuntimeError(
  54. "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
  55. )
  56. cfg.ir_optim = True
  57. cfg.enable_mkldnn = enable_mkldnn
  58. self.text_detector = TextDetector(cfg)
  59. def merge_configs(self, ):
  60. # deafult cfg
  61. backup_argv = copy.deepcopy(sys.argv)
  62. sys.argv = sys.argv[:1]
  63. cfg = parse_args()
  64. update_cfg_map = vars(read_params())
  65. for key in update_cfg_map:
  66. cfg.__setattr__(key, update_cfg_map[key])
  67. sys.argv = copy.deepcopy(backup_argv)
  68. return cfg
  69. def read_images(self, paths=[]):
  70. images = []
  71. for img_path in paths:
  72. assert os.path.isfile(
  73. img_path), "The {} isn't a valid file.".format(img_path)
  74. img = cv2.imread(img_path)
  75. if img is None:
  76. logger.info("error in loading image:{}".format(img_path))
  77. continue
  78. images.append(img)
  79. return images
  80. def predict(self, images=[], paths=[]):
  81. """
  82. Get the text box in the predicted images.
  83. Args:
  84. images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
  85. paths (list[str]): The paths of images. If paths not images
  86. Returns:
  87. res (list): The result of text detection box and save path of images.
  88. """
  89. if images != [] and isinstance(images, list) and paths == []:
  90. predicted_data = images
  91. elif images == [] and isinstance(paths, list) and paths != []:
  92. predicted_data = self.read_images(paths)
  93. else:
  94. raise TypeError("The input data is inconsistent with expectations.")
  95. assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
  96. all_results = []
  97. for img in predicted_data:
  98. if img is None:
  99. logger.info("error in loading image")
  100. all_results.append([])
  101. continue
  102. dt_boxes, elapse = self.text_detector(img)
  103. logger.info("Predict time : {}".format(elapse))
  104. rec_res_final = []
  105. for dno in range(len(dt_boxes)):
  106. rec_res_final.append({
  107. 'text_region': dt_boxes[dno].astype(np.int32).tolist()
  108. })
  109. all_results.append(rec_res_final)
  110. return all_results
  111. @serving
  112. def serving_method(self, images, **kwargs):
  113. """
  114. Run as a service.
  115. """
  116. images_decode = [base64_to_cv2(image) for image in images]
  117. results = self.predict(images_decode, **kwargs)
  118. return results
  119. if __name__ == '__main__':
  120. ocr = OCRDet()
  121. ocr._initialize()
  122. image_path = [
  123. './doc/imgs/11.jpg',
  124. './doc/imgs/12.jpg',
  125. ]
  126. res = ocr.predict(paths=image_path)
  127. print(res)