删除有图像没标签的图像或有标签没图像的标签

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值