用labelme给YOLOv11数据标记
时间: 2025-04-03 17:05:12 浏览: 53
### 使用 Labelme 工具为 YOLOv1 准备和标记训练数据
Labelme 是一款功能强大的图像标注工具,支持多种形状的标注(矩形框、多边形等)。然而,YOLOv1 并不直接兼容 Labelme 的默认导出格式。因此,在使用 Labelme 进行标注之后,需要将其转换为目标检测模型所需的特定格式。
#### 数据集结构
在准备数据之前,需确保创建清晰的数据集目录结构。通常情况下,YOLO 需要两个主要部分:图片文件夹和对应的标签文件夹。每张图片应有一个同名 `.txt` 文件作为其标签文件[^1]。
#### 转换流程说明
由于 YOLOv1 和较新的版本如 YOLOv5 或 YOLOv8 在标签格式上基本一致,均采用标准化坐标表示目标边界框的位置与大小。以下是具体操作:
1. **安装依赖库**
安装 `labelme` 及其他必要的 Python 库用于后续脚本运行。
```bash
pip install labelme
```
2. **标注图像**
打开 Labelme GUI 界面加载待处理图片并绘制包围盒或其他几何图形描述对象位置关系。保存 JSON 文件形式记录所有元信息包括类别名称及其空间分布参数等细节。
3. **编写转换脚本**
创建一个自定义 Python 脚本来解析由 Labelme 导出的 JSON 文件,并按照 YOLO 格式重新组织成纯文本文件(.txt),其中每一行代表单个实例的信息遵循如下模式:
```
<class_id> <x_center_normalized> <y_center_normalized> <width_normalized> <height_normalized>
```
下列代码片段展示了实现这一目的方法之一:
```python
import os
import json
def convert_labelme_to_yolo(json_file, output_dir):
with open(json_file) as f:
data = json.load(f)
image_width = data['imageWidth']
image_height = data['imageHeight']
yolo_annotations = []
for shape in data['shapes']:
label = shape['label']
points = shape['points'] # [[x1,y1],[x2,y2]]
# Convert to bounding box coordinates (xmin, ymin, xmax, ymax)
xmin = min(points[0][0], points[1][0])
xmax = max(points[0][0], points[1][0])
ymin = min(points[0][1], points[1][1])
ymax = max(points[0][1], points[1][1])
# Normalize and calculate center point & width/height
x_center = ((xmax + xmin)/2) / image_width
y_center = ((ymax + ymin)/2) / image_height
width = abs(xmax - xmin) / image_width
height = abs(ymax - ymin) / image_height
class_id = get_class_id(label) # Define this function based on your classes list.
line = f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}"
yolo_annotations.append(line)
base_name = os.path.splitext(os.path.basename(json_file))[0]
txt_path = os.path.join(output_dir, f"{base_name}.txt")
with open(txt_path, 'w') as out_f:
out_f.write("\n".join(yolo_annotations))
def get_class_id(class_name):
"""Map each unique string label to an integer ID."""
return {"cat": 0, "dog": 1}[class_name.lower()] # Example mapping; adjust accordingly.
if __name__ == "__main__":
input_jsons = "/path/to/json/files"
output_txts = "/desired/output/directory"
for filename in os.listdir(input_jsons):
if filename.endswith(".json"):
full_path = os.path.join(input_jsons, filename)
convert_labelme_to_yolo(full_path, output_txts)
```
4. **验证结果**
对生成后的 .txt 文件逐一审查确认无误后再投入实际训练过程之中。
通过上述步骤即可顺利完成从 Labelme 到适合于 YOLOv1 输入需求的数据预处理工作流构建任务。
阅读全文
相关推荐


















