python实现批量json标签文件转yolo格式标签
时间: 2023-06-25 15:04:58 浏览: 234
以下是将批量json标签文件转换为yolo格式标签的python代码示例:
```python
import os
import json
def convert(json_path, img_width, img_height):
with open(json_path, 'r') as f:
data = json.load(f)
yolo_labels = []
for obj in data['annotations']:
bbox = obj['bbox']
x_center = (bbox[0] + bbox[2] / 2) / img_width
y_center = (bbox[1] + bbox[3] / 2) / img_height
width = bbox[2] / img_width
height = bbox[3] / img_height
class_id = obj['category_id']
yolo_labels.append(f"{class_id} {x_center} {y_center} {width} {height}")
return "\n".join(yolo_labels)
if __name__ == '__main__':
json_dir = 'path/to/json/dir'
yolo_dir = 'path/to/yolo/dir'
img_width = 1280
img_height = 720
if not os.path.exists(yolo_dir):
os.makedirs(yolo_dir)
for json_file in os.listdir(json_dir):
json_path = os.path.join(json_dir, json_file)
yolo_path = os.path.join(yolo_dir, os.path.splitext(json_file)[0] + '.txt')
yolo_labels = convert(json_path, img_width, img_height)
with open(yolo_path, 'w') as f:
f.write(yolo_labels)
```
上述代码将遍历指定目录下的所有json标签文件,并将其转换为yolo格式标签,最终保存在另一个目录中,文件名与原json标签文件相同,只是扩展名改为`.txt`。其中,需要指定图片的宽度和高度,以便将bbox坐标转换为yolo格式。
阅读全文