module.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. # -*- coding:utf-8 -*-
  2. from __future__ import absolute_import
  3. from __future__ import division
  4. from __future__ import print_function
  5. import os
  6. import sys
  7. sys.path.insert(0, ".")
  8. import time
  9. from paddlehub.common.logger import logger
  10. from paddlehub.module.module import moduleinfo, runnable, serving
  11. import cv2
  12. import numpy as np
  13. import paddlehub as hub
  14. from tools.infer.utility import base64_to_cv2
  15. from tools.infer.predict_system import TextSystem
  16. @moduleinfo(
  17. name="ocr_system",
  18. version="1.0.0",
  19. summary="ocr system service",
  20. author="paddle-dev",
  21. author_email="paddle-dev@baidu.com",
  22. type="cv/text_recognition")
  23. class OCRSystem(hub.Module):
  24. def _initialize(self, use_gpu=False, enable_mkldnn=False):
  25. """
  26. initialize with the necessary elements
  27. """
  28. from ocr_system.params import read_params
  29. cfg = read_params()
  30. cfg.use_gpu = use_gpu
  31. if use_gpu:
  32. try:
  33. _places = os.environ["CUDA_VISIBLE_DEVICES"]
  34. int(_places[0])
  35. print("use gpu: ", use_gpu)
  36. print("CUDA_VISIBLE_DEVICES: ", _places)
  37. cfg.gpu_mem = 8000
  38. except:
  39. raise RuntimeError(
  40. "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."
  41. )
  42. cfg.ir_optim = True
  43. cfg.enable_mkldnn = enable_mkldnn
  44. self.text_sys = TextSystem(cfg)
  45. def read_images(self, paths=[]):
  46. images = []
  47. for img_path in paths:
  48. assert os.path.isfile(
  49. img_path), "The {} isn't a valid file.".format(img_path)
  50. img = cv2.imread(img_path)
  51. if img is None:
  52. logger.info("error in loading image:{}".format(img_path))
  53. continue
  54. images.append(img)
  55. return images
  56. def predict(self, images=[], paths=[]):
  57. """
  58. Get the chinese texts in the predicted images.
  59. Args:
  60. images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
  61. paths (list[str]): The paths of images. If paths not images
  62. Returns:
  63. res (list): The result of chinese texts and save path of images.
  64. """
  65. if images != [] and isinstance(images, list) and paths == []:
  66. predicted_data = images
  67. elif images == [] and isinstance(paths, list) and paths != []:
  68. predicted_data = self.read_images(paths)
  69. else:
  70. raise TypeError("The input data is inconsistent with expectations.")
  71. assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
  72. all_results = []
  73. for img in predicted_data:
  74. if img is None:
  75. logger.info("error in loading image")
  76. all_results.append([])
  77. continue
  78. starttime = time.time()
  79. dt_boxes, rec_res = self.text_sys(img)
  80. elapse = time.time() - starttime
  81. logger.info("Predict time: {}".format(elapse))
  82. dt_num = len(dt_boxes)
  83. rec_res_final = []
  84. for dno in range(dt_num):
  85. text, score = rec_res[dno]
  86. rec_res_final.append({
  87. 'text': text,
  88. 'confidence': float(score),
  89. 'text_region': dt_boxes[dno].astype(np.int).tolist()
  90. })
  91. all_results.append(rec_res_final)
  92. return all_results
  93. @serving
  94. def serving_method(self, images, **kwargs):
  95. """
  96. Run as a service.
  97. """
  98. images_decode = [base64_to_cv2(image) for image in images]
  99. results = self.predict(images_decode, **kwargs)
  100. return results
  101. if __name__ == '__main__':
  102. ocr = OCRSystem()
  103. image_path = [
  104. './doc/imgs/11.jpg',
  105. './doc/imgs/12.jpg',
  106. ]
  107. res = ocr.predict(paths=image_path)
  108. print(res)