Tensorflow2.0---DeepLab v3+分割网络原理及代码解析(二)

Tensorflow2.0—DeepLab v3+分割网络原理及代码解析(二)-数据生成

这篇blog主要介绍下数据的生成~

一、原始图片的标注

首先,第一步就是要收集你训练的图片,这个毋庸置疑哈,然后用labelme去标注。这里选择labelme而不是选择labelimg标注工具的原因是labelme支持分割网络的标注。标注之后,应该是这样的~
在这里插入图片描述
一张图片对应一个标注好的json文件~~~~

二、转换png格式标注文件

然后,将图片和标注文件一起放到datasets/before里面,然后运行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

if __name__ == '__main__':
    jpgs_path = "datasets/JPEGImages" #保存原图
    pngs_path = "datasets/SegmentationClass" #保存转换后的png标注图片
    classes = ["_background_", "dog"] # _background_ 不能丢

    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, encoding='utf-8'))

            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')

其中,有两个函数值得注意一点(都是labelme库中的)

def img_b64_to_arr(img_b64):
    f = io.BytesIO()
    f.write(base64.b64decode(img_b64))
    img_arr = np.array(PIL.Image.open(f))
    return img_arr

该函数将json文件中"iamgeData"字段的字符转换为原始图像

def shapes_to_label(img_shape, shapes, label_name_to_value, type='class'):
    assert type in ['class', 'instance']

    cls = np.zeros(img_shape[:2], dtype=np.int32)
    if type == 'instance':
        ins = np.zeros(img_shape[:2], dtype=np.int32)
        instance_names = ['_background_']
    for shape in shapes:
        points = shape['points']
        label = shape['label']
        shape_type = shape.get('shape_type', None)
        if type == 'class':
            cls_name = label
        elif type == 'instance':
            cls_name = label.split('-')[0]
            if label not in instance_names:
                instance_names.append(label)
            ins_id = instance_names.index(label)
        cls_id = label_name_to_value[cls_name]
        mask = shape_to_mask(img_shape[:2], points, shape_type)
        cls[mask] = cls_id
        if type == 'instance':
            ins[mask] = ins_id

    if type == 'instance':
        return cls, ins
    return cls

该函数的作用是经过掩码生成png格式的标注文件
最后,会将before里面的图片和标注文件分别存放至JPEGImages和SegmentationClass中。

在这里插入图片描述
在这里插入图片描述
然后将JPEGImages的所有图片复制到VOCdevkit/VOC2007/JPEGImages中,将SegmentationClass的所有png文件复制到VOCdevkit/VOC2007/SegmentationClass中。

三、数据集切分

运行voc_annotation.py,即可完成训练集,验证集的切分,并且生成train.txt、trainval.txt、test.txt、val.txt
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Win10系统下,使用DeepLab V3进行语义分割训练自己的数据集可以通过以下步骤实现: 1. 准备数据集:首先,需要进行数据集的准备工作。收集大量的图像数据,并为每张图像标注像素级别的语义标签。确保训练图像和标签数据是一一对应的。 2. 安装依赖环境:在Win10系统下,首先需要安装Python和TensorFlow深度学习框架,并配置好相应的环境变量。确保能够成功导入相关的库和模块。 3. 下载DeepLab V3:从GitHub上下载DeepLab V3的源代码,并解压到本地目录。在命令行中切换到DeepLab V3的根目录。 4. 数据预处理:使用脚本文件对数据集进行预处理,将图像和标签数据转换成模型可接受的格式。这可以通过运行预处理脚本来完成。 5. 配置参数:在配置文件中设置相关的训练参数,如训练图像的路径、标签的路径、模型的参数等。可以根据实际需要进行调整。 6. 运行训练:在命令行中运行训练脚本,该脚本会调用DeepLab V3模型进行训练。根据配置文件中的设置,模型将使用训练数据进行迭代训练,以优化模型的性能。 7. 评估模型:训练完成后,可以运行评估脚本对训练得到的模型进行评估。该脚本将使用测试数据进行预测,并计算出预测结果的准确性。 8. 使用模型:训练完成后,可以使用已训练好的模型对新的图像进行语义分割。通过在命令行中运行预测脚本,将输入图像作为参数进行预测,即可得到相应的语义分割结果。 以上是在Win10系统下使用DeepLab V3进行语义分割训练自己的数据集的基本步骤。根据具体情况和需求,可能还需要进行一些额外的调整和改进。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

进我的收藏吃灰吧~~

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

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

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

打赏作者

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

抵扣说明:

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

余额充值