【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)
相关推荐
张3蜂7 分钟前
Python venv 详解:为什么要用、怎么用、怎么用好
开发语言·python
老赵全栈实战15 分钟前
《从零搭建RAG系统第3天:文档加载+文本向量化+向量存入Milvus》
python
火龙果研究院19 分钟前
在CentOS上安装Python 3.13需要从源码编译
开发语言·python·centos
龙山云仓36 分钟前
No156:AI中国故事-对话司马迁——史家绝唱与AI记忆:时间叙事与因果之链
大数据·开发语言·人工智能·python·机器学习
niuniudengdeng41 分钟前
一种基于高维物理张量与XRF实景复刻的一步闭式解工业级3D打印品生成模型
人工智能·python·数学·算法·3d
overmind1 小时前
oeasy Python 114 在列表指定位置插入insert
开发语言·python
喵手1 小时前
Python爬虫实战:监控型爬虫实战 - 从结构检测到智能告警的完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·监控型爬虫实战·从结构哦检测到智能告警
深蓝电商API1 小时前
爬虫中 Cookie 池维护与自动刷新
爬虫·python
蜡笔羊驼2 小时前
LALIC环境安装过程
开发语言·python·深度学习
Starry_hello world2 小时前
Python(1)
python