import os
# 图片文件夹路径
image_folder_path = r"D:\Desktop\biaozhu\zuixin\img"
# txt文件夹路径
txt_folder_path = r"D:\Desktop\biaozhu\zuixin\xml"
# 获取所有xml文件的文件名,不包括扩展名
xml_files = set(os.path.splitext(filename)[0] for filename in os.listdir(txt_folder_path) if filename.endswith('.xml'))
# 遍历图片文件夹,删除没有对应xml文件名的图片
for image_filename in os.listdir(image_folder_path):
if image_filename.endswith('.jpg') or image_filename.endswith('.png'):
image_name = os.path.splitext(image_filename)[0]
if image_name not in xml_files:
image_path = os.path.join(image_folder_path, image_filename)
os.remove(image_path)
print(f"Deleted {image_filename} because the corresponding xml file was not found.")