删除图片数据中没有对应json文件的图片数据

import os
from tqdm import tqdm

def delete_images_with_json(jpg_folder, json_folder):
    # 获取数据文件夹中的所有文件名
    json_files = os.listdir(json_folder)
    jpg_files = os.listdir(jpg_folder)
    # 获取 JSON JPG 文件的文件名集合(不包括扩展名)
    # json_file_names = set(os.path.splitext(file)[0] for file in json_files if file.endswith(".json"))
    json_file_names = set(os.path.splitext(file)[0] for file in json_files if file.endswith(".png"))
    jpg_file_names = set(os.path.splitext(file)[0] for file in jpg_files if file.endswith(".jpg"))
    # 遍历数据文件夹中的所有文件
    for jpg_file in tqdm(jpg_files):
        # 如果不是 JPG 文件,则判断是否存在对应 JSON 文件
        if jpg_file.endswith(".jpg"):
            # 获取对应 JSON 文件的文件名(不包括扩展名)
            # json_file_name = os.path.splitext(jpg_file)[0] + ".json"
            json_file_name = os.path.splitext(jpg_file)[0] + ".png"
            # 如果不存在对应的 JSON 文件,则删除对应的图片文件
            if os.path.splitext(json_file_name)[0] not in json_file_names:
                jpg_file_path = os.path.join(jpg_folder, jpg_file)
                os.remove(jpg_file_path)
                # print("已删除文件:", jpg_file_path)

    # 遍历数据文件夹中的所有文件
    for json_file in tqdm(json_files):
        # 如果不是 JSON 文件,则判断是否存在对应 JPG 文件
        # 获取对应 TXT 文件的目录
        json_path = os.path.join(json_folder, json_file)
        # if json_file.endswith(".json"):
        if json_file.endswith(".png"):
            # 获取对应 JPG 文件的文件名(不包括扩展名)
            jpg_file_name = os.path.splitext(json_file)[0] + ".jpg"
            # 如果不存在对应的 JPG 文件,则删除对应的图片文件
            if os.path.splitext(jpg_file_name)[0] not in jpg_file_names:
                json_file_path = os.path.join(json_folder, json_file)
                os.remove(json_file_path)
                # print("已删除文件:", json_file_path)
            # 如果txt为空文件,删除空文件和对应jpg文件
            if os.path.exists(json_path) and os.stat(json_path).st_size == 0:
                os.remove(json_path)  # 删除空的TXT文件
                os.remove(os.path.join(jpg_folder, jpg_file_name))  # 删除对应的JPG文件







def main ():
    # 设置数据文件夹的路径
    jpg_folder = "./jpg"
    json_folder = "./png"

    # 调用函数删除没有对应 JSON 文件的JPG文件
    delete_images_with_json(jpg_folder,json_folder)
    print()


if __name__ == "__main__":
    main()

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值