训练自己的Mask-RCNN实例分割模型

首先,要进行本文试验,需具备GPU,CPU上只能看看效果,没法进行实测

图像深度学习技术的四大方向

图像深度学习算法主要而已分为4大类:1)图像识别,实现图像中单一目标的类别识别;2)目标检测:实现图像中多个目标,且目标间可能存在粘连和堆叠的情况,对图片中的所有目标范围进行定位,同时对获得的目标进行识别;3)语义分割:pixel-wise的图像识别模型,输入图像和输出标签图逐像素对应,获得原图中所有像素的类别,可以根据识别结果获得目标的轮廓,形状和类别;4)实例分割,将目标检测和语义分割进行组合,简单来说,就是先进行目标检测获得各类别的区域,在对对应区域进行语义分割。相对于语义分割的优势在于:可以对同类目标的堆叠进行分割和识别。作者将详细记录如何进行该四类模型在自己所用数据集上的训练和测试。识别,目标检测和语义分割网上已经有一些可行的教程,后续会整理一下与大家分享,本文主要记录如何训练自己的实例分割模型。

1.Mask-RCNN模型测试

https://github.com/matterport/Mask_RCNN

PS:原文中有教程,但是实测中发现,对于自己的数据还是比较不友好的,需要一定的修改,英语水平还行,又比较有耐心的可以自行尝试从该文章中进行自己的数据训练测试。

下载后的模型结构大概是这样的,有能力的尽量阅读一下README.md,里面讲了模型的一些工作原理,也介绍了该模型的用法

1)安装requiremets.txt中的要求进行需求包的安装,直接运行setup.py,可能会有一些毛病。不行的话就自己一个个装把,不费事。需求包如下,需要注意的是imgaug安装可能会失败,没找到好的解决办法,反正就一直装,运气好两三遍就可以装好了(装过两台电脑,一台2次就装好了,一台装了大概半个小时,忘了几次了),可以参考https://github.com/aleju/imgaug (建议pip和conda都试试).PS:除了文件中要求的需求包外,还需要安装pycocotools

2)先跑跑已有的模型,看看效果

在release的Mask-rcnn2.0版本中,下载预训练的coco模型权重(mask_rcnn_coco.h5)https://github.com/matterport/Mask_RCNN/releases

将mask_rcnn_coco.h5放到工程的根目录下,运行samples文件夹红的demo.ipynb,获得测试结果图如下,是不是很期待在自己的数据上跑是什么效果了

2.准备自己的数据

使用VIA进行标注,不需要下载软件,直接在网页上运行http://www.robots.ox.ac.uk/~vgg/software/via/via.html

1.在Region Attributes 中新建一个类别信息,根据自己的需要进行设置

2.加载图片,进行标注,本文仅演示一下流程,就标注了3张图片

全部图片标注完成后,输出成.json格式

3.在根目录中简历一个datasets文件夹,结构如下图所示,将数据和标签json文件放到同一个文间架中(懒得标注,val中的数据是train中复制黏贴过去的)

3.训练自己的数据

1)在samples文件夹下新建如下几个文件(README.md可以不要,3个文件代码贴在下面,建议详细看看注释,根据自己的数据需要修改的部分也都注释出来了)

cdw.py(有几个参数需要根据数据进行修改,在代码中用中文注释出来了,详细看下英文注释有利于代码的理解)

"""
Mask R-CNN
Train on your dataset (CDW is my research Construction and Demolition Waste).

Revised according to the work:
Copyright (c) 2018 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla

------------------------------------------------------------

Usage: import the module (see Jupyter notebooks for examples), or run from
       the command line as such:

    # Train a new model starting from pre-trained COCO weights
    python3 cdw.py train --dataset=/path/to/cdw/dataset --weights=coco

    # Resume training a model that you had trained earlier
    python3 cdw.py train --dataset=/path/to/cdw/dataset --weights=last

    # Train a new model starting from ImageNet weights
    python3 cdw.py train --dataset=/path/to/cdw/dataset --weights=imagenet

"""

import os
import sys
import json
import datetime
import numpy as np
import skimage.draw

# Root directory of the project
ROOT_DIR = os.path.abspath("../../")

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn.config import Config
from mrcnn import model as modellib, utils

# Path to trained weights file
COCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")

# Directory to save logs and model checkpoints, if not provided
# through the command line argument --logs
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")

############################################################
#  Configurations
############################################################


class CDWConfig(Config):
    """Configuration for training on the toy  dataset.
    Derives from the base Config class and overrides some values.
    """
    # Give the configuration a recognizable name
    NAME = "cdw" #建议将名字改成自己数据集的简称,注意上下信息要对应

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Number of classes (including background)
    NUM_CLASSES = 1 + 4  # 模型识别的类别数=Background + wood, brick, concrete and rubber

    # Number of training steps per epoch
    STEPS_PER_EPOCH = 100

    # Skip detections with < 50% confidence
    DETECTION_MIN_CONFIDENCE = 0.5


############################################################
#  Dataset
############################################################

class CDWDataset(utils.Dataset):

    def load_cdw(self, dataset_dir, subset):
        """Load a subset of the CDW dataset.
        dataset_dir: Root directory of the dataset.
        subset: Subset to load: train or val
        """
        # Add classes. We have only one class to add.
        #添加类别名称,这里的“cdw”要和上面设的名字一样
        self.add_class("cdw", 1, "wood")
        self.add_class("cdw", 2, "brick")
        self.add_class("cdw", 3, "concrete")
        self.add_class("cdw", 4, "rubber")

        # Train or validation dataset?
        assert subset in ["train", "val"]
        dataset_dir = os.path.join(dataset_dir, subset)

        # Load annotations
        # VGG Image Annotator (up to version 1.6) saves each image in the form:
        # { 'filename': '28503151_5b5b7ec140_b.jpg',
        #   'regions': {
        #       '0': {
        #           'region_attributes': {'class':class_name},
        #           'shape_attributes': {
        #               'all_points_x': [...],
        #               'all_points_y': [...],
        #               'name': 'polygon'}},
        #       ... more regions ...
        #   },
        #   'size': 100202
        # }
        # We mostly care about the x and y coordinates of each region
        # Note: In VIA 2.0, regions was changed from a dict to a list.
        annotations = json.load(open(os.path.join(dataset_dir, "via_export_json.json")))
        annotations = list(annotations.values())  # don't need the dict keys

        # The VIA tool saves images in the JSON even if they don't have any
        # annotations. Skip unannotated images.
        annotations = [a for a in annotations if a['regions']]

        # Add images
        for a in annotations:
            # Get the x, y coordinaets of points of the polygons that make up
            # the outline of each object instance. These are stores in the
            # shape_attributes (see json format above)
            # The if condition is needed to support VIA versions 1.x and 2.x.
            if type(a['regions']) is dict:
                polygons = [r['shape_attributes'] for r in a['regions'].values()]
            else:
                polygons = [r['shape_attributes'] for r in a['regions']] 

            # load_mask() needs the image size to convert polygons to masks.
            # Unfortunately, VIA doesn't include it in JSON, so we must read
            # the image. This is only managable since the dataset is tiny.
            image_path = os.path.join(dataset_dir, a['filename'])
            image = skimage.io.imread(image_path)
            height, width = image.shape[:2]
            region_attribute=[r['region_attributes'] for r in a['regions']]
            #print(region_attribute)
            class_name = [a['class'] for a in region_attribute if a is not None]
            #print(class_name)
            self.add_image(
                "cdw",
                image_id=a['filename'],  # use file name as a unique image id
                path=image_path,
                width=width, height=height,
                polygons=polygons,
                cdw=class_name)

    def load_mask(self, image_id):
        """Generate instance masks for an image.
       Returns:
        masks: A bool array of shape [height, width, instance count] with
            one mask per instance.
        class_ids: a 1D array of class IDs of the instance masks.
        """
        # If not a cdw dataset image, delegate to parent class.
        image_info = self.image_info[image_id]
        if image_info["source"] != "cdw":
            return super(self.__class__, self).load_mask(image_id)

        # Convert polygons to a bitmap mask of shape
        # [height, width, instance_count]
        info = self.image_info[image_id]
        #print('image info',info)
        cdws = info['cdw']
        #print('cdws',cdws)
        mask = np.zeros([info["height"], info["width"], len(info["polygons"])],
                        dtype=np.uint8)
        for i, p in enumerate(info["polygons"]):
            # Get indexes of pixels inside the polygon and set them to 1
            rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])
            mask[rr, cc, i] = 1

        # Return mask, and array of class IDs of each instance.
        class_ids = np.array([self.class_names.index(s) for s in cdws])
        return mask,class_ids.astype(np.int32)

    def image_reference(self, image_id):
        """Return the path of the image."""
        info = self.image_info[image_id]
        if info["source"] == "cdw":
            return info["path"]
        else:
            super(self.__class__, self).image_reference(image_id)


def train(model):
    """Train the model."""
    # Training dataset.
    dataset_train = CDWDataset()
    dataset_train.load_cdw(args.dataset, "train")
    dataset_train.prepare()

    # Validation dataset
    dataset_val = CDWDataset()
    dataset_val.load_cdw(args.dataset, "val")
    dataset_val.prepare()

    # *** This training schedule is an example. Update to your needs ***
    # Since we're using a very small dataset, and starting from
    # COCO trained weights, we don't need to train too long. Also,
    # no need to train all layers, just the heads should do it.
    print("Training network heads")
    model.train(dataset_train, dataset_val,
                learning_rate=config.LEARNING_RATE,
                epochs=30,
                layers='heads')

############################################################
#  Training
############################################################

if __name__ == '__main__':
    import argparse

    # Parse command line arguments
    parser = argparse.ArgumentParser(
        description='Train Mask R-CNN to detect balloons.')
    parser.add_argument("command",
                        metavar="<command>",
                        help="train")
    parser.add_argument('--dataset', required=False,
                        metavar="/path/to/cdw/dataset/",
                        help='Directory of the CDW dataset')
    parser.add_argument('--weights', required=True,
                        metavar="/path/to/weights.h5",
                        help="Path to weights .h5 file or 'coco'")
    parser.add_argument('--logs', required=False,
                        default=DEFAULT_LOGS_DIR,
                        metavar="/path/to/logs/",
                        help='Logs and checkpoints directory (default=logs/)')
    parser.add_argument('--image', required=False,
                        metavar="path or URL to image",
                        help='Image to apply the color splash effect on')
    parser.add_argument('--video', required=False,
                        metavar="path or URL to video",
                        help='Video to apply the color splash effect on')
    args = parser.parse_args()

    # Validate arguments
    if args.command == "train":
        assert args.dataset, "Argument --dataset is required for training"
    elif args.command == "splash":
        assert args.image or args.video,\
               "Provide --image or --video to apply color splash"

    print("Weights: ", args.weights)
    print("Dataset: ", args.dataset)
    print("Logs: ", args.logs)

    # Configurations
    if args.command == "train":
        config = CDWConfig()
    else:
        class InferenceConfig(CDWConfig):
            # Set batch size to 1 since we'll be running inference on
            # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
            GPU_COUNT = 1
            IMAGES_PER_GPU = 1
        config = InferenceConfig()
    config.display()

    # Create model
    if args.command == "train":
        model = modellib.MaskRCNN(mode="training", config=config,
                                  model_dir=args.logs)
    else:
        model = modellib.MaskRCNN(mode="inference", config=config,
                                  model_dir=args.logs)

    # Select weights file to load
    if args.weights.lower() == "coco":
        weights_path = COCO_WEIGHTS_PATH
        # Download weights file
        if not os.path.exists(weights_path):
            utils.download_trained_weights(weights_path)
    elif args.weights.lower() == "last":
        # Find last trained weights
        weights_path = model.find_last()
    elif args.weights.lower() == "imagenet":
        # Start from ImageNet trained weights
        weights_path = model.get_imagenet_weights()
    else:
        weights_path = args.weights

    # Load weights
    print("Loading weights ", weights_path)
    if args.weights.lower() == "coco":
        # Exclude the last layers because they require a matching
        # number of classes
        model.load_weights(weights_path, by_name=True, exclude=[
            "mrcnn_class_logits", "mrcnn_bbox_fc",
            "mrcnn_bbox", "mrcnn_mask"])
    else:
        model.load_weights(weights_path, by_name=True)

    # Train or evaluate
    if args.command == "train":
        train(model)

    else:
        print("'{}' is not recognized. "
              "Use 'train' or 'splash'".format(args.command))

inspect_cdw_data.ipynb(此模块可以看到数据加载及预处理的过程,训练之前可以先看看数据处理是否正确)

insepect_cdw_model.ipynb(查看训练好的模型效果)

这两个文件代码太长啦,主要是验证py文件中的代码正确性,不影响最终测试,就不贴了,一定要看看自己的数据处理是否正确的话可以留个邮箱我发给你

inspect_cdw_data.ipynb部分处理结果如下:

1.加载Mask图像,同一类别中的不同目标需要加以区分

2.加载到原图中,检测目标和类别是否对应,同时根据Mask轮廓尝试BoundingBox

3.生成的一系列Anchors(在训练中需要一些如右图的反例来进行惩罚)

insepect_cdw_model.ipynb部分很多处理效果和上面数据处理是相似的,只是把它加载到模型中而已,代码中也有详细的注释啦

除了上述数据加载之外,后续网络处理的效果如下所示:

1.区域提取结果

2.对提取的所有区域进行识别,忽略结果为背景和置信度低于阈值的区域

3.特征提取网络输出的部分特征图

4.测试训练结果

demo_cdw.ipynb(放在samples目录下即可,放其他地方的话也可以,但是有些地方自己要改一下哦,主要几个路径改成自己实际用的就行啦)

#%% md

# Mask R-CNN Demo

A quick intro to using the pre-trained model to detect and segment objects.

#%%

import os
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt

# Root directory of the project
ROOT_DIR = os.path.abspath("../")

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn import utils
import mrcnn.model as modellib
from mrcnn import visualize

sys.path.append(os.path.join(ROOT_DIR, "samples/cdw/"))  # To find local version

from samples.cdw import cdw
%matplotlib inline 

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")

# Local path to trained weights file
CDW_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_cdw.h5")

# Directory of images to run detection on
IMAGE_DIR = os.path.join(ROOT_DIR, "datasets/cdw/test")

#%% md

## Configurations

We'll be using a model trained on the MS-COCO dataset. The configurations of this model are in the ```CocoConfig``` class in ```coco.py```.

For inferencing, modify the configurations a bit to fit the task. To do so, sub-class the ```CocoConfig``` class and override the attributes you need to change.

#%%

class InferenceConfig(cdw.CDWConfig):
    # Set batch size to 1 since we'll be running inference on
    # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

config = InferenceConfig()
config.display()

#%% md

## Create Model and Load Trained Weights

#%%

# Create model object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

# Load weights trained on MS-COCO
model.load_weights(CDW_MODEL_PATH, by_name=True)


#%%


class_names = ['BG','wood','brick','concrete','rubber']

#%% md

## Run Object Detection

#%%

# Load a random image from the images folder
file_names = next(os.walk(IMAGE_DIR))[2]
image = skimage.io.imread(os.path.join(IMAGE_DIR, random.choice(file_names)))

# Run detection
import time
t1=time.clock()
results = model.detect([image], verbose=1)
print("time:",time.clock()-t1)
# Visualize results
r = results[0]
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], 
                            class_names, r['scores'])

#%


#%%

在未知图片中的测试,可以看出来效果一般哈,比较只用了3张图片做训练啊,功能还是实现了的,测试一张图片360ms,在GPU上哦,笔记本CPU上要30多秒,所以没有GPU的可以看看效果,想要训练的话,请慎重。

主要参考

https://github.com/matterport/Mask_RCNN

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值