语义分割数据集png转yolo格式数据集
时间: 2025-07-09 22:06:36 浏览: 13
要将语义分割数据集中使用的PNG图像转换为适用于YOLO的目标检测格式,需要经历几个关键步骤。这包括理解YOLO的数据格式需求、准备标签映射文件、编写脚本以解析标注数据并将其转换为YOLO兼容的格式。
### 准备工作
首先,确保你已经准备好以下内容:
- PNG格式的图像文件。
- 对应的标注文件,通常是JSON或其他形式的文件,其中包含每个对象的位置信息(边界框)和类别标签。
- 一个文本文件,列出了所有可能的类别名称,每行一个类名。
### YOLO数据格式概述
YOLO使用一种简单的文本文件来存储标注信息,每个图像对应一个`.txt`文件。这些文件中的每一行代表一个物体,并且遵循如下格式:
```
<class_id> <x_center> <y_center> <width> <height>
```
这里的所有坐标值都是相对于图像宽度和高度归一化后的数值,范围从0到1。
- `class_id`:整数类型,表示物体所属类别的索引。
- `<x_center>, <y_center>`:边界框中心点的坐标。
- `<width>, <height>`:边界框的尺寸。
### 转换过程
#### 步骤1: 解析原始标注
你需要编写或找到能够读取你的原始标注文件(例如LabelMe生成的JSON文件)的代码。对于每一个图像文件,找到对应的JSON文件并提取出所有的边界框和类别信息。
#### 步骤2: 创建类别映射
创建一个名为`classes.names`的文件,列出所有可能出现的类别名称,每行一个。这个文件用于将类别名称转换为ID。
#### 步骤3: 编写转换脚本
接下来是编写Python脚本来自动化整个转换流程。下面提供了一个基本示例,它会遍历指定目录下的所有JSON文件,并为每个图像生成相应的YOLO格式的`.txt`文件。
```python
import os
import json
from pathlib import Path
def convert_bbox_to_yolo(img_size, bbox):
# bbox is [xmin, ymin, xmax, ymax]
dw = 1. / img_size[0]
dh = 1. / img_size[1]
x = (bbox[0] + bbox[2]) / 2 * dw
y = (bbox[1] + bbox[3]) / 2 * dh
w = (bbox[2] - bbox[0]) * dw
h = (bbox[3] - bbox[1]) * dh
return (x, y, w, h)
def process_json_file(json_path, output_dir, class_mapping):
with open(json_path, 'r') as f:
data = json.load(f)
image_filename = data['imagePath']
img_w = data['imageWidth']
img_h = data['imageHeight']
yolo_annotations = []
for shape in data['shapes']:
label = shape['label']
if label not in class_mapping:
continue # 或者抛出异常,取决于你的需求
class_id = class_mapping[label]
points = shape['points']
xmin = min(p[0] for p in points)
xmax = max(p[0] for p in points)
ymin = min(p[1] for p in points)
ymax = max(p[1] for p in points)
yolo_box = convert_bbox_to_yolo((img_w, img_h), [xmin, ymin, xmax, ymax])
yolo_annotations.append([class_id, *yolo_box])
txt_file_name = Path(image_filename).stem + '.txt'
with open(os.path.join(output_dir, txt_file_name), 'w') as out_f:
for ann in yolo_annotations:
line = ' '.join(str(x) for x in ann) + '\n'
out_f.write(line)
# 假设我们已经有了一个class_mapping字典
class_mapping = {'class1': 0, 'class2': 1} # 示例映射
input_json_folder = '/path/to/json/files'
output_annotation_folder = '/path/to/output/annotations'
os.makedirs(output_annotation_folder, exist_ok=True)
for filename in os.listdir(input_json_folder):
if filename.endswith('.json'):
process_json_file(os.path.join(input_json_folder, filename), output_annotation_folder, class_mapping)
```
这段代码假设你已经有了一个完整的类别映射表。如果你还没有,那么你需要根据实际情况调整逻辑,比如自动构建映射或者处理未知类别的情况。
#### 步骤4: 验证结果
最后,检查输出目录下是否正确地生成了`.txt`文件,并且它们的内容与原图中的对象相对应。你可以通过可视化工具加载图像及其对应的YOLO标注来验证这一点。
---
阅读全文
相关推荐


















