module.py 3.8 KB

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