labelme 转yolo v7
时间: 2025-05-10 20:59:46 浏览: 19
### 将LabelMe标注的数据转换为YOLOv7可用的格式
为了将LabelMe标注的数据转换为适用于YOLOv7模型训练的格式,可以遵循以下方法。此过程涉及解析JSON文件并将其重新组织为YOLO所需的结构。
#### 数据准备
LabelMe工具生成的是基于图像像素坐标的多边形标注数据。而YOLO系列框架通常需要边界框(bounding box)形式的目标检测标签。因此,第一步是从多边形提取最小外接矩形作为目标框[^1]。
#### 转换逻辑
对于每张图片对应的JSON文件:
- 解析`shapes`字段中的坐标点集合;
- 计算这些点构成的多边形的最小包围盒(即左上角和右下角坐标);
- 归一化处理得到相对位置的比例值[x_center, y_center, width, height];
- 输出到对应`.txt`文件中,每一行代表一个对象实例及其类别编号[^2]。
以下是具体实现代码:
```python
import os
import json
from labelme import utils as lbl_utils
def shape_to_yolo(shape, img_shape):
points = shape['points']
(xmin, ymin), (xmax, ymax) = min(points)[0], max(points)[1]
dw = 1./img_shape[1]
dh = 1./img_shape[0]
x = ((xmin+xmax)/2)*dw
y = ((ymin+ymax)/2)*dh
w = abs(xmax-xmin)*dw
h = abs(ymax-ymin)*dh
return f"{shape['label']} {x:.6f} {y:.6f} {w:.6f} {h:.6f}"
input_dir = './jsons/' # 存放原始json文件夹路径
output_dir = './labels/' # 结果保存目录
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.endswith('.json'):
with open(os.path.join(input_dir,filename)) as f:
data=json.load(f)
image_height,image_width,_=lbl_utils.img_b64_to_arr(data["imageData"]).shape
out_file=os.path.splitext(filename)[0]+'.txt'
lines=[shape_to_yolo(s,(image_height,image_width)) for s in data['shapes']]
with open(os.path.join(output_dir,out_file),'w')as wf:
wf.write('\n'.join(lines))
```
上述脚本实现了从LabelMe JSON至YOLO v7所需TXT格式的自动化转换流程[^3]。
#### 注意事项
- 类别索引应依据实际项目定义调整,默认取自`shape['label']`字符串名称。
- 如果存在多个类别的情况,则需预先设定好映射关系表来替换原生标签名成为整数ID表示法。
阅读全文
相关推荐







