writers.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 cv2
  16. import glob
  17. from utils.logging import get_logger
  18. class SimpleWriter(object):
  19. def __init__(self, config, tag):
  20. self.logger = get_logger()
  21. self.output_dir = config["Global"]["output_dir"]
  22. self.counter = 0
  23. self.label_dict = {}
  24. self.tag = tag
  25. self.label_file_index = 0
  26. def save_image(self, image, text_input_label):
  27. image_home = os.path.join(self.output_dir, "images", self.tag)
  28. if not os.path.exists(image_home):
  29. os.makedirs(image_home)
  30. image_path = os.path.join(image_home, "{}.png".format(self.counter))
  31. # todo support continue synth
  32. cv2.imwrite(image_path, image)
  33. self.logger.info("generate image: {}".format(image_path))
  34. image_name = os.path.join(self.tag, "{}.png".format(self.counter))
  35. self.label_dict[image_name] = text_input_label
  36. self.counter += 1
  37. if not self.counter % 100:
  38. self.save_label()
  39. def save_label(self):
  40. label_raw = ""
  41. label_home = os.path.join(self.output_dir, "label")
  42. if not os.path.exists(label_home):
  43. os.mkdir(label_home)
  44. for image_path in self.label_dict:
  45. label = self.label_dict[image_path]
  46. label_raw += "{}\t{}\n".format(image_path, label)
  47. label_file_path = os.path.join(label_home,
  48. "{}_label.txt".format(self.tag))
  49. with open(label_file_path, "w") as f:
  50. f.write(label_raw)
  51. self.label_file_index += 1
  52. def merge_label(self):
  53. label_raw = ""
  54. label_file_regex = os.path.join(self.output_dir, "label",
  55. "*_label.txt")
  56. label_file_list = glob.glob(label_file_regex)
  57. for label_file_i in label_file_list:
  58. with open(label_file_i, "r") as f:
  59. label_raw += f.read()
  60. label_file_path = os.path.join(self.output_dir, "label.txt")
  61. with open(label_file_path, "w") as f:
  62. f.write(label_raw)