SAM转yolo格式
时间: 2025-03-19 13:17:21 浏览: 38
### SAM格式数据转换为YOLO格式
为了将SAM生成的标注数据转换为YOLO格式,可以按照以下方法操作:
#### 1. 理解SAM和YOLO格式的区别
SAM生成的数据通常是JSON格式[^1],其中包含了图像的边界框、分割掩码以及其他元信息。而YOLO格式是一种轻量化的文本格式,每张图片对应的标签文件是一个`.txt`文件,其内容由类别编号以及归一化后的边界框坐标组成。
YOLO格式的具体定义如下:
- 每行表示一个对象。
- 行的内容结构为:`<class_id> <x_center> <y_center> <width> <height>`。
- 坐标均经过归一化处理(相对于图像宽度和高度),范围在0到1之间。
#### 2. JSON转YOLO的核心逻辑
要完成从SAM的JSON格式到YOLO格式的转换,需执行以下几个核心步骤的操作描述:
- **解析JSON文件**:读取SAM生成的JSON文件并提取必要的字段,如图像尺寸、边界框或分割掩码等。
- **计算边界框**:如果SAM提供了分割掩码,则需要通过这些掩码计算出最小外接矩形作为边界框。
- **归一化坐标**:根据YOLO的要求,将边界框的左上角和右下角坐标转化为中心点坐标,并将其归一化至[0, 1]区间。
- **保存为TXT文件**:最后,按上述格式写入相应的`.txt`文件中。
以下是Python脚本的一个示例实现:
```python
import json
from pathlib import Path
def convert_sam_to_yolo(json_file_path, output_dir):
with open(json_file_path, 'r') as f:
data = json.load(f)
image_width = data['imageWidth']
image_height = data['imageHeight']
yolo_annotations = []
for shape in data.get('shapes', []):
label = shape['label'] # 类别名称
points = shape['points'] # 边界框顶点列表 [[x1,y1], [x2,y2]]
# 计算边界框参数
x_coords = [point[0] for point in points]
y_coords = [point[1] for point in points]
bbox_width = max(x_coords) - min(x_coords)
bbox_height = max(y_coords) - min(y_coords)
center_x = (min(x_coords) + bbox_width / 2) / image_width
center_y = (min(y_coords) + bbox_height / 2) / image_height
norm_width = bbox_width / image_width
norm_height = bbox_height / image_height
class_id = get_class_id(label) # 自定义函数获取类别的ID映射关系
yolo_line = f"{class_id} {center_x:.6f} {center_y:.6f} {norm_width:.6f} {norm_height:.6f}"
yolo_annotations.append(yolo_line)
output_txt_path = Path(output_dir) / f"{Path(json_file_path).stem}.txt"
with open(output_txt_path, 'w') as out_f:
out_f.write("\n".join(yolo_annotations))
def get_class_id(class_name):
"""自定义类别名到ID的映射"""
class_mapping = {"cat": 0, "dog": 1, "person": 2}
return class_mapping[class_name]
# 使用实例
convert_sam_to_yolo("path/to/sam_output.json", "output/yolo/")
```
此脚本假设输入的是标准LabelMe样式的JSON文件[^2],并且存在一个简单的类别字符串到整数ID的映射表。实际应用可能需要调整具体的细节来适配不同的SAM输出形式。
#### 工具推荐
除了手动编写脚本之外,还可以利用一些现有的开源工具来进行这种格式之间的转换工作。例如AnyLabeling支持多种导入导出功能,能够方便地把不同类型的标注结果互相转化。
---
阅读全文
相关推荐



















