当前位置:网站首页>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‘
边栏推荐
- Define a structure fraction to represent a fraction, which is used to represent fractions such as 2/3 and 5/6
- Why is WPA3 security of enterprise business so important?
- 【RT-Thread】nxp rt10xx 设备驱动框架之--Pin搭建和使用
- IL Runtime
- 智慧之道(知行合一)
- RF Analyze Demo搭建 Step by Step
- Mysql database -dql
- kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
- CC2530 common registers for timer 1
- ANOVA example
猜你喜欢

Take you to API development by hand

C语言按行修改文件

Thread pool: the most common and error prone component of business code
智慧之道(知行合一)

UCORE overview

Simple use of unity pen XR grab

手把手带你入门 API 开发

Great changes! National housing prices fell below the 10000 yuan mark

Unity notes unityxr simple to use

线程池:业务代码最常用也最容易犯错的组件
随机推荐
CC2530 common registers for port interrupts
Visual studio "usually, each socket address (Protocol / network address / port) can only be used once“
[combinatorics] recursive equation (constant coefficient linear homogeneous recursive equation | constant coefficient, linear, homogeneous concept description | constant coefficient linear homogeneous
Mysql database DDL and DML
匯編實例解析--實模式下屏幕顯示
How SVN views modified file records
Define a structure fraction to represent a fraction, which is used to represent fractions such as 2/3 and 5/6
Solution to long waiting time of SSH connection to remote host
美团一面:为什么线程崩溃崩溃不会导致 JVM 崩溃
13mnnimo5-4 German standard steel plate 13MnNiMo54 boiler steel 13MnNiMo54 chemical properties
大变局!全国房价,跌破万元大关
27. Input 3 integers and output them in descending order. Pointer method is required.
Host based intrusion system IDS
Open vsftpd port under iptables firewall
【RT-Thread】nxp rt10xx 设备驱动框架之--Pin搭建和使用
跨境电商:外贸企业做海外社媒营销的优势
Life is still confused? Maybe these subscription numbers have the answers you need!
One brush 148 force deduction hot question-5 longest palindrome substring (m)
CC2530 common registers for serial communication
IL Runtime
