convert_dataset.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # copyright (c) 2024 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 json
  16. from .....utils.file_interface import custom_open
  17. from .....utils.errors import ConvertFailedError
  18. def check_src_dataset(root_dir, dataset_type):
  19. """check src dataset format validity"""
  20. if dataset_type in ("LabelMe"):
  21. anno_suffix = ".json"
  22. else:
  23. raise ConvertFailedError(
  24. message=f"数据格式转换失败!不支持{dataset_type}格式数据集。当前仅支持 LabelMe 格式。"
  25. )
  26. err_msg_prefix = f"数据格式转换失败!请参考上述`{dataset_type}格式数据集示例`检查待转换数据集格式。"
  27. for anno in ["label.txt", "annotations", "images"]:
  28. src_anno_path = os.path.join(root_dir, anno)
  29. if not os.path.exists(src_anno_path):
  30. raise ConvertFailedError(
  31. message=f"{err_msg_prefix}保证{src_anno_path}文件存在。"
  32. )
  33. return None
  34. def convert(dataset_type, input_dir):
  35. """convert dataset to multilabel format"""
  36. # check format validity
  37. check_src_dataset(input_dir, dataset_type)
  38. if dataset_type in ("LabelMe"):
  39. convert_labelme_dataset(input_dir)
  40. else:
  41. raise ConvertFailedError(
  42. message=f"数据格式转换失败!不支持{dataset_type}格式数据集。当前仅支持 LabelMe 格式。"
  43. )
  44. def convert_labelme_dataset(root_dir):
  45. image_dir = os.path.join(root_dir, "images")
  46. anno_path = os.path.join(root_dir, "annotations")
  47. label_path = os.path.join(root_dir, "label.txt")
  48. train_rate = 50
  49. gallery_rate = 30
  50. query_rate = 20
  51. tags = ["train", "gallery", "query"]
  52. label_dict = {}
  53. image_files = []
  54. with custom_open(label_path, "r") as f:
  55. lines = f.readlines()
  56. for idx, line in enumerate(lines):
  57. line = line.strip()
  58. label_dict[line] = str(idx)
  59. for json_file in os.listdir(anno_path):
  60. with custom_open(os.path.join(anno_path, json_file), "r") as f:
  61. data = json.load(f)
  62. filename = data["imagePath"].strip().split("/")[2]
  63. image_path = os.path.join("images", filename)
  64. for label, value in data["flags"].items():
  65. if value:
  66. image_files.append(f"{image_path} {label_dict[label]}\n")
  67. start = 0
  68. image_num = len(image_files)
  69. rate_list = [train_rate, gallery_rate, query_rate]
  70. for i, tag in enumerate(tags):
  71. rate = rate_list[i]
  72. if rate == 0:
  73. continue
  74. end = start + round(image_num * rate / 100)
  75. if sum(rate_list[i + 1 :]) == 0:
  76. end = image_num
  77. txt_file = os.path.abspath(os.path.join(root_dir, tag + ".txt"))
  78. with custom_open(txt_file, "w") as f:
  79. m = 0
  80. for id in range(start, end):
  81. m += 1
  82. f.write(image_files[id])
  83. start = end