39 lines
1.4 KiB
Python
39 lines
1.4 KiB
Python
import os
|
|
import glob
|
|
|
|
def fix_label_class_id(label_dir, old_id=1, new_id=0):
|
|
"""将指定目录下所有 .txt 文件中的类别 ID 替换"""
|
|
txt_files = glob.glob(os.path.join(label_dir, "*.txt"))
|
|
count = 0
|
|
for file in txt_files:
|
|
updated_lines = []
|
|
changed = False
|
|
with open(file, 'r', encoding='utf-8') as f:
|
|
for line in f:
|
|
parts = line.strip().split()
|
|
if not parts:
|
|
continue
|
|
try:
|
|
cls_id = int(parts[0])
|
|
if cls_id == old_id:
|
|
parts[0] = str(new_id)
|
|
changed = True
|
|
updated_lines.append(' '.join(parts))
|
|
except ValueError:
|
|
updated_lines.append(line.strip()) # 忽略非数字行
|
|
|
|
if changed:
|
|
with open(file, 'w', encoding='utf-8') as f:
|
|
f.write('\n'.join(updated_lines) + '\n')
|
|
print(f"✅ 修改: {os.path.basename(file)} ({old_id} → {new_id})")
|
|
count += 1
|
|
|
|
print(f"\n🎉 完成!共修改 {count} 个标注文件。")
|
|
|
|
# ============ 配置 ============
|
|
LABEL_DIR = "/home/hx/yolo/ultralytics_yolo11-main/dataset1/val" # 你的 YOLO 标签文件夹路径
|
|
OLD_ID = 1
|
|
NEW_ID = 0
|
|
|
|
if __name__ == "__main__":
|
|
fix_label_class_id(LABEL_DIR, OLD_ID, NEW_ID) |