【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)
相关推荐
炼丹师小米6 分钟前
Ubuntu24.04.1系统下VideoMamba环境配置
python·环境配置·videomamba
GFCGUO12 分钟前
ubuntu18.04运行OpenPCDet出现的问题
linux·python·学习·ubuntu·conda·pip
985小水博一枚呀2 小时前
【深度学习基础模型】神经图灵机(Neural Turing Machines, NTM)详细理解并附实现代码。
人工智能·python·rnn·深度学习·lstm·ntm
萧鼎3 小时前
Python调试技巧:高效定位与修复问题
服务器·开发语言·python
IFTICing3 小时前
【文献阅读】Attention Bottlenecks for Multimodal Fusion
人工智能·pytorch·python·神经网络·学习·模态融合
大神薯条老师3 小时前
Python从入门到高手4.3节-掌握跳转控制语句
后端·爬虫·python·深度学习·机器学习·数据分析
程序员爱德华3 小时前
Python环境安装教程
python
huanxiangcoco4 小时前
152. 乘积最大子数组
python·leetcode
萧鼎4 小时前
Python常见问题解答:从基础到进阶
开发语言·python·ajax
如果能为勤奋颁奖4 小时前
YOLO11改进|卷积篇|引入可变核卷积AKConv
yolo