【Yolox】修正标签类别

import os, glob

def alter(file,old_str,new_str):
    with open(file, "r", encoding="utf-8") as f1, open("%s.bak" % file, "w", encoding="utf-8") as f2:
        for lin in f1:
            print(lin)
            # lin = f.readlines()
            line_split = lin.strip().split()
            # line0 = line_split[0]
            if old_str in line_split[0]:
                line_split[0] = line_split[0].replace(old_str, new_str)
            f2.write(line_split[0] + ' ' +
                     line_split[1] + " " +
                     line_split[2] + " " +
                     line_split[3] + " " +
                     line_split[4]+'\n')

    os.remove(file)
    os.rename("%s.bak" % file, file)

txt_list = glob.glob("F:/1213bag/bag_all_yolox/add_new_6666/*.txt")
for txt_item in txt_list:
    alter(txt_item, "7", "2")
    alter(txt_item, "8", "0")
    alter(txt_item, "9", "3")
    alter(txt_item, "10", "6")
    alter(txt_item, "11", "1")
    alter(txt_item, "12", "4")

上面这个标签有时候更改会出现一些问题,按照下面这个来

import os

def modify_txt(oldtxt_path):
    for oldtxt in os.listdir(oldtxt_path):
        b = []
        txt_root=os.path.join(oldtxt_path+oldtxt)
        with open(txt_root,'r',encoding='utf-8') as f:
            _txt=f.readlines()# 读取所有行,readlines返回的是列表
            for i in _txt:
                b.append(i.split(' '))  #以空格分开
                for x in b:
                    # if x[0]=='10':  #这里换成你想要改的类别
                    #     x[0]='2'
                    #
                    a =  x[0]
                    print(x[0])
                    if x[0] == '24':
                        x[0] = '0'
                    elif x[0] == '25':
                        x[0] = '1'
                    elif x[0] == '28' or x[0] =='9':
                        x[0] = '2'
                    elif x[0] == '22' or x[0] =='26':
                        x[0] = '3'
                    elif x[0] == '23':
                        x[0] = '5'
                    elif x[0] == '27'or x[0] =='8':
                        x[0] = '7'
                    elif x[0] == '2':
                        x[0] = '9'
                    else:
                        x[0] = '10'
                #print(b)
            with open(txt_root,'w+',encoding='utf-8') as f: #把列表b里的信息再重新写入
                for c in b:
                    f.writelines(' '.join(c))
if __name__ == "__main__":
    p='F:/2022_11_09_08_29_17/txt/'#换成自己的路径,路径中不要出现中文,否则无法识别
    modify_txt(p)

你可能感兴趣的:(深度学习,python)