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()