convert_dataset.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 shutil
  16. import json
  17. import random
  18. import numpy as np
  19. import pandas as pd
  20. from tqdm import tqdm
  21. from .....utils.errors import ConvertFailedError
  22. def check_src_dataset(root_dir):
  23. """ check src dataset format validity """
  24. err_msg_prefix = f"数据格式转换失败!当前仅支持后续为'.xlsx/.xls'格式的数据转换。"
  25. for dst_anno, src_anno in [("train.xlsx", "train.xls"),
  26. ("val.xlsx", "val.xls")]:
  27. src_anno_path = os.path.join(root_dir, src_anno)
  28. dst_anno_path = os.path.join(root_dir, dst_anno)
  29. if not os.path.exists(src_anno_path) and not os.path.exists(
  30. dst_anno_path):
  31. if 'train' in dst_anno:
  32. raise ConvertFailedError(
  33. message=f"{err_msg_prefix}保证{src_anno_path}或{dst_anno_path}文件存在。"
  34. )
  35. continue
  36. def convert_excel_dataset(input_dir):
  37. """
  38. 将excel标注的数据集转换为PaddleX需要的格式
  39. Args:
  40. input_dir (str): 输入的目录,包含多个json格式的Labelme标注文件
  41. Returns:
  42. str: 返回一个字符串表示转换的结果,“转换成功”表示转换没有问题。
  43. Raises:
  44. 该函数目前没有特定的异常抛出。
  45. """
  46. # read excel file
  47. for dst_anno, src_anno in [("train.xlsx", "train.xls"),
  48. ("val.xlsx", "val.xls")]:
  49. src_anno_path = os.path.join(input_dir, src_anno)
  50. dst_anno_path = os.path.join(input_dir, dst_anno)
  51. if os.path.exists(src_anno_path):
  52. excel_file = pd.read_excel(src_anno_path)
  53. output_csv_dir = os.path.join(input_dir,
  54. src_anno.replace(".xlsx", ".csv"))
  55. excel_file.to_csv(output_csv_dir, index=False)
  56. if os.path.exists(dst_anno_path):
  57. excel_file = pd.read_excel(dst_anno_path)
  58. output_csv_dir = os.path.join(input_dir,
  59. dst_anno.replace(".xlsx", ".csv"))
  60. excel_file.to_csv(output_csv_dir, index=False)
  61. def convert(input_dir):
  62. """ convert dataset to coco format """
  63. # check format validity
  64. check_src_dataset(input_dir)
  65. convert_excel_dataset(input_dir)
  66. return input_dir