import os
def remove_unmatched_files(images_folder, labels_folder):
# 获取 images 和 labels 文件夹中的所有文件名(不含扩展名)
image_files = set(
os.path.splitext(f)[0] for f in os.listdir(images_folder) if os.path.isfile(os.path.join(images_folder, f)))
label_files = set(
os.path.splitext(f)[0] for f in os.listdir(labels_folder) if os.path.isfile(os.path.join(labels_folder, f)))
# 找到 images 文件夹中不在 labels 文件夹中的文件
unmatched_images = image_files - label_files
for image_file in unmatched_images:
image_path = os.path.join(images_folder, image_file + '.jpg') # 假设图片扩展名为 .jpg
if os.path.exists(image_path):
os.remove(image_path)
print(f"Deleted unmatched image: {image_path}")
# 找到 labels 文件夹中不在 images 文件夹中的文件
unmatched_labels = label_files - image_files
for label_file in unmatched_labels:
label_path = os.path.join(labels_folder, label_file + '.txt') # 假设标签扩展名为 .txt
if os.path.exists(label_path):
os.remove(label_path)
print(f"Deleted unmatched label: {label_path}")
if __name__ == "__main__":
# 设置图片和标签文件夹的路径
images_folder = r'C:\Users\DELL\Desktop\images'
labels_folder = r'C:\Users\DELL\Desktop\labels'
# 调用函数删除不匹配的文件
remove_unmatched_files(images_folder, labels_folder)
删除有图像没标签的图像或有标签没图像的标签
于 2024-08-16 21:37:00 首次发布