基础:将数据集划分为3类:train/test/val。利用txt文件保存图像的名称。
考虑到方便性,现将txt文件中的图像名称重命名,读取包含图像名的多个txt文件,给图像名加上前缀。
修改如下:
txt文件: 原始图像名称 ---> 修改后的图像名称
[txt_name].txt:[name].png ---> [txt_name]_[name].png
# encoding: utf-8
'''
读取包含图像名的多个txt文件,给图像名加上前缀。
包含数据集划分后的各图像名称的txt文件:train.txt,test.txt,val.txt
txt文件: 原始图像名称 ---> 修改后的图像名称
train: 2045.png ---> train_2045.png
test: 3873.png ---> test_3873.png
val: 6154.png ---> val_6154.png
'''
import os
import random
def read_file(filepath,txt_name):
file_list=[]
list2=[]
with open(filepath,'r') as fr:
data = fr.readlines()
data = ''.join(data).strip('\n').splitlines()
file_list=data
# print(file_list)
txt0=txt_name.split('.')[0]
for line in file_list:
line=txt0+'_'+line
list2.append(line)
return list2
def write_file(dst1,txt):
fo=open(dst1,'w')
for item in txt:
fo.write(str(item)+'\n')
if __name__ == "__main__":
root_path=r'F:\all_date\WHU'
txts=['train.txt','test.txt','val.txt']
for txt_name in txts:
to_path=os.path.join(root_path,txt_name)
txt_list=read_file(to_path,txt_name)
write_file(to_path,txt_list)