使用情况说明
深度学习进行目标检测任务的训练,有些图片很大,就要将图片和标签拆分了,扔到网络里训练。
出结果进行预测推理的时候也是一样,将大图拆成小图,送到网络里进行预测,会生成txt标注文件,这时的标注文件也是相对与小图的坐标的,要提交结果的时候,需要将小图的坐标转换成大图的坐标。
即,需要将txt进行合并,下面是合并txt的程序,可以和拆分txt和图片的文件一起,对照着看。
程序
import os
'''
这个程序是用来合infer推理后生成的txt,因此标签有置信度的分数,同时类别标签在开头
'''
input_dir_path = '/home/rtx2080ti/GeTu/AllTxt/Result' # 原来存放mask.txt文件的目录;
# os.mkdir('/home/rtx2080ti/GeTu/train/new_mask') # 没有目录的话,创建修改后存放的txt目录;
output_dir_path = '/home/rtx2080ti/GeTu/AllTxt/Merge' # 修改后存放的txt目录;
def MergeTxt(input_filename):
with open(input_dir_path+'/'+input_filename, 'r') as inputfile:
with open(output_dir_path+'/'+output_filename, 'a') as outputfile:
for line in inputfile:
list1 = line.rstrip('\n').split(' ')
print(list1) # list1是推理出来的小图的标签,分数,和坐标;
label = list1[0]
score = list1[1] # score为置信度得分;
x1 = float(list1[2])
y1 = float(list1[3])
x2 = float(list1[4])
y2 = float(list1[5])
x3 = float(list1[6])
y3 = float(list1[7])
x4 = float(list1[8])
y4 = float(list1[9])
# 开始转换坐标
x1 = float(x1 + w)
y1 = float(y1 + h)
x2 = float(x2 + w)
y2 = float(y2 + h)
x3 = float(x3 + w)
y3 = float(y3 + h)
x4 = float(x4 + w)
y4 = float(y4 + h)
list2 = [label, score, x1, y1, x2, y2, x3, y3, x4, y4]
print(list2) # list2是大图坐标下的的标签,分数,和坐标;
# 开始写入txt,第一列是类别,第二列是置信度分数,后面的是坐标;
outputfile.write(str(label) + " " + str(score) + " " + str(x1) + " " + str(y1) + " " + str(x2) + " " +
str(y2) + " " + str(x3) + " " + str(y3) + " " + str(x4) + " " + str(y4) + " " + '\n')
outputfile.close()
inputfile.close()
return outputfile
if __name__ == '__main__':
# 遍历输入路径,得到图片名
for input_filename in os.listdir(input_dir_path):
print(input_filename)
# 去除文件名后缀
name = input_filename[:-4]
# 得到原图像(也即txt)索引 + 切割高 + 切割宽
name_list = name.split('_')
# 得到输出的文件名
output_filename = name_list[0] + '.txt' # 原来是一个大图的写在一起
h = float(name_list[1]) # 相当于y0
w = float(name_list[2]) # 相当于x0
print(output_filename)
print(w, h)
MergeTxt(input_filename)
print('合并txt已完成!')