module.py 3.8 KB

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