YOLO:使用labelme进行图片数据标签制作,并转换为YOLO格式

作者:CSDN @ _养乐多_

本文将介绍如何使用 labelme 进行图片数据标签制作的方法,并将标签的格式从 JSON 格式转换为 YOLO 格式。



labelme标注有问题的话,推荐以下网站进行标注:https://www.makesense.ai/,使用教程:https://blog.csdn.net/weixin_72050316/article/details/133976974,如果需要二次开发该网站可以访问其源代码:https://gitee.com/homeleaf/make-sense

一、安装labelme

试过了labelme和labelImg,labelImg经常奔溃不太好用,最终选择labelme。

pip install labelme

二、使用流程

运行labelme,

在这里插入图片描述

比较好的数据管理方式是,将图片和标注信息分开保存,方便之后数据格式转换和数据集划分的脚本使用。所以需要将标注信息输出路径修改一下。我把图片都保存在images文件夹下了,输出标注信息的路径是和images同级的labels文件夹。最好取消同时保存图像数据按钮,并点击自动保存按钮。

总结:
1.点击自动保存;
2.更改标注信息输出路径到labels文件夹;
3.取消同时保存图像数据。

在这里插入图片描述

打开目录读取数据集,

编辑菜单中选择创建矩形,这是为了YOLO这种目标检测算法做标签用的。语义分割、目标追踪等就选多边形。

在这里插入图片描述

拖动矩形框并输入标注名称,点击ok即可自动保存。标注完之后选择下一张。
最后,labels文件夹下会保存所有的标注数据,不过是json格式。
如果想要用到YOLO算法中还需要将json格式修改为YOLO格式。

在这里插入图片描述

保存结果如下图所示,

在这里插入图片描述

三、json格式转为YOLO格式

category_dict,input_directory,output_directory 。
使用时,需要修改这三个变量。
category_dict:类别字典,对应类别名和类别ID;
input_directory :json保存的目录;
output_directory :YOLO格式标注的目录。

import json
import os

category_dict = {
    
    '飞机': '1'}  # 类别字典

def json_to_yolo(input_file_path, output_directory):
    data = json.load(open(input_file_path, encoding="utf-8"))  # 读取带有中文的文件
    image_width = data["imageWidth"]  # 获取json文件里图片的宽度
    image_height = data["imageHeight"]  # 获取json文件里图片的高度
    yolo_format_content = ''

    for shape in data["shapes"]:
        # 归一化坐标点,并计算中心点(cx, cy)、宽度和高度
        [[x1, y1], [x2, y2]] = shape['points']
        x1, x2 = x1 / image_width, x2 / image_width
        y1, y2 = y1 / image_height, y2 / image_height
        cx = (x1 + x2) / 2
        cy = (y1 + y2) / 2
        width = abs(x2 - x1)
        height = abs(y2 - y1)

        # 将数据组装成YOLO格式
        line = "%s %.4f %.4f %.4f %.4f\n" % (category_dict[shape['label']], cx, cy, width, height)  # 生成txt文件里每行的内容
        yolo_format_content += line

    # 生成txt文件的相应文件路径
    output_file_path = os.path.join(output_directory, os.path.basename(input_file_path).replace('json', 'txt'))
    with open(output_file_path, 'w', encoding='utf-8') as file_handle:
        file_handle.write(yolo_format_content)


input_directory = "E:/DataSet/test/labels/"
output_directory = "E:/DataSet/test/labels-yolo/"

file_list = os.listdir(input_directory)
json_file_list = [file for file in file_list if file.endswith(".json")]  # 获取所有json文件的路径

for json_file in json_file_list:
    json_to_yolo(os.path.join(input_directory, json_file), output_directory)

四、按比例划分数据集(训练、验证、测试)

如果需要将图片和标签数据集按比例划分为训练、验证、测试数据集,请参考以下博客。

参考博客《YOLO:VOC格式数据集转换为YOLO数据集格式》中的第2节。

猜你喜欢

转载自blog.csdn.net/qq_35591253/article/details/140986015