matterport / Mask_RCNN

Mask R-CNN for object detection and instance segmentation on Keras and TensorFlow
Other
24.41k stars 11.66k forks source link

Balloon Sample: What if we want to train for more than one class #372

Closed AliceDinh closed 6 years ago

AliceDinh commented 6 years ago

In coco.py, annotation format is coco annotation format. In balloon.py, the annotation is achieved by VIA which is different to coco format. In shapes.py, the annotation is not needed coz there is no dataset I successfully trained, evaluated and tested all samples and notebooks (coco, balloon, shapes) and I also created my own dataset, my annotation by VIA. I could train the model using my own dataset successfully, but only for one class (one category). I need to train for more class and I did try to modify funtions: load_objects() and load_mask() without success. So please help.

abhigim1988 commented 3 years ago

I am trying to add multiple classes for car damage part. Results are showing the mask in the predicted image but is not showing the class ID. Below is the code: Please help on what I am doing wrong """ Mask R-CNN Train to detect multiple classes.

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 os import sys import json import datetime import numpy as np import skimage.draw

Root directory of the project

ROOT_DIR = ROOT_DIR = os.getcwd()

Import Mask RCNN

sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn.config import Config from mrcnn import model as modellib, utils

Path to trained weights file

COCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")

Directory to save logs and model checkpoints, if not provided

through the command line argument --logs

DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")

############################################################

Configurations

############################################################

class CustomConfig(Config): """Configuration for training on the toy dataset. Derives from the base Config class and overrides some values. """

Give the configuration a recognizable name

NAME = "part"

# We use a GPU with 12GB memory, which can fit two images.
# Adjust down if you use a smaller GPU.
IMAGES_PER_GPU = 2

# Number of classes (including background)
NUM_CLASSES = 1 + 19  # Background + 5 classes (rear bump, front bump, headlamp, door, hood)

# Use smaller images for faster training. Set the limits of the small side
# the large side, and that determines the image shape.
IMAGE_MIN_DIM = 512
IMAGE_MAX_DIM = 512

# Number of training steps per epoch
STEPS_PER_EPOCH = 125

# Skip detections with < 90% confidence
DETECTION_MIN_CONFIDENCE = 0.9

############################################################

Dataset

############################################################

class CustomDataset(utils.Dataset):

def load_custom(self, dataset_dir, subset):
    self.add_class("part", 1, "scratch_Bumper")
    self.add_class("part", 2, "dent_Bumper")
    self.add_class("part", 3, "broken_Bumper")
    self.add_class("part", 4, "dislocated_Bumper")
    self.add_class("part", 5, "broken_Windshield")
    self.add_class("part", 6, "broken_Headlight")
    self.add_class("part", 7, "scratch_Bonnet")
    self.add_class("part", 8, "dent_Bonnet")
    self.add_class("part", 9, "broken_Bonnet")
    self.add_class("part", 10, "bent_Bonnet")
    self.add_class("part", 11, "scratch_Grille")
    self.add_class("part", 12, "dent_Grille")   
    self.add_class("part", 13, "broken_Grille")
    self.add_class("part", 14, "scratch_Fender")
    self.add_class("part", 15, "dent_Fender")   
    self.add_class("part", 16, "broken_Fender")
    self.add_class("part", 17, "Damaged_wheel") 
    self.add_class("part", 18, "broken_Indicator")
    self.add_class("part", 19, "broken_Foglights")

    # Train or validation dataset?
    assert subset in ["train", "val"]
    dataset_dir = os.path.join(dataset_dir, subset)

    # Load annotations
    # VGG Image Annotator saves each image in the form:
    # { 'filename': '28503151_5b5b7ec140_b.jpg',
    #   'regions': {
    #       '0': {
    #           'region_attributes': {},
    #           'shape_attributes': {
    #               'all_points_x': [...],
    #               'all_points_y': [...],
    #               'name': 'polygon'}},
    #       ... more regions ...
    #   },
    #   'size': 100202
    # }
    # We mostly care about the x and y coordinates of each region
    annotations1 = json.load(open(os.path.join(dataset_dir, subset + "_multiclass.json")))
    # print(annotations1)
    #annotations = [a for a in annotations1 if isinstance(a, dict)]
    #annotations = [a for a in annotations if "regions" in a.keys()]

    annotations = list(annotations1.values())  # don't need the dict keys

    # The VIA tool saves images in the JSON even if they don't have any
    # annotations. Skip unannotated images.
    annotations = [a for a in annotations if a['regions']]

    # The VIA tool saves images in the JSON even if they don't have any
    # annotations. Skip unannotated images.
    #annotations = [a for a in annotations if a['regions']]

    #class_nums = {'rear_bumper': 1, 'front_bumper': 2, 'headlamp': 3, 'hood': 4, 'door': 5}

    # Add images
    for a in annotations:
        # print(a)
        # Get the x, y coordinaets of points of the polygons that make up
        # the outline of each object instance. There are stores in the
        # shape_attributes (see json format above)
        #for r in a['regions']:
            #polygons = [{'all_points_x': r['shape_attributes']['all_points_x'], 'all_points_y': r['shape_attributes']['all_points_y']}]
        polygons = [r['shape_attributes'] for r in a['regions']]
        objects = [s['region_attributes'] for s in a['regions']]
        #num_ids = [int(class_nums[n['name']]) for n in objects]
        num_ids = []
        for n in objects:
            try:
                if n['name'] == 'scratch_Bumper':
                    num_ids.append(1)
                elif n['name'] == 'dent_Bumper':
                    num_ids.append(2)
                elif n['name'] == 'broken_Bumper':
                    num_ids.append(3)
                elif n['name'] == 'dislocated_Bumper':
                    num_ids.append(4)
                elif n['name'] == 'broken_Windshield':
                    num_ids.append(5)
                elif n['name'] == 'broken_Headlight':
                    num_ids.append(6)
                elif n['name'] == 'scratch_Bonnet':
                    num_ids.append(7)
                elif n['name'] == 'dent_Bonnet':
                    num_ids.append(8)
                elif n['name'] == 'broken_Bonnet':
                    num_ids.append(9)
                elif n['name'] == 'bent_Bonnet':
                    num_ids.append(10)
                elif n['name'] == 'scratch_Grille':
                    num_ids.append(11)
                elif n['name'] == 'dent_Grille':
                    num_ids.append(12)
                elif n['name'] == 'broken_Grille':
                    num_ids.append(13)
                elif n['name'] == 'scratch_Fender':
                    num_ids.append(14)
                elif n['name'] == 'dent_Fender':
                    num_ids.append(15)
                elif n['name'] == 'broken_Fender':
                    num_ids.append(16)
                elif n['name'] == 'Damaged_wheel':
                    num_ids.append(17)
                elif n['name'] == 'broken_Indicator':
                    num_ids.append(18)
                elif n['name'] == 'broken_Foglights':
                    num_ids.append(19)
            except:
                pass
        # load_mask() needs the image size to convert polygons to masks.
        # Unfortunately, VIA doesn't include it in JSON, so we must read
        # the image. This is only managable since the dataset is tiny.
        image_path = os.path.join(dataset_dir, a['filename'])
        image = skimage.io.imread(image_path)
        height, width = image.shape[:2]

        self.add_image(
            "part",  # for a single class just add the name here
            image_id=a['filename'],  # use file name as a unique image id
            path=image_path,
            width=width, height=height,
            polygons=polygons,
            num_ids=num_ids)

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.
    """
    # If not a balloon dataset image, delegate to parent class.
    image_info = self.image_info[image_id]
    if image_info["source"] != "part":
        return super(self.__class__, self).load_mask(image_id)

    # Convert polygons to a bitmap mask of shape
    # [height, width, instance_count]
    info = self.image_info[image_id]
    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"] == "part":
        return info["path"]
    else:
        super(self.__class__, self).image_reference(image_id)

def train(model): """Train the model."""

Training dataset.

dataset_train = CustomDataset()
dataset_train.load_custom(args.dataset, "train")
dataset_train.prepare()

# Validation dataset
dataset_val = CustomDataset()
dataset_val.load_custom(args.dataset, "val")
dataset_val.prepare()

# *** This training schedule is an example. Update to your needs ***
# Since we're using a very small dataset, and starting from
# COCO trained weights, we don't need to train too long. Also,
# no need to train all layers, just the heads should do it.
print("Training network heads")
model.train(dataset_train, dataset_val,
            learning_rate=config.LEARNING_RATE,
            epochs=8,
            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.
"""
# Make a grayscale copy of the image. The grayscale copy still
# has 3 RGB channels, though.
gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255
# We're treating all instances as one, so collapse the mask into one layer
mask = (np.sum(mask, -1, keepdims=True) >= 1)
# Copy color pixels from the original color image where mask is set
if mask.shape[0] > 0:
    splash = np.where(mask, image, gray).astype(np.uint8)
else:
    splash = gray
return splash

def detect_and_color_splash(model, image_path=None, video_path=None): assert image_path or video_path

# Image or video?
if image_path:
    # Run model detection and generate the color splash effect
    print("Running on {}".format(args.image))
    # Read image
    image = skimage.io.imread(args.image)
    # Detect objects
    r = model.detect([image], verbose=1)[0]
    # Color splash
    splash = color_splash(image, r['masks'])
    # Save output
    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
    # Video capture
    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)

    # Define codec and create video writer
    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)
        # Read next image
        success, image = vcapture.read()
        if success:
            # OpenCV returns images as BGR, convert to RGB
            image = image[..., ::-1]
            # Detect objects
            r = model.detect([image], verbose=0)[0]
            # Color splash
            splash = color_splash(image, r['masks'])
            # RGB -> BGR to save image to video
            splash = splash[..., ::-1]
            # Add image to video writer
            vwriter.write(splash)
            count += 1
    vwriter.release()
print("Saved to ", file_name)

############################################################

Training

############################################################

if name == 'main': import argparse

# Parse command line arguments
parser = argparse.ArgumentParser(
    description='Train Mask R-CNN to detect custom class.')
parser.add_argument("command",
                    metavar="<command>",
                    help="'train' or 'splash'")
parser.add_argument('--dataset', required=False,
                    metavar="/path/to/custom/dataset/",
                    help='Directory of the custom 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()

# Validate arguments
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)

# Configurations
if args.command == "train":
    config = CustomConfig()
else:
    class InferenceConfig(CustomConfig):
        # 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
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)

# Select weights file to load
if args.weights.lower() == "coco":
    weights_path = COCO_WEIGHTS_PATH
    # Download weights file
    if not os.path.exists(weights_path):
        utils.download_trained_weights(weights_path)
elif args.weights.lower() == "last":
    # Find last trained weights
    weights_path = model.find_last()[1]
elif args.weights.lower() == "imagenet":
    # Start from ImageNet trained weights
    weights_path = model.get_imagenet_weights()
else:
    weights_path = args.weights

# Load weights
print("Loading weights ", weights_path)
if args.weights.lower() == "coco":
    # Exclude the last layers because they require a matching
    # number of classes
    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)

# Train or evaluate
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))
Genius-farmer commented 3 years ago

any solutions for VGG annotator v2.0?

nataliameira commented 3 years ago

I have created a custom dataset module for training on any desired dataset. Here is the link. I hope it helps.

Hello. I have tested your implementation, but my model only finds 1 class for everyone. Can you help me?

SriRamGovardhanam commented 3 years ago

I have created a custom dataset module for training on any desired dataset. Here is the link. I hope it helps.

Hello. I have tested your implementation, but my model only finds 1 class for everyone. Can you help me?

I hope these two sources may help you https://github.com/SriRamGovardhanam/wastedata-Mask_RCNN-multiple-classes https://medium.com/analytics-vidhya/training-your-own-data-set-using-mask-r-cnn-for-detecting-multiple-classes-3960ada85079

nataliameira commented 3 years ago

I have created a custom dataset module for training on any desired dataset. Here is the link. I hope it helps.

Hello. I have tested your implementation, but my model only finds 1 class for everyone. Can you help me?

I hope these two sources may help you https://github.com/SriRamGovardhanam/wastedata-Mask_RCNN-multiple-classes https://medium.com/analytics-vidhya/training-your-own-data-set-using-mask-r-cnn-for-detecting-multiple-classes-3960ada85079

I get this error:

Traceback (most recent call last):
  File "custom.py", line 378, in <module>
    train(model)
  File "custom.py", line 197, in train
    dataset_train.load_custom(args.dataset, "train")
  File "custom.py", line 129, in load_custom
    polygons = [r['shape_attributes'] for r in a['regions']]
  File "custom.py", line 129, in <listcomp>
    polygons = [r['shape_attributes'] for r in a['regions']]
TypeError: string indices must be integers

I don't understand this error. Do you know what it can be? Could it be my labels?

Adblu commented 3 years ago

matterport is preatty poor in compare to mmdetection or detectron2. Consider using them ;)

agbozo1 commented 2 years ago

I have created a custom dataset module for training on any desired dataset. Here is the link. I hope it helps.

Hello. I have tested your implementation, but my model only finds 1 class for everyone. Can you help me?

I hope these two sources may help you https://github.com/SriRamGovardhanam/wastedata-Mask_RCNN-multiple-classes https://medium.com/analytics-vidhya/training-your-own-data-set-using-mask-r-cnn-for-detecting-multiple-classes-3960ada85079

I get this error:

Traceback (most recent call last):
  File "custom.py", line 378, in <module>
    train(model)
  File "custom.py", line 197, in train
    dataset_train.load_custom(args.dataset, "train")
  File "custom.py", line 129, in load_custom
    polygons = [r['shape_attributes'] for r in a['regions']]
  File "custom.py", line 129, in <listcomp>
    polygons = [r['shape_attributes'] for r in a['regions']]
TypeError: string indices must be integers

I don't understand this error. Do you know what it can be? Could it be my labels?

From a similar experience, the issues could any of these: