YOLO训练中的图片不小心删除了,但是标签文件还没删,可以根据剩下的文件找到对应的标签,把多余的标签文件删除了。
import os
# 图片文件夹路径
image_folder_path = r"E:\ZhuoMian\gongjain\tupian"
# txt文件夹路径
txt_folder_path = r"E:\ZhuoMian\gongjain\txt"
# 获取所有图片文件的文件名,不包括扩展名
image_files = set(os.path.splitext(filename)[0] for filename in os.listdir(image_folder_path) if filename.endswith('.jpg') or filename.endswith('.png'))
# 遍历文本文件夹,删除没有对应图片文件的文本文件
for txt_filename in os.listdir(txt_folder_path):
if txt_filename.endswith('.txt'):
txt_name = os.path.splitext(txt_filename)[0]
if txt_name not in image_files:
txt_path = os.path.join(txt_folder_path, txt_filename)
os.remove(txt_path)
print(f"Deleted {txt_filename} because the corresponding image file was not found.")