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
|
import os
import json
def convert_json_format(input_file, output_file):
"""将自定义格式的JSON转换为LabelMe格式"""
with open(input_file, 'r', encoding='utf-8') as f:
data = json.load(f)
# 检查数据格式
if isinstance(data, list) and len(data) > 0:
original_data = data[0]
else:
original_data = data
# 构建新的LabelMe格式数据
new_data = {
"imagePath": original_data.get("image", ""),
"verified": original_data.get("verified", False),
"shapes": []
}
# 转换annotations为shapes
for annotation in original_data.get("annotations", []):
label = annotation.get("label", "")
coordinates = annotation.get("coordinates", {})
if coordinates:
x = coordinates.get("x", 0)
y = coordinates.get("y", 0)
width = coordinates.get("width", 0)
height = coordinates.get("height", 0)
# 计算边界框的两个对角点
x_min = x - width / 2
y_min = y - height / 2
x_max = x + width / 2
y_max = y + height / 2
shape = {
"label": label,
"points": [
[x_min, y_min],
[x_max, y_max]
]
}
new_data["shapes"].append(shape)
# 保存转换后的数据
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(new_data, f, ensure_ascii=False, indent=2)
# 批量转换目录中的所有JSON文件
def batch_convert(input_dir, output_dir):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for filename in os.listdir(input_dir):
if filename.endswith('.json'):
input_path = os.path.join(input_dir, filename)
output_path = os.path.join(output_dir, filename)
convert_json_format(input_path, output_path)
print(f"已转换: {filename}")
# 使用示例
if __name__ == "__main__":
input_directory = r"./" # 输入目录,包含自定义格式的JSON文件
output_directory = r"./out" # 输出目录,保存转换后的LabelMe格式JSON文件
batch_convert(input_directory, output_directory)
print("所有文件转换完成!")
|