convert_dataset.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  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 tqdm import tqdm
  17. from pycocotools.coco import COCO
  18. from .....utils.errors import ConvertFailedError
  19. from .....utils.logging import info, warning
  20. def check_src_dataset(root_dir, dataset_type):
  21. """check src dataset format validity"""
  22. if dataset_type in ("COCO"):
  23. anno_suffix = ".json"
  24. else:
  25. raise ConvertFailedError(
  26. message=f"数据格式转换失败!不支持{dataset_type}格式数据集。当前仅支持 COCO 格式。"
  27. )
  28. err_msg_prefix = f"数据格式转换失败!请参考上述`{dataset_type}格式数据集示例`检查待转换数据集格式。"
  29. for anno in ["annotations/instance_train.json", "annotations/instance_val.json"]:
  30. src_anno_path = os.path.join(root_dir, anno)
  31. if not os.path.exists(src_anno_path):
  32. raise ConvertFailedError(
  33. message=f"{err_msg_prefix}保证{src_anno_path}文件存在。"
  34. )
  35. return None
  36. def convert(dataset_type, input_dir):
  37. """convert dataset to multilabel format"""
  38. # check format validity
  39. check_src_dataset(input_dir, dataset_type)
  40. if dataset_type in ("COCO"):
  41. convert_coco_dataset(input_dir)
  42. else:
  43. raise ConvertFailedError(
  44. message=f"数据格式转换失败!不支持{dataset_type}格式数据集。当前仅支持 COCO 格式。"
  45. )
  46. def convert_coco_dataset(root_dir):
  47. for anno in ["annotations/instance_train.json", "annotations/instance_val.json"]:
  48. src_img_dir = root_dir
  49. src_anno_path = os.path.join(root_dir, anno)
  50. coco2multilabels(src_img_dir, src_anno_path, root_dir)
  51. def coco2multilabels(src_img_dir, src_anno_path, root_dir):
  52. image_dir = os.path.join(root_dir, "images")
  53. label_type = (
  54. os.path.basename(src_anno_path).replace("instance_", "").replace(".json", "")
  55. )
  56. anno_save_path = os.path.join(root_dir, "{}.txt".format(label_type))
  57. coco = COCO(src_anno_path)
  58. cat_id_map = {
  59. old_cat_id: new_cat_id for new_cat_id, old_cat_id in enumerate(coco.getCatIds())
  60. }
  61. num_classes = len(list(cat_id_map.keys()))
  62. with open(anno_save_path, "w") as fp:
  63. lines = []
  64. for img_id in tqdm(sorted(coco.getImgIds())):
  65. img_info = coco.loadImgs([img_id])[0]
  66. img_filename = img_info["file_name"]
  67. img_w = img_info["width"]
  68. img_h = img_info["height"]
  69. img_filepath = os.path.join(image_dir, img_filename)
  70. if not os.path.exists(img_filepath):
  71. warning(
  72. "Illegal image file: {}, "
  73. "and it will be ignored".format(img_filepath)
  74. )
  75. continue
  76. if img_w < 0 or img_h < 0:
  77. warning(
  78. "Illegal width: {} or height: {} in annotation, "
  79. "and im_id: {} will be ignored".format(img_w, img_h, img_id)
  80. )
  81. continue
  82. ins_anno_ids = coco.getAnnIds(imgIds=[img_id])
  83. instances = coco.loadAnns(ins_anno_ids)
  84. label = [0] * num_classes
  85. for instance in instances:
  86. label[cat_id_map[instance["category_id"]]] = 1
  87. img_filename = os.path.join("images", img_filename)
  88. fp.writelines("{}\t{}\n".format(img_filename, ",".join(map(str, label))))
  89. fp.close()
  90. if label_type == "train":
  91. label_txt_save_path = os.path.join(root_dir, "label.txt")
  92. with open(label_txt_save_path, "w") as fp:
  93. label_name_list = []
  94. for cat in coco.cats.values():
  95. id = cat["id"]
  96. name = cat["name"]
  97. fp.writelines("{} {}\n".format(id, name))
  98. fp.close()
  99. info("Save label names to {}.".format(label_txt_save_path))