gen_label.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
  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. import os
  15. import argparse
  16. import json
  17. def gen_rec_label(input_path, out_label):
  18. with open(out_label, 'w') as out_file:
  19. with open(input_path, 'r') as f:
  20. for line in f.readlines():
  21. tmp = line.strip('\n').replace(" ", "").split(',')
  22. img_path, label = tmp[0], tmp[1]
  23. label = label.replace("\"", "")
  24. out_file.write(img_path + '\t' + label + '\n')
  25. def gen_det_label(root_path, input_dir, out_label):
  26. with open(out_label, 'w') as out_file:
  27. for label_file in os.listdir(input_dir):
  28. img_path = os.path.join(root_path, label_file[3:-4] + ".jpg")
  29. label = []
  30. with open(
  31. os.path.join(input_dir, label_file), 'r',
  32. encoding='utf-8-sig') as f:
  33. for line in f.readlines():
  34. tmp = line.strip("\n\r").replace("\xef\xbb\xbf",
  35. "").split(',')
  36. points = tmp[:8]
  37. s = []
  38. for i in range(0, len(points), 2):
  39. b = points[i:i + 2]
  40. b = [int(t) for t in b]
  41. s.append(b)
  42. result = {"transcription": tmp[8], "points": s}
  43. label.append(result)
  44. out_file.write(img_path + '\t' + json.dumps(
  45. label, ensure_ascii=False) + '\n')
  46. if __name__ == "__main__":
  47. parser = argparse.ArgumentParser()
  48. parser.add_argument(
  49. '--mode',
  50. type=str,
  51. default="rec",
  52. help='Generate rec_label or det_label, can be set rec or det')
  53. parser.add_argument(
  54. '--root_path',
  55. type=str,
  56. default=".",
  57. help='The root directory of images.Only takes effect when mode=det ')
  58. parser.add_argument(
  59. '--input_path',
  60. type=str,
  61. default=".",
  62. help='Input_label or input path to be converted')
  63. parser.add_argument(
  64. '--output_label',
  65. type=str,
  66. default="out_label.txt",
  67. help='Output file name')
  68. args = parser.parse_args()
  69. if args.mode == "rec":
  70. print("Generate rec label")
  71. gen_rec_label(args.input_path, args.output_label)
  72. elif args.mode == "det":
  73. gen_det_label(args.root_path, args.input_path, args.output_label)