如题,假设需要删除的标签名称为"area", "exit"。沿用前一篇文章中提到的文件结构。则批量删除labelme标签可使用如下代码:
批量删除labelme标签:
import os import json # 基本路径 base_path = "E:/yolov8/20240624/escala/" label_dirs = ["labelmes/test", "labelmes/train", "labelmes/val"] new_label_dirs = ["labelmes_new/test", "labelmes_new/train", "labelmes_new/val"] # 创建新的标注目录 for new_label_dir in new_label_dirs: os.makedirs(os.path.join(base_path, new_label_dir), exist_ok=True) # 需要删除的标签 labels_to_remove = {"area", "exit"} # 遍历所有标注目录 for label_dir, new_label_dir in zip(label_dirs, new_label_dirs): label_dir_path = os.path.join(base_path, label_dir) new_label_dir_path = os.path.join(base_path, new_label_dir) for label_file in os.listdir(label_dir_path): if label_file.endswith('.json'): labelme_anno_path = os.path.join(label_dir_path, label_file) new_labelme_anno_path = os.path.join(new_label_dir_path, label_file) with open(labelme_anno_path, 'r') as f: labelme_annotations = json.load(f) # 过滤掉指定标签 new_shapes = [shape for shape in labelme_annotations["shapes"] if shape["label"] not in labels_to_remove] labelme_annotations["shapes"] = new_shapes # 将处理后的标注文件保存到新的目录 with open(new_labelme_anno_path, 'w') as f: json.dump(labelme_annotations, f, indent=2) print(f"Processed {label_file} and saved to {new_labelme_anno_path}")
@ 1313