【python】修改目标检测的txt标签(yolo)的类别ID映射

脚本功能:

针对目录下的所有yolo格式的txt标签文件,将class类别的id修改为指定id。

实际应用常见不多

代码

复制代码
# -*- coding: utf-8 -*-
# @Time : 2023/9/11 10:58
# @Author : CLW
# @FileName: change_txt_label.py
# @Software: PyCharm

import os

'''
算法功能:
针对目录下的所有yolo格式的txt标签文件,将类别的id修改为指定id
要求:old_class_idx与reset_class_idx的分别表示修改前的id和修改后的id,需要做到一一对应。
old_class_idx = [0, 1],reset_class_idx = [2, 3]
表示原有txt标签的0都替换成2, 原有txt标签的1都替换成3
'''

'''
####################    输入参数设置(开始)    #################### 
'''
org_label_dir = r'/test_data/change_txt_label'
new_label_dir = r'/test_data/change_txt_label/new_labels'
label_type = 'txt'
old_class_idx = [0, 1]
reset_class_idx = [2, 3]    # 一一对应进行修改
'''
####################    输入参数设置(结束)    #################### 
'''

if not os.path.exists(new_label_dir):
    os.mkdir(new_label_dir)
for root, dir, files in os.walk(org_label_dir):
    for file in files:
        print(file)
        if file[-3:] == label_type:
            txt_file = os.path.join(root,file)
            with open(txt_file, 'r') as f:
                objects = f.readlines()
                outlines = []
                for object in objects:
                    object = object.strip().split(' ')
                    for i in range(len(old_class_idx)):
                        if object[0] == str(old_class_idx[i]):
                            object[0] = str(reset_class_idx[i]);
                    outlines.append( " ".join([str(a) for a in object]) + '\n')
            txt_path = file[:-3] + 'txt'  # xml文件路径
            txt_path = os.path.join(new_label_dir, txt_path)
            with open(txt_path, 'w') as out_txt:
                out_txt.writelines(outlines)
相关推荐
ZWaruler1 小时前
二: 字典及函数的使用
python
蚰蜒螟1 小时前
深入解析JVM字节码解释器执行流程(OpenJDK 17源码实现)
开发语言·jvm·python
墨绿色的摆渡人1 小时前
pytorch小记(二十):深入解析 PyTorch 的 `torch.randn_like`:原理、参数与实战示例
人工智能·pytorch·python
几道之旅2 小时前
mAP、AP50、AR50:目标检测中的核心评价指标解析
人工智能·目标检测·目标跟踪
英英_2 小时前
python 自动化教程
开发语言·python·自动化
万能程序员-传康Kk2 小时前
【Python+flask+mysql】网易云数据可视化分析(全网首发)
python·mysql·信息可视化·数据分析·flask·可视化·网易云
先做个垃圾出来………2 小时前
汉明距离(Hamming Distance)
开发语言·python·算法
测试者家园2 小时前
用 VS Code / PyCharm 编写你的第一个 Python 程序
ide·vscode·python·职场和发展·零基础·pycharm·零基础学python
墨绿色的摆渡人3 小时前
pytorch小记(二十一):PyTorch 中的 torch.randn 全面指南
人工智能·pytorch·python
大叔_爱编程3 小时前
p024基于Django的网上购物系统的设计与实现
python·django·vue·毕业设计·源码·课程设计·网上购物系统