【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)
相关推荐
benchmark_cc5 小时前
REST API 和 Python SDK 应该怎么选?量化交易数据接口选型实战
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
Ysn07196 小时前
YOLO-Master工程:modules.py 全景详解与 MoE 迁移启发
yolo
2601_962382436 小时前
python快乐编程网络爬虫课后答案
python·网络爬虫·学习工具·课后答案·刷题app
鹏哥带你干乡墅7 小时前
优选乡墅赋能培训平台如何帮助提升乡村建设?
大数据·人工智能·python
veminhe8 小时前
python调用接口获取网络信息
python
Allen_LVyingbo8 小时前
医疗AI基础2026-构建可靠智能体的编程路径(上)
大数据·数据库·人工智能·python·自动化
Rnan-prince9 小时前
堆与TopK · 从零到通透 —— 9 节全系列复盘
python·算法
2601_9622946110 小时前
Python接口自动化测试实战:使用requests库
python·接口自动化测试·异常处理·requests库·api测试
砚底藏山河10 小时前
【量化纯GET实战 #23】多股票相关性:用收益率看板块联动
java·数据库·python·金融·数据分析
阿童木写作10 小时前
跨境电商翻译工具推荐:批量图片翻译+视频字幕实时翻译
人工智能·python·音视频