Press "Enter" to skip to content

『深度应用』一小时教你上手训练MaskRCNN·Keras开源实战(Windows&Linux)

0. 前言介绍

 

开源地址: github.com/matterport/…

 

个人主页: www.yansongsong.cn/

 

MaskRCNN 是何凯明基于以往的 faster rcnn 架构提出的新的卷积网络,一举完成了 object instance segmentation. 该方法在有效地目标的同时完成了高质量的语义分割。 文章的主要思路就是把原有的 Faster-RCNN 进行扩展,添加一个分支使用现有的检测对目标进行并行预测。

 

此开源代码:这是在 Python 3,Keras 和 TensorFlow 上实现 Mask R-CNN 。该模型为图像中对象的每个实例生成边界框和分割蒙版。它基于特征金字塔网络(FPN)和 ResNet101 骨干网。

 

存储库包括:

Mask R-CNN 的源代码,建立在 FPN 和 ResNet101 之上。
MS COCO 的培训代码
MS COCO 的预训练重量
Jupyter 笔记本可以在每一步都可视化检测管道
ParallelModel 类用于多 GPU 培训
评估 MS COCO 指标(AP)
您自己的数据集培训示例

代码记录在案,设计易于扩展。如果您在研究中使用它,请考虑引用此存储库(下面的 bibtex)。如果您从事 3D 视觉,您可能会发现我们最近发布的 Matterport3D 数据集也很有用。该数据集是由我们的客户捕获的 3D 重建空间创建的,这些客户同意将其公开供学术使用。您可以 在此处 查看更多示例。

 

1. MaskRCNN 环境搭建

 

首先在项目源码地址下载源码到本机中: github.com/matterport/…

 

1.1 要求

 

Python 3.4,TensorFlow 1.3,Keras 2.0.8 和其他常见软件包 requirements.txt

亲测 Python 版本为 3.6 也可以,建议 3.4 及以上。
Python 安装建议使用 mini conda 安装和管理环境
TensorFlow,Keras 也建议直接使用 conda install tensorflow keras

1.2 MS COCO 要求:

 

要在 MS COCO 上进行训练或测试,还需要:

pycocotools(下面的安装说明)
MS COCO 数据集
下载 5K  迷你  和 35K  验证 – 减去迷你的  子集。最初的 快速 R-CNN 实现 中的更多细节。

如果您使用 Docker,则已验证代码可以在 此 Docker 容器上运行

 

为什幺需要安装 pycocotools,经过看源码发现,训练 coco 数据集时用到了 pycocotools 这个模块,如果不安装会报错无法正常运行。

 

1.3 安装

 

 

克隆此存储库: github.com/matterport/…

 

安装依赖项( CD 进入项目根目录,pip3 不行的话可以尝试用 pip )

pip3 install -r requirements.txt

 

在 linux 安装时,使用此方法一切正常,就是速度会有些慢,因为安装内容较多。

 

使用 Windows 安装时可能会遇到 shapely,无法安装的情况,解决方法如下:

 

conda install shapely -y

 

从存储库根目录运行安装程序

python3 setup.py install
不报错的话就安装完成了,如果报错可以根据错误提示,网络搜索解决。
python3 不行的话就用 python,还要注意一点你使用哪个python环境安装,后面运行的时候也要用此python环境运行MaskRCNN。

 

 

4.从发布页面下载预先训练的COCO权重(mask_rcnn_coco.h5)。

 

这里提供一个下载地址,可以直接下载使用: github.com/matterport/…

 

 

(可选) pycocotools 从这些回购中的一个训练或测试 MS COCO 安装。( 这里就是 1.2 MS COCO 要求,需要安装 pycocotools


Linux:
https
//github.com/waleedka/coco


Windows:
https
//github.com/philferriere/cocoapi 。您必须在路径上安装 Visual C ++ 2015 构建工具(有关其他详细信息,请参阅存储库)

经过本人安装测试,可以使用较为简单的方式来安装:

Linux 中直接使用:

pip3 install pycocotools

windows 中需要先安装 Visual C++ 2015,下载地址: go.microsoft.com/fwlink/?Lin…
然后执行:注意要和安装 MaskRCNN 同一 Python 环境

pip3 install git+https://github.com/philferriere/cocoapi.git

 

 

上述都执行完成的话,keras 版本的 MaskRCNN 就安装完成了。下面我们动手试用一下。

 

2. 使用演示

 

用安装 Mask RCNN 的 python 环境打开 jupyter notebook,命令行,或 shell 运行:

 

jupyter notebook

 

指定 jupyter notebook 默认路径,便于打开项目工程可以参考这个博客: www.cnblogs.com/awakenedy/p…

 

运行完成后,会自动打开一个网页,如果不能就手动复制一下地址打开。

 

进入下载的 MaskRCNN 的根目录,打开 samples/demo.ipynb 文件。

 

代码如下:

 

Mask R-CNN Demo

 

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

 

In [1]: 导入相关文件,设置参数,下载网络模型等:由于下载速度慢,建议直接下载 github.com/matterport/… 到根目录在运行下面代码

 

import matplotlib.pyplot as plt
ROOT_DIR = os.path.abspath("../")
sys.path.append(ROOT_DIR)  
import mrcnn.model as modellib
from mrcnn import visualize
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/"))  
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
if not os.path.exists(COCO_MODEL_PATH):
   utils.download_trained_weights(COCO_MODEL_PATH)
IMAGE_DIR = os.path.join(ROOT_DIR, "images")

 

Using TensorFlow backend.

 

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.

 

In [2]: 进行一些参数设置

 

class InferenceConfig(coco.CocoConfig):
config = InferenceConfig()

 

BACKBONE_STRIDES               [4, 8, 16, 32, 64]
BBOX_STD_DEV                   [0.1 0.1 0.2 0.2]
COMPUTE_BACKBONE_SHAPE         None
DETECTION_MAX_INSTANCES        100
DETECTION_MIN_CONFIDENCE       0.7
DETECTION_NMS_THRESHOLD        0.3
FPN_CLASSIF_FC_LAYERS_SIZE     1024
IMAGE_SHAPE                    [1024 1024    3]
LOSS_WEIGHTS                   {'rpn_class_loss': 1.0, 'rpn_bbox_loss': 1.0, 'mrcnn_class_loss': 1.0, 'mrcnn_bbox_loss': 1.0, 'mrcnn_mask_loss': 1.0}
MEAN_PIXEL                     [123.7 116.8 103.9]
POST_NMS_ROIS_INFERENCE        1000
POST_NMS_ROIS_TRAINING         2000
RPN_ANCHOR_RATIOS              [0.5, 1, 2]
RPN_ANCHOR_SCALES              (32, 64, 128, 256, 512)
RPN_BBOX_STD_DEV               [0.1 0.1 0.2 0.2]
RPN_TRAIN_ANCHORS_PER_IMAGE    256
TOP_DOWN_PYRAMID_SIZE          256

 

Create Model and Load Trained Weights

 

In [3]: 建立网络模型,载入参数

 

model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)
model.load_weights(COCO_MODEL_PATH, by_name=True)

 

WARNING:tensorflow:From c:\datas\apps\rj\miniconda3\envs\tf_gpu\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
WARNING:tensorflow:From c:\datas\apps\rj\miniconda3\envs\tf_gpu\lib\site-packages\mask_rcnn-2.1-py3.6.egg\mrcnn\model.py:772: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:

 

Class Names

 

The model classifies objects and returns class IDs, which are integer value that identify each class. Some datasets assign integer values to their classes and some don’t. For example, in the MS-COCO dataset, the’person’class is 1 and’teddy bear’ is 88. The IDs are often sequential, but not always. The COCO dataset, for example, has classes associated with class IDs 70 and 72, but not 71.

 

To improve consistency, and to support training on data from multiple sources at the same time, our Dataset class assigns it’s own sequential integer IDs to each class. For example, if you load the COCO dataset using our  Dataset class, the ‘person’ class would get class ID = 1 (just like COCO) and the ‘teddy bear’ class is 78 (different from COCO). Keep that in mind when mapping class IDs to class names.

 

To get the list of class names, you’d load the dataset and then use the class_names property like this.

 

dataset = coco.CocoDataset()
dataset.load_coco(COCO_DIR, "train")
print(dataset.class_names)

 

We don’t want to require you to download the COCO dataset just to run this demo, so we’re including the list of class names below. The index of the class name in the list represent its ID (first class is 0, second is 1, third is 2, …etc.)

 

In [4]: 配置类别名

 

class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane',
'bus', 'train', 'truck', 'boat', 'traffic light',
'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird',
'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear',
'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie',
'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
'kite', 'baseball bat', 'baseball glove', 'skateboard',
'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup',
'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',
'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed',
'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote',
'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors',
'teddy bear', 'hair drier', 'toothbrush']

 

Run Object Detection

 

In [5]: 读入照片进行识别,原文中采用从 images 文件夹随机读取的方式。我这里注释掉了前两句,采用读取自己准备的照片,这里是我的母校照片。

 

大家只需要将 image_file 改为自己准备照片地址即可。

 

# 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)))
image_file = os.path.join(IMAGE_DIR, "ahnu.jpg")
image = skimage.io.imread(image_file)
results = model.detect([image], verbose=1)
visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], 
                            class_names, r['scores'])

 

image                    shape: (768, 1024, 3)        min:    0.00000  max:  255.00000  uint8
molded_images            shape: (1, 1024, 1024, 3)    min: -123.70000  max:  151.10000  float64
image_metas              shape: (1, 93)               min:    0.00000  max: 1024.00000  float64
anchors                  shape: (1, 261888, 4)        min:   -0.35390  max:    1.29134  float32

 

 

3. 训练模型

 

我训练了 samples/shapes/train_shapes.ipynb例子,并成功调用了多GPU,如果大家遇到问题可以看我下面的解决方法。。

 

3.1 MS COCO 培训

 

我们为 MS COCO 提供预先训练的砝码,使其更容易入手。您可以使用这些权重作为起点来训练您自己在网络上的变化。培训和评估代码在 samples/coco/coco.py 。您可以在 Jupyter 笔记本中导入此模块(请参阅提供的笔记本中的示例),或者您可以直接从命令行运行它:

 

python3 samples/coco/coco.py train 
python3 samples/coco/coco.py train 
python3 samples/coco/coco.py train 
python3 samples/coco/coco.py train

 

您还可以使用以下命令运行 COCO 评估代码:

 

python3 samples/coco/coco.py evaluate --dataset=/path/to/coco/ --model=last

 

应设置培训计划,学习率和其他参数 samples/coco/coco.py

 

3.2 对您自己的数据集进行培训

 

首先阅读 关于气球颜色飞溅样本的博客文章 。它涵盖了从注释图像到培训再到在示例应用程序中使用结果的过程。

 

总之,要在您自己的数据集上训练模型,您需要扩展两个类:

 

Config 该类包含默认配置。对其进行子类化并修改您需要更改的属性。

 

Dataset 此类提供了一种使用任何数据集的一致方法。它允许您使用新数据集进行培训,而无需更改模型的代码。它还支持同时加载多个数据集,如果要检测的对象在一个数据集中并非全部可用,则此选项非常有用。

 

见例子 samples/shapes/train_shapes.ipynbsamples/coco/coco.pysamples/balloon/balloon.py ,和 samples/nucleus/nucleus.py

 

本人测试了 samples/shapes/train_shapes.ipynb,单GPU训练基本都没有问题,使用多GPU运行时可能会出现这个问题:

 

Keras object has no attribute ‘_is_graph_network’

 

解决方法:

 

降级 Keras 到 2.1.6 可以解决这个问题

 

pip install keras==2.1.6

 

加速安装

 

pip install keras==2.1.6 -i https://pypi.tuna.tsinghua.edu.cn/simple

 

3.3 与官方文件的不同之处

 

这个实现大部分都遵循 Mask RCNN 文章,但在一些情况下我们偏向于代码简单性和泛化。这些是我们意识到的一些差异。如果您遇到其他差异,请告诉我们。

 

**图像大小调整:**为了支持每批训练多个图像,我们将所有图像调整为相同大小。例如,MS COCO 上的 1024x1024px。我们保留纵横比,因此如果图像不是正方形,我们用零填充它。在论文中,调整大小使得最小边为 800px,最大边为 1000px。

 

边界框:一些数据集提供边界框,一些仅提供蒙版。为了支持对多个数据集的训练,我们选择忽略数据集附带的边界框,而是动态生成它们。我们选择封装掩码所有像素的最小盒子作为边界框。这简化了实现,并且还使得应用图像增强变得容易,否则图像增强将更难以应用于边界框,例如图像旋转。

为了验证这种方法,我们将计算出的边界框与 COCO 数据集提供的边界框进行了比较。我们发现~ 2%的边界框相差 1px 或更多,~0.05%相差 5px 或更多,仅 0.01%相差 10px 或更多。

 

**学习率:**本文使用 0.02 的学习率,但我们发现它太高,并且经常导致重量爆炸,特别是当使用小批量时。这可能与 Caffe 和 TensorFlow 如何计算梯度(总和与批次和 GPU 之间的平均值之间的差异)有关。或者,也许官方模型使用渐变剪辑来避免这个问题。我们使用渐变剪辑,但不要过于激进。我们发现较小的学习率无论如何都会更快收敛,所以我们继续这样做。

 

4. 总结

 

花了数个小时完成了这个上手教程,希望能对 MaskRCNN 感兴趣朋友提供帮助。

 

如果觉得有用的话,欢迎点赞收藏,也欢迎翻阅我之前博客。

Be First to Comment

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注