【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)
相关推荐
hef28833 分钟前
SQL和Python怎么选?数据分析工具实战指南
python·sql·数据分析
徐安安ye33 分钟前
FlashAttention长程依赖建模:局部+全局的Hybrid Spiral结构设计
python·深度学习·机器学习
IT策士1 小时前
Django 从 0 到 1 打造完整电商平台:商品排序与浏览量统计
后端·python·django
godspeed_lucip1 小时前
LLM和Agent——专题3: Agentic Workflow 入门(4)
人工智能·python
godspeed_lucip1 小时前
LLM和Agent——专题3: Agentic Workflow 入门(2)
网络·人工智能·python
mingshili1 小时前
[Python] Python中自带模块级的单例模式-不需要定义单例类
python·单例模式
alphaTao1 小时前
LeetCode 每日一题 2026/5/18-2026/5/24
python·leetcode
徐安安_ye11 小时前
FlashAttention学习路线:从调API到写算子,你该走哪条路
python·学习
IT策士2 小时前
Django 从 0 到 1 打造完整电商平台:商品搜索
后端·python·django
茉莉玫瑰花茶2 小时前
LangGraph 持久化(Persistence)[ 2 ]
开发语言·python·ai·langgraph