labelme的json文件转txt
时间: 2025-06-28 20:05:50 浏览: 16
### 将LabelMe JSON标注文件转换为TXT格式
为了将LabelMe生成的JSON标注文件转换为适用于YOLO模型训练所需的TXT格式,可以采用Python脚本完成此操作。该过程涉及解析JSON文件中的图像尺寸以及边界框坐标,并按照特定格式写入到对应的TXT文件中。
#### 函数定义用于转换坐标系
考虑到不同工具间坐标的表示方法可能存在差异,在实际编写转换函数前先定义辅助函数`convert`来处理可能存在的负数问题并标准化坐标值[^3]:
```python
def convert(size, box):
dw = 1./size[0]
dh = 1./size[1]
x = abs((box[0] + box[2]/2) * dw)
w = abs(box[2] * dw)
y = abs((box[1] + box[3]/2) * dh)
h = abs(box[3] * dh)
return (x, y, w, h)
```
#### 主要逻辑流程说明
接下来展示一段完整的代码片段用来读取指定路径下的所有`.json`文件并将它们逐个转化为相应的`.txt`文件保存至目标目录下[^1]:
```python
import os
from labelme import utils as lblu
import numpy as np
def json_to_txt(json_path, txt_dir):
if not os.path.exists(txt_dir):
os.makedirs(txt_dir)
for filename in os.listdir(json_path):
if filename.endswith(".json"):
base_name = os.path.splitext(filename)[0]
with open(os.path.join(json_path, filename), 'r', encoding='utf-8') as f:
data = lblu.load(f.read())
img_shape = data['imageHeight'], data['imageWidth']
lines = []
for shape in data["shapes"]:
points = shape["points"]
# 计算矩形框参数
min_x = min([p[0] for p in points])
max_x = max([p[0] for p in points])
min_y = min([p[1] for p in points])
max_y = max([p[1] for p in points])
bndbox = [min_x, min_y, max_x-min_x, max_y-min_y]
bb = convert(img_shape, bndbox)
class_id = 0 # 这里假设只有一个类别
line = "{} {} {} {} {}".format(class_id, bb[0], bb[1], bb[2], bb[3])
lines.append(line)
output_file = os.path.join(txt_dir, '{}.txt'.format(base_name))
with open(output_file, 'w') as out_f:
for l in lines:
out_f.write(l + '\n')
if __name__ == '__main__':
json_directory = './jsons'
text_output_directory = './labels'
json_to_txt(json_directory, text_output_directory)
```
上述程序会遍历给定的JSON文件夹(`json_directory`)内的每一个JSON文件,提取其中的信息并通过调用之前提到过的`convert()`函数调整坐标范围后存储于新的TXT文档之中;最终这些新创建好的TXT文件会被放置在一个名为`text_output_directory`的新建子文件夹内。
阅读全文
相关推荐


















