【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)
相关推荐
声声codeGrandMaster3 分钟前
seq2seq概念和数据集处理
人工智能·pytorch·python·算法·ai
m0_609160495 分钟前
如何使用Python查询MongoDB并转为Pandas DataFrame_数据分析集成实战
jvm·数据库·python
woxihuan12345616 分钟前
c++怎么利用std--variant处理多种二进制子协议包的自动分支解析【进阶】
jvm·数据库·python
专注VB编程开发20年19 分钟前
逍遥Pya IDE -- 可视化Python开发工具,类似VBA WPS(JSA)
ide·python·wps
轩轩的学习之路23 分钟前
claudecode安装+第三方模型,无root
linux·人工智能·python
键盘上的猫头鹰25 分钟前
Jupyter notebook安装与启动
python·数据分析
闲人编程31 分钟前
Agent的安全边界:如何防止AI失控(对齐问题)
网络·python·ai·agent·权限·智能体·cai
Generalzy32 分钟前
为什么 Go 的注释,能控制编译器?
java·python·golang
西洼工作室35 分钟前
缓存工具类封装:内存与Redis无缝切换
redis·python·缓存·全栈
m0_6091604940 分钟前
Go语言Beego框架如何用_Go语言Beego框架入门教程【高效】
jvm·数据库·python