yolov5实例分割数据集制作
时间: 2025-06-28 16:13:51 浏览: 8
### 准备和标注YOLOv5实例分割数据集
#### 数据收集
为了训练YOLOv5进行实例分割,首先需要收集大量的图像样本。这些图像应该覆盖目标物体可能出现的各种场景、角度以及光照条件。高质量且多样化的数据对于提高模型性能至关重要。
#### 工具选择:LabelMe
推荐使用`LabelMe`工具来进行数据标注[^1]。该软件允许用户通过绘制多边形的方式精确地标记出每一个对象的轮廓边界,从而生成像素级别的掩膜(mask),这是实现精准实例分割的基础。
#### 创建项目结构
按照YOLOv5的要求组织文件夹:
- `images/`: 存放原始图片;
- `labels/`: 放置由LabelMe导出后的JSON格式标签文件;
#### 执行具体操作流程
##### 安装依赖库
确保安装了必要的Python包以便后续处理:
```bash
pip install labelme
```
##### 进行图像标注
启动LabelMe界面后加载待标记的照片,在界面上依次点击各个兴趣区域(ROI)创建闭合路径完成单个物品的选择工作。保存时会自动形成关联json文档描述所选形状的信息。
##### 转换为YOLO格式
由于YOLO框架不直接接受上述形式作为输入参数之一,因此还需要进一步加工转换成特定样式。可以利用官方提供的脚本辅助此环节的任务执行:
```python
import os
from pathlib import Path
from labelme.utils.shape import shape_to_mask
import numpy as np
import json
def convert_labelme_json(json_file, output_dir):
with open(json_file) as f:
data = json.load(f)
image_path = Path(data['imagePath'])
mask = np.zeros((data['imageHeight'], data['imageWidth']), dtype=np.uint8)
for shape in data["shapes"]:
points = shape["points"]
label = shape["label"]
cls_id = int(label.split('_')[-1]) # Assuming labels are like 'class_0', etc.
region = shape_to_mask(
(data['imageHeight'], data['imageWidth']),
points,
shape_type=shape.get('shape_type', None),
)
mask[region] = cls_id
out_img_path = str(Path(output_dir)/f"{image_path.stem}.png")
Image.fromarray(mask).save(out_img_path)
if __name__ == '__main__':
input_folder = './input/jsons/' # path to folder containing LabelMe JSON files
output_folder = './output/masks/' # destination directory where masks will be saved
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.endswith(".json"):
file_path = os.path.join(input_folder, filename)
try:
convert_labelme_json(file_path, output_folder)
except Exception as e:
print(f'Failed converting {filename}: ', str(e))
```
这段代码遍历指定目录下的所有`.json`文件,并将其对应的二值化遮罩图存储至另一位置供下一步骤调用[^2]。
#### 验证与优化
最后一步是对已有的资料进行全面审查,确认无误后再投入实际应用当中去。这期间可能涉及到调整某些超参设定或是补充额外样本来弥补不足之处。
阅读全文
相关推荐


















