当你在训练代码时,是否遇见过图片与标签不一致的情况?
主要分为以下两种情况:
- 图片多了,标签少了
- 标签多了,图片少了
解决方法:
使用代码前请确保标签名字和图片名字对应,且图片后缀一致。
import os
import shutil
from tqdm import tqdm
def main(txt_path,img_path):
img_list=[]
txt_list=[]
for i in tqdm(os.listdir(txt_path)):
txt_name=i.split(".")[0]
txt_suffix=i.split(".")[-1]
txt_list.append(txt_name)
for j in os.listdir(img_path):
img_name=j.split(".")[0]
img_suffix=j.split(".")[-1]
img_list.append(img_name)
#检查对应的图片是不是有标签,无标签则删除该图片
for img in tqdm(img_list):
if img not in txt_list:
remove_img_path=img_path+"/{}.{}".format(img,img_suffix)
os.remove(remove_img_path)
print(remove_img_path)
#检查对应的标签是不是有图片,无图片则删除该标签
for txt in tqdm(txt_list):
if txt not in img_list:
remove_txt_path=txt_path+"/{}.{}".format(txt,txt_suffix)
os.remove(remove_txt_path)
print(remove_txt_path)
if __name__ == '__main__':
# 需修改为自己的标签文件夹路径
txt_path = r"D:\desk\test_align\labels"
# 需修改为自己的图片文件夹路径
img_path = r"D:\desk\test_align\images"
main(txt_path,img_path)
仅修改txt_path和img——path即可运行
实验准备
H_175_1.jpg图片无标签
classes.txt标签无对应图片
开始实验
实验结果
可以正确移除有无图片的标签以及无标签的图片
完美~,代码寄几用~