json文件格式转换yolo
时间: 2025-04-26 17:48:04 浏览: 34
### 将JSON文件转换为YOLO格式
在目标检测任务中,不同工具和框架使用的数据标注格式各异。为了使YOLO模型能够读取并利用这些标注信息进行训练或评估,需将原始的JSON格式转化为YOLO特定的格式。
#### JSON到YOLO格式转换原理
YOLO格式是一种简化的目标检测标注方式,每张图像对应一个文本文件,其中每一行代表一个物体实例的位置及其类别索引。具体来说,对于每个对象而言,其位置由中心坐标(x_center, y_center),宽度(w)以及高度(h)四个参数描述,并且这四个数值均被归一化到了0至1之间[^1]。
当处理来自`labelme`或其他工具产生的JSON文件时,主要工作在于解析该文件内的几何形状(通常是多边形或多点集合),计算边界框(bounding box),再将其按上述规则写入相应的`.txt`文件内[^2]。
#### Python代码实现
下面给出一段Python代码片段作为示范,展示如何完成这一过程:
```python
import os
import json
def convert_json_to_yolo(json_file_path, output_dir):
with open(json_file_path, 'r') as f:
data = json.load(f)
image_width = data['imageWidth']
image_height = data['imageHeight']
shapes = data.get('shapes', [])
lines = []
for shape in shapes:
label = shape['label'] # 获取标签名称
points = shape['points'] # 获取多边形顶点列表
# 计算最小外接矩形
x_coords = [point[0] for point in points]
y_coords = [point[1] for point in points]
min_x, max_x = min(x_coords), max(x_coords)
min_y, max_y = min(y_coords), max(y_coords)
center_x = (min_x + max_x) / 2.0
center_y = (min_y + max_y) / 2.0
width = abs(max_x - min_x)
height = abs(max_y - min_y)
normalized_center_x = round(center_x / image_width, 6)
normalized_center_y = round(center_y / image_height, 6)
normalized_width = round(width / image_width, 6)
normalized_height = round(height / image_height, 6)
class_id = get_class_index(label) # 假设有一个函数可以根据标签获取对应的类ID
line = " ".join([str(class_id),
str(normalized_center_x),
str(normalized_center_y),
str(normalized_width),
str(normalized_height)])
lines.append(line)
base_name = os.path.splitext(os.path.basename(json_file_path))[0]
out_txt_path = os.path.join(output_dir, "{}.txt".format(base_name))
with open(out_txt_path, 'w') as f:
f.write("\n".join(lines))
def get_class_index(label):
"""假设这里定义了一个映射关系"""
classes = ['person', 'bicycle', 'car', ... ] # 完整分类表应根据实际情况填写
try:
index = classes.index(label.lower())
except ValueError:
raise Exception("未知类别: {}".format(label))
return index
```
此段程序首先加载指定路径下的JSON文件内容;接着遍历所有标记的对象,针对每一个对象提取出必要的信息——即包围盒的位置与大小,并对其进行标准化处理以便适应YOLO的要求;最后将结果保存成新的TXT文档[^3]。
阅读全文
相关推荐
















