将json转换yolotxt
时间: 2025-01-10 10:12:32 浏览: 111
### 将JSON格式数据转换为YOLO格式的txt文件
为了实现这一目标,可以采用Python编写专门的脚本来解析JSON文件并将其内容按照YOLO格式的要求写入TXT文件。以下是具体方法:
对于FLIR或COCO这样的数据集,其标注信息通常存储在一个复杂的JSON结构中,包含了多个对象的信息以及每张图片对应的标签列表。因此,在处理这类数据时,需要遍历整个JSON文档,提取出每一个实例的位置坐标(边界框)、所属类别以及其他可能存在的属性。
#### 解析JSON文件
首先读取指定路径下的JSON文件,并加载成字典形式以便于后续操作。这一步骤可以通过`json.load()`函数轻松完成[^2]。
```python
import json
def load_json(json_file_path):
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
return data
```
#### 转换逻辑
接下来定义核心转换逻辑,即如何将从JSON中获取的对象信息映射到YOLO所需要的格式上。YOLO格式要求每一行表示一个物体,由五个数值组成:分类ID、中心点X坐标比例、中心点Y坐标比例、宽度比例和高度比例。这些值都是相对于整幅图像尺寸的比例值。
```python
from pathlib import Path
def convert_to_yolo_format(image_info, categories_dict, output_dir):
image_width = image_info['width']
image_height = image_info['height']
txt_filename = Path(output_dir) / (Path(image_info['file_name']).stem + '.txt')
lines = []
for annotation in image_info.get('annotations', []): # 假设每个image_info有annotations字段
category_id = str(annotation["category_id"])
bbox = annotation["bbox"]
x_center = round((bbox[0] + bbox[2]/2.) / image_width, 6)
y_center = round((bbox[1] + bbox[3]/2.) / image_height, 6)
width_ratio = round(bbox[2] / image_width, 6)
height_ratio = round(bbox[3] / image_height, 6)
line = " ".join([str(categories_dict[category_id]),
str(x_center), str(y_center),
str(width_ratio), str(height_ratio)])
lines.append(line)
if lines:
with open(txt_filename, 'w') as f:
f.write('\n'.join(lines))
```
这里假设输入参数中的`categories_dict`是一个字典,键为原始类别编号而值为目标模型训练所需的新编号;`output_dir`则是用于保存生成的`.txt`文件的目标目录。
#### 执行转换过程
最后通过循环调用上述两个辅助函数来逐一对所有记录进行处理,并最终得到符合YOLO标准的数据集。
```python
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print("Usage: python script.py <json_file> <output_directory>")
exit(-1)
json_file_path = sys.argv[1]
output_directory = sys.argv[2]
dataset = load_json(json_file_path)
images = dataset['images'] # 获取所有的图片信息
annotations = {item['id']: item for item in dataset['annotations']} # 创建annotation索引表
categories = {str(item['id']): idx for idx, item in enumerate(dataset['categories'], start=0)} # 类别映射关系
for img in images:
img_annots = [annot for annot in annotations.values() if annot['image_id'] == img['id']]
img.update({'annotations': img_annots})
convert_to_yolo_format(img, categories, output_directory)
```
此代码片段展示了完整的流程,包括命令行参数解析、加载JSON文件、创建必要的映射表以及实际执行转换的过程。
阅读全文
相关推荐
















