labelme标注图片标签为json格式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
"version": "5.2.1",
"flags": {},
"shapes": [
{
"label": "ng",
"points": [
[
663.9770114942528,
393.28735632183907
],
[
691.5632183908044,
431.2183908045977
]
],
"group_id": null,
"description": "",
"shape_type": "rectangle",
"flags": {}
}
],
"imagePath": "1.png",
"imageData": "xxxxxxxxxxxxxxxxxxxxxx"
"imageHeight": 1536,
"imageWidth": 1536
}

Yolo格式的图片标签格式为txt:

每行:class_id x_center y_center width height

1
0 0.441257 0.268394 0.017960 0.024695

LabelMe(rectangle)转 YOLO 格式脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
import json
from tqdm import tqdm

# 自定义类别列表,顺序对应 class_id(请根据你的数据修改)
CLASS_LIST = ['ng']

def convert_labelme_rect_to_yolo(json_path, output_dir):
"""
将LabelMe标注的矩形框转换为YOLO格式。

Args:
json_path (str): LabelMe标注文件的路径。
output_dir (str): 输出YOLO格式文件的目录。

Returns:
None

Raises:
FileNotFoundError: 如果指定的LabelMe标注文件不存在。
JSONDecodeError: 如果JSON文件解析失败。
KeyError: 如果JSON文件中缺少必要的键。

"""
with open(json_path, 'r') as f:
data = json.load(f)

image_width = data['imageWidth']
image_height = data['imageHeight']
image_name = os.path.splitext(data['imagePath'])[0]
yolo_lines = []

for shape in data['shapes']:
if shape['shape_type'] != 'rectangle':
continue # 跳过非矩形

label = shape['label']
if label not in CLASS_LIST:
continue # 跳过不在类别列表中的标签

class_id = CLASS_LIST.index(label)
(x1, y1), (x2, y2) = shape['points']

# 计算归一化后的中心坐标和宽高
x_center = ((x1 + x2) / 2) / image_width
y_center = ((y1 + y2) / 2) / image_height
bbox_width = abs(x2 - x1) / image_width
bbox_height = abs(y2 - y1) / image_height

yolo_line = f"{class_id} {x_center:.6f} {y_center:.6f} {bbox_width:.6f} {bbox_height:.6f}"
yolo_lines.append(yolo_line)

# 写入 .txt 文件
os.makedirs(output_dir, exist_ok=True)
output_path = os.path.join(output_dir, image_name + '.txt')
with open(output_path, 'w') as f:
f.write('\n'.join(yolo_lines))

print(f"✅ Converted: {json_path} -> {output_path}")

def convert_all_jsons(input_dir, output_dir):
"""
将指定目录下的所有JSON文件转换为YOLO格式并保存到输出目录。

Args:
input_dir (str): 输入目录路径,该目录下应包含多个JSON文件。
output_dir (str): 输出目录路径,转换后的YOLO格式文件将保存在此目录下。

Returns:
None

Raises:
FileNotFoundError: 如果输入目录不存在,则抛出此异常。
NotADirectoryError: 如果输入路径不是一个目录,则抛出此异常。
"""
os.makedirs(output_dir, exist_ok=True)
for file in tqdm(os.listdir(input_dir)):
if file.endswith('.json'):
convert_labelme_rect_to_yolo(os.path.join(input_dir, file), output_dir)

# 使用示例
if __name__ == '__main__':
input_folder = './json' # 替换为你的LabelMe JSON文件夹路径
output_folder = './label' # 输出YOLO标注文件夹
convert_all_jsons(input_folder, output_folder)

每个 JSON 会生成一个 .txt 文件,与图片同名。

所有值都已归一化到 [0, 1]