MaskRCNN训练自己的数据集 小白篇

本文旨在帮助对代码无从下手的小白训练自己数据集,分享一些自己遇到的坑&解决方案,以及一些方便大家制作数据集的代码。
附成品代码:download.csdn.net/download/weixin_43758528/11965024

参考博客见下文链接。

博主电脑配置:win10 + GTX1050Ti + cuda9.0 + cudnn7 + tensorflow-gpu1.5.0(配置见下文链接)
博主使用jupyter notebook对直接对源码进行更改,方便大家修改代码。

预先准备

maskrcnn配置教程:https://blog.csdn.net/chenmoran0928/article/details/79999073
注:win10若遇到cuda9安装不上的情况(显示NVIDIA驱动程序与此Windows版本不兼容),请将win10版本升级至1803及以上,并在NVIDIA官网https://www.geforce.cn/drivers安装自己显卡对应的最新驱动。

mask rcnn训练自己的数据集:https://blog.csdn.net/qq_29462849/article/details/81037343
注:该博客有些地方一带而过,像博主一样的小白可能会有诸多疑问。接下来我列举一些我曾经遇到的问题。

正文

数据集制作

labelme制作数据集方法:https://blog.csdn.net/u012746060/article/details/81871733
注:当你成功生成 .json 文件后想进行转换,可能会发现上文给出的转换代码不能使用(报错显示没有labelme_json_to_dataset.exe文件)。如果你遇到了这个问题,可以试试如下代码:

import os
path = 'D:/label'  # path为json文件存放的路径
json_file = os.listdir(path)
os.system("activate labelme")
for file in json_file: 
    os.system("labelme_json_to_dataset.exe %s"%(path + '/' + file))

博主用以上代码成功实现了转换。

数据集格式:
在这里插入图片描述
json文件夹下存放labelme生成的json文件
pic文件夹下存放原图
labelme_json文件夹下存放json文件转换生成的文件夹
cv2_mask文件夹下存放mask文件

何为mask文件? 打开json转换而来的文件夹,里面的label.png文件即为mask文件。
新版labelme能看到标注的mask(类似下图的红色区域),则此文件可直接使用(反之若图片全黑,则必须利用代码对图片进行修改)。
在这里插入图片描述
mask文件需要重命名为原图的名字,如test.jpg/png对应的mask文件需要修改为test.png。
人工操作比较复杂,此处给出博主使用的代码(需要先完成除cv2_mask外所有步骤):

#! /usr/bin/env python
# coding=utf-8
import os
import shutil
import time
import sys
import importlib
importlib.reload(sys)


def copy_and_rename(fpath_input, fpath_output):
    for file in os.listdir(fpath_input):
        for inner in os.listdir(fpath_input+file+'/'):
            print(inner)
            if os.path.splitext(inner)[0] == "label":
                former = os.path.join(fpath_input, file)
                oldname = os.path.join(former, inner)
                print(oldname)
                newname_1 = os.path.join(fpath_output,
                                         file.split('_')[0] + ".png")
                #os.rename(oldname, newname)
                shutil.copyfile(oldname, newname_1)


if __name__ == '__main__':
    print('start ...')
    t1 = time.time() * 1000
    #time.sleep(1) #1s
    fpath_input = ".../train_data/labelme_json/" #...为train_data文件夹地址,按自己的地址修改
    fpath_output = ".../train_data/cv2_mask/"
    copy_and_rename(fpath_input, fpath_output)
    t2 = time.time() * 1000
    print('take time:' + str(t2 - t1) + 'ms')
    print('end.')

运行后即可得到对应的文件。
(若报错split(’_’)[0],则先删掉split命令运行一次,再恢复原代码运行一次,就不报错了。玄学)

代码修改

博主使用sample中的train_shapes.ipynb文件进行修改。(参考https://blog.csdn.net/l297969586/article/details/79140840/)

1、修改ROOT_DIR
在这里插入图片描述
修改为MaskRCNN根目录(以防更改后的train_shapes.ipynb被移动到其他地址)

补充: from PIL import Image

2、修改配置
在这里插入图片描述
将NUM_CLASSES修改为1+N(背景+标签数)。如你的数据集中标注了2物体,则N=2 。
修改IMAGE_MIN_DIM为你的数据集图片中最小维度
修改IMAGE_MAX_DIM为最大维度

3、修改训练代码:参考https://blog.csdn.net/l297969586/article/details/79140840/
(1)删除dataset中前两个模块的所有代码(仅保留Load and display random samples)
(2)将参考文章中”△4、重新写一个训练类 “内所有代码复制下来
(3)根据自己标签的名称和数量,修改函数load_shapes中的 Add_classes
(4)将函数load_shapes中,图中所示内容替换为以下代码
在这里插入图片描述

			filestr = imglist[i].split(".")[0]
            mask_path = mask_floder + "/" + filestr + ".png"
            yaml_path=dataset_root_path+"/labelme_json/"+filestr+"_json/info.yaml"

(5)根据自己标签的名称和数量,修改函数load_mask中 if labels[i].find("…")!=-1: labels_form.append("…")

4、代码主体修改:参考文章同上
(1)将参考文章中”4、代码主体修改“内所有代码复制下来
(2)将各folder地址改为对应地址(如dataset_root_path 改为 dataset_root_path = os.path.join(ROOT_DIR, “train_data”)),同理更改img_folder和mask_folder
(3)修改width和height为自己图片的宽和高
(4)修改函数load_shapes中的宽和高与上一步一致
在这里插入图片描述
5、开始测试代码吧!

常见报错

1、class_ids = class_ids[_idx] IndexError: boolean index did not match indexed array along dimension 0; dimension is 0 but corresponding boolean dimension is 128
出现类似此错误的原因有很多,所以请依次检查以下内容:
(1)mask文件是否正确。
(2)配置中NUM_CLASSES是否修改。
(3)上文“代码修改”第三条中(3)(5)是否正确修改。

2、缺少pillow
安装PIL即可

3、找不到指定模块…xx/Shapely
pip install shapely

参考文章:
[1]: https://blog.csdn.net/chenmoran0928/article/details/79999073
[2]: https://blog.csdn.net/qq_29462849/article/details/81037343
[3]: https://blog.csdn.net/u012746060/article/details/81871733
[4]: https://blog.csdn.net/l297969586/article/details/79140840/
[5]: https://blog.csdn.net/u012746060/article/details/82143285

  • 7
    点赞
  • 117
    收藏
    觉得还不错? 一键收藏
  • 41
    评论
Mask R-CNN 是一种基于 Faster R-CNN 的目标检测算法,可以检测出物体的位置,还可以精确地分割出物体的 mask。下面是一个 Mask R-CNN 训练自己数据集的基本步骤: 1. 准备数据集 首先,您需要准备自己的数据集,包括图片和标注。图片可以是任何大小,但最好是统一大小,以便于训练。标注可以使用标准的 COCO 标注格式,包括标注文件和类别文件。 2. 定义类别 您需要定义自己数据集的类别,例如人、车、动物等等。您可以创建一个名为 `CustomConfig` 的类,继承自 `Config` 类,并在其中设置 `NUM_CLASSES` 参数为您的类别数量加 1(因为需要加入一个背景类别): ```python class CustomConfig(Config): # Give the configuration a recognizable name NAME = "custom_dataset" # Train on 1 GPU and 1 image per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # Number of classes (including background) NUM_CLASSES = 1 + 4 # Background + 4 classes ``` 3. 定义数据集加载器 您需要定义一个数据集加载器,将准备好的数据集导入到模型中。您可以创建一个名为 `CustomDataset` 的类,继承自 `utils.Dataset` 类,并在其中实现 `load_dataset()`、`load_image()`、`load_mask()`、`image_reference()` 等方法,具体实现可以参考 Mask R-CNN 官方代码。 ```python class CustomDataset(utils.Dataset): def load_dataset(self, dataset_dir, subset): self.add_class("custom_dataset", 1, "class1") self.add_class("custom_dataset", 2, "class2") self.add_class("custom_dataset", 3, "class3") self.add_class("custom_dataset", 4, "class4") # Load annotations annotations = json.load(open(os.path.join(dataset_dir, "annotations.json"))) annotations = annotations["annotations"] # Add images and annotations to dataset for a in annotations: image_id = a["image_id"] image_path = os.path.join(dataset_dir, "images", str(image_id) + ".jpg") if not os.path.exists(image_path): continue if a["iscrowd"]: continue if a["category_id"] not in [1, 2, 3, 4]: continue self.add_image( "custom_dataset", image_id=image_id, path=image_path, width=a["width"], height=a["height"], annotations=a["bbox"] ) def load_mask(self, image_id): # Load annotations for image annotations = self.image_info[image_id]["annotations"] # Create one mask per instance masks = np.zeros([self.image_info[image_id]["height"], self.image_info[image_id]["width"], len(annotations)], dtype=np.uint8) # Load masks for i, a in enumerate(annotations): x1, y1, w, h = a x2 = x1 + w y2 = y1 + h masks[y1:y2, x1:x2, i] = 1 # Return masks and class IDs return masks, np.ones([len(annotations)], dtype=np.int32) def image_reference(self, image_id): info = self.image_info[image_id] return info["path"] ``` 4. 训练模型 在训练之前,您需要将预训练 COCO 权重加载到模型中: ```python model.load_weights(COCO_MODEL_PATH, by_name=True, exclude=["mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask"]) ``` 然后,您可以使用 `train()` 方法训练模型。在训练之前,您需要创建一个名为 `CustomConfig` 的配置对象,并设置好超参数和文件路径: ```python config = CustomConfig() config.display() model = modellib.MaskRCNN(mode="training", config=config, model_dir=MODEL_DIR) # Train the head branches model.train(dataset_train, dataset_val, learning_rate=config.LEARNING_RATE, epochs=30, layers='heads') ``` 5. 测试模型 在测试模型之前,您需要将模型切换到 inference 模式: ```python model = modellib.MaskRCNN(mode="inference", config=config, model_dir=MODEL_DIR) ``` 然后,您可以使用 `detect()` 方法对图片进行检测和分割: ```python results = model.detect([image], verbose=1) r = results[0] visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores']) ``` 以上就是使用 Mask R-CNN 训练自己数据集的基本步骤。具体实现可以参考 Mask R-CNN 官方代码。
评论 41
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值