labelme yolo 分割
时间: 2025-05-06 08:54:39 浏览: 32
### Labelme与YOLO格式数据标注及分割任务
#### 使用Labelme进行YOLO格式的数据标注
Labelme 是一款灵活的图像标注工具,支持多种形状的标注(如多边形、矩形、圆形等)。要将其标注数据转换为 YOLO 格式的标签文件,需遵循特定的格式要求。
YOLO 格式的核心在于其标签文件是以 `.txt` 文件形式存在,每行表示一个目标对象的信息。具体格式如下:
- 每个目标由五个数值组成:类别索引 `class_id`, 归一化后的中心坐标 `(x_center, y_center)` 和宽高 `(width, height)`。
- 所有值均经过归一化处理,取值范围在 `[0, 1]` 内。
以下是将 Labelme JSON 格式转换为 YOLO 格式的 Python 实现示例:
```python
import os
import json
from PIL import Image
def convert_labelme_to_yolo(json_file, output_dir):
with open(json_file) as f:
data = json.load(f)
image_path = os.path.join(os.path.dirname(json_file), data['imagePath'])
img = Image.open(image_path)
width, height = img.size
shapes = data['shapes']
class_names = {i: shape['label'] for i, shape in enumerate(set(s['label'] for s in shapes))}
txt_name = os.path.splitext(os.path.basename(json_file))[0] + '.txt'
txt_path = os.path.join(output_dir, txt_name)
with open(txt_path, 'w') as f:
for shape in shapes:
points = shape['points']
label = shape['label']
if len(points) != 2 or shape['shape_type'] != 'rectangle':
continue # 只处理矩形标注
x_min, y_min = min(points[0][0], points[1][0]), min(points[0][1], points[1][1])
x_max, y_max = max(points[0][0], points[1][0]), max(points[0][1], points[1][1])
x_center = (x_min + x_max) / 2 / width
y_center = (y_min + y_max) / 2 / height
w = abs(x_max - x_min) / width
h = abs(y_max - y_min) / height
class_id = list(class_names.keys())[list(class_names.values()).index(label)]
line = f"{class_id} {x_center:.6f} {y_center:.6f} {w:.6f} {h:.6f}\n"
f.write(line)
if __name__ == "__main__":
labelme_dataset_path = 'path_to_labelme_dataset' # 替换为实际路径
output_dir = 'output_labels'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for file in os.listdir(labelme_dataset_path):
if file.endswith('.json'):
convert_labelme_to_yolo(os.path.join(labelme_dataset_path, file), output_dir)
```
此代码片段实现了从 Labelme 的 JSON 文件到 YOLO 格式的 `.txt` 文件的转换[^2]。
---
#### 对于分割任务的支持
除了基本的目标检测外,YOLO 还可以通过扩展实现实例分割功能。例如,在 YOLOv5 中引入了 Polygon Mask 支持,而 YOLOv8 则进一步增强了对复杂掩码的支持能力。
当使用 Labelme 创建多边形标注时,可以提取顶点信息并将它们转化为适合 YOLO 分割模型使用的格式。通常情况下,分割任务中的标注会包含一系列顶点坐标列表,这些坐标同样需要被归一化至 `[0, 1]` 范围内。
下面是一个针对分割任务的简单转换逻辑:
```python
def convert_polygon_to_yolo(shape, width, height):
points = []
for point in shape["points"]:
normalized_x = point[0] / width
normalized_y = point[1] / height
points.extend([normalized_x, normalized_y])
return " ".join(map(str, points))
def save_segmentation_annotations(shapes, image_size, output_path):
width, height = image_size
lines = []
for idx, shape in enumerate(shapes):
polygon_str = convert_polygon_to_yolo(shape, width, height)
line = f"{idx} {polygon_str}"
lines.append(line)
with open(output_path, "w") as f:
f.write("\n".join(lines))
```
上述方法适用于生成基于多边形的分割标注文件[^3]。
---
#### 示例流程总结
假设有一个图片及其对应的 Labelme JSON 文件,则按照以下步骤操作即可完成转换:
1. 解析 JSON 文件获取标注信息;
2. 提取边界框或多边形顶点位置;
3. 将原始像素单位映射成相对比例;
4. 输出符合 YOLO 需求的标准文本文件。
最终得到的结果可用于训练诸如 YOLOv5 或者 YOLOv8 等深度学习框架下的目标检测或语义/实例分割模型[^4]。
---
阅读全文
相关推荐


















