训练图像是.png格式,label是.xml格式,对应的文件名相同,如果在文件夹多出几个png文件,这几个文件没有对应的xml文件,这时要删除这几个多余的png文件。
path = r'D:\img\text_1000_xml'
# filepath, tmpfilename = os.path.split(path)->分离路径和文件名
file_list = os.listdir(path)
xml_shotname = []
for file in file_list:
if file.endswith('.xml'):
#splitext分离文件名的前缀和后缀
shotname, extension = os.path.splitext(file)
xml_shotname.append(shotname)
for file in file_list:
if file.endswith('.png'):
shotname, extension = os.path.splitext(file)
if shotname not in xml_shotname:
print(shotname)
os.remove(os.path.join(path,file))
接下来把png和txt分别复制到两个不同文件夹
import shutil
path = r'D:\img\text_1000_xml'
path_images = r'D:\img\images'
path_labels = r'D:\img\labels'
file_list = os.listdir(path)
xml_shotname = []
for file in file_list:
if file.endswith('.txt'):
shutil.copy(os.path.join(path,file),path_labels)
if file.endswith('.png'):
shutil.copy(os.path.join(path,file),path_images)
一个txt里面有很多行路径,把每行路径中某些字符替换成其它字符
import os
path = r'D:\yolo-v3-training'
f = open(os.path.join(path, 'training_list_tmp_new.txt'),'r')
f1 = open(os.path.join(path, 'training_list_tmp_new_test.txt'),'w')
for line in f:
# 进行判断
if 'img' in line:
new_line = line.replace('img','label')
print(new_line)
f1.write(new_line)
如果把有检测框和无检测框的图片放在一个文件夹下比较,对新图片在原图片name的基础上加个后缀,这种命名方式比较合理,可以使用os的rename方法
import os
path_img = r'D:\transparent_img\text_reality_save'
texts = os.listdir(path_img)
i = 0
for text in texts:
shotname, extension = os.path.splitext(text)
print(shotname)
# new_name = shotname.replace('.','')
new_name = shotname+'_new'
a = os.path.join(path_img,text)
b = os.path.join(path_img,new_name+extension)
os.rename(a,b)
网友评论