【小脚本】如何将.json格式的标签,一键划分数据集比例并转成适配yolo5训练格式

117 阅读3分钟

1、功能简介

当我们拿到json标注数据,如何完成数据一键划分,并转成YOLO5适配的训练格式呢,下面两个脚本可以让这个问题立马结果;

2、脚本

数据集的一键划分:

import os
import random

trainval_percent = 0.9
train_percent = 0.9
jsonfilepath = 'data_get/Annotations'
txtsavepath = 'data_get/ImageSets'
total_json = os.listdir(jsonfilepath)

num = len(total_json)
list = range(num)
tv = int(num * trainval_percent)
tr = int(tv * train_percent)
trainval = random.sample(list, tv)
train = random.sample(trainval, tr)

ftrainval = open('/data/private/ImageSets/trainval.txt', 'w')
ftest = open('/data/private/ImageSets/test.txt', 'w')
ftrain = open('/data/private/ImageSets/train.txt', 'w')
fval = open('/data/private/ImageSets/val.txt', 'w')


for i in list:
    name = total_json[i][:-5] + '\n'

    if i in trainval:
        ftrainval.write(name)
        if i in train:
            ftrain.write(name)
        else:
            fval.write(name)
    else:
        ftest.write(name)

ftrainval.close()
ftrain.close()
fval.close()
ftest.close()

数据集的一键转换:

import json
import os
from os import listdir, getcwd
from os.path import join

sets = ['train', 'test', 'val']
classes = ['point']  # 根据你的JSON文件中的类别进行设置


def convert(size, box):  # size:(原图w,原图h) , box:(xmin,xmax,ymin,ymax)
    dw = 1. / size[0]  # 1/w
    dh = 1. / size[1]  # 1/h
    x = (box[0] + box[1]) / 2.0  # 物体在图中的中心点x坐标
    y = (box[2] + box[3]) / 2.0  # 物体在图中的中心点y坐标
    w = box[1] - box[0]  # 物体实际像素宽度
    h = box[3] - box[2]  # 物体实际像素高度
    x = x * dw  # 物体中心点x的坐标比(相当于 x/原图w)
    w = w * dw  # 物体宽度的宽度比(相当于 w/原图w)
    y = y * dh  # 物体中心点y的坐标比(相当于 y/原图h)
    h = h * dh  # 物体宽度的宽度比(相当于 h/原图h)
    return (x, y, w, h)  # 返回 相对于原图的物体中心点的x坐标比,y坐标比,宽度比,高度比,取值范围[0-1]


def convert_annotation(image_id):

    # 对应的通过year 找到相应的文件夹,并且打开相应image_id的json文件
    in_file = open('data_get/Annotations/%s.json' % (image_id), encoding='utf-8')
    # 准备在对应的image_id 中写入对应的label,分别为
    # <object-class> <x> <y> <width> <height>
    out_file = open('data_get/labels/%s.txt' % (image_id), 'w', encoding='utf-8')
    # 解析json文件
    data = json.load(in_file)
    # 获得图片的尺寸大小
    w = int(data['imageWidth'])
    h = int(data['imageHeight'])
    # 遍历目标obj
    for obj in data['shapes']:
        # 获得类别 =string 类型
        cls = obj['label']
        # 如果类别不是对应在我们预定好的class文件中,则跳过
        if cls not in classes:
            continue
        # 通过类别名称找到id
        cls_id = classes.index(cls)
        # 获取对应的bndbox的数组 = ['xmin','xmax','ymin','ymax']
        points = obj['points']
        xmin = min(points[0][0], points[1][0])
        xmax = max(points[0][0], points[1][0])
        ymin = min(points[0][1], points[1][1])
        ymax = max(points[0][1], points[1][1])
        b = (xmin, xmax, ymin, ymax)
        print(image_id, cls, b)
        # 带入进行归一化操作
        # w = 宽, h = 高, b= bndbox的数组 = ['xmin','xmax','ymin','ymax']
        bb = convert((w, h), b)
        # bb 对应的是归一化后的(x,y,w,h)
        # 生成 class x y w h 在label文件中
        out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')


wd = getcwd()
print(wd)

for image_set in sets:

    # 先找labels文件夹如果不存在则创建
    if not os.path.exists('data_get/labels/'):
        os.makedirs('data_get/labels/')
    # 读取在ImageSets/Main 中的train、test..等文件的内容
    # 包含对应的文件名称
    image_ids = open('data_get/ImageSets/%s.txt' % (image_set)).read().strip().split()
    # 打开对应的2012_train.txt 文件对其进行写入准备
    list_file = open('data_get/%s.txt' % (image_set), 'w')
    # 将对应的文件_id以及全路径写进去并换行
    for image_id in image_ids:
        list_file.write('data_get/images/%s.bmp\n' % (image_id))
        # 调用  year = 年份  image_id = 对应的文件名_id
        convert_annotation(image_id)
    # 关闭文件
    list_file.close()

下面就能愉快的训练啦!!!

本文由博客一文多发平台 OpenWrite 发布!