20251102.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. import os
  2. # ================= 核心配置 =================
  3. # 根据你的截图,你的根目录应该是这一层(包含 images 和 labels 的上一级)
  4. # 请务必核对这个路径是否正确!
  5. root_path = r"D:\data\20251210\20251210"
  6. img_folder_name = "images"
  7. lbl_folder_name = "labels"
  8. sub_folders = ["test", "train", "val"]
  9. global_index = 0
  10. digit_padding = 6
  11. # 支持的后缀(已忽略大小写)
  12. valid_image_exts = ['.jpg', '.jpeg', '.png', '.bmp']
  13. valid_label_exts = ['.txt', '.xml', '.json']
  14. # ===========================================
  15. def debug_sync_rename():
  16. global global_index
  17. print("----------- 开始检查路径 -----------")
  18. if not os.path.exists(root_path):
  19. print(f"❌ 错误:根目录不存在 -> {root_path}")
  20. print("请检查路径中是否有空格、拼写错误,或者盘符不对。")
  21. input("按回车键退出...")
  22. return
  23. else:
  24. print(f"✅ 根目录存在: {root_path}")
  25. images_root = os.path.join(root_path, img_folder_name)
  26. labels_root = os.path.join(root_path, lbl_folder_name)
  27. if not os.path.exists(images_root):
  28. print(f"❌ 错误:找不到 images 文件夹 -> {images_root}")
  29. input("按回车键退出...")
  30. return
  31. print(f"✅ images 目录存在: {images_root}")
  32. print(f"✅ labels 目录 (期望路径): {labels_root}")
  33. print("------------------------------------")
  34. # 遍历子文件夹
  35. for sub in sub_folders:
  36. curr_img_dir = os.path.join(images_root, sub)
  37. curr_lbl_dir = os.path.join(labels_root, sub)
  38. print(f"\n正在扫描子文件夹: [{sub}]")
  39. if not os.path.exists(curr_img_dir):
  40. print(f"⚠️ 跳过:找不到图片子目录 -> {curr_img_dir}")
  41. continue
  42. # 获取文件
  43. try:
  44. files = os.listdir(curr_img_dir)
  45. except Exception as e:
  46. print(f"❌ 读取文件夹出错: {e}")
  47. continue
  48. # 筛选图片
  49. img_files = sorted([f for f in files if os.path.splitext(f)[1].lower() in valid_image_exts])
  50. if len(img_files) == 0:
  51. print(f"⚠️ 在 {sub} 中没有找到支持的图片文件!")
  52. print(f" 该文件夹下的前5个文件是: {files[:5]}")
  53. continue
  54. print(f" -> 发现 {len(img_files)} 张图片,准备处理...")
  55. # 开始重命名循环
  56. count = 0
  57. for old_img_name in img_files:
  58. stem, img_ext = os.path.splitext(old_img_name)
  59. # 构造新名字
  60. new_stem = f"{global_index:0{digit_padding}d}"
  61. # 1. 改名图片
  62. old_img_path = os.path.join(curr_img_dir, old_img_name)
  63. new_img_name = f"{new_stem}{img_ext}"
  64. new_img_path = os.path.join(curr_img_dir, new_img_name)
  65. # 2. 改名标签
  66. label_renamed = False
  67. for lbl_ext in valid_label_exts:
  68. old_lbl_name = f"{stem}{lbl_ext}"
  69. old_lbl_path = os.path.join(curr_lbl_dir, old_lbl_name)
  70. if os.path.exists(old_lbl_path):
  71. new_lbl_name = f"{new_stem}{lbl_ext}"
  72. new_lbl_path = os.path.join(curr_lbl_dir, new_lbl_name)
  73. if old_lbl_path != new_lbl_path:
  74. os.rename(old_lbl_path, new_lbl_path)
  75. label_renamed = True
  76. break # 找到对应标签就不找其他后缀了
  77. # 执行图片改名
  78. if old_img_path != new_img_path:
  79. os.rename(old_img_path, new_img_path)
  80. global_index += 1
  81. count += 1
  82. # 为了避免刷屏,只打印前3个和最后一个的处理记录
  83. if count <= 3:
  84. status = "同步修改成功" if label_renamed else "只改了图片(无标签)"
  85. print(f" [{status}] {old_img_name} -> {new_img_name}")
  86. print(f" -> {sub} 文件夹处理完毕。")
  87. print(f"\n🎉 所有操作结束!最大序号停留在: {global_index - 1}")
  88. input("按回车键退出...")
  89. if __name__ == "__main__":
  90. debug_sync_rename()