当前位置:网站首页>How to train mask r-cnn model with your own data
How to train mask r-cnn model with your own data
2022-07-03 17:09:00 【Carina2333333】
Reference article
Mask R-CNN tensorflow Train your data 【 From labeling data to final training and testing 】 Super full tutorial , Vomit blood and step on the pit ,Ubuntu 16.04 Perfect operation _Somafish The blog of -CSDN Blog Preface because of the need of work , You have to use Mask-Rcnn To train your data , Before writing this blog, the landlord searched Baidu for various training methods , But the blog posts searched The writing is quite ambiguous , Finally, I tried all kinds of things Finally let the training run , Also here Write this blog post For everyone . This tutorial Apply to Ubuntu Users of the system 、Windows The user of the system I use Mask RCNN-->https://github.com/matterpor...https://blog.csdn.net/doudou_here/article/details/87855273Mask RCNN Train your own dataset _ A stupid Feixian blog -CSDN Blog _maskrcnn Train your own dataset The version is tensorflow+keras Version of , The official version is just open source 10 Hours (caffe2), Update later .. One 、 Tools cuda And cudnn Please refer to my previous blog for installation : http://blog.csdn.net/l297969586/article/details/53320706 http://blog.csdn.net/l297969586/article/details/67632608 ...
https://blog.csdn.net/l297969586/article/details/79140840MaskRCNN Train your own dataset Xiaobai - Grey letter network ( Software development blog aggregation )
https://www.freesion.com/article/1999844623/
First paste the runthrough code and the corresponding output ( Some parameters need to be adjusted )
import os
import sys
import random
import math
import re
import time
import numpy as np
import cv2
import matplotlib
import tensorflow as tf
import matplotlib.pyplot as plt
from PIL import Image
import yaml
# 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
%matplotlib inline
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
iter_num = 0
# 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)
Output :
Configuration
class ShapesConfig(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 = "shapes"
# 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 = 1
# Number of classes (including background)
NUM_CLASSES = 1 + 3 # background + 3 shapes
# 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 = 480
IMAGE_MAX_DIM = 640
# Use smaller anchors because our image and objects are small
RPN_ANCHOR_SCALES = (8*6, 16*6, 32*6, 64*6, 128*6) # 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 = 32
# Use a small epoch since the data is simple
STEPS_PER_EPOCH = 100
# use small validation steps since the epoch is small
VALIDATION_STEPS = 5
config = ShapesConfig()
config.display()
Output :
Dataset
class DrugDataset(utils.Dataset):
"""Generates the shapes synthetic dataset. The dataset consists of simple
shapes (triangles, squares, circles) placed randomly on a blank surface.
The images are generated on the fly. No file access required.
"""
# Get the number of instances in the figure ( object )
def get_obj_index(self, image):
n = np.max(image)
return n
# analysis labelme Obtained in yaml file , To get mask The instance label corresponding to each layer
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())
labels=temp['label_names']
del labels[0]
return labels
# Rewrite 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))
if at_pixel == index + 1:
mask[j, i, index] = 1
return mask
def load_shapes(self, count, height, width, img_floder, mask_floder, imglist,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("shapes", 1, "rectangle")
self.add_class("shapes", 2, "ball")
self.add_class("shapes", 3, "triangle")
# 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().
for i in range(count):
filestr = imglist[i].split(".")[0]
# filestr = filestr.split("_")[1]
mask_path = mask_floder + "\\" + filestr + ".png"
yaml_path=dataset_root_path+"labelme_json\\"+filestr+"_json\\info.yaml"
cv_img = cv2.imread(dataset_root_path+"labelme_json\\"+filestr+"_json\\img.png")
self.add_image("shapes", image_id=i, path=img_floder + "\\" + imglist[i],
width=cv_img.shape[1], height=cv_img.shape[0], mask_path=mask_path,yaml_path=yaml_path)
# print(mask_path)
def load_mask(self, image_id):
"""Generate instance masks for shapes of the given image ID.
"""
global iter_num
info = self.image_info[image_id]
count = 1 # number of object
img = Image.open(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)
# Handle occlusions
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=[]
labels=self.from_yaml_get_class(image_id)
labels_form=[]
for i in range(len(labels)):
if labels[i].find("rectangle")!= -1:
#print "box"
labels_form.append("rectangle")
elif labels[i].find("ball")!= -1:
#print "column"
labels_form.append("ball")
elif labels[i].find("triangle")!= -1:
#print "package"
labels_form.append("triangle")
# Map class names to class IDs.
class_ids = np.array([self.class_names.index(s) for s in labels_form])
return mask, class_ids.astype(np.int32)
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
# Foundation setup
dataset_root_path="C:\\Users\\91078\\Desktop\\testImg\\"
img_floder = dataset_root_path+"pic"
mask_floder = dataset_root_path+"cv2_mask"
#yaml_floder = dataset_root_path
imglist = os.listdir(img_floder)
count = len(imglist)
width = 480
height = 640
# Training dataset
dataset_train = DrugDataset()
# dataset_train.load_shapes(500, config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1])
dataset_train.load_shapes(count, 640, 480, img_floder, mask_floder, imglist,dataset_root_path)
dataset_train.prepare()
# Validation dataset
dataset_val = DrugDataset()
# dataset_val.load_shapes(50, config.IMAGE_SHAPE[0], config.IMAGE_SHAPE[1])
dataset_val.load_shapes(count, 640, 480, img_floder, mask_floder, imglist,dataset_root_path)
dataset_val.prepare()
Create Model
# Create model in training mode
model = modellib.MaskRCNN(mode="training", config=config,
model_dir=MODEL_DIR)
Output :
# 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()[1], by_name=True)
Training
# 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=1,
layers='heads')
Output :
Well trained .h5 The file is in the project logs Inside looking for
ERROR
AttributeError: ‘Model‘ object has no attribute ‘metrics_tensors‘
边栏推荐
- BYD and great wall hybrid market "get together" again
- UCORE overview
- C language modifies files by line
- [try to hack] active detection and concealment technology
- Necessary ability of data analysis
- 智慧之道(知行合一)
- How to promote cross department project collaboration | community essay solicitation
- 网络安全web渗透技术
- 定义一个结构体Fraction,表示分数,用于表示 2/3, 5/6这样的分数
- C language string practice
猜你喜欢
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
CC2530 common registers for crystal oscillator settings
【RT-Thread】nxp rt10xx 设备驱动框架之--hwtimer搭建和使用
MySQL Basics
CC2530 common registers for port interrupts
kubernetes资源对象介绍及常用命令(四)
Recommendation of good books on learning QT programming
How do large consumer enterprises make digital transformation?
Thread pool: the most common and error prone component of business code
29: Chapter 3: develop Passport Service: 12: develop [obtain user account information, interface]; (use VO class to package the found data to meet the requirements of the interface for the returned da
随机推荐
kubernetes资源对象介绍及常用命令(三)
Fast Ethernet and Gigabit Ethernet: what's the difference?
[combinatorics] recursive equation (example 1 of recursive equation | list recursive equation)
Thread pool: the most common and error prone component of business code
[combinatorics] recursive equation (general solution structure of recursive equation with multiple roots | linear independent solution | general solution with multiple roots | solution example of recu
Prepare for the golden three silver four, 100+ software test interview questions (function / interface / Automation) interview questions. win victory the moment one raises one 's standard
27. 输入3个整数,按从大到小的次序输出。要求用指针方法实现。
Kindeditor editor upload image ultra wide automatic compression -php code
One brush 146 force buckle hot question-3 longest substring without repeated characters (m)
【RT-Thread】nxp rt10xx 设备驱动框架之--hwtimer搭建和使用
29:第三章:开发通行证服务:12:开发【获得用户账户信息,接口】;(使用VO类包装查到的数据,以符合接口对返回数据的要求)(在多处都会用到的逻辑,在Controller中可以把其抽成一个共用方法)
Apache服务挂起Asynchronous AcceptEx failed.
[combinatorics] recursive equation (the relationship theorem between the solution of the recursive equation and the characteristic root | the linear property theorem of the solution of the recursive e
[2. Basics of Delphi grammar] 1 Identifiers and reserved words
Squid 服务启动脚本
New library online | cnopendata complete data of Chinese insurance institution outlets
线程池:业务代码最常用也最容易犯错的组件
[combinatorics] recursive equation (definition of general solution | structure theorem of general solution of recursive equation without multiple roots)
LeetCode13.罗马数字转整数(三种解法)
New library online | cnopendata China bird watching record data