常用目标检测的格式转换脚本文件txt,json等
文章目录
前言
⭐️ ⭐️ ⭐️ 还在完善中
⭐️ ⭐️ ⭐️
本节主要介绍在目标检测领域内,常用的格式转换脚本
一、json格式转yolo的txt格式
json格式的目标检测数据集标签格式转yolo目标检测的标签txt的格式
代码如下(示例): 主要修改 classes, json_folder_path, output_dir
"""
目标检测的 json --> 转为 yolo的txt
"""
import json
import os
def convert(size, box):
dw = 1. / size[0]
dh = 1. / 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_path, output_dir, classes):
with open(json_path, 'r', encoding='utf-8') as f:
data = json.load(f)
base_name = os.path.splitext(os.path.basename(data['imagePath']))[0]
txt_path = os.path.join(output_dir, base_name + '.txt')
with open(txt_path, 'w', encoding='utf-8') as txt_file:
for shape in data['shapes']:
if shape['shape_type'] == 'rectangle':
label = shape['label']
if label not in classes:
continue
cls_id = classes.index(label)
points = shape['points']
x1, y1 = points[0]
x2, y2 = points[1] # Assuming the points are diagonal
bb = convert((data['imageWidth'], data['imageHeight']), [x1, y1, x2, y2])
txt_file.write(f"{
cls_id} {
' '.join(map(str, bb))}\n")
if __name__ == "__main__":
# 指定YOLO类别
classes = ['loose', 'un-loose'] # 根据实际类别名称进行修改
# JSON格式的标签文件路径
json_folder_path = './json' # 替换为实际的JSON文件夹路径