Python——目标检测标签中的英文名转化为对应的类别编号

Yolov5进行目标检测流程在下文中已做说明:

Python------一文详解使用yolov5进行目标检测全流程(无需gpu)_yolo不用gpu-CSDN博客

在Yolov5使用中中,标签数据里类别的中文名,需要转换成类别编号。相关代码如下:

python 复制代码
## 将标签中的英文名转化为对应的类别编号
import os

path = r'./datasets/labels/test1/'  # 转换前txt保存的文件夹
save = r'./datasets/labels/test/'  # 转换后txt保存的文件夹

for item in os.listdir(path):  # 遍历文件夹里的文件
    path_item = os.path.join(path, item)
    path_item2 = os.path.join(save, item)  # 保存的路径
    a = []
    with open(path_item, 'r') as f1, open(path_item2, "a") as f2:
        for line in f1:
            a.append(line)
        print(a)
        for i in a:
            if ' ' in str(i):  # 遍历每一行
                b = str(i)   # 提取第i行
                m = b.split(' ')    # 以空格为分隔符,进行切分
                dic = {'airplane': "0",  # 字典对类型进行转换
                       'airport': "1",
                       'baseballfield': "2",
                       'basketballcourt': "3",
                       'bridge': "4",
                       'chimney': "5",
                       'dam': "6",
                       'Expressway-Service-area': "7",
                       'Expressway-toll-station': "8",
                       'golffield': "9",
                       'groundtrackfield': "10",
                       'harbor': "11",
                       'overpass': "12",
                       'ship': "13",
                       'stadium': "14",
                       'storagetank': "15",
                       'tenniscourt': "16",
                       'trainstation': "17",
                       'vehicle': "18",
                       'windmill': "19",
                       }
                m[0] = dic.get(m[0])  # 对每行的第一个变量(即类别),将其替换成相应的值
                b = ' '.join(m)  # 将列表m重新拼接成一个字符串

                print(b)
                f2.write("%s" % (b))
        print('替换完成')
相关推荐
用户8356290780511 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon2 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly2 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程2 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly4 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风11 小时前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风11 小时前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi1 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风1 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风1 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python