Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
matterport
GitHub Repository: matterport/Mask_RCNN
Path: blob/master/samples/balloon/balloon.py
240 views
1
"""
2
Mask R-CNN
3
Train on the toy Balloon dataset and implement color splash effect.
4
5
Copyright (c) 2018 Matterport, Inc.
6
Licensed under the MIT License (see LICENSE for details)
7
Written by Waleed Abdulla
8
9
------------------------------------------------------------
10
11
Usage: import the module (see Jupyter notebooks for examples), or run from
12
the command line as such:
13
14
# Train a new model starting from pre-trained COCO weights
15
python3 balloon.py train --dataset=/path/to/balloon/dataset --weights=coco
16
17
# Resume training a model that you had trained earlier
18
python3 balloon.py train --dataset=/path/to/balloon/dataset --weights=last
19
20
# Train a new model starting from ImageNet weights
21
python3 balloon.py train --dataset=/path/to/balloon/dataset --weights=imagenet
22
23
# Apply color splash to an image
24
python3 balloon.py splash --weights=/path/to/weights/file.h5 --image=<URL or path to file>
25
26
# Apply color splash to video using the last weights you trained
27
python3 balloon.py splash --weights=last --video=<URL or path to file>
28
"""
29
30
import os
31
import sys
32
import json
33
import datetime
34
import numpy as np
35
import skimage.draw
36
37
# Root directory of the project
38
ROOT_DIR = os.path.abspath("../../")
39
40
# Import Mask RCNN
41
sys.path.append(ROOT_DIR) # To find local version of the library
42
from mrcnn.config import Config
43
from mrcnn import model as modellib, utils
44
45
# Path to trained weights file
46
COCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
47
48
# Directory to save logs and model checkpoints, if not provided
49
# through the command line argument --logs
50
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")
51
52
############################################################
53
# Configurations
54
############################################################
55
56
57
class BalloonConfig(Config):
58
"""Configuration for training on the toy dataset.
59
Derives from the base Config class and overrides some values.
60
"""
61
# Give the configuration a recognizable name
62
NAME = "balloon"
63
64
# We use a GPU with 12GB memory, which can fit two images.
65
# Adjust down if you use a smaller GPU.
66
IMAGES_PER_GPU = 2
67
68
# Number of classes (including background)
69
NUM_CLASSES = 1 + 1 # Background + balloon
70
71
# Number of training steps per epoch
72
STEPS_PER_EPOCH = 100
73
74
# Skip detections with < 90% confidence
75
DETECTION_MIN_CONFIDENCE = 0.9
76
77
78
############################################################
79
# Dataset
80
############################################################
81
82
class BalloonDataset(utils.Dataset):
83
84
def load_balloon(self, dataset_dir, subset):
85
"""Load a subset of the Balloon dataset.
86
dataset_dir: Root directory of the dataset.
87
subset: Subset to load: train or val
88
"""
89
# Add classes. We have only one class to add.
90
self.add_class("balloon", 1, "balloon")
91
92
# Train or validation dataset?
93
assert subset in ["train", "val"]
94
dataset_dir = os.path.join(dataset_dir, subset)
95
96
# Load annotations
97
# VGG Image Annotator (up to version 1.6) saves each image in the form:
98
# { 'filename': '28503151_5b5b7ec140_b.jpg',
99
# 'regions': {
100
# '0': {
101
# 'region_attributes': {},
102
# 'shape_attributes': {
103
# 'all_points_x': [...],
104
# 'all_points_y': [...],
105
# 'name': 'polygon'}},
106
# ... more regions ...
107
# },
108
# 'size': 100202
109
# }
110
# We mostly care about the x and y coordinates of each region
111
# Note: In VIA 2.0, regions was changed from a dict to a list.
112
annotations = json.load(open(os.path.join(dataset_dir, "via_region_data.json")))
113
annotations = list(annotations.values()) # don't need the dict keys
114
115
# The VIA tool saves images in the JSON even if they don't have any
116
# annotations. Skip unannotated images.
117
annotations = [a for a in annotations if a['regions']]
118
119
# Add images
120
for a in annotations:
121
# Get the x, y coordinaets of points of the polygons that make up
122
# the outline of each object instance. These are stores in the
123
# shape_attributes (see json format above)
124
# The if condition is needed to support VIA versions 1.x and 2.x.
125
if type(a['regions']) is dict:
126
polygons = [r['shape_attributes'] for r in a['regions'].values()]
127
else:
128
polygons = [r['shape_attributes'] for r in a['regions']]
129
130
# load_mask() needs the image size to convert polygons to masks.
131
# Unfortunately, VIA doesn't include it in JSON, so we must read
132
# the image. This is only managable since the dataset is tiny.
133
image_path = os.path.join(dataset_dir, a['filename'])
134
image = skimage.io.imread(image_path)
135
height, width = image.shape[:2]
136
137
self.add_image(
138
"balloon",
139
image_id=a['filename'], # use file name as a unique image id
140
path=image_path,
141
width=width, height=height,
142
polygons=polygons)
143
144
def load_mask(self, image_id):
145
"""Generate instance masks for an image.
146
Returns:
147
masks: A bool array of shape [height, width, instance count] with
148
one mask per instance.
149
class_ids: a 1D array of class IDs of the instance masks.
150
"""
151
# If not a balloon dataset image, delegate to parent class.
152
image_info = self.image_info[image_id]
153
if image_info["source"] != "balloon":
154
return super(self.__class__, self).load_mask(image_id)
155
156
# Convert polygons to a bitmap mask of shape
157
# [height, width, instance_count]
158
info = self.image_info[image_id]
159
mask = np.zeros([info["height"], info["width"], len(info["polygons"])],
160
dtype=np.uint8)
161
for i, p in enumerate(info["polygons"]):
162
# Get indexes of pixels inside the polygon and set them to 1
163
rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])
164
mask[rr, cc, i] = 1
165
166
# Return mask, and array of class IDs of each instance. Since we have
167
# one class ID only, we return an array of 1s
168
return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)
169
170
def image_reference(self, image_id):
171
"""Return the path of the image."""
172
info = self.image_info[image_id]
173
if info["source"] == "balloon":
174
return info["path"]
175
else:
176
super(self.__class__, self).image_reference(image_id)
177
178
179
def train(model):
180
"""Train the model."""
181
# Training dataset.
182
dataset_train = BalloonDataset()
183
dataset_train.load_balloon(args.dataset, "train")
184
dataset_train.prepare()
185
186
# Validation dataset
187
dataset_val = BalloonDataset()
188
dataset_val.load_balloon(args.dataset, "val")
189
dataset_val.prepare()
190
191
# *** This training schedule is an example. Update to your needs ***
192
# Since we're using a very small dataset, and starting from
193
# COCO trained weights, we don't need to train too long. Also,
194
# no need to train all layers, just the heads should do it.
195
print("Training network heads")
196
model.train(dataset_train, dataset_val,
197
learning_rate=config.LEARNING_RATE,
198
epochs=30,
199
layers='heads')
200
201
202
def color_splash(image, mask):
203
"""Apply color splash effect.
204
image: RGB image [height, width, 3]
205
mask: instance segmentation mask [height, width, instance count]
206
207
Returns result image.
208
"""
209
# Make a grayscale copy of the image. The grayscale copy still
210
# has 3 RGB channels, though.
211
gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255
212
# Copy color pixels from the original color image where mask is set
213
if mask.shape[-1] > 0:
214
# We're treating all instances as one, so collapse the mask into one layer
215
mask = (np.sum(mask, -1, keepdims=True) >= 1)
216
splash = np.where(mask, image, gray).astype(np.uint8)
217
else:
218
splash = gray.astype(np.uint8)
219
return splash
220
221
222
def detect_and_color_splash(model, image_path=None, video_path=None):
223
assert image_path or video_path
224
225
# Image or video?
226
if image_path:
227
# Run model detection and generate the color splash effect
228
print("Running on {}".format(args.image))
229
# Read image
230
image = skimage.io.imread(args.image)
231
# Detect objects
232
r = model.detect([image], verbose=1)[0]
233
# Color splash
234
splash = color_splash(image, r['masks'])
235
# Save output
236
file_name = "splash_{:%Y%m%dT%H%M%S}.png".format(datetime.datetime.now())
237
skimage.io.imsave(file_name, splash)
238
elif video_path:
239
import cv2
240
# Video capture
241
vcapture = cv2.VideoCapture(video_path)
242
width = int(vcapture.get(cv2.CAP_PROP_FRAME_WIDTH))
243
height = int(vcapture.get(cv2.CAP_PROP_FRAME_HEIGHT))
244
fps = vcapture.get(cv2.CAP_PROP_FPS)
245
246
# Define codec and create video writer
247
file_name = "splash_{:%Y%m%dT%H%M%S}.avi".format(datetime.datetime.now())
248
vwriter = cv2.VideoWriter(file_name,
249
cv2.VideoWriter_fourcc(*'MJPG'),
250
fps, (width, height))
251
252
count = 0
253
success = True
254
while success:
255
print("frame: ", count)
256
# Read next image
257
success, image = vcapture.read()
258
if success:
259
# OpenCV returns images as BGR, convert to RGB
260
image = image[..., ::-1]
261
# Detect objects
262
r = model.detect([image], verbose=0)[0]
263
# Color splash
264
splash = color_splash(image, r['masks'])
265
# RGB -> BGR to save image to video
266
splash = splash[..., ::-1]
267
# Add image to video writer
268
vwriter.write(splash)
269
count += 1
270
vwriter.release()
271
print("Saved to ", file_name)
272
273
274
############################################################
275
# Training
276
############################################################
277
278
if __name__ == '__main__':
279
import argparse
280
281
# Parse command line arguments
282
parser = argparse.ArgumentParser(
283
description='Train Mask R-CNN to detect balloons.')
284
parser.add_argument("command",
285
metavar="<command>",
286
help="'train' or 'splash'")
287
parser.add_argument('--dataset', required=False,
288
metavar="/path/to/balloon/dataset/",
289
help='Directory of the Balloon dataset')
290
parser.add_argument('--weights', required=True,
291
metavar="/path/to/weights.h5",
292
help="Path to weights .h5 file or 'coco'")
293
parser.add_argument('--logs', required=False,
294
default=DEFAULT_LOGS_DIR,
295
metavar="/path/to/logs/",
296
help='Logs and checkpoints directory (default=logs/)')
297
parser.add_argument('--image', required=False,
298
metavar="path or URL to image",
299
help='Image to apply the color splash effect on')
300
parser.add_argument('--video', required=False,
301
metavar="path or URL to video",
302
help='Video to apply the color splash effect on')
303
args = parser.parse_args()
304
305
# Validate arguments
306
if args.command == "train":
307
assert args.dataset, "Argument --dataset is required for training"
308
elif args.command == "splash":
309
assert args.image or args.video,\
310
"Provide --image or --video to apply color splash"
311
312
print("Weights: ", args.weights)
313
print("Dataset: ", args.dataset)
314
print("Logs: ", args.logs)
315
316
# Configurations
317
if args.command == "train":
318
config = BalloonConfig()
319
else:
320
class InferenceConfig(BalloonConfig):
321
# Set batch size to 1 since we'll be running inference on
322
# one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
323
GPU_COUNT = 1
324
IMAGES_PER_GPU = 1
325
config = InferenceConfig()
326
config.display()
327
328
# Create model
329
if args.command == "train":
330
model = modellib.MaskRCNN(mode="training", config=config,
331
model_dir=args.logs)
332
else:
333
model = modellib.MaskRCNN(mode="inference", config=config,
334
model_dir=args.logs)
335
336
# Select weights file to load
337
if args.weights.lower() == "coco":
338
weights_path = COCO_WEIGHTS_PATH
339
# Download weights file
340
if not os.path.exists(weights_path):
341
utils.download_trained_weights(weights_path)
342
elif args.weights.lower() == "last":
343
# Find last trained weights
344
weights_path = model.find_last()
345
elif args.weights.lower() == "imagenet":
346
# Start from ImageNet trained weights
347
weights_path = model.get_imagenet_weights()
348
else:
349
weights_path = args.weights
350
351
# Load weights
352
print("Loading weights ", weights_path)
353
if args.weights.lower() == "coco":
354
# Exclude the last layers because they require a matching
355
# number of classes
356
model.load_weights(weights_path, by_name=True, exclude=[
357
"mrcnn_class_logits", "mrcnn_bbox_fc",
358
"mrcnn_bbox", "mrcnn_mask"])
359
else:
360
model.load_weights(weights_path, by_name=True)
361
362
# Train or evaluate
363
if args.command == "train":
364
train(model)
365
elif args.command == "splash":
366
detect_and_color_splash(model, image_path=args.image,
367
video_path=args.video)
368
else:
369
print("'{}' is not recognized. "
370
"Use 'train' or 'splash'".format(args.command))
371
372