def segment_from_image(image_path): class_names = load_coco_names('coco.names') model = mrcnn.model.MaskRCNN(mode="inference", model_dir="./logs", config=InferenceConfig()) model.load_weights(COCO_MODEL_PATH, by_name=True) image = cv2.imread(image_path) img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = model.detect([img], verbose=1)[0] for i in range(len(results['rois'])): left = results['rois'][i, 1] top = results['rois'][i, 0] right = results['rois'][i, 3] bottom = results['rois'][i, 2] text = class_names[results['class_ids'][i]] + str( round(results['scores'][i], 3)) mask = results['masks'][..., i] np.random.seed(results['class_ids'][i]) mask = np.stack([ mask.astype('int') * np.ones(image.shape[:-1]) * np.random.randint(0, 255, 1), mask.astype('int') * np.ones(image.shape[:-1]) * np.random.randint(0, 255, 1), mask.astype('int') * np.ones(image.shape[:-1]) * np.random.randint(0, 255, 1) ], axis=2).astype('uint8') cv2.rectangle(image, (left, top), (right, bottom), (0, 0, 255), 1) cv2.putText(image, text, (left, top), cv2.FONT_HERSHEY_DUPLEX, (right - left) / 300, (255, 255, 255), 1) image = cv2.addWeighted(image, 1, mask, 0.5, 0) cv2.imshow('result', image) cv2.waitKey()
def load_model(config, mode='inference', model_path=None): # Recreate the model in inference mode model = mrcnn.model.MaskRCNN(mode=mode, config=config, model_dir=model_dir) # Get path to saved weights # Either set a specific path or find last trained weights # model_path = os.path.join(ROOT_DIR, ".h5 file name here") if model_path is None: model_path = model.find_last() # Load trained weights print("Loading weights from ", model_path) model.load_weights(model_path, by_name=True) return model
def main(args): config = MRIConfig() model = mrcnn.model.MaskRCNN(mode='training', config=config, model_dir=args.model_dir) if args.weights_path == 'last': model.load_weights(model.find_last(), by_name=True) else: model.load_weights(args.weights_path, by_name=True, exclude=[ "mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask", "rpn_model" ]) data_train = MRIDataset() data_train.load_mri(args.train_data_list, args.classes) data_train.prepare() data_val = MRIDataset() data_val.load_mri(args.val_data_list, args.classes) data_val.prepare() augmentation = iaa.SomeOf((0, None), [ iaa.Fliplr(0.5), iaa.Multiply((0.8, 1.2)), iaa.ContrastNormalization((0.8, 1.2)), ]) if args.train_head: model.train(data_train, data_val, learning_rate=config.LEARNING_RATE, epochs=20, augmentation=augmentation, layers='heads') model.train(data_train, data_val, learning_rate=config.LEARNING_RATE, epochs=50, augmentation=augmentation, layers='all')
def main(self): print("detecting cars...") """Create a model object and load the weights.""" model = mrcnn.model.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=self.config) model.load_weights(COCO_MODEL_PATH, by_name=True) """Check class numbers""" dataset = coco.CocoDataset() dataset.load_coco(MODEL_DIR, "train") dataset.prepare() """Load an image""" IMAGE = self.dir #os.path.abspath("../../resources/images/stjohns.jpg") image = skimage.io.imread(IMAGE) results = model.detect([image], verbose=1) """Visualize results""" r = results[0] r = self.filter_vehicles(r) """Save image""" t = int(time.time()) name = str(t) + ".png" path = os.path.abspath("../output") mrcnn.visualize.display_instances(path, name, image, r['rois'], r['masks'], r['class_ids'], dataset.class_names, r['scores'], title='# os detect cars: {}'.format( len(r['class_ids']))) return len(r['class_ids'])
def train(config, dataset_train, dataset_val, epochs, tune_epochs, init_with='coco'): # Create model in training mode model = mrcnn.model.MaskRCNN(mode="training", config=config, model_dir=model_dir) # Which weights to start with? 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=[ 'conv1', '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(), by_name=True) # 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=epochs, layers=r'(conv1)|(mrcnn\_.*)|(rpn\_.*)|(fpn\_.*)') # Fine tune all layers # Passing layers="all" trains all 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 / 10, epochs=tune_epochs, layers='all') return model
logs = os.path.join(logs, todayString) if not os.path.exists(logs): os.makedirs(logs) runs = args.runs learningRates = args.learningRates epochs = args.epochs layers = args.layers assert runs == len(learningRates) == len(epochs) == len(layers) config = dataset.Config() model = model.MaskRCNN(mode="training", config=config, model_dir=logs) print("Loading weights ", weights) model.load_weights(weights, by_name=True) dataset_train = dataset.Dataset() for index in range(len(trainImagesPaths)): trainImagesPath = trainImagesPaths[index] trainAnnotationsPath = trainAnnotationsPaths[index] assert os.path.exists(trainImagesPath) assert os.path.exists(trainAnnotationsPath) dataset_train.load_coco(trainImagesPath, trainAnnotationsPath) dataset_train.prepare() dataset_val = dataset.Dataset() for index in range(len(valImagesPaths)): valImagesPath = valImagesPaths[index] valAnnotationsPath = valAnnotationsPaths[index]
# set the number of GPUs to use along with the number of images per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # Number of classes = number of classes + 1 (+1 for the background). The background class is named BG NUM_CLASSES = len(CLASS_NAMES) # Initialize the Mask R-CNN model for inference and then load the weights. # This step builds the Keras model architecture. model = mrcnn.model.MaskRCNN(mode="inference", config=SimpleConfig(), model_dir=os.getcwd()) # Load the weights into the model. model.load_weights(filepath="mask_rcnn_coco.h5", by_name=True) # load the input image, convert it from BGR to RGB channel image = cv2.imread("sample_image.jpg") image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Perform a forward pass of the network to obtain the results r = model.detect([image], verbose=0) # Get the results for the first image. r = r[0] # Visualize the detected objects. mrcnn.visualize.display_instances(image=image, boxes=r['rois'], masks=r['masks'],
train_set.load_dataset(dataset_dir='E:\\Mask_RCNN-tf2\\kangaroo', is_train=True) train_set.prepare() # prepare test/val set valid_dataset = KangarooDataset() valid_dataset.load_dataset(dataset_dir='E:\\Mask_RCNN-tf2\\kangaroo', is_train=False) valid_dataset.prepare() # prepare config kangaroo_config = KangarooConfig() # define the model model = mrcnn.model.MaskRCNN(mode='training', model_dir='./', config=kangaroo_config) model.load_weights(filepath='mask_rcnn_coco.h5', by_name=True, exclude=["mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask"]) model.train(train_dataset=train_set, val_dataset=valid_dataset, learning_rate=kangaroo_config.LEARNING_RATE, epochs=20, layers='heads') model_path = 'Kangaro_mask_rcnn_trained.h5' model.keras_model.save_weights(model_path)
# Validation validation_dataset = BalloonDataset() validation_dataset.load_balloon( dataset_dir= 'C:/Users/Choi Jun Ho/maskrcnn/Mask-RCNN-TF2/lane_detection/lane', subset='val') validation_dataset.prepare() # Model Configuration lane_config = LaneConfig() # Build the Mask R-CNN Model Architecture model = mrcnn.model.MaskRCNN(mode='training', model_dir='./', config=lane_config) model.load_weights( filepath='C:/Users/Choi Jun Ho/maskrcnn/Mask-RCNN-TF2/mask_rcnn_coco.h5', by_name=True, exclude=[ "mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask" ]) model.train(train_dataset=train_dataset, val_dataset=validation_dataset, learning_rate=lane_config.LEARNING_RATE, epochs=1, layers='heads') model_path = 'C:/Users/Choi Jun Ho/maskrcnn/Mask-RCNN-TF2/lane_detection/lane_mask_rcnn_trained1.h5' model.keras_model.save_weights(model_path)
# set the number of GPUs to use along with the number of images per GPU GPU_COUNT = 1 IMAGES_PER_GPU = 1 # Number of classes = number of classes + 1 (+1 for the background). The background class is named BG NUM_CLASSES = len(CLASS_NAMES) # Initialize the Mask R-CNN model for inference and then load the weights. # This step builds the Keras model architecture. model = mrcnn.model.MaskRCNN(mode="inference", config=SimpleConfig(), model_dir=os.getcwd()) # Load the weights into the model. model.load_weights(filepath="Kangaro_mask_rcnn_trained.h5", by_name=True) # load the input image, convert it from BGR to RGB channel image = cv2.imread("sample2.jpg") image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Perform a forward pass of the network to obtain the results r = model.detect([image], verbose=0) # Get the results for the first image. r = r[0] # Visualize the detected objects. mrcnn.visualize.display_instances(image=image, boxes=r['rois'], masks=r['masks'],
layers = args.layers assert runs == len(learningRates) == len(epochs) == len(layers) config = dataset.Config() model = model.MaskRCNN(mode="training", config=config, model_dir=logs) log_file = open(os.path.join(logs, "log.txt"), "w") log("Startin from weights at: " + weights + "\n", log_file) if args.excludeWeightsOfLayers: log( "Excluding layers {} from weight loading to fully retrain them.\n". format(args.excludeWeightsOfLayers), log_file) model.load_weights(weights, by_name=True, exclude=args.excludeWeightsOfLayers) else: model.load_weights(weights, by_name=True) dataset_train = dataset.Dataset() for index in range(len(trainImagesPaths)): trainImagesPath = trainImagesPaths[index] trainAnnotationsPath = trainAnnotationsPaths[index] assert os.path.exists( trainImagesPath), "Images path {} does not exist.".format( trainImagesPath) assert os.path.exists(trainAnnotationsPath ), "Annotations file {} does not exist.".format( trainAnnotationsPath) log(
# Number of classes = number of classes + 1 (+1 for the background). The background class is named BG NUM_CLASSES = len(CLASS_NAMES) # Initialize the Mask R-CNN model for inference and then load the weights. # This step builds the Keras model architecture. model = mrcnn.model.MaskRCNN(mode="inference", config=SimpleConfig(), model_dir=os.getcwd()) # Load the weights into the model. model.load_weights( filepath="E:\\Mask_RCNN-tf2\\kangaroo\\mask_rcnn_kangaroo_cfg_0020.h5", # model.load_weights(filepath="E:\\Mask_RCNN-tf2\\kangaroo\\mask_rcnn_coco.h5", by_name=True, exclude=[ "mrcnn_class_logits", "mrcnn_bbox_fc", "mrcnn_bbox", "mrcnn_mask" ]) # 增加了 exclude # load the input image, convert it from BGR to RGB channel image = cv2.imread("E:\\Mask_RCNN-tf2\\kangaroo\\images\\00005.jpg") image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Perform a forward pass of the network to obtain the results r = model.detect([image], verbose=0) # Get the results for the first image. r = r[0] # Visualize the detected objects.
'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush' ] # Configuration that will be used by the Mask-RCNN library class MaskRCNNConfig(mrcnn.config.Config): NAME = "coco_pretrained_model_config" IMAGES_PER_GPU = 1 GPU_COUNT = 1 NUM_CLASSES = 1 + 80 # COCO dataset has 80 classes + one background class DETECTION_MIN_CONFIDENCE = 0.6 # Download COCO trained weights from Releases if needed if not os.path.exists(os.getenv('COCO_MODEL_PATH')): mrcnn.utils.download_trained_weights(os.getenv('COCO_MODEL_PATH')) # Create a Mask-RCNN model in inference mode model = mrcnn.model.MaskRCNN(mode="inference", model_dir=os.getenv('R_CNN_MODEL_DIR'), config=MaskRCNNConfig()) # Load pre-trained model model.load_weights(os.getenv('COCO_MODEL_PATH'), by_name=True)