| | """
|
| | Mask R-CNN
|
| | Train on the toy Balloon dataset and implement color splash effect.
|
| |
|
| | Copyright (c) 2018 Matterport, Inc.
|
| | Licensed under the MIT License (see LICENSE for details)
|
| | Written by Waleed Abdulla
|
| |
|
| | ------------------------------------------------------------
|
| |
|
| | Usage: import the module (see Jupyter notebooks for examples), or run from
|
| | the command line as such:
|
| |
|
| | # Train a new model starting from pre-trained COCO weights
|
| | python3 balloon.py train --dataset=/path/to/balloon/dataset --weights=coco
|
| |
|
| | # Resume training a model that you had trained earlier
|
| | python3 balloon.py train --dataset=/path/to/balloon/dataset --weights=last
|
| |
|
| | # Train a new model starting from ImageNet weights
|
| | python3 balloon.py train --dataset=/path/to/balloon/dataset --weights=imagenet
|
| |
|
| | # Apply color splash to an image
|
| | python3 balloon.py splash --weights=/path/to/weights/file.h5 --image=<URL or path to file>
|
| |
|
| | # Apply color splash to video using the last weights you trained
|
| | python3 balloon.py splash --weights=last --video=<URL or path to file>
|
| | """
|
| | import glob
|
| | import os
|
| | import pdb
|
| | import sys
|
| | import json
|
| | import datetime
|
| | import numpy as np
|
| | import skimage.draw
|
| | import platform
|
| | import pdb
|
| | import glob
|
| | from PIL import Image
|
| |
|
| |
|
| | ROOT_DIR = os.path.abspath("../../../")
|
| |
|
| |
|
| | if platform.system() == "Windows":
|
| | base_dir = "C:/data/"
|
| | else:
|
| | base_dir = "/root/host/ssd/mine-sector-detection/"
|
| |
|
| |
|
| |
|
| | sys.path.append(ROOT_DIR)
|
| | from mrcnn.config import Config
|
| | from mrcnn import model as modellib, utils
|
| |
|
| |
|
| | COCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
|
| |
|
| |
|
| |
|
| | DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| | class BalloonConfig(Config):
|
| | """Configuration for training on the toy dataset.
|
| | Derives from the base Config class and overrides some values.
|
| | """
|
| |
|
| | NAME = "mining_sectors"
|
| |
|
| |
|
| |
|
| | IMAGES_PER_GPU = 1
|
| |
|
| |
|
| | NUM_CLASSES = 10
|
| |
|
| |
|
| | STEPS_PER_EPOCH = 50
|
| |
|
| |
|
| | DETECTION_MIN_CONFIDENCE = 0.9
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| | class BalloonDataset(utils.Dataset):
|
| |
|
| | def load_balloon(self, dataset_dir, subset):
|
| | """Load a subset of the Balloon dataset.
|
| | dataset_dir: Root directory of the dataset.
|
| | subset: Subset to load: train or val
|
| | """
|
| |
|
| | self.add_class("balloon", 0, "surrounding")
|
| | self.add_class("balloon", 1, "ASM")
|
| | self.add_class("balloon", 2, "LSM")
|
| | self.add_class("balloon", 3, "Leaching Heap")
|
| | self.add_class("balloon", 4, "Mining Facilities")
|
| | self.add_class("balloon", 5, "Open Pit")
|
| | self.add_class("balloon", 6, "Processing Plant")
|
| | self.add_class("balloon", 7, "Stockyard")
|
| | self.add_class("balloon", 8, "Tailings Storage Facility")
|
| | self.add_class("balloon", 9, "Waste Rock Dump")
|
| |
|
| |
|
| | assert subset in ["images_trainset", "images_testset"]
|
| | dataset_dir = os.path.join(dataset_dir, subset)
|
| |
|
| | image_paths = sorted(glob.glob(os.path.join(dataset_dir, "*.png")))
|
| |
|
| | for idx, image_path in enumerate(image_paths):
|
| | filename = os.path.basename(image_path)
|
| | self.add_image(
|
| | "balloon",
|
| | image_id=idx,
|
| | image_fname=os.path.basename(image_path),
|
| | path=image_path,
|
| | width=256,
|
| | height=256)
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| | def load_mask(self, image_id):
|
| |
|
| | """Generate instance masks for an image.
|
| | Returns:
|
| | masks: A bool array of shape [height, width, instance count] with
|
| | one mask per instance.
|
| | class_ids: a 1D array of class IDs of the instance masks.
|
| | """
|
| |
|
| |
|
| |
|
| | image_info = self.image_info[image_id]
|
| | if image_info["source"] != "balloon":
|
| | return super(self.__class__, self).load_mask(image_id)
|
| |
|
| |
|
| |
|
| | info = self.image_info[image_id]
|
| |
|
| |
|
| |
|
| |
|
| |
|
| | mask = np.zeros([256, 256, 1], dtype=np.uint8)
|
| | return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)
|
| |
|
| | '''
|
| | mask = np.zeros([info["height"], info["width"], len(info["polygons"])],
|
| | dtype=np.uint8)
|
| | for i, p in enumerate(info["polygons"]):
|
| | # Get indexes of pixels inside the polygon and set them to 1
|
| | rr, cc = skimage.draw.polygon(p['all_points_y'], p['all_points_x'])
|
| | mask[rr, cc, i] = 1
|
| |
|
| | # Return mask, and array of class IDs of each instance. Since we have
|
| | # one class ID only, we return an array of 1s
|
| | return mask.astype(np.bool), np.ones([mask.shape[-1]], dtype=np.int32)
|
| | '''
|
| |
|
| | def image_reference(self, image_id):
|
| | """Return the path of the image."""
|
| | info = self.image_info[image_id]
|
| | if info["source"] == "balloon":
|
| | return info["path"]
|
| | else:
|
| | super(self.__class__, self).image_reference(image_id)
|
| |
|
| |
|
| | def train(model):
|
| |
|
| | """Train the model."""
|
| |
|
| | dataset_train = BalloonDataset()
|
| | dataset_train.load_balloon(args.dataset, "images_trainset")
|
| | dataset_train.prepare()
|
| |
|
| |
|
| | dataset_val = BalloonDataset()
|
| | dataset_val.load_balloon(args.dataset, "images_testset")
|
| | dataset_val.prepare()
|
| |
|
| | dataset_train.load_mask(23)
|
| |
|
| |
|
| |
|
| |
|
| |
|
| | print("Training network heads")
|
| | model.train(dataset_train, dataset_val,
|
| | learning_rate=config.LEARNING_RATE,
|
| | epochs=30,
|
| | layers='heads')
|
| |
|
| |
|
| | def color_splash(image, mask):
|
| | """Apply color splash effect.
|
| | image: RGB image [height, width, 3]
|
| | mask: instance segmentation mask [height, width, instance count]
|
| |
|
| | Returns result image.
|
| | """
|
| |
|
| |
|
| | gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255
|
| |
|
| | if mask.shape[-1] > 0:
|
| |
|
| | mask = (np.sum(mask, -1, keepdims=True) >= 1)
|
| | splash = np.where(mask, image, gray).astype(np.uint8)
|
| | else:
|
| | splash = gray.astype(np.uint8)
|
| | return splash
|
| |
|
| |
|
| | def detect_and_color_splash(model, image_path=None, video_path=None):
|
| | assert image_path or video_path
|
| |
|
| |
|
| | if image_path:
|
| |
|
| | print("Running on {}".format(args.image))
|
| |
|
| | image = skimage.io.imread(args.image)
|
| |
|
| | r = model.detect([image], verbose=1)[0]
|
| |
|
| | splash = color_splash(image, r['masks'])
|
| |
|
| | file_name = "splash_{:%Y%m%dT%H%M%S}.png".format(datetime.datetime.now())
|
| | skimage.io.imsave(file_name, splash)
|
| | elif video_path:
|
| | import cv2
|
| |
|
| | vcapture = cv2.VideoCapture(video_path)
|
| | width = int(vcapture.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| | height = int(vcapture.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| | fps = vcapture.get(cv2.CAP_PROP_FPS)
|
| |
|
| |
|
| | file_name = "splash_{:%Y%m%dT%H%M%S}.avi".format(datetime.datetime.now())
|
| | vwriter = cv2.VideoWriter(file_name,
|
| | cv2.VideoWriter_fourcc(*'MJPG'),
|
| | fps, (width, height))
|
| |
|
| | count = 0
|
| | success = True
|
| | while success:
|
| | print("frame: ", count)
|
| |
|
| | success, image = vcapture.read()
|
| | if success:
|
| |
|
| | image = image[..., ::-1]
|
| |
|
| | r = model.detect([image], verbose=0)[0]
|
| |
|
| | splash = color_splash(image, r['masks'])
|
| |
|
| | splash = splash[..., ::-1]
|
| |
|
| | vwriter.write(splash)
|
| | count += 1
|
| | vwriter.release()
|
| | print("Saved to ", file_name)
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| | if __name__ == '__main__':
|
| | import argparse
|
| |
|
| |
|
| | parser = argparse.ArgumentParser(
|
| | description='Train Mask R-CNN to detect balloons.')
|
| | parser.add_argument("command",
|
| | metavar="<command>",
|
| | help="'train' or 'splash'")
|
| | parser.add_argument('--dataset', required=False,
|
| | metavar="/path/to/balloon/dataset/",
|
| | help='Directory of the Balloon dataset')
|
| | parser.add_argument('--weights', required=True,
|
| | metavar="/path/to/weights.h5",
|
| | help="Path to weights .h5 file or 'coco'")
|
| | parser.add_argument('--logs', required=False,
|
| | default=DEFAULT_LOGS_DIR,
|
| | metavar="/path/to/logs/",
|
| | help='Logs and checkpoints directory (default=logs/)')
|
| | parser.add_argument('--image', required=False,
|
| | metavar="path or URL to image",
|
| | help='Image to apply the color splash effect on')
|
| | parser.add_argument('--video', required=False,
|
| | metavar="path or URL to video",
|
| | help='Video to apply the color splash effect on')
|
| | args = parser.parse_args()
|
| |
|
| |
|
| | if args.command == "train":
|
| | assert args.dataset, "Argument --dataset is required for training"
|
| | elif args.command == "splash":
|
| | assert args.image or args.video,\
|
| | "Provide --image or --video to apply color splash"
|
| |
|
| | print("Weights: ", args.weights)
|
| | print("Dataset: ", args.dataset)
|
| | print("Logs: ", args.logs)
|
| |
|
| |
|
| | if args.command == "train":
|
| | config = BalloonConfig()
|
| | else:
|
| | class InferenceConfig(BalloonConfig):
|
| |
|
| |
|
| | GPU_COUNT = 1
|
| | IMAGES_PER_GPU = 1
|
| | config = InferenceConfig()
|
| | config.display()
|
| |
|
| |
|
| | if args.command == "train":
|
| | model = modellib.MaskRCNN(mode="training", config=config,
|
| | model_dir=args.logs)
|
| | else:
|
| | model = modellib.MaskRCNN(mode="inference", config=config,
|
| | model_dir=args.logs)
|
| |
|
| |
|
| | if args.weights.lower() == "coco":
|
| | weights_path = COCO_WEIGHTS_PATH
|
| |
|
| | if not os.path.exists(weights_path):
|
| | utils.download_trained_weights(weights_path)
|
| | elif args.weights.lower() == "last":
|
| |
|
| | weights_path = model.find_last()
|
| | elif args.weights.lower() == "imagenet":
|
| |
|
| | weights_path = model.get_imagenet_weights()
|
| | else:
|
| | weights_path = args.weights
|
| |
|
| |
|
| | print("Loading weights ", weights_path)
|
| | if args.weights.lower() == "coco":
|
| |
|
| |
|
| | model.load_weights(weights_path, by_name=True, exclude=[
|
| | "mrcnn_class_logits", "mrcnn_bbox_fc",
|
| | "mrcnn_bbox", "mrcnn_mask"])
|
| | else:
|
| | model.load_weights(weights_path, by_name=True)
|
| |
|
| |
|
| | if args.command == "train":
|
| | train(model)
|
| | elif args.command == "splash":
|
| | detect_and_color_splash(model, image_path=args.image,
|
| | video_path=args.video)
|
| | else:
|
| | print("'{}' is not recognized. "
|
| | "Use 'train' or 'splash'".format(args.command)) |