您好,
会员登录 快速注册
退出 ( 条未读消息)
关于本站 意见反馈 首页

公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!
全部文章分类
  • 人工智能 >

  • 编程语言 >

  • WPF系列 >

  • ASP.NET系列 >

  • Linux >

  • 数据库 >

  • 嵌入式 >

  • WEB技术 >

  • PLC系列 >

  • 微服务与框架 >

  • 小宅DIY >

  • 学习资料 >

OpenCv基础 ANN车牌识别 yolov5车牌识别 指针式仪表识别 ROS系列 YOLO Halcon Detectron2 昇腾AI ChatGPT在线体验 英伟达JETSON ChatGLM ChatTTS FunASR 地平线 ByteTrack 魔搭社区 LangChain
C C# C++ Python Java Go
WPF
ASP.NET小功能 GPS定位系统-MVC GPS定位系统-VUE ASP.NET WebRTC
Linux Linux内核 Shell MakeFile
MySql SqlServer Oracle
STM8 STM32 51单片机
VUE入门 HTML JavaScript CSS layui镜像网站 ElementUi中文官网 element-plus 图标
三菱 欧姆龙 西门子 施耐德 松下 台达
IOTSharp IOTGateway ABP FRAMEWORK Docker
亚克力音响 编程仙途:智驭万法
面试题与技巧 Python入门技能树 微软C#教程
首页 编程之美 工具下载 全国就业 流量地图 文心一言
YOLO
YOLO 学习介绍 Labelme安装与运行 YOLOv5 安装开发环境 YOLOv5 官方数据集训练方法 YOLOv5 自定义数据集训练方法 YOLOv5 GPU训练方法 YOLOv5 调用USB摄像头识别 YOLOv5 在Ubuntu22.10安装运行环境 YOLOv5 实例分割-官方数据集训练方法 YOLOv5 实例分割-Labelme标注与json文件转txt YOLOv5 pt转onnx文件 YOLOv5 pt转engine文件 YOLOv5 C#中进行模型预测(.net版) YOLOv5 C#中进行模型预测(winform版) YOLOv5 C++进行模型预测 YOLOv5-7.0 安装开发环境 YOLOx 安装开发环境 YOLOx 官网数据集训练方法1(VOC) YOLOx 官网数据集训练方法2(COCO) YOLOx 自定义数据集训练方法1(VOC) YOLOx 自定义数据集训练方法2(COCO) YOLOx 调用USB摄像头识别 YOLOv8 安装开发环境 YOLOv8 官方数据集训练方法 YOLOv8 pt转onnx文件与测试 YOLOv11 安装开发环境 YOLOv11 自定义目标检测模型训练
YOLOv5 实例分割-官方数据集训练方法
YOLOv5 pt转onnx文件
激萌の小宅 小宅博客网 YOLO

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 3

    累计评价

YOLOv5 实例分割-Labelme标注与json文件转txt

labelme启动方法请参考博客:Labelme安装与运行

打开labelme之后,使用Create Polygons沿着我们需要检测的目标轮廓进行进行多边形标注,如下:

QQ截图20230412143523.jpg


标注完之后,使用下面代码将labelme标注的*.json文件转换成yolov5_v7.0sege数据集文件*.txt

import json
import os
import glob
import os.path as osp


def labelme2yolov2Seg(jsonfilePath="", resultDirPath="", classList=["YiBiao", "ZhiZhen"]):
    """
    此函数用来将labelme软件标注好的数据集转换为yolov5_7.0sege中使用的数据集
    :param jsonfilePath: labelme标注好的*.json文件所在文件夹
    :param resultDirPath: 转换好后的*.txt保存文件夹
    :param classList: 数据集中的类别标签
    :return:
    """
    # 0.创建保存转换结果的文件夹
    if(not os.path.exists(resultDirPath)):
        os.mkdir(resultDirPath)

    # 1.获取目录下所有的labelme标注好的Json文件,存入列表中
    jsonfileList = glob.glob(osp.join(jsonfilePath, "*.json"))
    print(jsonfileList)  # 打印文件夹下的文件名称

    # 2.遍历json文件,进行转换
    for jsonfile in jsonfileList:
        # 3. 打开json文件
        with open(jsonfile, "r") as f:
            file_in = json.load(f)

            # 4. 读取文件中记录的所有标注目标
            shapes = file_in["shapes"]

            # 5. 使用图像名称创建一个txt文件,用来保存数据
            with open(resultDirPath + "\\" + jsonfile.split("\\")[-1].replace(".json", ".txt"), "w") as file_handle:
                # 6. 遍历shapes中的每个目标的轮廓
                for shape in shapes:
                    # 7.根据json中目标的类别标签,从classList中寻找类别的ID,然后写入txt文件中
                    file_handle.writelines(str(classList.index(shape["label"])) + " ")

                    # 8. 遍历shape轮廓中的每个点,每个点要进行图像尺寸的缩放,即x/width, y/height
                    for point in shape["points"]:
                        x = point[0]/file_in["imageWidth"]  # mask轮廓中一点的X坐标
                        y = point[1]/file_in["imageHeight"]  # mask轮廓中一点的Y坐标
                        file_handle.writelines(str(x) + " " + str(y) + " ")  # 写入mask轮廓点

                    # 9.每个物体一行数据,一个物体遍历完成后需要换行
                    file_handle.writelines("\n")
            # 10.所有物体都遍历完,需要关闭文件
            file_handle.close()
        # 10.所有物体都遍历完,需要关闭文件
        f.close()

if __name__ == "__main__":
    jsonfilePath = "E:\\yolo\\yolov5-master\\datasets\\labelme\\json"  # 要转换的json文件所在目录
    resultDirPath = "E:\\yolo\\yolov5-master\\datasets\\labelme\\txt"  # 要生成的txt文件夹
    labelme2yolov2Seg(jsonfilePath=jsonfilePath, resultDirPath=resultDirPath, classList=["YiBiao", "ZhiZhen"])


然后将我们的jpg图片和转换后的txt文件按“coco128-seg”数据集格式,扔到datasets目录下,最后进行识别测试,测试结果如下:

QQ截图20230412144005.jpg


代码优化

博主对上面代码重新优化了一下,如下:

'''
将json文件转为yolo所需要的txt文件。将未转换的标注放入labels文件夹中,图片放入images文件夹中
json中[x1,y1,x2,y2],(x1,y1)表示目标左上角坐标,(x2,y2)表示目标右下角坐标,图片左上角坐标为(0,0)
yolo的txt中[class,x_center,y_center,width,height](需要根据图片宽高进行归一化处理)
yolo(类别 中心点的x 中心点的y 宽度w 高度h)
'''

import json
import os
from PIL import Image


def convert(img_size, box):  # 坐标转换
    dw = 1. / (img_size[0])
    dh = 1. / (img_size[1])
    x = (box[0] + box[2]) / 2.0
    y = (box[1] + box[3]) / 2.0
    # 左上到右下,否则负数
    w = box[2] - box[0]
    h = box[3] - box[1]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh

    return x, y, w, h


def decode_json(json_floder_path, json_name):
    # txt输出路径
    txtpath = 'yolov5-master/datasets/coco/labels/train2017/'
    txt_name = txtpath + json_name[0:-5] + '.txt'  # 生成txt文件存放的路径
    print(txt_name)
    txt_file = open(txt_name, 'w')
    json_path = os.path.join(json_floder_path, json_name)
    data = json.load(open(json_path, 'r', encoding='utf-8'))

    # 图片路径
    imgpath = 'yolov5-master/datasets/labelme/'
    image_path = imgpath + json_name[0:-5] + '.jpg'  # 图片存放路径

    # 使用pillow读取图片,获取图片的宽和高
    img_pillow = Image.open(image_path)
    img_w = img_pillow.width  # 图片宽度
    img_h = img_pillow.height  # 图片高度
    print(image_path, img_w, img_h)

    # 所有样本名称列表
    labels = ['person', 'bicycle', 'car']

    for i in data['shapes']:
        for index, label in enumerate(labels):
            if i['label'] == label:
                x1, y1 = i['points'][0]
                x2, y2 = i['points'][1]
                bb = (x1, y1, x2, y2)
                bbox = convert((img_w, img_h), bb)
                txt_file.write(str(index) + " " + " ".join([str(a) for a in bbox]) + '\n')
                break


if __name__ == "__main__":
    json_floder_path = 'yolov5-master/datasets/labelme'  # json文件的路径
    json_names = os.listdir(json_floder_path)
    for json_name in json_names:
        if json_name.split(".")[-1] == "json":
            decode_json(json_floder_path, json_name)

YOLOv5 实例分割-官方数据集训练方法
YOLOv5 pt转onnx文件

友情链接: CSDN激萌の小宅 95知识库 自考题库 罗分明个人网络博客 精益编程leanboot

小宅博客  www.bilibili996.com All Rights Reserved. 备案号: 闽ICP备2024034575号

网站经营许可证  福建省福州市 Copyright©2021-2025 版权所有

小宅博客
首页 智能家居 地图定位
公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 3

    累计评价

YOLOv5 实例分割-Labelme标注与json文件转txt

labelme启动方法请参考博客:Labelme安装与运行

打开labelme之后,使用Create Polygons沿着我们需要检测的目标轮廓进行进行多边形标注,如下:

QQ截图20230412143523.jpg


标注完之后,使用下面代码将labelme标注的*.json文件转换成yolov5_v7.0sege数据集文件*.txt

import json
import os
import glob
import os.path as osp


def labelme2yolov2Seg(jsonfilePath="", resultDirPath="", classList=["YiBiao", "ZhiZhen"]):
    """
    此函数用来将labelme软件标注好的数据集转换为yolov5_7.0sege中使用的数据集
    :param jsonfilePath: labelme标注好的*.json文件所在文件夹
    :param resultDirPath: 转换好后的*.txt保存文件夹
    :param classList: 数据集中的类别标签
    :return:
    """
    # 0.创建保存转换结果的文件夹
    if(not os.path.exists(resultDirPath)):
        os.mkdir(resultDirPath)

    # 1.获取目录下所有的labelme标注好的Json文件,存入列表中
    jsonfileList = glob.glob(osp.join(jsonfilePath, "*.json"))
    print(jsonfileList)  # 打印文件夹下的文件名称

    # 2.遍历json文件,进行转换
    for jsonfile in jsonfileList:
        # 3. 打开json文件
        with open(jsonfile, "r") as f:
            file_in = json.load(f)

            # 4. 读取文件中记录的所有标注目标
            shapes = file_in["shapes"]

            # 5. 使用图像名称创建一个txt文件,用来保存数据
            with open(resultDirPath + "\\" + jsonfile.split("\\")[-1].replace(".json", ".txt"), "w") as file_handle:
                # 6. 遍历shapes中的每个目标的轮廓
                for shape in shapes:
                    # 7.根据json中目标的类别标签,从classList中寻找类别的ID,然后写入txt文件中
                    file_handle.writelines(str(classList.index(shape["label"])) + " ")

                    # 8. 遍历shape轮廓中的每个点,每个点要进行图像尺寸的缩放,即x/width, y/height
                    for point in shape["points"]:
                        x = point[0]/file_in["imageWidth"]  # mask轮廓中一点的X坐标
                        y = point[1]/file_in["imageHeight"]  # mask轮廓中一点的Y坐标
                        file_handle.writelines(str(x) + " " + str(y) + " ")  # 写入mask轮廓点

                    # 9.每个物体一行数据,一个物体遍历完成后需要换行
                    file_handle.writelines("\n")
            # 10.所有物体都遍历完,需要关闭文件
            file_handle.close()
        # 10.所有物体都遍历完,需要关闭文件
        f.close()

if __name__ == "__main__":
    jsonfilePath = "E:\\yolo\\yolov5-master\\datasets\\labelme\\json"  # 要转换的json文件所在目录
    resultDirPath = "E:\\yolo\\yolov5-master\\datasets\\labelme\\txt"  # 要生成的txt文件夹
    labelme2yolov2Seg(jsonfilePath=jsonfilePath, resultDirPath=resultDirPath, classList=["YiBiao", "ZhiZhen"])


然后将我们的jpg图片和转换后的txt文件按“coco128-seg”数据集格式,扔到datasets目录下,最后进行识别测试,测试结果如下:

QQ截图20230412144005.jpg


代码优化

博主对上面代码重新优化了一下,如下:

'''
将json文件转为yolo所需要的txt文件。将未转换的标注放入labels文件夹中,图片放入images文件夹中
json中[x1,y1,x2,y2],(x1,y1)表示目标左上角坐标,(x2,y2)表示目标右下角坐标,图片左上角坐标为(0,0)
yolo的txt中[class,x_center,y_center,width,height](需要根据图片宽高进行归一化处理)
yolo(类别 中心点的x 中心点的y 宽度w 高度h)
'''

import json
import os
from PIL import Image


def convert(img_size, box):  # 坐标转换
    dw = 1. / (img_size[0])
    dh = 1. / (img_size[1])
    x = (box[0] + box[2]) / 2.0
    y = (box[1] + box[3]) / 2.0
    # 左上到右下,否则负数
    w = box[2] - box[0]
    h = box[3] - box[1]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh

    return x, y, w, h


def decode_json(json_floder_path, json_name):
    # txt输出路径
    txtpath = 'yolov5-master/datasets/coco/labels/train2017/'
    txt_name = txtpath + json_name[0:-5] + '.txt'  # 生成txt文件存放的路径
    print(txt_name)
    txt_file = open(txt_name, 'w')
    json_path = os.path.join(json_floder_path, json_name)
    data = json.load(open(json_path, 'r', encoding='utf-8'))

    # 图片路径
    imgpath = 'yolov5-master/datasets/labelme/'
    image_path = imgpath + json_name[0:-5] + '.jpg'  # 图片存放路径

    # 使用pillow读取图片,获取图片的宽和高
    img_pillow = Image.open(image_path)
    img_w = img_pillow.width  # 图片宽度
    img_h = img_pillow.height  # 图片高度
    print(image_path, img_w, img_h)

    # 所有样本名称列表
    labels = ['person', 'bicycle', 'car']

    for i in data['shapes']:
        for index, label in enumerate(labels):
            if i['label'] == label:
                x1, y1 = i['points'][0]
                x2, y2 = i['points'][1]
                bb = (x1, y1, x2, y2)
                bbox = convert((img_w, img_h), bb)
                txt_file.write(str(index) + " " + " ".join([str(a) for a in bbox]) + '\n')
                break


if __name__ == "__main__":
    json_floder_path = 'yolov5-master/datasets/labelme'  # json文件的路径
    json_names = os.listdir(json_floder_path)
    for json_name in json_names:
        if json_name.split(".")[-1] == "json":
            decode_json(json_floder_path, json_name)