【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)
相关推荐
databook7 分钟前
手把手带你走一遍:机器学习模型如何用FastAPI和Docker部署
python·docker·fastapi
DanCheng-studio24 分钟前
计算机技术与科学毕业设计简单的方向建议
python·毕业设计·毕设
言乐633 分钟前
Python排名统计折线图
开发语言·python·django·virtualenv·pygame
浩瀚地学38 分钟前
deepagents学习打卡day08
经验分享·笔记·python·学习·agent
卷无止境44 分钟前
便宜模型和贵模型到底差在哪儿?一份关于Claude与GPT分级体系的深度梳理
后端·python
玩美移动1 小时前
AI Skin Analysis API 技术解析:文件上传、异步任务与结果读取
java·人工智能·python
j7~1 小时前
【Python】(篇六)《基础语法(函数、列表和元组、字典、文件)》---详解
开发语言·python·文件·函数·字典·编程学习·元组与列表
Wx-bishekaifayuan2 小时前
springboot户外登山社交小程序19787-计算机课程设计、毕业设计
spring boot·后端·python·spring·elasticsearch·django·课程设计
FYKJ_20102 小时前
springboot刑事案件管理系统03047-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
Python图像识别3 小时前
18-【2027毕设】YOLO11烟雾检测识别系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·深度学习·yolo·毕业设计·毕设