手把手教你使用Labelme制作自己的语义分割数据集(附代码)

1 参考资料

参考视频:Pytorch 搭建自己的Unet语义分割平台
代码资源下载链接:unet-pytorch
在这里插入图片描述

2 数据集存放路径

我自己的项目路径:D:\demo\unet-pytorch-main
在这里插入图片描述)

  1. before 文件夹:
    这个文件夹可能是为了存放一些预处理过的图片数据。在语义分割任务中,预处理包括裁剪、缩放、去除噪音等操作,以准备图像数据用于训练或推理。

  2. JPEGImages 文件夹:
    这个文件夹通常用于存放原始图片数据。

  3. SegmentationClass 文件夹:
    这个文件夹用于存放与每个图像对应的标签或掩码图像,这些图像描述了图像中每个像素的类别或类别的分割边界。用于语义分割任务的标签图像通常使用像素级别的注释,其中每个像素都被分配了一个特定的标签值。

我们把图片放入before文件夹和JPEGImages文件中
在这里插入图片描述

3 启动Labelme

首先打开命令提示符,激活pytorch环境

activate pytorch

3.1 没装过labelme

pip intall labelme==3.16.7

在这里插入图片描述

3.2 安装过labelme

直接输入labelme即可
在这里插入图片描述

在这里插入图片描述
启动成功~

4 在Labelme打标签

在这里插入图片描述
点击save Automatically这个按钮,会在每打完一张图的标签之后自动保存。
在这里插入图片描述
点击Create Polygons,开始打标签
cltr + Z可以撤回打错了的标签
在这里插入图片描述
打完标签之后,创建类别,按ok保存。
在这里插入图片描述

在这里插入图片描述
每张小动物的标签打完之后,会产生json格式的文件。
在这里插入图片描述

5 json格式转换数据集

json_to_dataset.py 用于将 JSON(JavaScript Object Notation)格式的标注数据转换为特定的数据集格式。
通过判断标注文件中的图像数据类型,将图像数据转换为 numpy 数组。然后,根据标注文件中的形状信息和类别映射,将图像的形状转换为标签图像的形状,并将标签图像保存为 PNG 格式。
在这里插入图片描述
在这里插入图片描述
运行成功~
在这里插入图片描述

5.1 json_to_dataset.py

import base64
import json
import os
import os.path as osp

import numpy as np
import PIL.Image
from labelme import utils

'''
制作自己的语义分割数据集需要注意以下几点:
1、我使用的labelme版本是3.16.7,建议使用该版本的labelme,有些版本的labelme会发生错误,
   具体错误为:Too many dimensions: 3 > 2
   安装方式为命令行pip install labelme==3.16.7
2、此处生成的标签图是8位彩色图,与视频中看起来的数据集格式不太一样。
   虽然看起来是彩图,但事实上只有8位,此时每个像素点的值就是这个像素点所属的种类。
   所以其实和视频中VOC数据集的格式一样。因此这样制作出来的数据集是可以正常使用的。也是正常的。
'''
if __name__ == '__main__':
    jpgs_path   = "datasets/JPEGImages"
    pngs_path   = "datasets/SegmentationClass"
    #classes     = ["_background_","aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"]
    classes     = ["_background_","cat","dog"]
    
    count = os.listdir("./datasets/before/") 
    for i in range(0, len(count)):
        path = os.path.join("./datasets/before", count[i])

        if os.path.isfile(path) and path.endswith('json'):
            data = json.load(open(path))
            
            if data['imageData']:
                imageData = data['imageData']
            else:
                imagePath = os.path.join(os.path.dirname(path), data['imagePath'])
                with open(imagePath, 'rb') as f:
                    imageData = f.read()
                    imageData = base64.b64encode(imageData).decode('utf-8')

            img = utils.img_b64_to_arr(imageData)
            label_name_to_value = {'_background_': 0}
            for shape in data['shapes']:
                label_name = shape['label']
                if label_name in label_name_to_value:
                    label_value = label_name_to_value[label_name]
                else:
                    label_value = len(label_name_to_value)
                    label_name_to_value[label_name] = label_value
            
            # label_values must be dense
            label_values, label_names = [], []
            for ln, lv in sorted(label_name_to_value.items(), key=lambda x: x[1]):
                label_values.append(lv)
                label_names.append(ln)
            assert label_values == list(range(len(label_values)))
            
            lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)
            
                
            PIL.Image.fromarray(img).save(osp.join(jpgs_path, count[i].split(".")[0]+'.jpg'))

            new = np.zeros([np.shape(img)[0],np.shape(img)[1]])
            for name in label_names:
                index_json = label_names.index(name)
                index_all = classes.index(name)
                new = new + index_all*(np.array(lbl) == index_json)

            utils.lblsave(osp.join(pngs_path, count[i].split(".")[0]+'.png'), new)
            print('Saved ' + count[i].split(".")[0] + '.jpg and ' + count[i].split(".")[0] + '.png')

  • 24
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
以下是一个示例的Python代码,用于对指定类别的labelme标注的语义分割数据进行增强: ```python import os import cv2 import numpy as np def semantic_segmentation_augmentation(directory, save_directory, target_class): # 遍历指定目录下的文件 for filename in os.listdir(directory): if filename.endswith(".json"): # 查找以.json结尾的文件 json_file = os.path.join(directory, filename) image_file = json_file.replace(".json", ".jpg") # 将.json替换为.jpg if os.path.isfile(image_file): # 检查对应的图片文件是否存在 # 读取图片文件 image = cv2.imread(image_file) height, width, _ = image.shape # 读取JSON文件并获取标注信息 with open(json_file, 'r') as f: json_data = json.load(f) # 创建空白的语义分割图像 seg_image = np.zeros((height, width), dtype=np.uint8) # 处理每个标注对象 for shape in json_data['shapes']: class_name = shape['label'] if class_name == target_class: points = shape['points'] polygon_points = np.array(points, dtype=np.int32) cv2.fillPoly(seg_image, [polygon_points], 255) # 将增强后的语义分割图像保存到指定目录 save_path = os.path.join(save_directory, filename.replace(".json", ".png")) cv2.imwrite(save_path, seg_image) print(f"语义分割图像保存成功:{save_path}") else: print(f"找不到对应的图片文件:{image_file}") # 指定包含labelme标注文件的目录和保存增强后数据的目录 directory = "path/to/labelme/files" save_directory = "path/to/save/augmented/data" # 指定目标类别名称 target_class = "class_name" semantic_segmentation_augmentation(directory, save_directory, target_class) ``` 你需要将代码中的`"path/to/labelme/files"`替换为包含标注文件的实际目录路径,将`"path/to/save/augmented/data"`替换为你想要保存增强后数据的目录路径,将`"class_name"`替换为你想要增强的目标类别名称。运行代码后,它会遍历目录中的所有.json文件,读取标注信息并创建相应的语义分割图像,然后将增强后的语义分割图像保存到指定目录。 希望这可以帮到你!如果有任何问题,请随时问我。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

失舵之舟-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值