采用Mask RCNN分割自己的数据集

本文档介绍了如何使用Mask RCNN库对个人数据集进行图像分割。首先,从GitHub下载源代码并安装依赖。然后,通过Jupyter Notebook加载预训练的coco权重。重点在于修改samples目录下的代码,尤其是BrainwebConfig和BrainwebDataset类,以适应自定义数据。在BrainwebConfig中设置环境配置,在BrainwebDataset中覆盖load_brainweb和load_mask函数。训练和测试函数也需要相应调整。训练时,根据模式选择合适的MaskRCNN实例化方式。
摘要由CSDN通过智能技术生成
  1. 下载源工程代码:https://github.com/matterport/Mask_RCNN;
  2. 解压,进入主文件夹,安装所需模块:
pip3 install -r requirements.txt;
  1. 下载Jupyter Notebook以及coco权重:mask_rcnn_coco.h5,了解Jupyter Notebook的使用方法,采用Jupyter Notebook打开文件夹samples下的balloon或者shapes子文件夹,在web界面左上角的file下面将其download为python格式的文件;

    说明: samples文件夹下面的几个示例例程基本都有三个文件:inspect_data,inspect_model,shapes,其中第一个文件是生成数据,第二个用来检测模型,可查看分步计算的结果并展示,第三个是主文件,用来训练或者预测分割;

  2. 结合shapes和balloon两个例程,在其基础上进行修改使得代码可以处理自己的数据,就是继承已有的类(mrcnn类)进行函数覆盖,使其适用于自己的data。在继承的过程中,除了sample文件夹下面的代码在改变,其他如mrcnn文件夹下面的文件都不要动。具体来说需要修改的有以下几个类:

  • 类1: class BrainwebConfig(Config), 在其下面定义自己的环境配置,例如每个GPU处理的图像数目、每步迭代的次数等;

  • 类2:class BrainwebDataset(utils.Dataset),继承原数据类,定义自己的类,该类需要覆盖的函数主要有两个:load_brainweb和load_mask。

    在load_brainweb函数中需要注意的主要有两个函数:add_class,add_image,前者添加类别,后者添加有关图像的信息,特别需要注意的是,在这一步并不需要导入所有图像的数据,只需要添加原始图像所在路径和有关图像的信息即可,原add_image中没有的参数都将被合并至self.imageinfo的一个dict下,以方便后续使用,比如mask数据的导入,具体代码如下图:

   # 添加图像
   for img_name in train_img_names:
       image_path = os.path.join(dataset_dir, img_name)
       image = skimage.io.imread(image_path)
       height, width = image.shape[:2]
       self.add_image("data", image_id = img_name,  path = image_path,width = width, height=height)

在load_mask函数中需要利用到self.image_info中的信息,所以load_brainweb和load_mask要配合使用;具体代码如下:

        # 添加图像
        # 以下是自己编写的读取mask的代码
        image_info = self.image_info[image_id]
        mask = np.zeros([image_info["height"], image_info["width"], 3], dtype=np.uint8)                        # 每个实例中只有3种mask
        image_name = image_info['id']
        
        root_path = '/home/work/Mask_RCNN/datasets/data/mask_train_val/label_0_255_'
        for r_num in range(3):
            mask_name = root_path + str(r_num+
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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 官方代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值