MASK-RCNN 沿用 Faster RCNN 的思想,由于我也只用来训练做测试了,具体原理可见原文Github知乎

标注数据

环境准备

标注数据使用 labelme,在安装之前需要安装 pyqt5,使用教程可以参考labelme 详解

1
2
pip install pyqt5
pip install labelme

格式转换

labelme 保存的都是 json 文件,需要使用 label_json_to_dataset.exe 转换一下,在 labelme 安装路径下找到 label_json_to_dataset.exe,使用

1
for /r <path of json> %i in (*.json) do labelme_json_to_dataset %i

之后会生成一个同名的文件夹,里面包含了 mask 文件、label.png、info.yaml、label_viz.png、label_names.txt 五个文件(如果生成的文件缺少 info.yaml,这是由于 lableme 版本造成的,可以使用 3.20.0,也可以修改 label_json_to_dataset.exe,参考labelme:缺少生成"info.yaml" 文件

由于 labelme 生成的 label.png 是 16bit 而在 cv2 中使用的都是 8bit,所以需要转换一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def img_16to8():
from PIL import Image
import numpy as np
import shutil
import os

src_dir = r'\\labelme_json'
dest_dir = r'\\cv2_mask'
for child_dir in os.listdir(src_dir):
new_name = child_dir.split('_')[0] + '.png'
old_mask = os.path.join(os.path.join(src_dir, child_dir), 'label.png')
img = Image.open(old_mask)
img = Image.fromarray(np.uint8(np.array(img)))
new_mask = os.path.join(dest_dir, new_name)
img.save(new_mask)

训练图片的格式

由于我参考的博客是将这些训练集分为了四个文件夹,所以我也是同样的做法

1
2
3
4
├─cv2_mask       // 转换后的mask图像
├─json // labelme生成的json文件
├─labelme_json // json_to_dataset生成的文件夹
└─pic // 原始的图像数据集

训练

代码采用官方开源的仓库,环境是官方提供的 Python3.4、TensorFlow1.3,Keras2.0.8 有可能出现问题,所以推荐使用 cuda=8.0、cudnn=6.0、Python=3.5、TensorFlow-gpu=1.3.0、Keras=2.1.2,再安装仓库提供的 requirements 安装即可,并且需要python setup.py install

训练代码以及预测代码可以参考下面的博客
https://blog.csdn.net/u012746060/article/details/82143285
https://blog.csdn.net/qq_36810544/article/details/83582397
https://blog.csdn.net/Xiongchao99/article/details/79778046
https://blog.csdn.net/qq_29462849/article/details/81037343

1
2
3
4
5
6
NUM_CLASSES=1+? # background + your classes number
IMAGE_MIN_DIM = 800 # your image pixel
IMAGE_MAX_DIM = 1280 #
Add_classes in load_shapes() # the number and type of your classes
labels_form.append("type") in load_mask() # the number and type of your classes
dataset_root_path='./' # the path of dataset

需要注意的是每次修改完

结果

使用三十张训练图片,标记了六处,训练了 30 回得到的结果,貌似还不错
result.jpg