infer_cls.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. import paddle
  25. from ppocr.data import create_operators, transform
  26. from ppocr.modeling.architectures import build_model
  27. from ppocr.postprocess import build_post_process
  28. from ppocr.utils.save_load import init_model
  29. from ppocr.utils.utility import get_image_file_list
  30. import tools.program as program
  31. def main():
  32. global_config = config['Global']
  33. # build post process
  34. post_process_class = build_post_process(config['PostProcess'],
  35. global_config)
  36. # build model
  37. model = build_model(config['Architecture'])
  38. init_model(config, model, logger)
  39. # create data ops
  40. transforms = []
  41. for op in config['Eval']['dataset']['transforms']:
  42. op_name = list(op)[0]
  43. if 'Label' in op_name:
  44. continue
  45. elif op_name == 'KeepKeys':
  46. op[op_name]['keep_keys'] = ['image']
  47. transforms.append(op)
  48. global_config['infer_mode'] = True
  49. ops = create_operators(transforms, global_config)
  50. model.eval()
  51. for file in get_image_file_list(config['Global']['infer_img']):
  52. logger.info("infer_img: {}".format(file))
  53. with open(file, 'rb') as f:
  54. img = f.read()
  55. data = {'image': img}
  56. batch = transform(data, ops)
  57. images = np.expand_dims(batch[0], axis=0)
  58. images = paddle.to_tensor(images)
  59. preds = model(images)
  60. post_result = post_process_class(preds)
  61. for rec_reuslt in post_result:
  62. logger.info('\t result: {}'.format(rec_reuslt))
  63. logger.info("success!")
  64. if __name__ == '__main__':
  65. config, device, logger, vdl_writer = program.preprocess()
  66. main()