登陆注册
6359

YOLO:将json文件转换为txt文件

站长网2023-07-28 10:30:541

因为YOLO训练的时候有自己的标注格式,因此需要将labelme标注的json格式的数据转成yolo需要的txt格式。

json各部分的含义在上一篇中已经详细介绍。

今天记录的是如何将json转换成txt。

yolo需要的标注是五个值:类别 中心点x坐标 中心点y坐标 框的宽 框的高

因此我们需要将json中相应的值进行转换,并写入txt中。

1、将左上角右下角坐标注转换为中心点坐标

注:在转换时同时需要做归一化,归一化的方法是除以图片的宽或高,以得到0~1之间的值。

代码如下:

#将json的坐标转换为yolo的坐标转换后x,y为中心点坐标,w h为框的宽和高

def convert(img_size, box): # 坐标转换

dw = 1. / (img_size[0])

dh = 1. / (img_size[1])

x = (box[0] box[2]) / 2.0 * dw

y = (box[1] box[3]) / 2.0 * dh

w = (box[2] - box[0]) * dw

h = (box[3] - box[1]) *dh

return x, y, w, h #返回标准化后的值,即0-1之间的值

2、将json文件转换为txt文件,路径为json文件的路径,名字与json的文件名相同。

代码如下:

#仅对一个json文件转换成txt文件

def json2txt(json_file):

txt_name = json_file.split(".")[0] ".txt" # 生成txt文件存放的路径,放在原文档,仅将json转换为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_file, 'r', encoding='utf-8'))#打开json文件

# print(data)

# print(data["imagePath"])

image_path = json_file.split("labels")[0] "images\\" data["imagePath"]# 图片存放路径,要求图片与标签命名相同

# print(image_path)

h = data['imageHeight']#获取图片宽高

w = data['imageWidth']

# print(h, w)

for item in data['shapes']:

# print(item)

classify = classify_map[item['label']]# 此处为框的类别

# print(classify)

points = item['points']

# print(points)

x1 = min(points[0][0], points[1][0])

y1 = min(points[0][1], points[1][1])

x2 = max(points[0][0], points[1][0])

y2 = max(points[0][1], points[1][1])

box = [float(x1), float(y1), float(x2), float(y2)]

bb = (x1, y1, x2, y2)

bbox = convert((w, h), bb)

txt_file.write(str(classify) " " " ".join([str(a) for a in bbox]) '\n') # 此处将该目标类别记为“0”

3、对一个文件夹中的所有json转为txt文件。

代码如下:

#对一个文件夹中的所有json转为txt文件

def json2txts(path):

count = 0

files = os.listdir(path)

for file in files:

if file[-5:] == ".json":

json_file = path "\\" file

# print(json_file)

json2txt(json_file)

count = count 1

print("共将", count, "个json文件转成---->txt文件")

至此,即可将文件夹中所有的json文件均转为yolo训练时所需要的txt文件了。

0001
评论列表
共(0)条