infer_cls.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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"], global_config)
  35. # build model
  36. model = build_model(config["Architecture"])
  37. load_model(config, model)
  38. # create data ops
  39. transforms = []
  40. for op in config["Eval"]["dataset"]["transforms"]:
  41. op_name = list(op)[0]
  42. if "Label" in op_name:
  43. continue
  44. elif op_name == "KeepKeys":
  45. op[op_name]["keep_keys"] = ["image"]
  46. elif op_name == "SSLRotateResize":
  47. op[op_name]["mode"] = "test"
  48. transforms.append(op)
  49. global_config["infer_mode"] = True
  50. ops = create_operators(transforms, global_config)
  51. model.eval()
  52. for file in get_image_file_list(config["Global"]["infer_img"]):
  53. logger.info("infer_img: {}".format(file))
  54. with open(file, "rb") as f:
  55. img = f.read()
  56. data = {"image": img}
  57. batch = transform(data, ops)
  58. images = np.expand_dims(batch[0], axis=0)
  59. images = paddle.to_tensor(images)
  60. preds = model(images)
  61. post_result = post_process_class(preds)
  62. for rec_result in post_result:
  63. logger.info("\t result: {}".format(rec_result))
  64. logger.info("success!")
  65. if __name__ == "__main__":
  66. config, device, logger, vdl_writer = program.preprocess()
  67. main()