mask rcnn训练自己的数据集

本文介绍如何基于Mask R-CNN训练自己的数据集,包括数据准备、源代码使用、训练参数设置和训练过程中遇到的问题。参考了开源项目、图像标记工具LabelMe,以及训练数据转换工具。训练数据集包含图像、JSON文件和掩码标签,训练代码需配合pycocotools库。文章还提供了训练和测试模型的代码,以及模型的保存和使用方式。
摘要由CSDN通过智能技术生成

前言

最近迷上了mask rcnn,也是由于自己工作需要吧,特意研究了其源代码,并基于自己的数据进行训练~
本博客参考https://blog.csdn.net/disiwei1012/article/details/79928679#commentsedit

实验目的

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
哎~说多了都是泪,谁让我是工科生呢?只能检测工件了。。。做不了高大上的东西了,哈哈

主要参考及工具

基于Mask RCNN开源项目:https://github.com/matterport/Mask_RCNN
图片标记工具基于开源项目:https://github.com/wkentaro/labelme
训练工具:win10+GTX1060+cuda9.1+cudnn7+tensorflow-gpu-1.6.0+keras-2.1.6,140幅图像,一共3类,1小时左右

有关labelme的使用可以参考:https://blog.csdn.net/shwan_ma/article/details/77823281

有关mask-rcnn和Faster RCNN算法可以参考:
https://blog.csdn.net/linolzhang/article/details/71774168
https://blog.csdn.net/lk123400/article/details/54343550/

准备训练数据集

这是我简历的四个文件夹,下面一一道来~
这里写图片描述
1.pic
这里写图片描述
这是训练的图像,一共700幅

2.json
这里写图片描述
这是通过labelme处理训练图像后生成的文件

3.labelme_json
这里写图片描述
这里写图片描述
这个是处理.json文件后产生的数据,使用方法为labelme_json_to_dataset+空格+文件名称.json,这个前提是labelme要准确安装并激活。但是这样会产生一个问题,对多幅图像这样处理,太麻烦,在这里提供一个工具,可以直接在.json文件目录下转换所有的json文件,链接:json数据转换工具

4.cv2_mask文件

由于labelme生成的掩码标签 label.png为16位存储,opencv默认读取8位,需要将16位转8位,可通过C++程序转化,代码请参考这篇博文:http://blog.csdn.net/l297969586/article/details/79154150
这里写图片描述
一团黑,不过不要怕,正常的~

源代码

运行该代码,需要安装pycocotools,在windows下安装该工具非常烦,有的可以轻松的安装成功,有的重装系统也很难成功,哎,都是坑~~关于Windows下安装pycocotools请参考:https://blog.csdn.net/chixia1785/article/details/80040172https://blog.csdn.net/gxiaoyaya/article/details/78363391

测试的源代码

Github上开源的代码,是基于ipynb的,我直接把它转换成.py文件,首先做个测试,基于coco数据集上训练好的模型,可以调用摄像头~~~

import os
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import cv2
import time
# 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
# Import COCO config
sys.path.append(os.path.join(ROOT_DIR, "samples/coco/"))  # To find local version
import coco


# 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(MODEL_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)
    print("cuiwei***********************")

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

class InferenceConfig(coco.CocoConfig):
    # 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 object in inference mode.
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config)

# Load w
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 官方代码。
评论 562
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值