infer_rec.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import numpy as np
  18. import os
  19. import sys
  20. __dir__ = os.path.dirname(os.path.abspath(__file__))
  21. sys.path.append(__dir__)
  22. sys.path.append(os.path.abspath(os.path.join(__dir__, '..')))
  23. os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
  24. os.environ['FLAGS_eager_delete_tensor_gb'] = '0'
  25. import paddle
  26. from ocr.ppocr.data import create_operators, transform
  27. from ocr.ppocr.modeling.architectures import build_model
  28. from ocr.ppocr.postprocess import build_post_process
  29. from ocr.ppocr.utils.save_load import init_model
  30. from ocr.ppocr.utils.utility import get_image_file_list
  31. import ocr.tools.program as program
  32. def main():
  33. global_config = config['Global']
  34. # build post process
  35. post_process_class = build_post_process(config['PostProcess'],
  36. global_config)
  37. # build model
  38. if hasattr(post_process_class, 'character'):
  39. config['Architecture']["Head"]['out_channels'] = len(
  40. getattr(post_process_class, 'character'))
  41. model = build_model(config['Architecture'])
  42. init_model(config, model, logger)
  43. # create data ops
  44. transforms = []
  45. for op in config['Eval']['dataset']['transforms']:
  46. op_name = list(op)[0]
  47. if 'Label' in op_name:
  48. continue
  49. elif op_name in ['RecResizeImg']:
  50. op[op_name]['infer_mode'] = True
  51. elif op_name == 'KeepKeys':
  52. if config['Architecture']['algorithm'] == "SRN":
  53. op[op_name]['keep_keys'] = [
  54. 'image', 'encoder_word_pos', 'gsrm_word_pos',
  55. 'gsrm_slf_attn_bias1', 'gsrm_slf_attn_bias2'
  56. ]
  57. else:
  58. op[op_name]['keep_keys'] = ['image']
  59. transforms.append(op)
  60. global_config['infer_mode'] = True
  61. ops = create_operators(transforms, global_config)
  62. model.eval()
  63. for file in get_image_file_list(config['Global']['infer_img']):
  64. logger.info("infer_img: {}".format(file))
  65. with open(file, 'rb') as f:
  66. img = f.read()
  67. data = {'image': img}
  68. batch = transform(data, ops)
  69. if config['Architecture']['algorithm'] == "SRN":
  70. encoder_word_pos_list = np.expand_dims(batch[1], axis=0)
  71. gsrm_word_pos_list = np.expand_dims(batch[2], axis=0)
  72. gsrm_slf_attn_bias1_list = np.expand_dims(batch[3], axis=0)
  73. gsrm_slf_attn_bias2_list = np.expand_dims(batch[4], axis=0)
  74. others = [
  75. paddle.to_tensor(encoder_word_pos_list),
  76. paddle.to_tensor(gsrm_word_pos_list),
  77. paddle.to_tensor(gsrm_slf_attn_bias1_list),
  78. paddle.to_tensor(gsrm_slf_attn_bias2_list)
  79. ]
  80. images = np.expand_dims(batch[0], axis=0)
  81. images = paddle.to_tensor(images)
  82. if config['Architecture']['algorithm'] == "SRN":
  83. preds = model(images, others)
  84. else:
  85. preds = model(images)
  86. post_result = post_process_class(preds)
  87. for rec_reuslt in post_result:
  88. logger.info('\t result: {}'.format(rec_reuslt))
  89. logger.info("success!")
  90. if __name__ == '__main__':
  91. config, device, logger, vdl_writer = program.preprocess()
  92. main()