infer_cls.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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.insert(0, 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 load_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. load_model(config, model)
  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. elif op_name == "SSLRotateResize":
  48. op[op_name]["mode"] = "test"
  49. transforms.append(op)
  50. global_config['infer_mode'] = True
  51. ops = create_operators(transforms, global_config)
  52. model.eval()
  53. for file in get_image_file_list(config['Global']['infer_img']):
  54. logger.info("infer_img: {}".format(file))
  55. with open(file, 'rb') as f:
  56. img = f.read()
  57. data = {'image': img}
  58. batch = transform(data, ops)
  59. images = np.expand_dims(batch[0], axis=0)
  60. images = paddle.to_tensor(images)
  61. preds = model(images)
  62. post_result = post_process_class(preds)
  63. for rec_result in post_result:
  64. logger.info('\t result: {}'.format(rec_result))
  65. logger.info("success!")
  66. if __name__ == '__main__':
  67. config, device, logger, vdl_writer = program.preprocess()
  68. main()