json转为yolo txt python代码
时间: 2023-07-05 08:11:01 浏览: 107
下面是将JSON转换为YOLO txt的Python代码:
```python
import json
import os
# json文件路径
json_file = 'path/to/your/json/file.json'
# 类别名
classes = ["class1", "class2", "class3"]
# yolo txt文件路径
txt_file = 'path/to/your/yolo/txt/file.txt'
# 图像路径
img_dir = 'path/to/your/image/directory'
# 读取json文件
with open(json_file, 'r') as f:
data = json.load(f)
# 解析json数据并写入yolo txt文件
with open(txt_file, 'w') as f:
for img in data:
img_filename = img['filename']
img_width = img['width']
img_height = img['height']
for obj in img['objects']:
class_name = obj['classTitle']
if class_name not in classes:
continue
class_id = classes.index(class_name)
x, y, w, h = obj['points']['exterior'][0] + obj['points']['exterior'][1]
x = x / img_width
y = y / img_height
w = w / img_width
h = h / img_height
line = str(class_id) + ' ' + str(x) + ' ' + str(y) + ' ' + str(w) + ' ' + str(h) + '\n'
f.write(os.path.join(img_dir, img_filename) + ' ' + line)
print('Convert Done!')
```
其中,需要将`path/to/your/json/file.json`、`path/to/your/yolo/txt/file.txt`和`path/to/your/image/directory`替换为实际的路径。在`classes`列表中,需要按照实际需要定义类别名。运行代码后,会在指定的路径下生成YOLO txt文件。
阅读全文