上结果图(这里以展示图片有,但是标签没有为例)
代码运行前:
代码运行后:
并自动输出删除的文件名保存到txt
上代码,换成自己的路径
import os
def delete_images_without_labels(image_folder, labels_folder, output_txt):
# 获取image文件夹中的所有图片文件
image_files = [f for f in os.listdir(image_folder) if f.endswith('.png')]
# 获取labels文件夹中的所有文本文件
label_files = [f for f in os.listdir(labels_folder) if f.endswith('.txt')]
# 找到有对应标签的图片文件
labeled_images = set([os.path.splitext(label)[0] for label in label_files])
# 找到没有对应标签的图片文件
images_without_labels = [image for image in image_files if os.path.splitext(image)[0] not in labeled_images]
# 删除没有对应标签的图片文件
for image in images_without_labels:
image_path = os.path.join(image_folder, image)
os.remove(image_path)
# 将删除的图片文件名保存在txt中
with open(output_txt, 'w') as txt_file:
txt_file.write('\n'.join(images_without_labels))
# 用法示例
image_folder_path = '/path/to/your/image/folder'
labels_folder_path = '/path/to/your/labels/folder'
output_txt_path = '/path/to/your/output.txt'
delete_images_without_labels(image_folder_path, labels_folder_path, output_txt_path)