其他分享
首页 > 其他分享> > 【MaskRCNN】训练自己的数据集

【MaskRCNN】训练自己的数据集

作者:互联网

该版本为tensorflow+keras版本的https://github.com/matterport/Mask_RCNN

本代码实现了一张图片的多个人体检测及分割。

一、环境

cuda版本:9.0 https://developer.nvidia.com/cuda-90-download-archive

cudnn版本:7.1

具体是哪个版本我忘了,验证的话,可以在安装tensorflow后,在python中import tensorflow,如果报错,那就换另一个cudnn,直到成功为止。 

keras版本:2.1.6

tensorflow-gpu版本:1.10.0

labelme(标注mask数据集用的):https://github.com/wkentaro/labelme

二、修改训练代码

主要修改train_shapes.ipynb,我个人感觉ipython-notebook不好用,所以我将它转成.py格式,就是把代码粘出来。

在samples下新建一个cells文件夹,然后在文件夹中新建一个train_cell.py文件。具体代码为

import os
import sys
import random
import math
import re
import time
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
from PIL import Image
import yaml

import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"

# 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 utils
import mrcnn.model as modellib
from mrcnn import visualize
from mrcnn.model import log

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

# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
    utils.download_trained_weights(COCO_MODEL_PATH)


class CellsConfig(Config):
    """Configuration for training on the toy shapes dataset.
    Derives from the base Config class and overrides values specific
    to the toy shapes dataset.
    """
    # Give the configuration a recognizable name
    NAME = "cells"

    # Train on 1 GPU and 8 images per GPU. We can put multiple images on each
    # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
    GPU_COUNT = 1
    IMAGES_PER_GPU = 4

    # Number of classes (including background)
    NUM_CLASSES = 1 + 1  # background + 1

    # Use small images for faster training. Set the limits of the small side
    # the large side, and that determines the image shape.
    IMAGE_MIN_DIM = 512
    IMAGE_MAX_DIM = 512

    # Use smaller anchors because our image and objects are small
    RPN_ANCHOR_SCALES = (8*2, 16*2, 32*2, 64*2, 128*2)  # anchor side in pixels

    # Reduce training ROIs per image because the images are small and have
    # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
    TRAIN_ROIS_PER_IMAGE = 200

    # Use a small epoch since the data is simple
    STEPS_PER_EPOCH = 1000

    # use small validation steps since the epoch is small
    VALIDATION_STEPS = 20

config = CellsConfig()
config.display()

def get_ax(rows=1, cols=1, size=8):
    """Return a Matplotlib Axes array to be used in
    all visualizations in the notebook. Provide a
    central point to control graph sizes.

    Change the default size attribute to control the size
    of rendered images
    """
    _, ax = plt.subplots(rows, cols, figsize=(size * cols, size * rows))
    return ax

class CellsDataset(utils.Dataset):
    def load_cells(self, height, width, dataset_root_path):
        """Generate the requested number of synthetic images.
        count: number of images to generate.
        height, width: the size of the generated images.
        """
        # Add classes
        self.add_class("cells", 1, "gland")

        # Add images
        # Generate random specifications of images (i.e. color and
        # list of shapes sizes and locations). This is more compact than
        # actual images. Images are generated on the fly in load_image().
        root_image_dir = os.path.join(dataset_root_path, "image")
        # mask形式如下,如果一张图片中有5个人,分别为person1,person2,person3,
        # 那么此时mask中对应的person1的值为1,person2的值为2,person3的值为3
        # yaml对应的标签就是person1,person2,person3
        root_mask_dir = os.path.join(dataset_root_path, "mask")
        root_yaml_dir = os.path.join(dataset_root_path, "yaml")
        imglist = [filename for filename in os.listdir(root_image_dir) if filename.endswith(".png")]
        for i in range(len(imglist)):
            filestr = imglist[i].split(".")[0]
            image_path = os.path.join(root_image_dir, filestr + ".png")
            mask_path = os.path.join(root_mask_dir, filestr + ".npy")
            yaml_path = os.path.join(root_yaml_dir, filestr + ".yaml")
            self.add_image("cells", image_id=i, path=image_path,
                           width=width, height=height, mask_path=mask_path, yaml_path=yaml_path)

    # 得到该图中有多少个实例(物体)
    def get_obj_index(self, image):
        n = np.max(image)
        return n

    # 解析labelme中得到的yaml文件,从而得到mask每一层对应的实例标签
    '''
    标签形式为
    label_names:
    - gland1
    - gland2
    - gland3
    '''
    def from_yaml_get_class(self, image_id):
        info = self.image_info[image_id]
        with open(info['yaml_path']) as f:
            temp = yaml.load(f.read(), Loader=yaml.FullLoader)
            labels = temp['label_names']
        return labels

    # 重新写draw_mask
    def draw_mask(self, num_obj, mask, image, image_id):
        info = self.image_info[image_id]
        for index in range(num_obj):
            for i in range(info['width']):
                for j in range(info['height']):
                    # at_pixel = image.getpixel((i, j))
                    at_pixel = image[j, i]
                    if at_pixel == index + 1:
                        mask[j, i, index] = 1
        return mask

    def load_mask(self, image_id):
        """Generate instance masks for shapes of the given image ID.
        """
        info = self.image_info[image_id]
        count = 1  # number of object
        # img = Image.open(info['mask_path'])
        img = np.load(info['mask_path'])
        num_obj = self.get_obj_index(img)
        mask = np.zeros([info['height'], info['width'], num_obj], dtype=np.uint8)
        mask = self.draw_mask(num_obj, mask, img, image_id)

        # 这部分是为了防止标签出现重叠,所以就有了从mask的最后一层开始,
        # 前一层删除与当前层及之后所有层重叠的地方
        occlusion = np.logical_not(mask[:, :, -1]).astype(np.uint8)
        for i in range(count - 2, -1, -1):
            mask[:, :, i] = mask[:, :, i] * occlusion
            occlusion = np.logical_and(occlusion, np.logical_not(mask[:, :, i]))

        labels = self.from_yaml_get_class(image_id)
        labels_form = []
        for i in range(len(labels)):
            if labels[i].find("gland") != -1:
                labels_form.append("gland")
        class_ids = np.array([self.class_names.index(s) for s in labels_form])
        return mask, class_ids.astype(np.int32)

dataset_root_path = r"F:\maskrcnn\train"
# Training dataset
dataset_train = CellsDataset()
dataset_train.load_cells(config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1], dataset_root_path)
dataset_train.prepare()

# Validation dataset
dataset_val = CellsDataset()
dataset_val.load_cells(config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1], dataset_root_path)
dataset_val.prepare()

# Load and display random samples
# image_ids = np.random.choice(dataset_train.image_ids, 4)
# for image_id in image_ids:
#     image = dataset_train.load_image(image_id)
#     mask, class_ids = dataset_train.load_mask(image_id)
#     visualize.display_top_masks(image, mask, class_ids, dataset_train.class_names)

########################################################
###################### MASK RCNN #######################
########################################################
# Create model in training mode
model = modellib.MaskRCNN(mode="training", config=config,
                          model_dir=MODEL_DIR)

# Which weights to start with?
init_with = "coco"  # imagenet, coco, or last

if init_with == "imagenet":
    model.load_weights(model.get_imagenet_weights(), by_name=True)
elif init_with == "coco":
    # Load weights trained on MS COCO, but skip layers that
    # are different due to the different number of classes
    # See README for instructions to download the COCO weights
    model.load_weights(COCO_MODEL_PATH, by_name=True,
                       exclude=["mrcnn_class_logits", "mrcnn_bbox_fc",
                                "mrcnn_bbox", "mrcnn_mask"])
elif init_with == "last":
    # Load the last model you trained and continue training
    model.load_weights(model.find_last(), by_name=True)

# Train the head branches
# Passing layers="heads" freezes all layers except the head
# layers. You can also pass a regular expression to select
# which layers to train by name pattern.
model.train(dataset_train, dataset_val,
            learning_rate=config.LEARNING_RATE,
            epochs=30,
            layers='heads')

# Fine tune all layers
# Passing layers="all" trains all layers. You can also
# pass a regular expression to select which layers to
# train by name pattern.
model.train(dataset_train, dataset_val,
            learning_rate=config.LEARNING_RATE / 10,
            epochs=100,
            layers="all")

# Save weights
# Typically not needed because callbacks save after every epoch
# Uncomment to save manually
# model_path = os.path.join(MODEL_DIR, "mask_rcnn_shapes.h5")
# model.keras_model.save_weights(model_path)

三、制作数据

由于我的数据标签并不是使用labelme方式得到的,但是为了能使得上面的代码有效运行,将我的数据都整理成如下形式:

train文件夹下有三个子文件夹image,mask,yaml

image当中保存的是rgb三通道的图像

image1.png

image2.png

image3.png

...

mask当中保存的是npy文件,名字与image中相同,只是后缀不同

image1.npy

image2.npy

image3.npy

...

yaml中保存的是yaml文件,名字与image中相同,只是后缀不同

image1.yaml

image2.yaml

image3.yaml

...

针对image、mask和yaml的image1.png、image1.npy和image1.yaml进行具体介绍

image1.png如图所示,图像尺寸为513*604:


image1.npy保存的是mask文件,本来是要保存png的,但是我防止我一副图片超过了255个物体,那么保存为灰度图像就有点蠢,不如直接保存为npy文件。

上面这张图并不是我npy中实际保存的,仅仅是为了方便显示。npy中具体保存了两个人的实例分割标记。比如红色的person1,在标签中就是数字1,也就是红色部分全是1;绿色的person2,在标签中就是数字2,区域就是绿色部分,又规定标签是单通道的,所以npy是一个513*604的矩阵,矩阵中保存了背景0,person1对应的1,person2对应的2。


image1.yaml的具体内容如下

label_names:
- person1
- person2

记住了,这个yaml中的顺序必须与image1.npy中的数字对应起来,npy中的数字1代表什么类别,那么这个第一个就是什么类别,顺序千万不要搞错了。不然你后面的训练都是错误的。

标签:训练,image,mask,MaskRCNN,dataset,yaml,import,path,数据
来源: https://blog.csdn.net/u013066730/article/details/101209325