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('替换完成')
相关推荐
爱睡懒觉的焦糖玛奇朵19 小时前
【从视频到数据集:焦糖玛奇朵的魔法工具使用说明】
人工智能·python·深度学习·学习·算法·yolo·音视频
yangshicong20 小时前
第11章:结构化输出与数据提取 —— 让 AI 直接返回你想要的数据格式
数据库·人工智能·redis·python·langchain·ai编程
言之。20 小时前
【Python】免费的中文 AI 配音方案
开发语言·人工智能·python
Warson_L20 小时前
python dict key详解
python
天天进步201520 小时前
Python全栈项目:从零手操一个高性能 API 网关
开发语言·python
安生生申1 天前
使用pygame实现2048
开发语言·python·pygame
徐图图不糊涂1 天前
搭建简易版的Rag系统
python·pycharm
灰灰勇闯IT1 天前
pyasc:用 Python 调用 CANN 的推理能力
开发语言·python
明月_清风1 天前
FastAPI 从入门到实战:3 分钟构建高性能异步 API
后端·python·fastapi
bellus-1 天前
ubuntu26测试win10的ollama大模型性能
python